86b88b40b975b4a0ccf3deaae10c2cb175bccf5d
[rockboxthemes.git] / private / themesite.class.php
blob86b88b40b975b4a0ccf3deaae10c2cb175bccf5d
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_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']) : '',
45 db::quote($message)
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);
57 $ret = array();
58 while ($target = $targets->next()) {
59 $ret[] = $target;
61 return $ret;
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);
71 $return = array();
72 while ($theme = $themes->next()) {
73 $starttime = microtime(true);
74 $zipfile = sprintf("%s/%s/%s/%s",
75 config::datadir,
76 $theme['mainlcd'],
77 $theme['shortname'],
78 $theme['zipfile']
80 $result = $this->checkwps($zipfile, $theme['mainlcd'], $theme['remotelcd']);
82 /*
83 * Store the results and check if at least one check passed (for
84 * the summary)
86 $passany = false;
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
93 * retrieval?
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')",
97 $theme['RowID'],
98 db::quote($version_type),
99 db::quote($result['version']),
100 db::quote($target),
101 db::quote($result['pass'] ? 1 : 0)
103 $this->db->query($sql);
106 $return[] = array(
107 'theme' => $theme,
108 'result' => $result,
109 'summary' => array('theme' => $theme['name'], 'pass' => $passany, 'duration' => microtime(true) - $starttime)
112 return $return;
115 public function adminlogin($user, $pass) {
116 $sql = sprintf("SELECT COUNT(*) as count FROM admins WHERE name='%s' AND pass='%s'",
117 db::quote($user),
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) {
125 $ret = array();
126 switch($approved) {
127 case 'any':
128 $approved_clause = "";
129 break;
130 case 'hidden':
131 $approved_clause = " AND th.approved = 0 ";
132 break;
133 case 'approved':
134 default:
135 $approved_clause = " AND th.approved = 1 ";
136 break;
138 if ($onlyverified == true) {
139 $verified = " AND th.emailverification = 1 ";
141 else {
142 $verified = "";
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",
145 $verified,
146 $approved_clause,
147 db::quote($target),
148 $orderby
150 $themes = $this->db->query($sql);
151 while ($theme = $themes->next()) {
152 $ret[] = $theme;
154 return $ret;
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'",
166 db::quote($name),
167 db::quote($mainlcd)
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",
176 $themeid,
177 $status_text[$oldstatus],
178 $status_text[$newstatus],
179 $reason
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'",
186 db::quote($themeid)
189 /* Delete the files */
190 foreach(array($this->themedir_public, $this->themedir_private) as $root) {
191 $dir = sprintf("%s/%s/%s",
192 $root,
193 $theme['mainlcd'],
194 $theme['shortname']
196 if (file_exists($dir)) {
197 foreach(glob(sprintf("%s/*", $dir)) as $file) {
198 unlink($file);
200 rmdir($dir);
204 else {
205 $sql = sprintf("UPDATE themes SET approved='%d', reason='%s' WHERE RowID='%d'",
206 db::quote($newstatus),
207 db::quote($reason),
208 db::quote($themeid)
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) {
213 $temp = $to;
214 $to = $from;
215 $from = $temp;
217 rename($from, $to);
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);
225 $msg = <<<END
226 Your theme {$theme['name']} was removed from the Rockbox theme site. The
227 following reason should explain why:
229 ----------
230 {$reason}
231 ----------
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.
235 END;
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)
246 VALUES
247 ('%s', '%s', '%s', '%s', '%s', %s)",
248 db::quote($shortname),
249 db::quote($fullname),
250 db::quote($mainlcd),
251 db::quote($pic),
252 db::quote($depth),
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)) {
260 mkdir($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) {
272 $err = array();
273 return $err;
276 public function prepareverification($id, $email, $author) {
277 $token = md5(uniqid());
278 $sql = sprintf("UPDATE themes SET emailverification='%s' WHERE RowID='%s'",
279 db::quote($token),
280 db::quote($id)
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 */
285 $msg = <<<END
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.
290 $url
292 Thank for your contributions
294 The Rockbox Theme Site team.
295 END;
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'",
304 db::quote($token)
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) {
311 $err = array();
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",
317 $root,
318 $mainlcd,
319 $shortname
323 /* This is the actual destination dir */
324 $destdir = sprintf("%s/%s/%s",
325 config::defaultstatus == 1 ? $this->themedir_public : $this->themedir_private,
326 $mainlcd,
327 $shortname
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'])) {
339 continue;
341 $dest = sprintf("%s/%s",
342 $destdir,
343 $file['name']
346 if (!@move_uploaded_file($file['tmp_name'], $dest)) {
347 /* Upload went wrong, clean up */
348 foreach ($movedfiles as $movedfile) {
349 unlink($movedfile);
351 rmdir($destdir);
352 $err[] = sprintf("Couldn't move %s.", $file['name'], $dest);
353 return $err;
355 else {
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,
361 db::quote($author),
362 db::quote($email),
363 db::quote($name),
364 db::quote($mainlcd),
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));
378 return $id;
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'],'.')
394 return $pathinfo;
398 * Convenience function called from several locations
400 private function getzipentrycontents($zip, $ze) {
401 $ret = "";
402 zip_entry_open($zip, $ze);
403 while($read = zip_entry_read($ze)) {
404 $ret .= $read;
406 zip_entry_close($ze);
407 return $ret;
411 * xxx: I don't know what kind of validation is wanted for cfg files
413 public function validatecfg($cfg, $files) {
414 $conf = array();
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) {
419 extract($matches);
420 switch($name) {
421 default:
422 break;
428 public function lcd2targets($lcd) {
429 $ret = array();
430 $sql = sprintf("SELECT shortname FROM targets WHERE mainlcd='%s' OR remotelcd='%s'",
431 db::quote($lcd),
432 db::quote($lcd)
434 $targets = $this->db->query($sql);
435 while ($target = $targets->next()) {
436 $ret[] = $target['shortname'];
438 return $ret;
442 * Check a WPS against two revisions: current and the latest release
444 public function checkwps($zipfile, $mainlcd, $remotelcd) {
445 $return = array();
447 /* First, create a temporary dir */
448 $tmpdir = sprintf("%s/temp-%s", preconfig::privpath, md5(uniqid()));
449 mkdir($tmpdir);
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 */
456 $olddir = getcwd();
457 chdir($tmpdir);
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) {
468 $result = array();
469 $checkwps = sprintf("%s/checkwps/%s/checkwps.%s",
470 '..', /* We'll be in a subdir of the private dir */
471 $version,
472 $shortname
474 $result['version'] = trim(file_get_contents(sprintf('%s/checkwps/%s/VERSION',
475 '..',
476 $version,
477 $shortname
478 )));
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;
489 /* chdir back */
490 chdir($olddir);
492 /* Remove the tempdir */
493 $this->rmdir_recursive($tmpdir);
494 return $return;
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);
502 if (is_dir($path)) {
503 $this->rmdir_recursive($path);
505 else {
506 unlink($path);
509 $dir->close();
510 rmdir($dirname);
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) {
529 $err = array();
530 $zip = zip_open($themezipupload['tmp_name']);
531 $totalsize = 0;
532 $files = array();
533 $wpsfound = array();
534 $rwpsfound = array();
535 $shortname = '';
536 $cfg = '';
538 if (is_int($zip)) {
539 $err[] = sprintf("Couldn't open zipfile %s", $themezipupload['name']);
540 return $err;
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'])) {
560 case 'cfg':
561 /* Save the contents for later checking */
562 $cfg = $this->getzipentrycontents($zip, $ze);
563 case 'wps':
564 case 'rwps':
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']);
569 break;
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'])) {
602 case "thumbs.db":
603 case "desktop.ini":
604 case ".ds_store":
605 case ".directory":
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));
627 return $err;
630 public function validatesshot($upload, $mainlcd) {
631 $err = array();
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']);
637 else {
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.";
645 return $err;