3 * StatusNet, the distributed open-source microblogging tool
5 * Utilities for theme files and paths
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.
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.
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/>.
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/
30 if (!defined('STATUSNET') && !defined('LACONICA')) {
35 * Encapsulation of the validation-and-save process when dealing with
36 * a user-uploaded StatusNet theme archive...
38 * @todo extract theme metadata from css/display.css
39 * @todo allow saving multiple themes
43 protected $sourceFile;
45 private $prevErrorReporting;
47 public function __construct($filename)
49 if (!class_exists('ZipArchive')) {
50 throw new Exception(_("This server cannot handle theme uploads without ZIP support."));
52 $this->sourceFile = $filename;
55 public static function fromUpload($name)
57 if (!isset($_FILES[$name]['error'])) {
58 throw new ServerException(_("The theme file is missing or the upload failed."));
60 if ($_FILES[$name]['error'] != UPLOAD_ERR_OK) {
61 throw new ServerException(_("The theme file is missing or the upload failed."));
63 return new ThemeUploader($_FILES[$name]['tmp_name']);
67 * @param string $destDir
68 * @throws Exception on bogus files
70 public function extract($destDir)
72 $zip = $this->openArchive();
74 // First pass: validate but don't save anything to disk.
75 // Any errors will trip an exception.
76 $this->traverseArchive($zip);
78 // Second pass: now that we know we're good, actually extract!
79 $tmpDir = $destDir . '.tmp' . getmypid();
80 $this->traverseArchive($zip, $tmpDir);
84 if (file_exists($destDir)) {
85 $killDir = $tmpDir . '.old';
87 $ok = rename($destDir, $killDir);
90 common_log(LOG_ERR, "Could not move old custom theme from $destDir to $killDir");
91 throw new ServerException(_("Failed saving theme."));
98 $ok = rename($tmpDir, $destDir);
101 common_log(LOG_ERR, "Could not move saved theme from $tmpDir to $destDir");
102 throw new ServerException(_("Failed saving theme."));
106 $this->recursiveRmdir($killDir);
113 protected function traverseArchive($zip, $outdir=false)
115 $sizeLimit = 2 * 1024 * 1024; // 2 megabyte space limit?
116 $blockSize = 4096; // estimated; any entry probably takes this much space
120 $commonBaseDir = false;
122 for ($i = 0; $i < $zip->numFiles; $i++) {
123 $data = $zip->statIndex($i);
124 $name = str_replace('\\', '/', $data['name']);
126 if (substr($name, -1) == '/') {
127 // A raw directory... skip!
131 // Is this a safe or skippable file?
132 $path = pathinfo($name);
133 if ($this->skippable($path['filename'], $path['extension'])) {
134 // Documentation and such... booooring
137 $this->validateFile($path['filename'], $path['extension']);
140 // Check the directory structure...
141 $dirs = explode('/', $path['dirname']);
142 $baseDir = array_shift($dirs);
143 if ($commonBaseDir === false) {
144 $commonBaseDir = $baseDir;
146 if ($commonBaseDir != $baseDir) {
147 throw new ClientException(_("Invalid theme: bad directory structure."));
151 foreach ($dirs as $dir) {
152 $this->validateFileOrFolder($dir);
156 $fullPath[] = $path['basename'];
157 $localFile = implode('/', $fullPath);
158 if ($localFile == 'css/display.css') {
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."),
169 throw new ClientException($msg);
173 $this->extractFile($zip, $data['name'], "$outdir/$localFile");
178 throw new ClientException(_("Invalid theme archive: " .
179 "missing file css/display.css"));
184 * @fixme Probably most unrecognized files should just be skipped...
186 protected function skippable($filename, $ext)
188 $skip = array('txt', 'html', 'rtf', 'doc', 'docx', 'odt', 'xcf');
189 if (strtolower($filename) == 'readme') {
192 if (in_array(strtolower($ext), $skip)) {
195 if ($filename == '' || substr($filename, 0, 1) == '.') {
196 // Skip Unix-style hidden files
199 if ($filename == '__MACOSX') {
200 // Skip awful metadata files Mac OS X slips in for you.
207 protected function validateFile($filename, $ext)
209 $this->validateFileOrFolder($filename);
210 $this->validateExtension($filename, $ext);
211 // @fixme validate content
214 protected function validateFileOrFolder($name)
216 if (!preg_match('/^[a-z0-9_\.-]+$/i', $name)) {
217 common_log(LOG_ERR, "Bad theme filename: $name");
218 $msg = _("Theme contains invalid file or folder name. " .
219 "Stick with ASCII letters, digits, underscore, and minus sign.");
220 throw new ClientException($msg);
222 if (preg_match('/\.(php|cgi|asp|aspx|js|vb)\w/i', $name)) {
223 common_log(LOG_ERR, "Unsafe theme filename: $name");
224 $msg = _("Theme contains unsafe file extension names; may be unsafe.");
225 throw new ClientException($msg);
230 protected function validateExtension($base, $ext)
232 $allowed = array('css', // CSS may need validation
233 'png', 'gif', 'jpg', 'jpeg',
234 'svg', // SVG images/fonts may need validation
235 'ttf', 'eot', 'woff');
236 if (!in_array(strtolower($ext), $allowed)) {
237 if ($ext == 'ini' && $base == 'theme') {
238 // theme.ini exception
241 $msg = sprintf(_("Theme contains file of type '.%s', " .
242 "which is not allowed."),
244 throw new ClientException($msg);
252 protected function openArchive()
254 $zip = new ZipArchive;
255 $ok = $zip->open($this->sourceFile);
257 common_log(LOG_ERR, "Error opening theme zip archive: " .
258 "{$this->sourceFile} code: {$ok}");
259 throw new Exception(_("Error opening theme archive."));
265 * @param ZipArchive $zip
266 * @param string $from original path inside ZIP archive
267 * @param string $to final destination path in filesystem
269 protected function extractFile($zip, $from, $to)
272 if (!file_exists($dir)) {
274 $ok = mkdir($dir, 0755, true);
277 common_log(LOG_ERR, "Failed to mkdir $dir while uploading theme");
278 throw new ServerException(_("Failed saving theme."));
280 } else if (!is_dir($dir)) {
281 common_log(LOG_ERR, "Output directory $dir not a directory while uploading theme");
282 throw new ServerException(_("Failed saving theme."));
285 // ZipArchive::extractTo would be easier, but won't let us alter
286 // the directory structure.
287 $in = $zip->getStream($from);
289 common_log(LOG_ERR, "Couldn't open archived file $from while uploading theme");
290 throw new ServerException(_("Failed saving theme."));
293 $out = fopen($to, "wb");
296 common_log(LOG_ERR, "Couldn't open output file $to while uploading theme");
297 throw new ServerException(_("Failed saving theme."));
300 $buffer = fread($in, 65536);
301 fwrite($out, $buffer);
307 private function quiet()
309 $this->prevErrorReporting = error_reporting();
310 error_reporting($this->prevErrorReporting & ~E_WARNING);
313 private function loud()
315 error_reporting($this->prevErrorReporting);
318 private function recursiveRmdir($dir)
321 while (($file = $list->read()) !== false) {
322 if ($file == '.' || $file == '..') {
325 $full = "$dir/$file";
327 $this->recursiveRmdir($full);