2 /***************************************************************************
4 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
5 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
6 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
7 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
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');
27 private $themedir_public;
28 private $themedir_private;
30 public function __construct($dbfile) {
31 $this->db
= new db($dbfile);
32 $this->themedir_public
= sprintf("%s/%s/%s", $_SERVER['DOCUMENT_ROOT'], config
::path
, config
::datadir
);
33 $this->themedir_private
= sprintf("%s/%s", preconfig
::privpath
, config
::datadir
);
37 * Log a message to the log table. Time, IP and admin user (if any)
38 * is automaticly added.
40 private function log($message) {
41 $sql_f = "INSERT INTO log (time, ip, admin, msg) VALUES (datetime('now'), '%s', '%s', '%s')";
42 $sql = sprintf($sql_f,
43 $_SERVER['REMOTE_ADDR'],
44 isset($_SESSION['user']) ? db
::quote($_SESSION['user']) : '',
47 $this->db
->query($sql);
50 private function targetlist($orderby) {
51 $sql = "SELECT shortname, fullname, pic, mainlcd, depth, remotelcd FROM targets ORDER BY " . $orderby;
52 return $this->db
->query($sql);
55 public function listtargets($orderby = 'fullname ASC') {
56 $targets = $this->targetlist($orderby);
58 while ($target = $targets->next()) {
65 * Run checkwps on all our themes
67 public function checkallthemes() {
68 $this->log("Running checkwps");
69 $sql = "SELECT RowID, * FROM themes";
70 $themes = $this->db
->query($sql);
72 while ($theme = $themes->next()) {
73 $starttime = microtime(true);
74 $zipfile = sprintf("%s/%s/%s/%s",
80 $result = $this->checkwps($zipfile, $theme['mainlcd'], $theme['remotelcd']);
83 * Store the results and check if at least one check passed (for
87 foreach($result as $version_type => $targets) {
88 foreach($targets as $target => $result) {
89 if ($result['pass']) $passany = true; /* For the summary */
91 * Maybe we want to have two tables - one with historic
92 * data, and one with only the latest results for fast
95 $this->db
->query(sprintf("DELETE FROM checkwps WHERE themeid=%d AND version_type='%s'", $theme['RowID'], db
::quote($version_type)));
96 $sql = sprintf("INSERT INTO checkwps (themeid, version_type, version_number, target, pass) VALUES (%d, '%s', '%s', '%s', '%s')",
98 db
::quote($version_type),
99 db
::quote($result['version']),
101 db
::quote($result['pass'] ?
1 : 0)
103 $this->db
->query($sql);
109 'summary' => array('theme' => $theme['name'], 'pass' => $passany, 'duration' => microtime(true) - $starttime)
115 public function adminlogin($user, $pass) {
116 $sql = sprintf("SELECT COUNT(*) as count FROM admins WHERE name='%s' AND pass='%s'",
118 db
::quote(md5($pass))
120 $result = $this->db
->query($sql)->next();
121 return $result['count'] == 1 ?
true : false;
124 public function listthemes($target, $orderby = 'timestamp DESC', $approved = 'approved', $onlyverified = true) {
128 $approved_clause = "";
131 $approved_clause = " AND th.approved = 0 ";
135 $approved_clause = " AND th.approved = 1 ";
138 if ($onlyverified == true) {
139 $verified = " AND th.emailverification = 1 ";
144 $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 $themes = $this->db
->query($sql);
151 while ($theme = $themes->next()) {
157 public function target2lcd($shortname) {
158 $sql = sprintf("SELECT mainlcd, remotelcd, depth FROM targets WHERE shortname='%s'",
159 db
::quote($shortname)
161 return $this->db
->query($sql)->next();
164 public function themenameexists($name, $mainlcd) {
165 $sql = sprintf("SELECT COUNT(*) as count FROM themes WHERE name='%s' AND mainlcd='%s'",
169 $result = $this->db
->query($sql)->next();
170 return $result['count'] > 0 ?
true : false;
173 public function changestatus($themeid, $newstatus, $oldstatus, $reason) {
174 $status_text = array('1' => 'Approved', '0' => 'hidden', '-1' => 'deleted');
175 $this->log(sprintf("Changing status of theme %d from %s to %s - Reason: %s",
177 $status_text[$oldstatus],
178 $status_text[$newstatus],
181 $sql = sprintf("SELECT shortname, mainlcd, email, name, author, zipfile FROM themes WHERE RowID='%d'", db
::quote($themeid));
182 $theme = $this->db
->query($sql)->next();
184 if ($newstatus == -1) {
185 $sql = sprintf("DELETE FROM themes WHERE RowID='%d'",
189 /* Delete the files */
190 foreach(array($this->themedir_public
, $this->themedir_private
) as $root) {
191 $dir = sprintf("%s/%s/%s",
196 if (file_exists($dir)) {
197 foreach(glob(sprintf("%s/*", $dir)) as $file) {
205 $sql = sprintf("UPDATE themes SET approved='%d', reason='%s' WHERE RowID='%d'",
206 db
::quote($newstatus),
210 $from = sprintf("%s/%s/%s/%s", $this->themedir_public
, $theme['mainlcd'], $theme['shortname'], $theme['zipfile']);
211 $to = sprintf("%s/%s/%s/%s", $this->themedir_private
, $theme['mainlcd'], $theme['shortname'], $theme['zipfile']);
212 if ($newstatus == 1) {
219 if ($oldstatus == 1 && $newstatus < 1) {
220 // Send a mail to notify the user that his theme has been
221 // hidden/deleted. No reason to distinguish, since the result
222 // for him is the same.
223 $to = sprintf("%s <%s>", $theme['author'], $theme['email']);
224 $subject = sprintf("Your theme '%s' has been removed from %s", $theme['name'], config
::hostname
);
226 Your theme {$theme['name']} was removed from the Rockbox theme site. The
227 following reason should explain why:
233 If you think this was a mistake, or disagree with the decision, contact the
234 theme site admins in the Rockbox Forums or on IRC.
236 $this->send_mail($subject, $to, $msg);
238 $this->db
->query($sql);
241 public function addtarget($shortname, $fullname, $mainlcd, $pic, $depth, $remotelcd = false) {
242 $this->log(sprintf("Add new target %s", $fullname));
244 $sql = sprintf("INSERT INTO targets
245 (shortname, fullname, mainlcd, pic, depth, remotelcd)
247 ('%s', '%s', '%s', '%s', '%s', %s)",
248 db
::quote($shortname),
249 db
::quote($fullname),
253 $remotelcd === false ?
'NULL' : sprintf("'%s'", db
::quote($remotelcd))
255 $this->db
->query($sql);
256 /* Create the target's dir in both the private and public theme dir */
257 foreach(array($this->themedir_public
, $this->themedir_private
) as $root) {
258 $themedir = sprintf("%s/%s", $root, $mainlcd);
259 if (!file_exists($themedir)) {
265 private function send_mail($subject, $to, $msg) {
266 $msg = wordwrap($msg, 78);
267 $headers = 'From: themes@rockbox.org';
268 mail($to, $subject, $msg, $headers);
271 public function validatetheme($zipfile) {
276 public function prepareverification($id, $email, $author) {
277 $token = md5(uniqid());
278 $sql = sprintf("UPDATE themes SET emailverification='%s' WHERE RowID='%s'",
282 $this->db
->query($sql);
283 $url = sprintf("%s%s/verify.php?t=%s", config
::hostname
, config
::path
, $token);
284 /* xxx: Someone rewrite this message to not sound horrible */
286 Hello, you just uploaded a Rockbox theme and now we need you to verify your
287 email address. To do this, simply open the link below in your browser. You
288 may have to copy/paste the text into your browser's location bar in some cases.
292 Thank for your contributions
294 The Rockbox Theme Site team.
296 /* ' (this is here to keep my syntax hilighting happy) */
297 $subject = "Rockbox Theme Site email verification";
298 $to = sprintf("%s <%s>", $author, $email);
299 $this->send_mail($subject, $to, $msg);
302 public function verifyemail($token) {
303 $sql = sprintf("UPDATE themes SET emailverification=1 WHERE emailverification='%s'",
306 $res = $this->db
->query($sql);
307 return $res->rowsaffected();
310 public function addtheme($name, $shortname, $author, $email, $mainlcd, $remotelcd, $description, $zipfile, $sshot_wps, $sshot_menu) {
312 /* return array("Skipping upload"); */
314 /* Create the destination dir in both private and public area */
315 foreach(array($this->themedir_public
, $this->themedir_private
) as $root) {
316 mkdir(sprintf("%s/%s/%s",
323 /* This is the actual destination dir */
324 $destdir = sprintf("%s/%s/%s",
325 config
::defaultstatus
== 1 ?
$this->themedir_public
: $this->themedir_private
,
330 /* Prepend wps- and menu- to screenshots */
331 $sshot_wps['name'] = empty($sshot_wps['name']) ?
'' : 'wps-'.$sshot_wps['name'];
332 $sshot_menu['name'] = empty($sshot_menu['name']) ?
'' : 'menu-'.$sshot_menu['name'];
334 /* Start moving files in place */
335 $uploads = array($zipfile, $sshot_wps, $sshot_menu);
336 $movedfiles = array();
337 foreach($uploads as $file) {
338 if ($file === false ||
empty($file['tmp_name'])) {
341 $dest = sprintf("%s/%s",
346 if (!@move_uploaded_file
($file['tmp_name'], $dest)) {
347 /* Upload went wrong, clean up */
348 foreach ($movedfiles as $movedfile) {
352 $err[] = sprintf("Couldn't move %s.", $file['name'], $dest);
356 $movedfiles[] = $dest;
359 $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)";
360 $sql = sprintf($sql_f,
365 db
::quote($zipfile['name']),
366 db
::quote($sshot_wps['name']),
367 $sshot_menu === false ?
'NULL' : sprintf("'%s'", db
::quote($sshot_menu['name'])),
368 $remotelcd === false ?
'NULL' : sprintf("'%s'", db
::quote($remotelcd)),
369 db
::quote($description),
370 db
::quote($shortname),
371 config
::defaultstatus
373 $result = $this->db
->query($sql);
374 $id = $result->insertid();
375 $check = $this->checkwps(sprintf("%s/%s/%s", config
::datadir
, $mainlcd, $zipfile['name']), $mainlcd, $remotelcd);
376 /* xxx: store these results */
377 $this->log(sprintf("Added theme %d (email: %s)", $id, $email));
382 * Use this rather than plain pathinfo for compatibility with PHP<5.2.0
384 private function my_pathinfo($path) {
385 $pathinfo = pathinfo($path);
386 /* Make sure we have the $pathinfo['filename'] element added in PHP 5.2.0 */
387 if (!isset($pathinfo['filename'])) {
388 $pathinfo['filename'] = substr(
389 $pathinfo['basename'],
391 strrpos($pathinfo['basename'],'.') === false ?
strlen($pathinfo['basename']) : strrpos($pathinfo['basename'],'.')
398 * Convenience function called from several locations
400 private function getzipentrycontents($zip, $ze) {
402 zip_entry_open($zip, $ze);
403 while($read = zip_entry_read($ze)) {
406 zip_entry_close($ze);
411 * xxx: I don't know what kind of validation is wanted for cfg files
413 public function validatecfg($cfg, $files) {
415 foreach(explode("\n", $cfg) as $line) {
416 if (substr($line, 0, 1) == '#') continue;
417 preg_match("/^(?P<name>[^:]*)\s*:\s*(?P<value>[^#]*)\s*$/", $line, $matches);
418 if (count($matches) > 0) {
428 public function lcd2targets($lcd) {
430 $sql = sprintf("SELECT shortname FROM targets WHERE mainlcd='%s' OR remotelcd='%s'",
434 $targets = $this->db
->query($sql);
435 while ($target = $targets->next()) {
436 $ret[] = $target['shortname'];
442 * Check a WPS against two revisions: current and the latest release
444 public function checkwps($zipfile, $mainlcd, $remotelcd) {
447 /* First, create a temporary dir */
448 $tmpdir = sprintf("%s/temp-%s", preconfig
::privpath
, md5(uniqid()));
451 /* Then, unzip the theme here */
452 $cmd = sprintf("%s -d %s %s", config
::unzip
, $tmpdir, escapeshellarg($zipfile));
453 exec($cmd, $dontcare, $ret);
455 /* Now, cd into that dir */
460 * For all .wps and .rwps, run checkwps of both release and current for
461 * all applicable targets
463 foreach(glob('.rockbox/wps/*wps') as $file) {
464 $p = $this->my_pathinfo($file);
465 $lcd = ($p['extension'] == 'rwps' ?
$remotelcd : $mainlcd);
466 foreach(array('release', 'current') as $version) {
467 foreach($this->lcd2targets($lcd) as $shortname) {
469 $checkwps = sprintf("%s/checkwps/%s/checkwps.%s",
470 '..', /* We'll be in a subdir of the private dir */
474 $result['version'] = trim(file_get_contents(sprintf('%s/checkwps/%s/VERSION',
479 if (file_exists($checkwps)) {
480 exec(sprintf("%s %s", $checkwps, $file), $output, $ret);
481 $result['pass'] = ($ret == 0);
482 $result['output'] = $output;
483 $return[$version][$shortname] = $result;
492 /* Remove the tempdir */
493 $this->rmdir_recursive($tmpdir);
497 private function rmdir_recursive($dirname) {
498 $dir = dir($dirname);
499 while (false !== ($entry = $dir->read())) {
500 if ($entry == '.' ||
$entry == '..') continue;
501 $path = sprintf("%s/%s", $dir->path
, $entry);
503 $this->rmdir_recursive($path);
514 * This rather unwieldy function validates the structure of a theme's
515 * zipfile. It checks the following:
516 * - Exactly 1 .wps file
517 * - 0 or 1 .rwps file
518 * - Only .bmp files in /.rockbox/backdrops/ and /.rockbox/wps/<shortname>/
519 * - All files are inside /.rockbox
520 * - All .wps, .rwps and .cfg files use the same shortname, which is also
521 * the one used for the subdir in /.rockbox/wps
523 * It does not uncompress any of the files.
525 * We continue checking for errors, rather than aborting, so the uploader
526 * gets a full list of things we didn't like.
528 public function validatezip($themezipupload) {
530 $zip = zip_open($themezipupload['tmp_name']);
534 $rwpsfound = array();
539 $err[] = sprintf("Couldn't open zipfile %s", $themezipupload['name']);
542 while ($ze = zip_read($zip)) {
543 $filename = zip_entry_name($ze);
544 $pathinfo = $this->my_pathinfo($filename);
545 $totalsize +
= zip_entry_filesize($ze);
546 $files[] = $filename;
548 /* Count .wps and .rwps files for later checking */
549 if (strtolower($pathinfo['extension']) == 'wps')
550 $wpsfound[] = $filename;
551 if (strtolower($pathinfo['extension']) == 'rwps')
552 $rwpsfound[] = $filename;
554 /* Check that all files are within .rockbox */
555 if (strpos($filename, '.rockbox') !== 0)
556 $err[] = sprintf("File outside /.rockbox/: %s", $filename);
558 /* Check that all .wps, .rwps and .cfg filenames use the same shortname */
559 switch(strtolower($pathinfo['extension'])) {
561 /* Save the contents for later checking */
562 $cfg = $this->getzipentrycontents($zip, $ze);
565 if ($shortname === '')
566 $shortname = $pathinfo['filename'];
567 elseif ($shortname !== $pathinfo['filename'])
568 $err[] = sprintf("Filename invalid: %s (should be %s.%s)", $filename, $shortname, $pathinfo['extension']);
573 * Check that the dir inside /.rockbox/wps also has the same name.
574 * This automatically ensures that there is only one.
576 if ($pathinfo['dirname'] == '.rockbox/wps' && $pathinfo['extension'] == '') {
577 if ($shortname === '')
578 $shortname = $pathinfo['filename'];
579 elseif ($shortname !== $pathinfo['filename'])
580 $err[] = sprintf("Invalid dirname: %s (should be %s.)", $filename, $shortname);
584 * Check that the only files we have inside /.rockbox/backdrops/
585 * and subdirs of /.rockbox/wps/ are .bmp files
587 if (strtolower($pathinfo['extension']) != 'bmp' &&
588 ($pathinfo['dirname'] == '.rockbox/backdrops' ||
// Files inside .rockbox/backdrops
589 ($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)
592 $err[] = sprintf("Non-bmp file not allowed here: %s", $filename);
595 /* Check for paths that are too deep */
596 if (count(explode('/', $pathinfo['dirname'])) > 3) {
597 $err[] = sprintf("Path too deep: %s", $filename);
600 /* Check for unwanted junk files */
601 switch(strtolower($pathinfo['basename'])) {
606 $err[] = sprintf("Unwanted file: %s", $filename);
610 /* Now we check all the things that could be wrong */
611 $this->validatecfg($cfg, $files);
613 if ($themezipupload['size'] > config
::maxzippedsize
)
614 $err[] = sprintf("Theme zip too large at %s (max size is %s)", $themezipupload['size'], config
::maxzippedsize
);
615 if ($totalsize > config
::maxthemesize
)
616 $err[] = sprintf("Unzipped theme size too large at %s (max size is %s)", $totalsize, config
::maxthemesize
);
617 if (count($files) > config
::maxfiles
)
618 $err[] = sprintf("Too many files+dirs in theme (%d). Maximum is %d.", count($files), config
::maxfiles
);
620 if (count($wpsfound) > 1)
621 $err[] = sprintf("More than one .wps found (%s).", implode(', ', $wpsfound));
622 elseif (count($wpsfound) == 0)
623 $err[] = "No .wps files found.";
625 if (count($rwpsfound) > 1)
626 $err[] = sprintf("More than one .rwps found (%s).", implode(', ', $rwpsfound));
630 public function validatesshot($upload, $mainlcd) {
632 $size = getimagesize($upload['tmp_name']);
633 $dimensions = sprintf("%dx%d", $size[0], $size[1]);
634 if ($size === false) {
635 $err[] = sprintf("Couldn't open screenshot %s", $upload['name']);
638 if ($dimensions != $mainlcd) {
639 $err[] = sprintf("Wrong resolution of %s. Should be %s (is %s).", $upload['name'], $mainlcd, $dimensions);
641 if ($size[2] != IMAGETYPE_PNG
) {
642 $err[] = "Screenshots must be of type PNG.";