webhook support
[phorkie.git] / src / phorkie / Repository.php
1 <?php
2 namespace phorkie;
3
4
5 class Repository
6 {
7     /**
8      * Repository ID (number in repositories directory)
9      *
10      * @var integer
11      */
12     public $id;
13
14     /**
15      * Full path to the .git repository
16      *
17      * @var string
18      */
19     public $gitDir;
20
21     /**
22      * Full path to the work tree directory
23      *
24      * @var string
25      */
26     public $workDir;
27
28     /**
29      * Revision of the repository that shall be shown
30      *
31      * @var string
32      */
33     public $hash;
34
35     /**
36      * Commit message of the last (or current) revision
37      *
38      * @var string
39      */
40     public $message;
41
42
43     /**
44      * Load Repository data from GET-Request
45      *
46      * @return void
47      *
48      * @throws Exception When something is wrong
49      */
50     public function loadFromRequest()
51     {
52         if (!isset($_GET['id'])) {
53             throw new Exception_Input('Paste ID missing');
54         }
55         if (!is_numeric($_GET['id'])) {
56             throw new Exception_Input('Paste ID not numeric');
57         }
58         if (isset($_GET['rev'])) {
59             $this->hash = $_GET['rev'];
60         }
61
62         $this->id = (int)$_GET['id'];
63         $this->loadDirs();
64         $this->loadHash();
65         $this->loadMessage();
66     }
67
68     public function loadById($id)
69     {
70         if (!is_numeric($id)) {
71             throw new Exception_Input('Paste ID not numeric');
72         }
73         $this->id = (int)$id;
74         $this->loadDirs();
75         $this->loadHash();
76     }
77
78     protected function loadDirs()
79     {
80         $gitDir = $GLOBALS['phorkie']['cfg']['gitdir'] . '/' . $this->id . '.git';
81         if (!is_dir($gitDir)) {
82             throw new Exception_NotFound(
83                 sprintf('Paste %d .git dir not found', $this->id)
84             );
85         }
86         $this->gitDir = $gitDir;
87
88         $workDir = $GLOBALS['phorkie']['cfg']['workdir'] . '/' . $this->id;
89         if (!is_dir($workDir)) {
90             throw new Exception_NotFound(
91                 sprintf('Paste %d work dir not found', $this->id)
92             );
93         }
94         $this->workDir = $workDir;
95     }
96
97     public function loadHash()
98     {
99         return;
100         if ($this->hash !== null) {
101             return;
102         }
103
104         $output = $this->getVc()->getCommand('log')
105             ->setOption('pretty', 'format:%H')
106             ->setOption('max-count', 1)
107             ->execute();
108         $output = trim($output);
109         if (strlen($output) !== 40) {
110             throw new Exception(
111                 'Loading commit hash failed: ' . $output
112             );
113         }
114         $this->hash = $output;
115     }
116
117     /**
118      * Populates $this->message
119      *
120      * @return void
121      */
122     public function loadMessage()
123     {
124         $rev = (isset($this->hash)) ? $this->hash : 'HEAD';
125         $output = $this->getVc()->getCommand('log')
126             ->setOption('oneline')
127             ->addArgument('-1')
128             ->addArgument($rev)
129             ->execute();
130         $output = trim($output);
131         if (strpos($output, ' ') > 0) {
132             $output = substr($output, strpos($output, ' '), strlen($output));
133             $this->message = trim($output);
134         } else {
135             $this->message = "This commit message intentionally left blank.";
136         }
137     }
138
139     public function getVc()
140     {
141         return new \VersionControl_Git($this->gitDir);
142     }
143
144     /**
145      * Loads the list of files in this repository
146      *
147      * @return File[] Array of files
148      */
149     public function getFiles()
150     {
151         $files = $this->getFilePaths();
152         $arFiles = array();
153         foreach ($files as $name) {
154             $arFiles[] = new File($name, $this);
155         }
156         return $arFiles;
157     }
158
159     protected function getFilePaths()
160     {
161         if ($this->hash === null) {
162             $hash = 'HEAD';
163         } else {
164             $hash = $this->hash;
165         }
166         $output = $this->getVc()->getCommand('ls-tree')
167             ->setOption('r')
168             ->setOption('name-only')
169             ->addArgument($hash)
170             ->execute();
171         return explode("\n", trim($output));
172     }
173
174     public function getFileByName($name, $bHasToExist = true)
175     {
176         $name = Tools::sanitizeFilename($name);
177         if ($name == '') {
178             throw new Exception_Input('Empty file name given');
179         }
180
181         if ($bHasToExist) {
182             $files = $this->getFilePaths();
183             if (array_search($name, $files) === false) {
184                 throw new Exception_Input('File does not exist');
185             }
186         }
187         return new File($name, $this);
188     }
189
190     public function hasFile($name)
191     {
192         try {
193             $this->getFileByName($name);
194         } catch (Exception $e) {
195             return false;
196         }
197         return true;
198     }
199
200     /**
201      * Permanently deletes the paste repository without any way to get
202      * it back.
203      *
204      * @return boolean True if all went well, false if not
205      */
206     public function delete()
207     {
208         $db = new Database();
209         $db->getIndexer()->deleteRepo($this);
210
211         $bOk = Tools::recursiveDelete($this->workDir)
212             && Tools::recursiveDelete($this->gitDir);
213
214         $not = new Notificator();
215         $not->delete($this);
216
217         return $bOk;
218     }
219
220     public function getTitle()
221     {
222         $desc = $this->getDescription();
223         if (trim($desc) != '') {
224             return $desc;
225         }
226
227         return 'paste #' . $this->id;
228     }
229
230     public function getDescription()
231     {
232         if (!is_readable($this->gitDir . '/description')) {
233             return null;
234         }
235         return file_get_contents($this->gitDir . '/description');
236     }
237
238     public function setDescription($description)
239     {
240         file_put_contents($this->gitDir . '/description', $description);
241     }
242
243     /**
244      * @return array Array with keys "email" and "name"
245      */
246     public function getOwner()
247     {
248         try {
249             $name = $this->getVc()->getCommand('config')
250                 ->addArgument('owner.name')->execute();
251         } catch (\VersionControl_Git_Exception $e) {
252             $name = $GLOBALS['phorkie']['auth']['anonymousName'];
253         }
254         try {
255             $email = $this->getVc()->getCommand('config')
256                 ->addArgument('owner.email')->execute();
257         } catch (\VersionControl_Git_Exception $e) {
258             $email = $GLOBALS['phorkie']['auth']['anonymousEmail'];
259         }
260
261         return array('name' => trim($name), 'email' => trim($email));
262     }
263
264     /**
265      * Get a link to the repository
266      *
267      * @param string  $type   Link type. Supported are:
268      *                        - "edit"
269      *                        - "delete"
270      *                        - "delete-confirm"
271      *                        - "display"
272      *                        - "fork"
273      *                        - "revision"
274      * @param string  $option Additional link option, e.g. revision number
275      * @param boolean $full   Return full URL or normal relative
276      *
277      * @return string
278      */
279     public function getLink($type, $option = null, $full = false)
280     {
281         if ($type == 'edit') {
282             $link = $this->id . '/edit';
283         } else if ($type == 'display') {
284             $link = $this->id;
285         } else if ($type == 'fork') {
286             $link = $this->id . '/fork';
287         } else if ($type == 'doap') {
288             $link = $this->id . '/doap';
289         } else if ($type == 'delete') {
290             $link = $this->id . '/delete';
291         } else if ($type == 'delete-confirm') {
292             $link = $this->id . '/delete/confirm';
293         } else if ($type == 'revision') {
294             $link = $this->id . '/rev/' . $option;
295         } else {
296             throw new Exception('Unknown link type');
297         }
298
299         if ($full) {
300             $link = Tools::fullUrl($link);
301         }
302         return $link;
303     }
304
305     public function getCloneURL($public = true)
306     {
307         $var = $public ? 'public' : 'private';
308         if (isset($GLOBALS['phorkie']['cfg']['git'][$var])) {
309             return $GLOBALS['phorkie']['cfg']['git'][$var] . $this->id . '.git';
310         }
311         return null;
312     }
313
314     /**
315      * Returns the history of the repository.
316      * We don't use VersionControl_Git's rev list fetcher since it does not
317      * give us separate email addresses and names, and it does not give us
318      * the amount of changed (added/deleted) lines.
319      *
320      * @return array Array of history objects
321      */
322     public function getHistory()
323     {
324         $output = $this->getVc()->getCommand('log')
325             ->setOption('pretty', 'format:commit %H%n%at%n%an%n%ae')
326             ->setOption('max-count', 10)
327             ->setOption('shortstat')
328             ->execute();
329
330         $arCommits = array();
331         $arOutput = explode("\n", $output);
332         $lines = count($arOutput);
333         $current = 0;
334         while ($current < $lines) {
335             $commit = new Repository_Commit();
336             list($name,$commit->hash) = explode(' ', $arOutput[$current]);
337             if ($name !== 'commit') {
338                 throw new Exception(
339                     'Git log output format not as expected: ' . $arOutput[$current]
340                 );
341             }
342             $commit->committerTime  = $arOutput[$current + 1];
343             $commit->committerName  = $arOutput[$current + 2];
344             $commit->committerEmail = $arOutput[$current + 3];
345
346             if (substr($arOutput[$current + 4], 0, 1) != ' ') {
347                 //commit without changed lines
348                 $arCommits[] = $commit;
349                 $current += 4;
350                 continue;
351             }
352
353             $arLineParts = explode(' ', trim($arOutput[$current + 4]));
354             $commit->filesChanged = $arLineParts[0];
355             $commit->linesAdded   = $arLineParts[3];
356             if (isset($arLineParts[5])) {
357                 $commit->linesDeleted = $arLineParts[5];
358             }
359
360             $current += 6;
361
362             $arCommits[] = $commit;
363         }
364
365         return $arCommits;
366     }
367
368     /**
369      * @return Repository_ConnectionInfo
370      */
371     public function getConnectionInfo()
372     {
373         return new Repository_ConnectionInfo($this);
374     }
375 }
376
377 ?>