Mail the uploader when a theme is hidden/deleted. Also store the reason given for...
[rockboxthemes.git] / private / themesite.class.php
blobec755fbcc18b73c75a8c617b0c768352efc957a5
1 <?php
2 /***************************************************************************
3 * __________ __ ___.
4 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
5 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
6 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
7 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
8 * \/ \/ \/ \/ \/
9 * $Id$
11 * Copyright (C) 2009 Jonas Häggqvist
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ****************************************************************************/
23 require_once('db.class.php');
25 class themesite {
26 private $db;
27 private $themedir_abs;
29 public function __construct($dbfile) {
30 $this->db = new db($dbfile);
31 $this->themedir_abs = sprintf("%s/%s", $_SERVER['DOCUMENT_ROOT'], config::datadir);
33 /* Make sure the theme dir exists */
34 if (!file_exists($this->themedir_abs)) {
35 if (!@mkdir($this->themedir_abs)) {
36 die("The theme dir doesn't exist, and I can't create it. Giving up.");
42 * Log a message to the log table. Time, IP and admin user (if any)
43 * is automaticly added.
45 private function log($message) {
46 $sql_f = "INSERT INTO log (time, ip, admin, msg) VALUES (datetime('now'), '%s', '%s', '%s')";
47 $sql = sprintf($sql_f,
48 $_SERVER['REMOTE_ADDR'],
49 isset($_SESSION['user']) ? db::quote($_SESSION['user']) : '',
50 db::quote($message)
52 $this->db->query($sql);
55 private function targetlist($orderby) {
56 $sql = "SELECT shortname, fullname, pic, mainlcd, depth, remotelcd FROM targets ORDER BY " . $orderby;
57 return $this->db->query($sql);
60 public function listtargets($orderby = 'fullname ASC') {
61 $targets = $this->targetlist($orderby);
62 $ret = array();
63 while ($target = $targets->next()) {
64 $ret[] = $target;
66 return $ret;
70 * Run checkwps on all our themes
72 public function checkallthemes() {
73 $this->log("Running checkwps");
74 $sql = "SELECT RowID, * FROM themes";
75 $themes = $this->db->query($sql);
76 $return = array();
77 while ($theme = $themes->next()) {
78 $starttime = microtime(true);
79 $zipfile = sprintf("%s/%s/%s/%s",
80 config::datadir,
81 $theme['mainlcd'],
82 $theme['shortname'],
83 $theme['zipfile']
85 $result = $this->checkwps($zipfile, $theme['mainlcd'], $theme['remotelcd']);
87 /*
88 * Store the results and check if at least one check passed (for
89 * the summary)
91 $passany = false;
92 foreach($result as $version_type => $targets) {
93 foreach($targets as $target => $result) {
94 if ($result['pass']) $passany = true; /* For the summary */
96 * Maybe we want to have two tables - one with historic
97 * data, and one with only the latest results for fast
98 * retrieval?
100 $this->db->query(sprintf("DELETE FROM checkwps WHERE themeid=%d AND version_type='%s'", $theme['RowID'], db::quote($version_type)));
101 $sql = sprintf("INSERT INTO checkwps (themeid, version_type, version_number, target, pass) VALUES (%d, '%s', '%s', '%s', '%s')",
102 $theme['RowID'],
103 db::quote($version_type),
104 db::quote($result['version']),
105 db::quote($target),
106 db::quote($result['pass'] ? 1 : 0)
108 $this->db->query($sql);
111 $return[] = array(
112 'theme' => $theme,
113 'result' => $result,
114 'summary' => array('theme' => $theme['name'], 'pass' => $passany, 'duration' => microtime(true) - $starttime)
117 return $return;
120 public function adminlogin($user, $pass) {
121 $sql = sprintf("SELECT COUNT(*) as count FROM admins WHERE name='%s' AND pass='%s'",
122 db::quote($user),
123 db::quote(md5($pass))
125 $result = $this->db->query($sql)->next();
126 return $result['count'] == 1 ? true : false;
129 public function listthemes($target, $orderby = 'timestamp DESC', $approved = 'approved', $onlyverified = true) {
130 $ret = array();
131 switch($approved) {
132 case 'any':
133 $approved_clause = "";
134 break;
135 case 'hidden':
136 $approved_clause = " AND th.approved = 0 ";
137 break;
138 case 'approved':
139 default:
140 $approved_clause = " AND th.approved = 1 ";
141 break;
143 if ($onlyverified == true) {
144 $verified = " AND th.emailverification = 1 ";
146 else {
147 $verified = "";
149 $sql = sprintf("SELECT name, timestamp, th.mainlcd as mainlcd, approved, reason, description, th.RowID as id, th.shortname AS shortname, zipfile, sshot_wps, sshot_menu, emailverification = 1 as verified FROM themes th, targets ta WHERE 1 %s %s AND th.mainlcd=ta.mainlcd and ta.shortname='%s' AND (ta.remotelcd IS NULL OR ta.remotelcd=th.remotelcd) ORDER BY %s",
150 $verified,
151 $approved_clause,
152 db::quote($target),
153 $orderby
155 $themes = $this->db->query($sql);
156 while ($theme = $themes->next()) {
157 $ret[] = $theme;
159 return $ret;
162 public function target2lcd($shortname) {
163 $sql = sprintf("SELECT mainlcd, remotelcd, depth FROM targets WHERE shortname='%s'",
164 db::quote($shortname)
166 return $this->db->query($sql)->next();
169 public function themenameexists($name, $mainlcd) {
170 $sql = sprintf("SELECT COUNT(*) as count FROM themes WHERE name='%s' AND mainlcd='%s'",
171 db::quote($name),
172 db::quote($mainlcd)
174 $result = $this->db->query($sql)->next();
175 return $result['count'] > 0 ? true : false;
178 public function changestatus($themeid, $newstatus, $oldstatus, $reason) {
179 $status_text = array('1' => 'Approved', '0' => 'hidden', '-1' => 'deleted');
180 $this->log(sprintf("Changing status of theme %d from %s to %s - Reason: %s",
181 $themeid,
182 $status_text[$oldstatus],
183 $status_text[$newstatus],
184 $reason
186 $sql = sprintf("SELECT shortname, mainlcd, email, name, author FROM themes WHERE RowID='%d'", db::quote($themeid));
187 $theme = $this->db->query($sql)->next();
189 if ($newstatus == -1) {
190 $sql = sprintf("DELETE FROM themes WHERE RowID='%d'",
191 db::quote($themeid)
194 /* Delete the files */
195 $dir = sprintf("%s/%s/%s",
196 config::datadir,
197 $theme['mainlcd'],
198 $theme['shortname']
200 if (file_exists($dir)) {
201 foreach(glob(sprintf("%s/*", $dir)) as $file) {
202 unlink($file);
204 rmdir($dir);
207 else {
208 $sql = sprintf("UPDATE themes SET approved='%d', reason='%s' WHERE RowID='%d'",
209 db::quote($newstatus),
210 db::quote($reason),
211 db::quote($themeid)
214 if ($oldstatus == 1 && $newstatus < 1) {
215 // Send a mail to notify the user that his theme has been
216 // hidden/deleted. No reason to distinguish, since the result
217 // for him is the same.
218 $to = sprintf("%s <%s>", $theme['author'], $theme['email']);
219 $subject = sprintf("Your theme '%s' has been removed from %s", $theme['name'], config::hostname);
220 $msg = <<<END
221 Your theme {$theme['name']} was removed from the Rockbox theme site. The
222 following reason should explain why:
224 ----------
225 {$reason}
226 ----------
228 If you think this was a mistake, or disagree with the decision, contact the
229 theme site admins in the Rockbox Forums or on IRC.
230 END;
231 $this->send_mail($subject, $to, $msg);
233 $this->db->query($sql);
236 public function addtarget($shortname, $fullname, $mainlcd, $pic, $depth, $remotelcd = false) {
237 $this->log(sprintf("Add new target %s", $fullname));
239 $sql = sprintf("INSERT INTO targets
240 (shortname, fullname, mainlcd, pic, depth, remotelcd)
241 VALUES
242 ('%s', '%s', '%s', '%s', '%s', %s)",
243 db::quote($shortname),
244 db::quote($fullname),
245 db::quote($mainlcd),
246 db::quote($pic),
247 db::quote($depth),
248 $remotelcd === false ? 'NULL' : sprintf("'%s'", db::quote($remotelcd))
250 $this->db->query($sql);
251 $themedir = sprintf("%s/%s", $this->themedir_abs, $mainlcd);
252 if (!file_exists($themedir)) {
253 mkdir($themedir);
257 private function send_mail($subject, $to, $msg) {
258 $msg = wordwrap($msg, 78);
259 $headers = 'From: themes@rockbox.org';
260 mail($to, $subject, $msg, $headers);
263 public function validatetheme($zipfile) {
264 $err = array();
265 return $err;
268 public function prepareverification($id, $email, $author) {
269 $token = md5(uniqid());
270 $sql = sprintf("UPDATE themes SET emailverification='%s' WHERE RowID='%s'",
271 db::quote($token),
272 db::quote($id)
274 $this->db->query($sql);
275 $url = sprintf("%s%s/verify.php?t=%s", config::hostname, config::path, $token);
276 /* xxx: Someone rewrite this message to not sound horrible */
277 $msg = <<<END
278 Hello, you just uploaded a Rockbox theme and now we need you to verify your
279 email address. To do this, simply open the link below in your browser. You
280 may have to copy/paste the text into your browser's location bar in some cases.
282 $url
284 Thank for your contributions
286 The Rockbox Theme Site team.
287 END;
288 /* ' (this is here to keep my syntax hilighting happy) */
289 $subject = "Rockbox Theme Site email verification";
290 $to = sprintf("%s <%s>", $author, $email);
291 $this->send_mail($subject, $to, $msg);
294 public function verifyemail($token) {
295 $sql = sprintf("UPDATE themes SET emailverification=1 WHERE emailverification='%s'",
296 db::quote($token)
298 $res = $this->db->query($sql);
299 return $res->rowsaffected();
302 public function addtheme($name, $shortname, $author, $email, $mainlcd, $remotelcd, $description, $zipfile, $sshot_wps, $sshot_menu) {
303 $err = array();
304 /* return array("Skipping upload"); */
306 /* Create the destination dir */
307 $destdir = sprintf("%s/%s/%s",
308 $this->themedir_abs,
309 $mainlcd,
310 $shortname
312 if (!file_exists($destdir) && !mkdir($destdir)) {
313 $err[] = sprintf("Couldn't create themedir %s", $destdir);
314 return $err;
317 /* Prepend wps- and menu- to screenshots */
318 $sshot_wps['name'] = empty($sshot_wps['name']) ? '' : 'wps-'.$sshot_wps['name'];
319 $sshot_menu['name'] = empty($sshot_menu['name']) ? '' : 'menu-'.$sshot_menu['name'];
321 /* Start moving files in place */
322 $uploads = array($zipfile, $sshot_wps, $sshot_menu);
323 $movedfiles = array();
324 foreach($uploads as $file) {
325 if ($file === false || empty($file['tmp_name'])) {
326 continue;
328 $dest = sprintf("%s/%s",
329 $destdir,
330 $file['name']
333 if (!@move_uploaded_file($file['tmp_name'], $dest)) {
334 /* Upload went wrong, clean up */
335 foreach ($movedfiles as $movedfile) {
336 unlink($movedfile);
338 rmdir($destdir);
339 $err[] = sprintf("Couldn't move %s.", $file['name'], $dest);
340 return $err;
342 else {
343 $movedfiles[] = $dest;
346 $sql_f = "INSERT INTO themes (author, email, name, mainlcd, zipfile, sshot_wps, sshot_menu, remotelcd, description, shortname, emailverification, timestamp, approved) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', %s, %s, '%s', '%s', 0, datetime('now'), %d)";
347 $sql = sprintf($sql_f,
348 db::quote($author),
349 db::quote($email),
350 db::quote($name),
351 db::quote($mainlcd),
352 db::quote($zipfile['name']),
353 db::quote($sshot_wps['name']),
354 $sshot_menu === false ? 'NULL' : sprintf("'%s'", db::quote($sshot_menu['name'])),
355 $remotelcd === false ? 'NULL' : sprintf("'%s'", db::quote($remotelcd)),
356 db::quote($description),
357 db::quote($shortname),
358 config::defaultstatus
360 $result = $this->db->query($sql);
361 $id = $result->insertid();
362 $check = $this->checkwps(sprintf("%s/%s/%s", config::datadir, $mainlcd, $zipfile['name']), $mainlcd, $remotelcd);
363 /* xxx: store these results */
364 $this->log(sprintf("Added theme %d (email: %s)", $id, $email));
365 return $id;
369 * Use this rather than plain pathinfo for compatibility with PHP<5.2.0
371 private function my_pathinfo($path) {
372 $pathinfo = pathinfo($path);
373 /* Make sure we have the $pathinfo['filename'] element added in PHP 5.2.0 */
374 if (!isset($pathinfo['filename'])) {
375 $pathinfo['filename'] = substr(
376 $pathinfo['basename'],
378 strrpos($pathinfo['basename'],'.') === false ? strlen($pathinfo['basename']) : strrpos($pathinfo['basename'],'.')
381 return $pathinfo;
385 * Convenience function called from several locations
387 private function getzipentrycontents($zip, $ze) {
388 $ret = "";
389 zip_entry_open($zip, $ze);
390 while($read = zip_entry_read($ze)) {
391 $ret .= $read;
393 zip_entry_close($ze);
394 return $ret;
398 * xxx: I don't know what kind of validation is wanted for cfg files
400 public function validatecfg($cfg, $files) {
401 $conf = array();
402 foreach(explode("\n", $cfg) as $line) {
403 if (substr($line, 0, 1) == '#') continue;
404 preg_match("/^(?P<name>[^:]*)\s*:\s*(?P<value>[^#]*)\s*$/", $line, $matches);
405 if (count($matches) > 0) {
406 extract($matches);
407 switch($name) {
408 default:
409 break;
415 public function lcd2targets($lcd) {
416 $ret = array();
417 $sql = sprintf("SELECT shortname FROM targets WHERE mainlcd='%s' OR remotelcd='%s'",
418 db::quote($lcd),
419 db::quote($lcd)
421 $targets = $this->db->query($sql);
422 while ($target = $targets->next()) {
423 $ret[] = $target['shortname'];
425 return $ret;
429 * Check a WPS against two revisions: current and the latest release
431 public function checkwps($zipfile, $mainlcd, $remotelcd) {
432 $return = array();
434 /* First, create a temporary dir */
435 $tmpdir = sprintf("%s/temp-%s", preconfig::privpath, md5(uniqid()));
436 mkdir($tmpdir);
438 /* Then, unzip the theme here */
439 $cmd = sprintf("%s -d %s %s", config::unzip, $tmpdir, escapeshellarg($zipfile));
440 exec($cmd, $dontcare, $ret);
442 /* Now, cd into that dir */
443 $olddir = getcwd();
444 chdir($tmpdir);
447 * For all .wps and .rwps, run checkwps of both release and current for
448 * all applicable targets
450 foreach(glob('.rockbox/wps/*wps') as $file) {
451 $p = $this->my_pathinfo($file);
452 $lcd = ($p['extension'] == 'rwps' ? $remotelcd : $mainlcd);
453 foreach(array('release', 'current') as $version) {
454 foreach($this->lcd2targets($lcd) as $shortname) {
455 $result = array();
456 $checkwps = sprintf("%s/checkwps/%s/checkwps.%s",
457 '..', /* We'll be in a subdir of the private dir */
458 $version,
459 $shortname
461 $result['version'] = trim(file_get_contents(sprintf('%s/checkwps/%s/VERSION',
462 '..',
463 $version,
464 $shortname
465 )));
466 if (file_exists($checkwps)) {
467 exec(sprintf("%s %s", $checkwps, $file), $output, $ret);
468 $result['pass'] = ($ret == 0);
469 $result['output'] = $output;
470 $return[$version][$shortname] = $result;
476 /* chdir back */
477 chdir($olddir);
479 /* Remove the tempdir */
480 $this->rmdir_recursive($tmpdir);
481 return $return;
484 private function rmdir_recursive($dirname) {
485 $dir = dir($dirname);
486 while (false !== ($entry = $dir->read())) {
487 if ($entry == '.' || $entry == '..') continue;
488 $path = sprintf("%s/%s", $dir->path, $entry);
489 if (is_dir($path)) {
490 $this->rmdir_recursive($path);
492 else {
493 unlink($path);
496 $dir->close();
497 rmdir($dirname);
501 * This rather unwieldy function validates the structure of a theme's
502 * zipfile. It checks the following:
503 * - Exactly 1 .wps file
504 * - 0 or 1 .rwps file
505 * - Only .bmp files in /.rockbox/backdrops/ and /.rockbox/wps/<shortname>/
506 * - All files are inside /.rockbox
507 * - All .wps, .rwps and .cfg files use the same shortname, which is also
508 * the one used for the subdir in /.rockbox/wps
510 * It does not uncompress any of the files.
512 * We continue checking for errors, rather than aborting, so the uploader
513 * gets a full list of things we didn't like.
515 public function validatezip($themezipupload) {
516 $err = array();
517 $zip = zip_open($themezipupload['tmp_name']);
518 $totalsize = 0;
519 $files = array();
520 $wpsfound = array();
521 $rwpsfound = array();
522 $shortname = '';
523 $cfg = '';
525 if (is_int($zip)) {
526 $err[] = sprintf("Couldn't open zipfile %s", $themezipupload['name']);
527 return $err;
529 while ($ze = zip_read($zip)) {
530 $filename = zip_entry_name($ze);
531 $pathinfo = $this->my_pathinfo($filename);
532 $totalsize += zip_entry_filesize($ze);
533 $files[] = $filename;
535 /* Count .wps and .rwps files for later checking */
536 if (strtolower($pathinfo['extension']) == 'wps')
537 $wpsfound[] = $filename;
538 if (strtolower($pathinfo['extension']) == 'rwps')
539 $rwpsfound[] = $filename;
541 /* Check that all files are within .rockbox */
542 if (strpos($filename, '.rockbox') !== 0)
543 $err[] = sprintf("File outside /.rockbox/: %s", $filename);
545 /* Check that all .wps, .rwps and .cfg filenames use the same shortname */
546 switch(strtolower($pathinfo['extension'])) {
547 case 'cfg':
548 /* Save the contents for later checking */
549 $cfg = $this->getzipentrycontents($zip, $ze);
550 case 'wps':
551 case 'rwps':
552 if ($shortname === '')
553 $shortname = $pathinfo['filename'];
554 elseif ($shortname !== $pathinfo['filename'])
555 $err[] = sprintf("Filename invalid: %s (should be %s.%s)", $filename, $shortname, $pathinfo['extension']);
556 break;
560 * Check that the dir inside /.rockbox/wps also has the same name.
561 * This automatically ensures that there is only one.
563 if ($pathinfo['dirname'] == '.rockbox/wps' && $pathinfo['extension'] == '') {
564 if ($shortname === '')
565 $shortname = $pathinfo['filename'];
566 elseif ($shortname !== $pathinfo['filename'])
567 $err[] = sprintf("Invalid dirname: %s (should be %s.)", $filename, $shortname);
571 * Check that the only files we have inside /.rockbox/backdrops/
572 * and subdirs of /.rockbox/wps/ are .bmp files
574 if (strtolower($pathinfo['extension']) != 'bmp' &&
575 ($pathinfo['dirname'] == '.rockbox/backdrops' || // Files inside .rockbox/backdrops
576 ($pathinfo['dirname'] != '.rockbox/wps' && strpos($pathinfo['dirname'], '.rockbox/wps') === 0) // Files in a subdir of .rockbox/wps (first part or dirname is .rockbox/wps, but it's not all of it)
579 $err[] = sprintf("Non-bmp file not allowed here: %s", $filename);
582 /* Check for paths that are too deep */
583 if (count(explode('/', $pathinfo['dirname'])) > 3) {
584 $err[] = sprintf("Path too deep: %s", $filename);
587 /* Check for unwanted junk files */
588 switch(strtolower($pathinfo['basename'])) {
589 case "thumbs.db":
590 case "desktop.ini":
591 case ".ds_store":
592 case ".directory":
593 $err[] = sprintf("Unwanted file: %s", $filename);
597 /* Now we check all the things that could be wrong */
598 $this->validatecfg($cfg, $files);
600 if ($themezipupload['size'] > config::maxzippedsize)
601 $err[] = sprintf("Theme zip too large at %s (max size is %s)", $themezipupload['size'], config::maxzippedsize);
602 if ($totalsize > config::maxthemesize)
603 $err[] = sprintf("Unzipped theme size too large at %s (max size is %s)", $totalsize, config::maxthemesize);
604 if (count($files) > config::maxfiles)
605 $err[] = sprintf("Too many files+dirs in theme (%d). Maximum is %d.", count($files), config::maxfiles);
607 if (count($wpsfound) > 1)
608 $err[] = sprintf("More than one .wps found (%s).", implode(', ', $wpsfound));
609 elseif (count($wpsfound) == 0)
610 $err[] = "No .wps files found.";
612 if (count($rwpsfound) > 1)
613 $err[] = sprintf("More than one .rwps found (%s).", implode(', ', $rwpsfound));
614 return $err;
617 public function validatesshot($upload, $mainlcd) {
618 $err = array();
619 $size = getimagesize($upload['tmp_name']);
620 $dimensions = sprintf("%dx%d", $size[0], $size[1]);
621 if ($size === false) {
622 $err[] = sprintf("Couldn't open screenshot %s", $upload['name']);
624 else {
625 if ($dimensions != $mainlcd) {
626 $err[] = sprintf("Wrong resolution of %s. Should be %s (is %s).", $upload['name'], $mainlcd, $dimensions);
628 if ($size[2] != IMAGETYPE_PNG) {
629 $err[] = "Screenshots must be of type PNG.";
632 return $err;