]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/themeuploader.php
Improve error message per discussion on http://translatewiki.net/wiki/Thread:Support...
[quix0rs-gnu-social.git] / lib / themeuploader.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Utilities for theme files and paths
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Paths
23  * @package   StatusNet
24  * @author    Brion Vibber <brion@status.net>
25  * @copyright 2010 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET') && !defined('LACONICA')) {
31     exit(1);
32 }
33
34 /**
35  * Encapsulation of the validation-and-save process when dealing with
36  * a user-uploaded StatusNet theme archive...
37  * 
38  * @todo extract theme metadata from css/display.css
39  * @todo allow saving multiple themes
40  */
41 class ThemeUploader
42 {
43     protected $sourceFile;
44     protected $isUpload;
45     private $prevErrorReporting;
46
47     public function __construct($filename)
48     {
49         if (!class_exists('ZipArchive')) {
50             throw new Exception(_("This server cannot handle theme uploads without ZIP support."));
51         }
52         $this->sourceFile = $filename;
53     }
54
55     public static function fromUpload($name)
56     {
57         if (!isset($_FILES[$name]['error'])) {
58             throw new ServerException(_("The theme file is missing or the upload failed."));
59         }
60         if ($_FILES[$name]['error'] != UPLOAD_ERR_OK) {
61             throw new ServerException(_("The theme file is missing or the upload failed."));
62         }
63         return new ThemeUploader($_FILES[$name]['tmp_name']);
64     }
65
66     /**
67      * @param string $destDir
68      * @throws Exception on bogus files
69      */
70     public function extract($destDir)
71     {
72         $zip = $this->openArchive();
73
74         // First pass: validate but don't save anything to disk.
75         // Any errors will trip an exception.
76         $this->traverseArchive($zip);
77
78         // Second pass: now that we know we're good, actually extract!
79         $tmpDir = $destDir . '.tmp' . getmypid();
80         $this->traverseArchive($zip, $tmpDir);
81
82         $zip->close();
83
84         if (file_exists($destDir)) {
85             $killDir = $tmpDir . '.old';
86             $this->quiet();
87             $ok = rename($destDir, $killDir);
88             $this->loud();
89             if (!$ok) {
90                 common_log(LOG_ERR, "Could not move old custom theme from $destDir to $killDir");
91                 throw new ServerException(_("Failed saving theme."));
92             }
93         } else {
94             $killDir = false;
95         }
96
97         $this->quiet();
98         $ok = rename($tmpDir, $destDir);
99         $this->loud();
100         if (!$ok) {
101             common_log(LOG_ERR, "Could not move saved theme from $tmpDir to $destDir");
102             throw new ServerException(_("Failed saving theme."));
103         }
104
105         if ($killDir) {
106             $this->recursiveRmdir($killDir);
107         }
108     }
109
110     /**
111      * 
112      */
113     protected function traverseArchive($zip, $outdir=false)
114     {
115         $sizeLimit = 2 * 1024 * 1024; // 2 megabyte space limit?
116         $blockSize = 4096; // estimated; any entry probably takes this much space
117
118         $totalSize = 0;
119         $hasMain = false;
120         $commonBaseDir = false;
121
122         for ($i = 0; $i < $zip->numFiles; $i++) {
123             $data = $zip->statIndex($i);
124             $name = str_replace('\\', '/', $data['name']);
125
126             if (substr($name, -1) == '/') {
127                 // A raw directory... skip!
128                 continue;
129             }
130
131             // Check the directory structure...
132             $path = pathinfo($name);
133             $dirs = explode('/', $path['dirname']);
134             $baseDir = array_shift($dirs);
135             if ($commonBaseDir === false) {
136                 $commonBaseDir = $baseDir;
137             } else {
138                 if ($commonBaseDir != $baseDir) {
139                     throw new ClientException(_("Invalid theme: bad directory structure."));
140                 }
141             }
142
143             foreach ($dirs as $dir) {
144                 $this->validateFileOrFolder($dir);
145             }
146
147             // Is this a safe or skippable file?
148             if ($this->skippable($path['filename'], $path['extension'])) {
149                 // Documentation and such... booooring
150                 continue;
151             } else {
152                 $this->validateFile($path['filename'], $path['extension']);
153             }
154
155             $fullPath = $dirs;
156             $fullPath[] = $path['basename'];
157             $localFile = implode('/', $fullPath);
158             if ($localFile == 'css/display.css') {
159                 $hasMain = true;
160             }
161             
162             $size = $data['size'];
163             $estSize = $blockSize * max(1, intval(ceil($size / $blockSize)));
164             $totalSize += $estSize;
165             if ($totalSize > $sizeLimit) {
166                 $msg = sprintf(_("Uploaded theme is too large; " .
167                                  "must be less than %d bytes uncompressed."),
168                                  $sizeLimit);
169                 throw new ClientException($msg);
170             }
171
172             if ($outdir) {
173                 $this->extractFile($zip, $data['name'], "$outdir/$localFile");
174             }
175         }
176
177         if (!$hasMain) {
178             throw new ClientException(_("Invalid theme archive: " .
179                                         "missing file css/display.css"));
180         }
181     }
182
183     protected function skippable($filename, $ext)
184     {
185         $skip = array('txt', 'rtf', 'doc', 'docx', 'odt');
186         if (strtolower($filename) == 'readme') {
187             return true;
188         }
189         if (in_array(strtolower($ext), $skip)) {
190             return true;
191         }
192         return false;
193     }
194
195     protected function validateFile($filename, $ext)
196     {
197         $this->validateFileOrFolder($filename);
198         $this->validateExtension($ext);
199         // @fixme validate content
200     }
201
202     protected function validateFileOrFolder($name)
203     {
204         if (!preg_match('/^[a-z0-9_-]+$/i', $name)) {
205             $msg = _("Theme contains invalid file or folder name. " .
206                      "Stick with ASCII letters, digits, underscore, and minus sign.");
207             throw new ClientException($msg);
208         }
209         return true;
210     }
211
212     protected function validateExtension($ext)
213     {
214         $allowed = array('css', 'png', 'gif', 'jpg', 'jpeg');
215         if (!in_array(strtolower($ext), $allowed)) {
216             $msg = sprintf(_("Theme contains file of type '.%s', " .
217                              "which is not allowed."),
218                            $ext);
219             throw new ClientException($msg);
220         }
221         return true;
222     }
223
224     /**
225      * @return ZipArchive
226      */
227     protected function openArchive()
228     {
229         $zip = new ZipArchive;
230         $ok = $zip->open($this->sourceFile); 
231         if ($ok !== true) {
232             common_log(LOG_ERR, "Error opening theme zip archive: " .
233                                 "{$this->sourceFile} code: {$ok}");
234             throw new Exception(_("Error opening theme archive."));
235         }
236         return $zip;
237     }
238
239     /**
240      * @param ZipArchive $zip
241      * @param string $from original path inside ZIP archive
242      * @param string $to final destination path in filesystem
243      */
244     protected function extractFile($zip, $from, $to)
245     {
246         $dir = dirname($to);
247         if (!file_exists($dir)) {
248             $this->quiet();
249             $ok = mkdir($dir, 0755, true);
250             $this->loud();
251             if (!$ok) {
252                 common_log(LOG_ERR, "Failed to mkdir $dir while uploading theme");
253                 throw new ServerException(_("Failed saving theme."));
254             }
255         } else if (!is_dir($dir)) {
256             common_log(LOG_ERR, "Output directory $dir not a directory while uploading theme");
257             throw new ServerException(_("Failed saving theme."));
258         }
259
260         // ZipArchive::extractTo would be easier, but won't let us alter
261         // the directory structure.
262         $in = $zip->getStream($from);
263         if (!$in) {
264             common_log(LOG_ERR, "Couldn't open archived file $from while uploading theme");
265             throw new ServerException(_("Failed saving theme."));
266         }
267         $this->quiet();
268         $out = fopen($to, "wb");
269         $this->loud();
270         if (!$out) {
271             common_log(LOG_ERR, "Couldn't open output file $to while uploading theme");
272             throw new ServerException(_("Failed saving theme."));
273         }
274         while (!feof($in)) {
275             $buffer = fread($in, 65536);
276             fwrite($out, $buffer);
277         }
278         fclose($in);
279         fclose($out);
280     }
281
282     private function quiet()
283     {
284         $this->prevErrorReporting = error_reporting();
285         error_reporting($this->prevErrorReporting & ~E_WARNING);
286     }
287
288     private function loud()
289     {
290         error_reporting($this->prevErrorReporting);
291     }
292
293     private function recursiveRmdir($dir)
294     {
295         $list = dir($dir);
296         while (($file = $list->read()) !== false) {
297             if ($file == '.' || $file == '..') {
298                 continue;
299             }
300             $full = "$dir/$file";
301             if (is_dir($full)) {
302                 $this->recursiveRmdir($full);
303             } else {
304                 unlink($full);
305             }
306         }
307         $list->close();
308         rmdir($dir);
309     }
310
311 }