move load method to top
[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         return Tools::recursiveDelete($this->workDir)
212             && Tools::recursiveDelete($this->gitDir);
213     }
214
215     public function getTitle()
216     {
217         $desc = $this->getDescription();
218         if (trim($desc) != '') {
219             return $desc;
220         }
221
222         return 'paste #' . $this->id;
223     }
224
225     public function getDescription()
226     {
227         if (!is_readable($this->gitDir . '/description')) {
228             return null;
229         }
230         return file_get_contents($this->gitDir . '/description');
231     }
232
233     public function setDescription($description)
234     {
235         file_put_contents($this->gitDir . '/description', $description);
236     }
237
238     /**
239      * @return array Array with keys "email" and "name"
240      */
241     public function getOwner()
242     {
243         try {
244             $name = $this->getVc()->getCommand('config')
245                 ->addArgument('owner.name')->execute();
246         } catch (\VersionControl_Git_Exception $e) {
247             $name = $GLOBALS['phorkie']['auth']['anonymousName'];
248         }
249         try {
250             $email = $this->getVc()->getCommand('config')
251                 ->addArgument('owner.email')->execute();
252         } catch (\VersionControl_Git_Exception $e) {
253             $email = $GLOBALS['phorkie']['auth']['anonymousEmail'];
254         }
255
256         return array('name' => trim($name), 'email' => trim($email));
257     }
258
259     /**
260      * Get a link to the repository
261      *
262      * @param string  $type   Link type. Supported are:
263      *                        - "edit"
264      *                        - "delete"
265      *                        - "delete-confirm"
266      *                        - "display"
267      *                        - "fork"
268      *                        - "revision"
269      * @param string  $option Additional link option, e.g. revision number
270      * @param boolean $full   Return full URL or normal relative
271      *
272      * @return string
273      */
274     public function getLink($type, $option = null, $full = false)
275     {
276         if ($type == 'edit') {
277             $link = '/' . $this->id . '/edit';
278         } else if ($type == 'display') {
279             $link = '/' . $this->id;
280         } else if ($type == 'fork') {
281             $link = '/' . $this->id . '/fork';
282         } else if ($type == 'doap') {
283             $link = '/' . $this->id . '/doap';
284         } else if ($type == 'delete') {
285             $link = '/' . $this->id . '/delete';
286         } else if ($type == 'delete-confirm') {
287             $link = '/' . $this->id . '/delete/confirm';
288         } else if ($type == 'revision') {
289             $link = '/' . $this->id . '/rev/' . $option;
290         } else {
291             throw new Exception('Unknown link type');
292         }
293
294         if ($full) {
295             $link = Tools::fullUrl($link);
296         }
297         return $link;
298     }
299
300     public function getCloneURL($public = true)
301     {
302         $var = $public ? 'public' : 'private';
303         if (isset($GLOBALS['phorkie']['cfg']['git'][$var])) {
304             return $GLOBALS['phorkie']['cfg']['git'][$var] . $this->id . '.git';
305         }
306         return null;
307     }
308
309     /**
310      * Returns the history of the repository.
311      * We don't use VersionControl_Git's rev list fetcher since it does not
312      * give us separate email addresses and names, and it does not give us
313      * the amount of changed (added/deleted) lines.
314      *
315      * @return array Array of history objects
316      */
317     public function getHistory()
318     {
319         $output = $this->getVc()->getCommand('log')
320             ->setOption('pretty', 'format:commit %H%n%at%n%an%n%ae')
321             ->setOption('max-count', 10)
322             ->setOption('shortstat')
323             ->execute();
324
325         $arCommits = array();
326         $arOutput = explode("\n", $output);
327         $lines = count($arOutput);
328         $current = 0;
329         while ($current < $lines) {
330             $commit = new Repository_Commit();
331             list($name,$commit->hash) = explode(' ', $arOutput[$current]);
332             if ($name !== 'commit') {
333                 throw new Exception(
334                     'Git log output format not as expected: ' . $arOutput[$current]
335                 );
336             }
337             $commit->committerTime  = $arOutput[$current + 1];
338             $commit->committerName  = $arOutput[$current + 2];
339             $commit->committerEmail = $arOutput[$current + 3];
340
341             if (substr($arOutput[$current + 4], 0, 1) != ' ') {
342                 //commit without changed lines
343                 $arCommits[] = $commit;
344                 $current += 4;
345                 continue;
346             }
347
348             $arLineParts = explode(' ', trim($arOutput[$current + 4]));
349             $commit->filesChanged = $arLineParts[0];
350             $commit->linesAdded   = $arLineParts[3];
351             if (isset($arLineParts[5])) {
352                 $commit->linesDeleted = $arLineParts[5];
353             }
354
355             $current += 6;
356
357             $arCommits[] = $commit;
358         }
359
360         return $arCommits;
361     }
362 }
363
364 ?>