fix crash when renaming file
[phorkie.git] / src / phorkie / Repository / Post.php
1 <?php
2 namespace phorkie;
3
4 class Repository_Post
5 {
6     public $repo;
7
8     /**
9      * When a new file is created during processing, its name
10      * is stored here for later use.
11      *
12      * @var string
13      */
14     public $newfileName;
15
16
17
18     public function __construct(Repository $repo = null)
19     {
20         $this->repo = $repo;
21     }
22
23     /**
24      * Processes the POST data, changes description and files
25      *
26      * @return boolean True if the post was successful
27      */
28     public function process($postData, $sessionData)
29     {
30         if (!isset($postData['files'])) {
31             return false;
32         }
33         if (!$this->hasContent($postData)) {
34             return false;
35         }
36
37         if (!$this->repo) {
38             $this->repo = $this->createRepo();
39         }
40
41         $vc = $this->repo->getVc();
42
43
44         $bChanged = false;
45         $bCommit  = false;
46         if ($postData['description'] != $this->repo->getDescription()) {
47             $this->repo->setDescription($postData['description']);
48             $bChanged = true;
49         }
50
51         foreach ($postData['files'] as $num => $arFile) {
52             $bUpload = false;
53             if ($_FILES['files']['error'][$num]['upload'] == 0) {
54                 //valid file upload
55                 $bUpload = true;
56             } else if ($arFile['content'] == '' && $arFile['name'] == '') {
57                 //empty (new) file
58                 continue;
59             }
60
61             $originalName = Tools::sanitizeFilename($arFile['original_name']);
62             $name         = Tools::sanitizeFilename($arFile['name']);
63
64             if ($arFile['type'] == '_auto_') {
65                 //FIXME: upload
66                 $arFile['type'] = $this->getType($arFile['content']);
67             }
68
69             if ($name == '') {
70                 if ($bUpload) {
71                     $name = Tools::sanitizeFilename(
72                         $_FILES['files']['name'][$num]['upload']
73                     );
74                 } else {
75                     $name = $this->getNextNumberedFile('phork')
76                         . '.' . $arFile['type'];
77                 }
78             }
79
80             $bNew = false;
81             $bDelete = false;
82             if (!isset($originalName) || $originalName == '') {
83                 //new file
84                 $bNew = true;
85                 if (strpos($name, '.') === false) {
86                     //automatically append file extension if none is there
87                     $name .= '.' . $arFile['type'];
88                 }
89                 $this->newfileName = $name;
90             } else if (!$this->repo->hasFile($originalName)) {
91                 //unknown file
92                 //FIXME: Show error message
93                 continue;
94             } else if (isset($arFile['delete']) && $arFile['delete'] == 1) {
95                 $bDelete = true;
96             } else if ($originalName != $name) {
97                 if (strpos($name, '/') === false) {
98                     //ignore names with a slash in it, would be new directory
99                     //FIXME: what to do with overwrites?
100                     $vc->getCommand('mv')
101                         ->addArgument($originalName)
102                         ->addArgument($name)
103                         ->execute();
104                     $bCommit = true;
105                 } else {
106                     $name = $originalName;
107                 }
108             }
109
110             $file = $this->repo->getFileByName($name, false);
111             if ($originalName !== '') {
112                 $originalFile = $this->repo->getFileByName($originalName, false);
113             }
114             if ($bDelete) {
115                 $command = $vc->getCommand('rm')
116                     ->addArgument($file->getFilename())
117                     ->execute();
118                 $bCommit = true;
119             } else if ($bUpload) {
120                 move_uploaded_file(
121                     $_FILES['files']['tmp_name'][$num]['upload'],
122                     $file->getFullPath()
123                 );
124                 $command = $vc->getCommand('add')
125                     ->addArgument($file->getFilename())
126                     ->execute();
127                 $bCommit = true;
128             } else if ($bNew
129                 || (isset($arFile['content']) && isset($originalFile)
130                     && $originalFile->getContent() != $arFile['content']
131                 )
132             ) {
133                 $dir = dirname($file->getFullPath());
134                 if (!is_dir($dir)) {
135                     mkdir($dir, 0777, true);
136                 }
137                 file_put_contents($file->getFullPath(), $arFile['content']);
138                 $command = $vc->getCommand('add')
139                     ->addArgument($file->getFilename())
140                     ->execute();
141                 $bCommit = true;
142             }
143         }
144
145         if (isset($sessionData['identity'])) {
146             $notes = $sessionData['identity'];
147         } else {
148             $notes = $sessionData['ipaddr'];
149         }
150
151         if ($bCommit) {
152             $vc->getCommand('commit')
153                 ->setOption('message', '')
154                 ->setOption('allow-empty-message')
155                 ->setOption('no-edit')
156                 ->setOption(
157                     'author',
158                     $sessionData['name'] . ' <' . $sessionData['email'] . '>'
159                 )
160                 ->execute();
161             //FIXME: git needs ref BEFORE add
162             //quick hack until http://pear.php.net/bugs/bug.php?id=19605 is fixed
163             //also waiting for https://pear.php.net/bugs/bug.php?id=19623
164             $vc->getCommand('notes --ref=identity add')
165                 ->setOption('force')
166                 ->setOption('message', "$notes")
167                 ->execute();
168             //update info for dumb git HTTP transport
169             //the post-update hook should do that IMO, but does not somehow
170             $vc->getCommand('update-server-info')->execute();
171
172             //we changed the hash by committing, so reload it
173             $this->repo->reloadHash();
174
175             $bChanged = true;
176         }
177
178         if ($bChanged) {
179             //FIXME: index changed files only
180             //also handle file deletions
181             $db = new Database();
182             $not = new Notificator();
183             if ($bNew) {
184                 $db->getIndexer()->addRepo($this->repo);
185                 $not->create($this->repo);
186             } else {
187                 $commits = $this->repo->getHistory();
188                 $db->getIndexer()->updateRepo(
189                     $this->repo,
190                     $commits[count($commits)-1]->committerTime,
191                     $commits[0]->committerTime
192                 );
193                 $not->edit($this->repo);
194             }
195         }
196
197         return true;
198     }
199
200     protected function hasContent($postData)
201     {
202         foreach ($postData['files'] as $num => $arFile) {
203             if ($_FILES['files']['error'][$num]['upload'] == 0) {
204                 return true;
205             }
206             if (isset($arFile['content']) && $arFile['content'] != '') {
207                 return true;
208             }
209             if (isset($arFile['name']) && $arFile['name'] != '') {
210                 //binary files do not have content
211                 return true;
212             }
213             if (isset($arFile['delete']) && $arFile['delete'] != '') {
214                 //binary files do not have content
215                 return true;
216             }
217         }
218         return false;
219     }
220
221     public function createRepo()
222     {
223         $rs = new Repositories();
224         $repo = $rs->createNew();
225         $vc = $repo->getVc();
226         $vc->getCommand('init')
227             //this should be setOption, but it fails with a = between name and value
228             ->addArgument('--separate-git-dir')
229             ->addArgument(
230                 $GLOBALS['phorkie']['cfg']['gitdir'] . '/' . $repo->id . '.git'
231             )
232             ->addArgument($repo->workDir)
233             ->execute();
234
235         $rs = new Repository_Setup($repo);
236         $rs->afterInit();
237
238         return $repo;
239     }
240
241     public function getNextNumberedFile($prefix)
242     {
243         $num = -1;
244         do {
245             ++$num;
246             $files = glob($this->repo->workDir . '/' . $prefix . $num . '.*');
247         } while (count($files));
248
249         return $prefix . $num;
250     }
251
252     public function getType($content, $returnError = false)
253     {
254         if (getenv('PATH') == '') {
255             //php-fpm does not fill $PATH by default
256             // we have to work around that since System::which() uses it
257             putenv('PATH=/usr/local/bin:/usr/bin:/bin');
258         }
259
260         $tmp = tempnam(sys_get_temp_dir(), 'phorkie-autodetect-');
261         file_put_contents($tmp, $content);
262         $type = Tool_MIME_Type_PlainDetect::autoDetect($tmp);
263         unlink($tmp);
264
265         if ($returnError && $type instanceof \PEAR_Error) {
266             return $type;
267         }
268
269         return $this->findExtForType($type);
270     }
271
272     protected function findExtForType($type)
273     {
274         $ext = 'txt';
275         foreach ($GLOBALS['phorkie']['languages'] as $lext => $arLang) {
276             if ($arLang['mime'] == $type) {
277                 $ext = $lext;
278                 break;
279             }
280         }
281         return $ext;
282     }
283 }
284
285 ?>