← Back
mainapp/permissions.php
<?php

function repo_get(PDO $db, int $repoId): ?array {
  $st = $db->prepare("SELECT r.*, u.username as owner_username
                      FROM repositories r
                      JOIN users u ON u.id = r.owner_id
                      WHERE r.id=? LIMIT 1");
  $st->execute([$repoId]);
  return $st->fetch() ?: null;
}

function repo_can_read(PDO $db, int $repoId, ?int $uid): bool {
  $repo = repo_get($db, $repoId);
  if (!$repo) return false;

  if ($repo['visibility'] === 'public') return true;
  if (!$uid) return false;
  if ((int)$repo['owner_id'] === $uid) return true;

  $st = $db->prepare("SELECT role FROM repo_collaborators WHERE repo_id=? AND user_id=? LIMIT 1");
  $st->execute([$repoId, $uid]);
  return (bool)$st->fetch();
}

function repo_can_write(PDO $db, int $repoId, ?int $uid): bool {
  if (!$uid) return false;

  $repo = repo_get($db, $repoId);
  if (!$repo) return false;
  if ((int)$repo['owner_id'] === $uid) return true;

  $st = $db->prepare("SELECT role FROM repo_collaborators WHERE repo_id=? AND user_id=? LIMIT 1");
  $st->execute([$repoId, $uid]);
  $row = $st->fetch();
  return $row && $row['role'] === 'write';
}