Fix access to files with spaces in Apache 2.4.52+
[phorkie.git] / src / phorkie / Repositories.php
1 <?php
2 namespace phorkie;
3
4 class Repositories
5 {
6     public function __construct()
7     {
8         $this->workDir = $GLOBALS['phorkie']['cfg']['workdir'];
9         $this->gitDir  = $GLOBALS['phorkie']['cfg']['gitdir'];
10     }
11
12     public function createNew(): Repository
13     {
14         chdir($this->gitDir);
15         $dirs = glob('*.git', GLOB_ONLYDIR);
16         foreach ($dirs as $key => $dir) {
17             $dirs[$key] = substr($dir, 0, -4);
18         }
19         sort($dirs, SORT_NUMERIC);
20
21         if ($GLOBALS['phorkie']['cfg']['randomIds']) {
22             $n = end($dirs) + mt_rand(65536, 16777216);
23         } else {
24             $n = end($dirs) + 1;
25         }
26
27         chdir($this->workDir);
28         $dir = $this->workDir . '/' . $n . '/';
29         mkdir($dir, fileperms($this->workDir) & 0777);
30         $r = new Repository();
31         $r->id = $n;
32         $r->workDir = $dir;
33         $r->gitDir = $this->gitDir . '/' . $n . '.git/';
34         mkdir($r->gitDir, fileperms($this->gitDir) & 0777);
35
36         return $r;
37     }
38
39     /**
40      * Get a list of repository objects
41      *
42      * @param integer $page    Page number, beginning with 0, or "last"
43      * @param integer $perPage Number of repositories per page
44      *
45      * @return array Array of Repositories first, number of repositories second
46      */
47     public function getList($page = 0, $perPage = 10): array
48     {
49         chdir($this->gitDir);
50         $dirs = glob('*.git', GLOB_ONLYDIR);
51         sort($dirs, SORT_NUMERIC);
52         if ($page === 'last') {
53             //always show the last 10
54             $page = intval(count($dirs) / $perPage);
55             $start = count($dirs) - $perPage;
56             if ($start < 0) {
57                 $start = 0;
58             }
59             $some = array_slice($dirs, $start, $perPage);
60         } else {
61             $some = array_slice($dirs, $page * $perPage, $perPage);
62         }
63
64         $repos = array();
65         foreach ($some as $oneDir) {
66             $r = new Repository();
67             try {
68                 $r->loadById(substr($oneDir, 0, -4));
69             } catch (\VersionControl_Git_Exception $e) {
70                 if (strpos($e->getMessage(), 'does not have any commits') !== false) {
71                     //the git repo is broken as the initial commit
72                     // has not been finished
73                     continue;
74                 }
75                 throw $e;
76             }
77             $repos[] = $r;
78         }
79         return array($repos, count($dirs), $page);
80     }
81 }
82
83 ?>