Store results for checkwps of both current and release.
[rockboxthemes.git] / private / themesite.class.php
blobb3be852ea1c5537bc2f2ee29fd0d76425729d885
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",
181 $themeid,
182 $status_text[$oldstatus],
183 $status_text[$newstatus]
186 if ($newstatus == -1) {
187 $theme = $this->db->query(sprintf("SELECT shortname, mainlcd FROM themes WHERE RowID='%d'", db::quote($themeid)))->next();
188 $sql = sprintf("DELETE FROM themes WHERE RowID='%d'",
189 db::quote($themeid)
192 /* Delete the files */
193 $dir = sprintf("%s/%s/%s",
194 config::datadir,
195 $theme['mainlcd'],
196 $theme['shortname']
198 if (file_exists($dir)) {
199 foreach(glob(sprintf("%s/*", $dir)) as $file) {
200 unlink($file);
202 rmdir($dir);
205 else {
206 $sql = sprintf("UPDATE themes SET approved='%d' WHERE RowID='%d'",
207 db::quote($newstatus),
208 db::quote($themeid)
211 if ($oldstatus == 1 && $newstatus < 1) {
212 // Send a mail to notify the user that his theme has been
213 // hidden/deleted
214 print("Yeah hi we deleted your themz lol");
216 print("SQL: $sql<br />\n");
217 $this->db->query($sql);
220 public function addtarget($shortname, $fullname, $mainlcd, $pic, $depth, $remotelcd = false) {
221 $this->log(sprintf("Add new target %s", $fullname));
223 $sql = sprintf("INSERT INTO targets
224 (shortname, fullname, mainlcd, pic, depth, remotelcd)
225 VALUES
226 ('%s', '%s', '%s', '%s', '%s', %s)",
227 db::quote($shortname),
228 db::quote($fullname),
229 db::quote($mainlcd),
230 db::quote($pic),
231 db::quote($depth),
232 $remotelcd === false ? 'NULL' : sprintf("'%s'", db::quote($remotelcd))
234 $this->db->query($sql);
235 $themedir = sprintf("%s/%s", $this->themedir_abs, $mainlcd);
236 if (!file_exists($themedir)) {
237 mkdir($themedir);
241 public function validatetheme($zipfile) {
242 $err = array();
243 return $err;
246 public function prepareverification($id, $email, $author) {
247 $token = md5(uniqid());
248 $sql = sprintf("UPDATE themes SET emailverification='%s' WHERE RowID='%s'",
249 db::quote($token),
250 db::quote($id)
252 $this->db->query($sql);
253 $url = sprintf("%s%s/verify.php?t=%s", config::hostname, config::path, $token);
254 /* xxx: Someone rewrite this message to not sound horrible */
255 $msg = <<<END
256 Hello, you just uploaded a Rockbox theme and now we need you to verify your
257 email address. To do this, simply open the link below in your browser. You
258 may have to copy/paste the text into your browser's location bar in some cases.
260 $url
262 Thank for your contributions
264 The Rockbox Theme Site team.
265 END;
266 /* ' (this is here to keep my syntax hilighting happy) */
267 $msg = wordwrap($msg, 78);
268 $subject = "Rockbox Theme Site email verification";
269 $to = sprintf("%s <%s>", $author, $email);
270 $headers = 'From: themes@rockbox.org';
271 mail($to, $subject, $msg, $headers);
274 public function verifyemail($token) {
275 $sql = sprintf("UPDATE themes SET emailverification=1 WHERE emailverification='%s'",
276 db::quote($token)
278 $res = $this->db->query($sql);
279 return $res->rowsaffected();
282 public function addtheme($name, $shortname, $author, $email, $mainlcd, $remotelcd, $description, $zipfile, $sshot_wps, $sshot_menu) {
283 $err = array();
284 /* return array("Skipping upload"); */
286 /* Create the destination dir */
287 $destdir = sprintf("%s/%s/%s",
288 $this->themedir_abs,
289 $mainlcd,
290 $shortname
292 if (!file_exists($destdir) && !mkdir($destdir)) {
293 $err[] = sprintf("Couldn't create themedir %s", $destdir);
294 return $err;
297 /* Prepend wps- and menu- to screenshots */
298 $sshot_wps['name'] = empty($sshot_wps['name']) ? '' : 'wps-'.$sshot_wps['name'];
299 $sshot_menu['name'] = empty($sshot_menu['name']) ? '' : 'menu-'.$sshot_menu['name'];
301 /* Start moving files in place */
302 $uploads = array($zipfile, $sshot_wps, $sshot_menu);
303 $movedfiles = array();
304 foreach($uploads as $file) {
305 if ($file === false || empty($file['tmp_name'])) {
306 continue;
308 $dest = sprintf("%s/%s",
309 $destdir,
310 $file['name']
313 if (!@move_uploaded_file($file['tmp_name'], $dest)) {
314 /* Upload went wrong, clean up */
315 foreach ($movedfiles as $movedfile) {
316 unlink($movedfile);
318 rmdir($destdir);
319 $err[] = sprintf("Couldn't move %s.", $file['name'], $dest);
320 return $err;
322 else {
323 $movedfiles[] = $dest;
326 $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)";
327 $sql = sprintf($sql_f,
328 db::quote($author),
329 db::quote($email),
330 db::quote($name),
331 db::quote($mainlcd),
332 db::quote($zipfile['name']),
333 db::quote($sshot_wps['name']),
334 $sshot_menu === false ? 'NULL' : sprintf("'%s'", db::quote($sshot_menu['name'])),
335 $remotelcd === false ? 'NULL' : sprintf("'%s'", db::quote($remotelcd)),
336 db::quote($description),
337 db::quote($shortname),
338 config::defaultstatus
340 $result = $this->db->query($sql);
341 $id = $result->insertid();
342 $check = $this->checkwps(sprintf("%s/%s/%s", config::datadir, $mainlcd, $zipfile['name']), $mainlcd, $remotelcd);
343 /* xxx: store these results */
344 $this->log(sprintf("Added theme %d (email: %s)", $id, $email));
345 return $id;
349 * Use this rather than plain pathinfo for compatibility with PHP<5.2.0
351 private function my_pathinfo($path) {
352 $pathinfo = pathinfo($path);
353 /* Make sure we have the $pathinfo['filename'] element added in PHP 5.2.0 */
354 if (!isset($pathinfo['filename'])) {
355 $pathinfo['filename'] = substr(
356 $pathinfo['basename'],
358 strrpos($pathinfo['basename'],'.') === false ? strlen($pathinfo['basename']) : strrpos($pathinfo['basename'],'.')
361 return $pathinfo;
365 * Convenience function called from several locations
367 private function getzipentrycontents($zip, $ze) {
368 $ret = "";
369 zip_entry_open($zip, $ze);
370 while($read = zip_entry_read($ze)) {
371 $ret .= $read;
373 zip_entry_close($ze);
374 return $ret;
378 * xxx: I don't know what kind of validation is wanted for cfg files
380 public function validatecfg($cfg, $files) {
381 $conf = array();
382 foreach(explode("\n", $cfg) as $line) {
383 if (substr($line, 0, 1) == '#') continue;
384 preg_match("/^(?P<name>[^:]*)\s*:\s*(?P<value>[^#]*)\s*$/", $line, $matches);
385 if (count($matches) > 0) {
386 extract($matches);
387 switch($name) {
388 default:
389 break;
395 public function lcd2targets($lcd) {
396 $ret = array();
397 $sql = sprintf("SELECT shortname FROM targets WHERE mainlcd='%s' OR remotelcd='%s'",
398 db::quote($lcd),
399 db::quote($lcd)
401 $targets = $this->db->query($sql);
402 while ($target = $targets->next()) {
403 $ret[] = $target['shortname'];
405 return $ret;
409 * Check a WPS against two revisions: current and the latest release
411 public function checkwps($zipfile, $mainlcd, $remotelcd) {
412 $return = array();
414 /* First, create a temporary dir */
415 $tmpdir = sprintf("%s/temp-%s", preconfig::privpath, md5(uniqid()));
416 mkdir($tmpdir);
418 /* Then, unzip the theme here */
419 $cmd = sprintf("%s -d %s %s", config::unzip, $tmpdir, escapeshellarg($zipfile));
420 exec($cmd, $dontcare, $ret);
422 /* Now, cd into that dir */
423 $olddir = getcwd();
424 chdir($tmpdir);
427 * For all .wps and .rwps, run checkwps of both release and current for
428 * all applicable targets
430 foreach(glob('.rockbox/wps/*wps') as $file) {
431 $p = $this->my_pathinfo($file);
432 $lcd = ($p['extension'] == 'rwps' ? $remotelcd : $mainlcd);
433 foreach(array('release', 'current') as $version) {
434 foreach($this->lcd2targets($lcd) as $shortname) {
435 $result = array();
436 $checkwps = sprintf("%s/checkwps/%s/checkwps.%s",
437 '..', /* We'll be in a subdir of the private dir */
438 $version,
439 $shortname
441 $result['version'] = trim(file_get_contents(sprintf('%s/checkwps/%s/VERSION',
442 '..',
443 $version,
444 $shortname
445 )));
446 if (file_exists($checkwps)) {
447 exec(sprintf("%s %s", $checkwps, $file), $output, $ret);
448 $result['pass'] = ($ret == 0);
449 $result['output'] = $output;
450 $return[$version][$shortname] = $result;
456 /* chdir back */
457 chdir($olddir);
459 /* Remove the tempdir */
460 $this->rmdir_recursive($tmpdir);
461 return $return;
464 private function rmdir_recursive($dirname) {
465 $dir = dir($dirname);
466 while (false !== ($entry = $dir->read())) {
467 if ($entry == '.' || $entry == '..') continue;
468 $path = sprintf("%s/%s", $dir->path, $entry);
469 if (is_dir($path)) {
470 $this->rmdir_recursive($path);
472 else {
473 unlink($path);
476 $dir->close();
477 rmdir($dirname);
481 * This rather unwieldy function validates the structure of a theme's
482 * zipfile. It checks the following:
483 * - Exactly 1 .wps file
484 * - 0 or 1 .rwps file
485 * - Only .bmp files in /.rockbox/backdrops/ and /.rockbox/wps/<shortname>/
486 * - All files are inside /.rockbox
487 * - All .wps, .rwps and .cfg files use the same shortname, which is also
488 * the one used for the subdir in /.rockbox/wps
490 * It does not uncompress any of the files.
492 * We continue checking for errors, rather than aborting, so the uploader
493 * gets a full list of things we didn't like.
495 public function validatezip($themezipupload) {
496 $err = array();
497 $zip = zip_open($themezipupload['tmp_name']);
498 $totalsize = 0;
499 $files = array();
500 $wpsfound = array();
501 $rwpsfound = array();
502 $shortname = '';
503 $cfg = '';
505 if (is_int($zip)) {
506 $err[] = sprintf("Couldn't open zipfile %s", $themezipupload['name']);
507 return $err;
509 while ($ze = zip_read($zip)) {
510 $filename = zip_entry_name($ze);
511 $pathinfo = $this->my_pathinfo($filename);
512 $totalsize += zip_entry_filesize($ze);
513 $files[] = $filename;
515 /* Count .wps and .rwps files for later checking */
516 if (strtolower($pathinfo['extension']) == 'wps')
517 $wpsfound[] = $filename;
518 if (strtolower($pathinfo['extension']) == 'rwps')
519 $rwpsfound[] = $filename;
521 /* Check that all files are within .rockbox */
522 if (strpos($filename, '.rockbox') !== 0)
523 $err[] = sprintf("File outside /.rockbox/: %s", $filename);
525 /* Check that all .wps, .rwps and .cfg filenames use the same shortname */
526 switch(strtolower($pathinfo['extension'])) {
527 case 'cfg':
528 /* Save the contents for later checking */
529 $cfg = $this->getzipentrycontents($zip, $ze);
530 case 'wps':
531 case 'rwps':
532 if ($shortname === '')
533 $shortname = $pathinfo['filename'];
534 elseif ($shortname !== $pathinfo['filename'])
535 $err[] = sprintf("Filename invalid: %s (should be %s.%s)", $filename, $shortname, $pathinfo['extension']);
536 break;
540 * Check that the dir inside /.rockbox/wps also has the same name.
541 * This automatically ensures that there is only one.
543 if ($pathinfo['dirname'] == '.rockbox/wps' && $pathinfo['extension'] == '') {
544 if ($shortname === '')
545 $shortname = $pathinfo['filename'];
546 elseif ($shortname !== $pathinfo['filename'])
547 $err[] = sprintf("Invalid dirname: %s (should be %s.)", $filename, $shortname);
551 * Check that the only files we have inside /.rockbox/backdrops/
552 * and subdirs of /.rockbox/wps/ are .bmp files
554 if (strtolower($pathinfo['extension']) != 'bmp' &&
555 ($pathinfo['dirname'] == '.rockbox/backdrops' || // Files inside .rockbox/backdrops
556 ($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)
559 $err[] = sprintf("Non-bmp file not allowed here: %s", $filename);
562 /* Check for paths that are too deep */
563 if (count(explode('/', $pathinfo['dirname'])) > 3) {
564 $err[] = sprintf("Path too deep: %s", $filename);
567 /* Check for unwanted junk files */
568 switch(strtolower($pathinfo['basename'])) {
569 case "thumbs.db":
570 case "desktop.ini":
571 case ".ds_store":
572 case ".directory":
573 $err[] = sprintf("Unwanted file: %s", $filename);
577 /* Now we check all the things that could be wrong */
578 $this->validatecfg($cfg, $files);
580 if ($themezipupload['size'] > config::maxzippedsize)
581 $err[] = sprintf("Theme zip too large at %s (max size is %s)", $themezipupload['size'], config::maxzippedsize);
582 if ($totalsize > config::maxthemesize)
583 $err[] = sprintf("Unzipped theme size too large at %s (max size is %s)", $totalsize, config::maxthemesize);
584 if (count($files) > config::maxfiles)
585 $err[] = sprintf("Too many files+dirs in theme (%d). Maximum is %d.", count($files), config::maxfiles);
587 if (count($wpsfound) > 1)
588 $err[] = sprintf("More than one .wps found (%s).", implode(', ', $wpsfound));
589 elseif (count($wpsfound) == 0)
590 $err[] = "No .wps files found.";
592 if (count($rwpsfound) > 1)
593 $err[] = sprintf("More than one .rwps found (%s).", implode(', ', $rwpsfound));
594 return $err;
597 public function validatesshot($upload, $mainlcd) {
598 $err = array();
599 $size = getimagesize($upload['tmp_name']);
600 $dimensions = sprintf("%dx%d", $size[0], $size[1]);
601 if ($size === false) {
602 $err[] = sprintf("Couldn't open screenshot %s", $upload['name']);
604 else {
605 if ($dimensions != $mainlcd) {
606 $err[] = sprintf("Wrong resolution of %s. Should be %s (is %s).", $upload['name'], $mainlcd, $dimensions);
608 if ($size[2] != IMAGETYPE_PNG) {
609 $err[] = "Screenshots must be of type PNG.";
612 return $err;