7428c8a0c093abd7f0d20a474dda6c7c028f1ed4
[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     /**
160      * Decodes unicode characters in git filenames
161      * They begin and end with double quote characters, and may contain
162      * backslash + 3 letter octal code numbers representing the character.
163      *
164      * For example,
165      * > "t\303\244st.txt"
166      * means
167      * > täst.txt
168      *
169      * On the shell, you can pipe them into "printf" and have them decoded.
170      *
171      * @param string Encoded git file name
172      *
173      * @return string Decoded file name
174      */
175     protected function decodeFileName($name)
176     {
177         $name = substr($name, 1, -1);
178         $name = str_replace('\"', '"', $name);
179         $name = preg_replace_callback(
180             '#\\\\[0-7]{3}#',
181             function ($ar) {
182                 return chr(octdec(substr($ar[0], 1)));
183             },
184             $name
185         );
186         return $name;
187     }
188
189     protected function getFilePaths()
190     {
191         if ($this->hash === null) {
192             $hash = 'HEAD';
193         } else {
194             $hash = $this->hash;
195         }
196         $output = $this->getVc()->getCommand('ls-tree')
197             ->setOption('r')
198             ->setOption('name-only')
199             ->addArgument($hash)
200             ->execute();
201         $files = explode("\n", trim($output));
202         foreach ($files as &$file) {
203             if ($file{0} == '"') {
204                 $file = $this->decodeFileName($file);
205             }
206         }
207         return $files;
208     }
209
210     public function getFileByName($name, $bHasToExist = true)
211     {
212         $name = Tools::sanitizeFilename($name);
213         if ($name == '') {
214             throw new Exception_Input('Empty file name given');
215         }
216
217         if ($bHasToExist) {
218             $files = $this->getFilePaths();
219             if (array_search($name, $files) === false) {
220                 throw new Exception_Input('File does not exist');
221             }
222         }
223         return new File($name, $this);
224     }
225
226     public function hasFile($name)
227     {
228         try {
229             $this->getFileByName($name);
230         } catch (Exception $e) {
231             return false;
232         }
233         return true;
234     }
235
236     /**
237      * Permanently deletes the paste repository without any way to get
238      * it back.
239      *
240      * @return boolean True if all went well, false if not
241      */
242     public function delete()
243     {
244         $db = new Database();
245         $db->getIndexer()->deleteRepo($this);
246
247         $bOk = Tools::recursiveDelete($this->workDir)
248             && Tools::recursiveDelete($this->gitDir);
249
250         $not = new Notificator();
251         $not->delete($this);
252
253         return $bOk;
254     }
255
256     public function getTitle()
257     {
258         $desc = $this->getDescription();
259         if (trim($desc) != '') {
260             return $desc;
261         }
262
263         return 'paste #' . $this->id;
264     }
265
266     public function getDescription()
267     {
268         if (!is_readable($this->gitDir . '/description')) {
269             return null;
270         }
271         return file_get_contents($this->gitDir . '/description');
272     }
273
274     public function setDescription($description)
275     {
276         file_put_contents($this->gitDir . '/description', $description);
277     }
278
279     /**
280      * @return array Array with keys "email" and "name"
281      */
282     public function getOwner()
283     {
284         try {
285             $name = $this->getVc()->getCommand('config')
286                 ->addArgument('owner.name')->execute();
287         } catch (\VersionControl_Git_Exception $e) {
288             $name = $GLOBALS['phorkie']['auth']['anonymousName'];
289         }
290         try {
291             $email = $this->getVc()->getCommand('config')
292                 ->addArgument('owner.email')->execute();
293         } catch (\VersionControl_Git_Exception $e) {
294             $email = $GLOBALS['phorkie']['auth']['anonymousEmail'];
295         }
296
297         return array('name' => trim($name), 'email' => trim($email));
298     }
299
300     /**
301      * Get a link to the repository
302      *
303      * @param string  $type   Link type. Supported are:
304      *                        - "edit"
305      *                        - "delete"
306      *                        - "delete-confirm"
307      *                        - "display"
308      *                        - "fork"
309      *                        - "revision"
310      * @param string  $option Additional link option, e.g. revision number
311      * @param boolean $full   Return full URL or normal relative
312      *
313      * @return string
314      */
315     public function getLink($type, $option = null, $full = false)
316     {
317         if ($type == 'edit') {
318             $link = $this->id . '/edit';
319         } else if ($type == 'display') {
320             $link = $this->id;
321         } else if ($type == 'fork') {
322             $link = $this->id . '/fork';
323         } else if ($type == 'doap') {
324             $link = $this->id . '/doap';
325         } else if ($type == 'delete') {
326             $link = $this->id . '/delete';
327         } else if ($type == 'delete-confirm') {
328             $link = $this->id . '/delete/confirm';
329         } else if ($type == 'revision') {
330             $link = $this->id . '/rev/' . $option;
331         } else {
332             throw new Exception('Unknown link type');
333         }
334
335         if ($full) {
336             $link = Tools::fullUrl($link);
337         }
338         return $link;
339     }
340
341     public function getCloneURL($public = true)
342     {
343         $var = $public ? 'public' : 'private';
344         if (isset($GLOBALS['phorkie']['cfg']['git'][$var])) {
345             return $GLOBALS['phorkie']['cfg']['git'][$var] . $this->id . '.git';
346         }
347         return null;
348     }
349
350     /**
351      * Returns the history of the repository.
352      * We don't use VersionControl_Git's rev list fetcher since it does not
353      * give us separate email addresses and names, and it does not give us
354      * the amount of changed (added/deleted) lines.
355      *
356      * @return array Array of history objects
357      */
358     public function getHistory()
359     {
360         $output = $this->getVc()->getCommand('log')
361             ->setOption('pretty', 'format:commit %H%n%at%n%an%n%ae')
362             ->setOption('max-count', 10)
363             ->setOption('shortstat')
364             ->execute();
365
366         $arCommits = array();
367         $arOutput = explode("\n", $output);
368         $lines = count($arOutput);
369         $current = 0;
370         while ($current < $lines) {
371             $commit = new Repository_Commit();
372             list($name,$commit->hash) = explode(' ', $arOutput[$current]);
373             if ($name !== 'commit') {
374                 throw new Exception(
375                     'Git log output format not as expected: ' . $arOutput[$current]
376                 );
377             }
378             $commit->committerTime  = $arOutput[$current + 1];
379             $commit->committerName  = $arOutput[$current + 2];
380             $commit->committerEmail = $arOutput[$current + 3];
381
382             if (substr($arOutput[$current + 4], 0, 1) != ' ') {
383                 //commit without changed lines
384                 $arCommits[] = $commit;
385                 $current += 4;
386                 continue;
387             }
388
389             $arLineParts = explode(' ', trim($arOutput[$current + 4]));
390             $commit->filesChanged = $arLineParts[0];
391             $commit->linesAdded   = $arLineParts[3];
392             if (isset($arLineParts[5])) {
393                 $commit->linesDeleted = $arLineParts[5];
394             }
395
396             $current += 6;
397
398             $arCommits[] = $commit;
399         }
400
401         return $arCommits;
402     }
403
404     /**
405      * @return Repository_ConnectionInfo
406      */
407     public function getConnectionInfo()
408     {
409         return new Repository_ConnectionInfo($this);
410     }
411 }
412
413 ?>