hand merge of speed tweaks

This commit is contained in:
Shish 2012-01-31 13:20:43 +00:00
commit aed5e1a30e
21 changed files with 254 additions and 220 deletions

View File

@ -915,7 +915,9 @@ class Artists implements Extension {
$artistID $artistID
)); ));
for ($i = 0 ; $i < count($result) ; $i++) $num = count($result);
for ($i = 0 ; $i < $num ; $i++)
{ {
$result[$i]["name"] = stripslashes($result[$i]["name"]); $result[$i]["name"] = stripslashes($result[$i]["name"]);
} }
@ -932,7 +934,9 @@ class Artists implements Extension {
$artistID $artistID
)); ));
for ($i = 0 ; $i < count($result) ; $i++) $num = count($result);
for ($i = 0 ; $i < $num ; $i++)
{ {
$result[$i]["url"] = stripslashes($result[$i]["url"]); $result[$i]["url"] = stripslashes($result[$i]["url"]);
} }
@ -1049,7 +1053,9 @@ class Artists implements Extension {
, $artistsPerPage , $artistsPerPage
)); ));
for ($i = 0 ; $i < count($listing) ; $i++) $number_of_listings = count($listing);
for ($i = 0 ; $i < $number_of_listings ; $i++)
{ {
$listing[$i]["name"] = stripslashes($listing[$i]["name"]); $listing[$i]["name"] = stripslashes($listing[$i]["name"]);
$listing[$i]["user_name"] = stripslashes($listing[$i]["user_name"]); $listing[$i]["user_name"] = stripslashes($listing[$i]["user_name"]);

View File

@ -55,7 +55,8 @@ class BlotterTheme extends Themelet {
// Now, time for entries list. // Now, time for entries list.
$table_rows = ""; $table_rows = "";
for ($i = 0 ; $i < count($entries) ; $i++) $num_entries = count($entries);
for ($i = 0 ; $i < $num_entries ; $i++)
{ {
/** /**
* Add table rows * Add table rows
@ -106,7 +107,8 @@ class BlotterTheme extends Themelet {
$html .= "<html><head><title>Blotter</title></head> $html .= "<html><head><title>Blotter</title></head>
<body><pre>"; <body><pre>";
for ($i = 0 ; $i < count($entries) ; $i++) $num_entries = count($entries);
for ($i = 0 ; $i < $num_entries ; $i++)
{ {
/** /**
* Blotter entries * Blotter entries
@ -156,7 +158,8 @@ $(document).ready(function() {
}); });
//--></script>"; //--></script>";
$entries_list = ""; $entries_list = "";
for ($i = 0 ; $i < count($entries) ; $i++) $num_entries = count($entries);
for ($i = 0 ; $i < $num_entries ; $i++)
{ {
/** /**
* Blotter entries * Blotter entries
@ -175,8 +178,8 @@ $(document).ready(function() {
$in_text = ""; $in_text = "";
$pos_break = ""; $pos_break = "";
$pos_align = "text-align: right; position: absolute; right: 0px;"; $pos_align = "text-align: right; position: absolute; right: 0px;";
if($position == "left") { $pos_break = "<br />"; $pos_align = ""; } if($position === "left") { $pos_break = "<br />"; $pos_align = ""; }
if(count($entries) == 0) { $out_text = "No blotter entries yet."; $in_text = "Empty.";} if(count($entries) === 0) { $out_text = "No blotter entries yet."; $in_text = "Empty.";}
else { $clean_date = date("m/d/y",strtotime($entries[0]['entry_date'])); else { $clean_date = date("m/d/y",strtotime($entries[0]['entry_date']));
$out_text = "Blotter updated: {$clean_date}"; $out_text = "Blotter updated: {$clean_date}";
$in_text = "<ul>$entries_list</ul>"; $in_text = "<ul>$entries_list</ul>";

View File

@ -56,7 +56,8 @@ class FlashFileHandler extends DataHandlerExtension {
private function str_to_binarray($string) { private function str_to_binarray($string) {
$binary = array(); $binary = array();
for($j=0; $j<strlen($string); $j++) { $length = strlen($string);
for($j=0; $j<$length; $j++) {
$c = ord($string[$j]); $c = ord($string[$j]);
for($i=7; $i>=0; $i--) { for($i=7; $i>=0; $i--) {
$binary[] = ($c >> $i) & 0x01; $binary[] = ($c >> $i) & 0x01;

View File

@ -67,7 +67,8 @@ class Home extends SimpleExtension {
$num_comma = number_format($total); $num_comma = number_format($total);
$counter_text = ""; $counter_text = "";
for($n=0; $n<strlen($strtotal); $n++) { $length = strlen($strtotal);
for($n=0; $n<$length; $n++) {
$cur = $strtotal[$n]; $cur = $strtotal[$n];
$counter_text .= " <img alt='$cur' src='$base_href/ext/home/counters/$counter_dir/$cur.gif' /> "; $counter_text .= " <img alt='$cur' src='$base_href/ext/home/counters/$counter_dir/$cur.gif' /> ";
} }

View File

@ -114,7 +114,8 @@ class Ratings implements Extension {
if(preg_match("/^rating=([sqeu]+)$/", $event->term, $matches)) { if(preg_match("/^rating=([sqeu]+)$/", $event->term, $matches)) {
$sqes = $matches[1]; $sqes = $matches[1];
$arr = array(); $arr = array();
for($i=0; $i<strlen($sqes); $i++) { $length = strlen($sqes);
for($i=0; $i<$length; $i++) {
$arr[] = "'" . $sqes[$i] . "'"; $arr[] = "'" . $sqes[$i] . "'";
} }
$set = join(', ', $arr); $set = join(', ', $arr);
@ -157,7 +158,8 @@ class Ratings implements Extension {
public static function privs_to_sql($sqes) { public static function privs_to_sql($sqes) {
$arr = array(); $arr = array();
for($i=0; $i<strlen($sqes); $i++) { $length = strlen($sqes);
for($i=0; $i<$length; $i++) {
$arr[] = "'" . $sqes[$i] . "'"; $arr[] = "'" . $sqes[$i] . "'";
} }
$set = join(', ', $arr); $set = join(', ', $arr);

View File

@ -56,7 +56,7 @@ class DBEngine {
} }
public function create_table_sql($name, $data) { public function create_table_sql($name, $data) {
return "CREATE TABLE $name ($data)"; return 'CREATE TABLE '.$name.' ('.$data.')';
} }
} }
class MySQL extends DBEngine { class MySQL extends DBEngine {
@ -82,7 +82,7 @@ class MySQL extends DBEngine {
public function create_table_sql($name, $data) { public function create_table_sql($name, $data) {
$data = $this->scoreql_to_sql($data); $data = $this->scoreql_to_sql($data);
$ctes = "ENGINE=InnoDB DEFAULT CHARSET='utf8'"; $ctes = "ENGINE=InnoDB DEFAULT CHARSET='utf8'";
return "CREATE TABLE $name ($data) $ctes"; return 'CREATE TABLE '.$name.' ('.$data.') '.$ctes;
} }
} }
class PostgreSQL extends DBEngine { class PostgreSQL extends DBEngine {
@ -107,7 +107,7 @@ class PostgreSQL extends DBEngine {
public function create_table_sql($name, $data) { public function create_table_sql($name, $data) {
$data = $this->scoreql_to_sql($data); $data = $this->scoreql_to_sql($data);
return "CREATE TABLE $name ($data)"; return 'CREATE TABLE '.$name.' ('.$data.')';
} }
} }
@ -155,14 +155,14 @@ class SQLite extends DBEngine {
$matches = array(); $matches = array();
if(preg_match("/INDEX\s*\((.*)\)/", $bit, $matches)) { if(preg_match("/INDEX\s*\((.*)\)/", $bit, $matches)) {
$col = $matches[1]; $col = $matches[1];
$extras .= "CREATE INDEX {$name}_{$col} on $name($col);"; $extras .= 'CREATE INDEX '.$name.'_'.$col.' on '.$name($col).';';
} }
else { else {
$cols[] = $bit; $cols[] = $bit;
} }
} }
$cols_redone = implode(", ", $cols); $cols_redone = implode(", ", $cols);
return "CREATE TABLE $name ($cols_redone); $extras"; return 'CREATE TABLE '.$name.' ('.$cols_redone.'); '.$extras;
} }
} }
// }}} // }}}
@ -296,17 +296,17 @@ class Database {
)); ));
$db_proto = $this->db->getAttribute(PDO::ATTR_DRIVER_NAME); $db_proto = $this->db->getAttribute(PDO::ATTR_DRIVER_NAME);
if($db_proto == "mysql") { if($db_proto === "mysql") {
$this->engine = new MySQL(); $this->engine = new MySQL();
} }
else if($db_proto == "pgsql") { else if($db_proto === "pgsql") {
$this->engine = new PostgreSQL(); $this->engine = new PostgreSQL();
} }
else if($db_proto == "sqlite") { else if($db_proto === "sqlite") {
$this->engine = new SQLite(); $this->engine = new SQLite();
} }
else { else {
die("Unknown PDO driver: $db_proto"); die('Unknown PDO driver: '.$db_proto);
} }
$matches = array(); $matches = array();
@ -335,10 +335,10 @@ class Database {
if (!array_key_exists(0, $args)) { if (!array_key_exists(0, $args)) {
foreach($args as $name=>$value) { foreach($args as $name=>$value) {
if(is_numeric($value)) { if(is_numeric($value)) {
$stmt->bindValue(":$name", $value, PDO::PARAM_INT); $stmt->bindValue(':'.$name, $value, PDO::PARAM_INT);
} }
else { else {
$stmt->bindValue(":$name", $value, PDO::PARAM_STR); $stmt->bindValue(':'.$name, $value, PDO::PARAM_STR);
} }
} }
$stmt->execute(); $stmt->execute();
@ -349,8 +349,8 @@ class Database {
return $stmt; return $stmt;
} }
catch(PDOException $pdoe) { catch(PDOException $pdoe) {
print "Message: ".$pdoe->getMessage(); print 'Message: '.$pdoe->getMessage();
print "<p>Error: $query"; print '<p>Error: '.$query;
exit; exit;
} }
} }

View File

@ -68,7 +68,7 @@ class PageRequestEvent extends Event {
} }
public function count_args() { public function count_args() {
return $this->arg_count - $this->part_count; return (int)($this->arg_count - $this->part_count);
} }
/* /*
@ -76,20 +76,20 @@ class PageRequestEvent extends Event {
*/ */
public function get_search_terms() { public function get_search_terms() {
$search_terms = array(); $search_terms = array();
if($this->count_args() == 2) { if($this->count_args() === 2) {
$search_terms = explode(' ', $this->get_arg(0)); $search_terms = explode(' ', $this->get_arg(0));
} }
return $search_terms; return $search_terms;
} }
public function get_page_number() { public function get_page_number() {
$page_number = 1; $page_number = 1;
if($this->count_args() == 1) { if($this->count_args() === 1) {
$page_number = int_escape($this->get_arg(0)); $page_number = int_escape($this->get_arg(0));
} }
else if($this->count_args() == 2) { else if($this->count_args() === 2) {
$page_number = int_escape($this->get_arg(1)); $page_number = int_escape($this->get_arg(1));
} }
if($page_number == 0) $page_number = 1; // invalid -> 0 if($page_number === 0) $page_number = 1; // invalid -> 0
return $page_number; return $page_number;
} }
public function get_page_size() { public function get_page_size() {

View File

@ -196,12 +196,12 @@ class Image {
} }
if(count($tags) == 0) { if(count($tags) == 0) {
$row = $database->get_row("SELECT images.* FROM images WHERE images.id $gtlt {$this->id} ORDER BY images.id $dir LIMIT 1"); $row = $database->get_row('SELECT images.* FROM images WHERE images.id '.$gtlt.' '.$this->id.' ORDER BY images.id '.$dir.' LIMIT 1');
} }
else { else {
$tags[] = "id$gtlt{$this->id}"; $tags[] = 'id'. $gtlt . $this->id;
$querylet = Image::build_search_querylet($tags); $querylet = Image::build_search_querylet($tags);
$querylet->append_sql(" ORDER BY images.id $dir LIMIT 1"); $querylet->append_sql(' ORDER BY images.id '.$dir.' LIMIT 1');
$row = $database->get_row($querylet->sql, $querylet->variables); $row = $database->get_row($querylet->sql, $querylet->variables);
} }
@ -251,8 +251,11 @@ class Image {
*/ */
public function get_image_link() { public function get_image_link() {
global $config; global $config;
if(strlen($config->get_string('image_ilink')) > 0) {
return $this->parse_link_template($config->get_string('image_ilink')); $image_ilink = $config->get_string('image_ilink'); // store a copy for speed.
if( !empty($image_ilink) ) { /* empty is faster than strlen */
return $this->parse_link_template($image_ilink);
} }
else if($config->get_bool('nice_urls', false)) { else if($config->get_bool('nice_urls', false)) {
return $this->parse_link_template(make_link('_images/$hash/$id - $tags.$ext')); return $this->parse_link_template(make_link('_images/$hash/$id - $tags.$ext'));
@ -280,8 +283,11 @@ class Image {
*/ */
public function get_thumb_link() { public function get_thumb_link() {
global $config; global $config;
if(strlen($config->get_string('image_tlink')) > 0) {
return $this->parse_link_template($config->get_string('image_tlink')); $image_tlink = $config->get_string('image_tlink'); // store a copy for speed.
if( !empty($image_tlink) ) { /* empty is faster than strlen */
return $this->parse_link_template($image_tlink);
} }
else if($config->get_bool('nice_urls', false)) { else if($config->get_bool('nice_urls', false)) {
return $this->parse_link_template(make_link('_thumbs/$hash/thumb.jpg')); return $this->parse_link_template(make_link('_thumbs/$hash/thumb.jpg'));
@ -338,8 +344,8 @@ class Image {
*/ */
public function get_mime_type() { public function get_mime_type() {
$type = strtolower($this->ext); $type = strtolower($this->ext);
if($type == "jpg") $type = "jpeg"; if($type === "jpg") $type = "jpeg";
return "image/$type"; return 'image/'.$type;
} }
/** /**
@ -379,7 +385,7 @@ class Image {
public function set_locked($tf) { public function set_locked($tf) {
global $database; global $database;
$ln = $tf ? "Y" : "N"; $ln = $tf ? "Y" : "N";
$sln = $database->engine->scoreql_to_sql("SCORE_BOOL_$ln"); $sln = $database->engine->scoreql_to_sql('SCORE_BOOL_'.$ln);
$sln = str_replace("'", "", $sln); $sln = str_replace("'", "", $sln);
$sln = str_replace('"', "", $sln); $sln = str_replace('"', "", $sln);
if($sln != $this->locked) { if($sln != $this->locked) {
@ -458,7 +464,7 @@ class Image {
global $database; global $database;
$this->delete_tags_from_image(); $this->delete_tags_from_image();
$database->execute("DELETE FROM images WHERE id=:id", array("id"=>$this->id)); $database->execute("DELETE FROM images WHERE id=:id", array("id"=>$this->id));
log_info("core-image", "Deleted Image #{$this->id} ({$this->hash})"); log_info("core-image", 'Deleted Image #'.$this->id.' ('.$this->hash.')');
unlink($this->get_image_filename()); unlink($this->get_image_filename());
unlink($this->get_thumb_filename()); unlink($this->get_thumb_filename());
@ -469,7 +475,7 @@ class Image {
* It DOES NOT remove anything from the database. * It DOES NOT remove anything from the database.
*/ */
public function remove_image_only() { public function remove_image_only() {
log_info("core-image", "Removed Image File ({$this->hash})"); log_info("core-image", 'Removed Image File ('.$this->hash.')');
@unlink($this->get_image_filename()); @unlink($this->get_image_filename());
@unlink($this->get_thumb_filename()); @unlink($this->get_thumb_filename());
} }
@ -550,7 +556,7 @@ class Image {
private static function build_search_querylet($terms) { private static function build_search_querylet($terms) {
assert(is_array($terms)); assert(is_array($terms));
global $database; global $database;
if($database->engine->name == "mysql") if($database->engine->name === "mysql")
return Image::build_ugly_search_querylet($terms); return Image::build_ugly_search_querylet($terms);
else else
return Image::build_accurate_search_querylet($terms); return Image::build_accurate_search_querylet($terms);
@ -593,7 +599,7 @@ class Image {
// various types of querylet // various types of querylet
foreach($terms as $term) { foreach($terms as $term) {
$positive = true; $positive = true;
if(strlen($term) > 0 && $term[0] == '-') { if(is_string($term) && !empty($term) && ($term[0] == '-')) {
$positive = false; $positive = false;
$term = substr($term, 1); $term = substr($term, 1);
} }
@ -641,7 +647,7 @@ class Image {
if(count($tag_querylets) == 0) { if(count($tag_querylets) == 0) {
$query = new Querylet("SELECT images.* FROM images "); $query = new Querylet("SELECT images.* FROM images ");
if(strlen($img_search->sql) > 0) { if(!empty($img_search->sql)) {
$query->append_sql(" WHERE "); $query->append_sql(" WHERE ");
$query->append($img_search); $query->append($img_search);
} }
@ -658,7 +664,7 @@ class Image {
) )
"), array("tag"=>$tag_querylets[0]->tag)); "), array("tag"=>$tag_querylets[0]->tag));
if(strlen($img_search->sql) > 0) { if(!empty($img_search->sql)) {
$query->append_sql(" AND "); $query->append_sql(" AND ");
$query->append($img_search); $query->append($img_search);
} }
@ -760,7 +766,7 @@ class Image {
// turn each term into a specific type of querylet // turn each term into a specific type of querylet
foreach($terms as $term) { foreach($terms as $term) {
$negative = false; $negative = false;
if((strlen($term) > 0) && ($term[0] == '-')) { if( !empty($term) && ($term[0] == '-')) {
$negative = true; $negative = true;
$term = substr($term, 1); $term = substr($term, 1);
} }
@ -789,11 +795,13 @@ class Image {
foreach($tag_querylets as $tq) { foreach($tag_querylets as $tq) {
global $tag_n; global $tag_n;
$sign = $tq->positive ? "+" : "-"; $sign = $tq->positive ? "+" : "-";
$sql .= " $sign (tag LIKE :tag$tag_n)"; //$sql .= " $sign (tag LIKE :tag$tag_n)";
$terms["tag$tag_n"] = $tq->tag; $sql .= ' '.$sign.' (tag LIKE :tag'.$tag_n.')';
//$terms["tag$tag_n"] = $tq->tag;
$terms['tag'.$tag_n] = $tq->tag;
$tag_n++; $tag_n++;
if($sign == "+") $positive_tag_count++; if($sign === "+") $positive_tag_count++;
else $negative_tag_count++; else $negative_tag_count++;
} }
$tag_search = new Querylet($sql, $terms); $tag_search = new Querylet($sql, $terms);
@ -815,14 +823,14 @@ class Image {
if($positive_tag_count + $negative_tag_count == 0) { if($positive_tag_count + $negative_tag_count == 0) {
$query = new Querylet("SELECT images.*,UNIX_TIMESTAMP(posted) AS posted_timestamp FROM images "); $query = new Querylet("SELECT images.*,UNIX_TIMESTAMP(posted) AS posted_timestamp FROM images ");
if(strlen($img_search->sql) > 0) { if(!empty($img_search->sql)) {
$query->append_sql(" WHERE "); $query->append_sql(" WHERE ");
$query->append($img_search); $query->append($img_search);
} }
} }
// one positive tag (a common case), do an optimised search // one positive tag (a common case), do an optimised search
else if($positive_tag_count == 1 && $negative_tag_count == 0) { else if($positive_tag_count === 1 && $negative_tag_count === 0) {
$query = new Querylet( $query = new Querylet(
// MySQL is braindead, and does a full table scan on images, running the subquery once for each row -_- // MySQL is braindead, and does a full table scan on images, running the subquery once for each row -_-
// "{$this->get_images} WHERE images.id IN (SELECT image_id FROM tags WHERE tag LIKE ?) ", // "{$this->get_images} WHERE images.id IN (SELECT image_id FROM tags WHERE tag LIKE ?) ",
@ -836,7 +844,7 @@ class Image {
", ",
$tag_search->variables); $tag_search->variables);
if(strlen($img_search->sql) > 0) { if(!empty($img_search->sql)) {
$query->append_sql(" AND "); $query->append_sql(" AND ");
$query->append($img_search); $query->append($img_search);
} }
@ -858,24 +866,24 @@ class Image {
if($tags_ok) { if($tags_ok) {
$tag_id_list = join(', ', $tag_id_array); $tag_id_list = join(', ', $tag_id_array);
$subquery = new Querylet(" $subquery = new Querylet('
SELECT images.*, SUM({$tag_search->sql}) AS score SELECT images.*, SUM('.$tag_search->sql.') AS score
FROM images FROM images
LEFT JOIN image_tags ON image_tags.image_id = images.id LEFT JOIN image_tags ON image_tags.image_id = images.id
JOIN tags ON image_tags.tag_id = tags.id JOIN tags ON image_tags.tag_id = tags.id
WHERE tags.id IN ({$tag_id_list}) WHERE tags.id IN ('.$tag_id_list.')
GROUP BY images.id GROUP BY images.id
HAVING score = :score", HAVING score = :score',
array_merge( array_merge(
$tag_search->variables, $tag_search->variables,
array("score"=>$positive_tag_count) array("score"=>$positive_tag_count)
) )
); );
$query = new Querylet(" $query = new Querylet('
SELECT *, UNIX_TIMESTAMP(posted) AS posted_timestamp SELECT *, UNIX_TIMESTAMP(posted) AS posted_timestamp
FROM ({$subquery->sql}) AS images ", $subquery->variables); FROM ('.$subquery->sql.') AS images ', $subquery->variables);
if(strlen($img_search->sql) > 0) { if(!empty($img_search->sql)) {
$query->append_sql(" WHERE "); $query->append_sql(" WHERE ");
$query->append($img_search); $query->append($img_search);
} }
@ -921,15 +929,15 @@ class Tag {
if(is_string($tags)) { if(is_string($tags)) {
$tags = explode(' ', $tags); $tags = explode(' ', $tags);
} }
else if(is_array($tags)) { //else if(is_array($tags)) {
// do nothing // do nothing
} //}
$tags = array_map("trim", $tags); $tags = array_map("trim", $tags);
$tag_array = array(); $tag_array = array();
foreach($tags as $tag) { foreach($tags as $tag) {
if(is_string($tag) && strlen($tag) > 0) { if(is_string($tag) && !empty($tag)) {
$tag_array[] = $tag; $tag_array[] = $tag;
} }
} }
@ -946,13 +954,13 @@ class Tag {
public static function implode($tags) { public static function implode($tags) {
assert(is_string($tags) || is_array($tags)); assert(is_string($tags) || is_array($tags));
if(is_string($tags)) { if(is_array($tags)) {
// do nothing
}
else if(is_array($tags)) {
sort($tags); sort($tags);
$tags = implode(' ', $tags); $tags = implode(' ', $tags);
} }
//else if(is_string($tags)) {
// do nothing
//}
return $tags; return $tags;
} }

View File

@ -225,8 +225,8 @@ class Page {
print $this->data; print $this->data;
break; break;
case "redirect": case "redirect":
header("Location: {$this->redirect}"); header('Location: '.$this->redirect);
print "You should be redirected to <a href='{$this->redirect}'>{$this->redirect}</a>"; print 'You should be redirected to <a href="'.$this->redirect.'">'.$this->redirect.'</a>';
break; break;
default: default:
print "Invalid page mode"; print "Invalid page mode";
@ -242,22 +242,22 @@ class Page {
// caching failed, add all files to html_headers. // caching failed, add all files to html_headers.
foreach(glob("lib/*.css") as $css) { foreach(glob("lib/*.css") as $css) {
$this->add_html_header("<link rel='stylesheet' href='$data_href/$css' type='text/css'>"); $this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$css.'" type="text/css">');
} }
$css_files = glob("ext/*/style.css"); $css_files = glob("ext/*/style.css");
if($css_files) { if($css_files) {
foreach($css_files as $css_file) { foreach($css_files as $css_file) {
$this->add_html_header("<link rel='stylesheet' href='$data_href/$css_file' type='text/css'>"); $this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$css_file.'" type="text/css">');
} }
} }
foreach(glob("lib/*.js") as $js) { foreach(glob("lib/*.js") as $js) {
$this->add_html_header("<script src='$data_href/$js' type='text/javascript'></script>"); $this->add_html_header('<script src="'.$data_href.'/'.$js.'" type="text/javascript"></script>');
} }
$js_files = glob("ext/*/script.js"); $js_files = glob("ext/*/script.js");
if($js_files) { if($js_files) {
foreach($js_files as $js_file) { foreach($js_files as $js_file) {
$this->add_html_header("<script src='$data_href/$js_file' type='text/javascript'></script>"); $this->add_html_header('<script src="'.$data_href.'/'.$js_file.'" type="text/javascript"></script>');
} }
} }
} }
@ -358,16 +358,16 @@ class Page {
} }
} }
// tell the client where to get the css cache file // tell the client where to get the css cache file
$this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$cache_location.$md5sum.'.css'.'" type="text/css">'); $this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$cache_location.$md5sum.'.css" type="text/css">');
} else { } else {
// Caching of CSS disabled. // Caching of CSS disabled.
foreach(glob("lib/*.css") as $css) { foreach(glob("lib/*.css") as $css) {
$this->add_html_header("<link rel='stylesheet' href='$data_href/$css' type='text/css'>"); $this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$css.'" type="text/css">');
} }
$css_files = glob("ext/*/style.css"); $css_files = glob("ext/*/style.css");
if($css_files) { if($css_files) {
foreach($css_files as $css_file) { foreach($css_files as $css_file) {
$this->add_html_header("<link rel='stylesheet' href='$data_href/$css_file' type='text/css'>"); $this->add_html_header('<link rel="stylesheet" href="'.$data_href.'/'.$css_file.'" type="text/css">');
} }
} }
} }
@ -408,16 +408,16 @@ class Page {
} }
} }
// tell the client where to get the js cache file // tell the client where to get the js cache file
$this->add_html_header('<script src="'.$data_href.'/'.$cache_location.$md5sum.'.js'.'" type="text/javascript"></script>'); $this->add_html_header('<script src="'.$data_href.'/'.$cache_location.$md5sum.'.js" type="text/javascript"></script>');
} else { } else {
// Caching of Javascript disabled. // Caching of Javascript disabled.
foreach(glob("lib/*.js") as $js) { foreach(glob("lib/*.js") as $js) {
$this->add_html_header("<script src='$data_href/$js' type='text/javascript'></script>"); $this->add_html_header('<script src="'.$data_href.'/'.$js.'" type="text/javascript"></script>');
} }
$js_files = glob("ext/*/script.js"); $js_files = glob("ext/*/script.js");
if($js_files) { if($js_files) {
foreach($js_files as $js_file) { foreach($js_files as $js_file) {
$this->add_html_header("<script src='$data_href/$js_file' type='text/javascript'></script>"); $this->add_html_header('<script src="'.$data_href.'/'.$js_file.'" type="text/javascript"></script>');
} }
} }
} }

View File

@ -40,7 +40,7 @@ class User {
public static function by_session($name, $session) { public static function by_session($name, $session) {
global $config, $database; global $config, $database;
if($database->engine->name == "mysql") { if($database->engine->name === "mysql") {
$query = "SELECT * FROM users WHERE name = :name AND md5(concat(pass, :ip)) = :sess"; $query = "SELECT * FROM users WHERE name = :name AND md5(concat(pass, :ip)) = :sess";
} }
else { else {
@ -53,12 +53,12 @@ class User {
public static function by_id($id) { public static function by_id($id) {
assert(is_numeric($id)); assert(is_numeric($id));
global $database; global $database;
if($id == 1) { if($id === 1) {
$cached = $database->cache->get("user-id:$id"); $cached = $database->cache->get('user-id:'.$id);
if($cached) return new User($cached); if($cached) return new User($cached);
} }
$row = $database->get_row("SELECT * FROM users WHERE id = :id", array("id"=>$id)); $row = $database->get_row("SELECT * FROM users WHERE id = :id", array("id"=>$id));
if($id == 1) $database->cache->set("user-id:$id", $row, 300); if($id === 1) $database->cache->set('user-id:'.$id, $row, 300);
return is_null($row) ? null : new User($row); return is_null($row) ? null : new User($row);
} }
@ -98,7 +98,7 @@ class User {
*/ */
public function is_anonymous() { public function is_anonymous() {
global $config; global $config;
return ($this->id == $config->get_int('anon_id')); return ($this->id === $config->get_int('anon_id'));
} }
/** /**
@ -108,7 +108,7 @@ class User {
*/ */
public function is_logged_in() { public function is_logged_in() {
global $config; global $config;
return ($this->id != $config->get_int('anon_id')); return ($this->id !== $config->get_int('anon_id'));
} }
/** /**
@ -125,20 +125,20 @@ class User {
global $database; global $database;
$yn = $admin ? 'Y' : 'N'; $yn = $admin ? 'Y' : 'N';
$database->Execute("UPDATE users SET admin=:yn WHERE id=:id", array("yn"=>$yn, "id"=>$this->id)); $database->Execute("UPDATE users SET admin=:yn WHERE id=:id", array("yn"=>$yn, "id"=>$this->id));
log_info("core-user", "Made {$this->name} admin=$yn"); log_info("core-user", 'Made '.$this->name.' admin='.$yn);
} }
public function set_password($password) { public function set_password($password) {
global $database; global $database;
$hash = md5(strtolower($this->name) . $password); $hash = md5(strtolower($this->name) . $password);
$database->Execute("UPDATE users SET pass=:hash WHERE id=:id", array("hash"=>$hash, "id"=>$this->id)); $database->Execute("UPDATE users SET pass=:hash WHERE id=:id", array("hash"=>$hash, "id"=>$this->id));
log_info("core-user", "Set password for {$this->name}"); log_info("core-user", 'Set password for '.$this->name);
} }
public function set_email($address) { public function set_email($address) {
global $database; global $database;
$database->Execute("UPDATE users SET email=:email WHERE id=:id", array("email"=>$address, "id"=>$this->id)); $database->Execute("UPDATE users SET email=:email WHERE id=:id", array("email"=>$address, "id"=>$this->id));
log_info("core-user", "Set email for {$this->name}"); log_info("core-user", 'Set email for '.$this->name);
} }
/** /**
@ -148,7 +148,7 @@ class User {
public function get_avatar_html() { public function get_avatar_html() {
// FIXME: configurable // FIXME: configurable
global $config; global $config;
if($config->get_string("avatar_host") == "gravatar") { if($config->get_string("avatar_host") === "gravatar") {
if(!empty($this->email)) { if(!empty($this->email)) {
$hash = md5(strtolower($this->email)); $hash = md5(strtolower($this->email));
$s = $config->get_string("avatar_gravatar_size"); $s = $config->get_string("avatar_gravatar_size");
@ -180,7 +180,7 @@ class User {
public function get_auth_html() { public function get_auth_html() {
$at = $this->get_auth_token(); $at = $this->get_auth_token();
return "<input type='hidden' name='auth_token' value='$at'>"; return '<input type="hidden" name="auth_token" value="'.$at.'">';
} }
public function check_auth_token() { public function check_auth_token() {

View File

@ -21,6 +21,10 @@ function html_escape($input) {
* @retval int * @retval int
*/ */
function int_escape($input) { function int_escape($input) {
/*
Side note, Casting to an integer is FASTER than using intval.
http://hakre.wordpress.com/2010/05/13/php-casting-vs-intval/
*/
return (int)$input; return (int)$input;
} }
@ -56,13 +60,13 @@ function sql_escape($input) {
function bool_escape($input) { function bool_escape($input) {
$input = strtolower($input); $input = strtolower($input);
return ( return (
$input == "y" || $input === "y" ||
$input == "yes" || $input === "yes" ||
$input == "t" || $input === "t" ||
$input == "true" || $input === "true" ||
$input == "on" || $input === "on" ||
$input == 1 || $input === 1 ||
$input == true $input === true
); );
} }
@ -86,7 +90,7 @@ function parse_shorthand_int($limit) {
return (int)$limit; return (int)$limit;
} }
if(preg_match('/^([\d\.]+)([gmk])?b?$/i', "$limit", $m)) { if(preg_match('/^([\d\.]+)([gmk])?b?$/i', (string)$limit, $m)) {
$value = $m[1]; $value = $m[1];
if (isset($m[2])) { if (isset($m[2])) {
switch(strtolower($m[2])) { switch(strtolower($m[2])) {
@ -118,7 +122,7 @@ function to_shorthand_int($int) {
return sprintf("%.1fKB", $int / 1024); return sprintf("%.1fKB", $int / 1024);
} }
else { else {
return "$int"; return (string)$int;
} }
} }
@ -214,17 +218,17 @@ function make_link($page=null, $query=null) {
} }
if(is_null($query)) { if(is_null($query)) {
return str_replace("//", "/", "$base/$page"); return str_replace("//", "/", $base.'/'.$page );
} }
else { else {
if(strpos($base, "?")) { if(strpos($base, "?")) {
return "$base/$page&$query"; return $base .'/'. $page .'&'. $query;
} }
else if(strpos($query, "#") === 0) { else if(strpos($query, "#") === 0) {
return "$base/$page$query"; return $base .'/'. $page . $query;
} }
else { else {
return "$base/$page?$query"; return $base .'/'. $page .'?'. $query;
} }
} }
} }
@ -293,14 +297,14 @@ function make_http($link) {
function make_form($target, $method="POST", $multipart=False, $form_id="", $onsubmit="") { function make_form($target, $method="POST", $multipart=False, $form_id="", $onsubmit="") {
global $user; global $user;
$auth = $user->get_auth_html(); $auth = $user->get_auth_html();
$extra = empty($form_id) ? '' : " id='$form_id'"; $extra = empty($form_id) ? '' : 'id="'. $form_id .'"';
if($multipart) { if($multipart) {
$extra .= " enctype='multipart/form-data'"; $extra .= " enctype='multipart/form-data'";
} }
if($onsubmit) { if($onsubmit) {
$extra .= " onsubmit='$onsubmit'"; $extra .= ' onsubmit="'.$onsubmit.'"';
} }
return "<form action='$target' method='$method'$extra>$auth"; return '<form action="'.$target.'" method="'.$method.'" '.$extra.'>'.$auth;
} }
/** /**
@ -310,7 +314,7 @@ function make_form($target, $method="POST", $multipart=False, $form_id="", $onsu
function theme_file($filepath) { function theme_file($filepath) {
global $config; global $config;
$theme = $config->get_string("theme","default"); $theme = $config->get_string("theme","default");
return make_link("themes/$theme/$filepath"); return make_link('themes/'.$theme.'/'.$filepath);
} }
@ -412,7 +416,7 @@ function _count_execs($db, $sql, $inputarray) {
if((DEBUG_SQL === true) || (is_null(DEBUG_SQL) && @$_GET['DEBUG_SQL'])) { if((DEBUG_SQL === true) || (is_null(DEBUG_SQL) && @$_GET['DEBUG_SQL'])) {
$fp = @fopen("data/sql.log", "a"); $fp = @fopen("data/sql.log", "a");
if($fp) { if($fp) {
if(is_array($inputarray)) { if(isset($inputarray) && is_array($inputarray)) {
fwrite($fp, preg_replace('/\s+/msi', ' ', $sql)." -- ".join(", ", $inputarray)."\n"); fwrite($fp, preg_replace('/\s+/msi', ' ', $sql)." -- ".join(", ", $inputarray)."\n");
} }
else { else {
@ -443,12 +447,12 @@ function _count_execs($db, $sql, $inputarray) {
*/ */
function get_theme_object(Extension $class, $fatal=true) { function get_theme_object(Extension $class, $fatal=true) {
$base = get_class($class); $base = get_class($class);
if(class_exists("Custom{$base}Theme")) { if(class_exists('Custom'.$base.'Theme')) {
$class = "Custom{$base}Theme"; $class = 'Custom'.$base.'Theme';
return new $class(); return new $class();
} }
elseif ($fatal || class_exists("{$base}Theme")) { elseif ($fatal || class_exists($base.'Theme')) {
$class = "{$base}Theme"; $class = $base.'Theme';
return new $class(); return new $class();
} else { } else {
return false; return false;
@ -552,14 +556,14 @@ function get_base_href() {
$possible_vars = array('SCRIPT_NAME', 'PHP_SELF', 'PATH_INFO', 'ORIG_PATH_INFO'); $possible_vars = array('SCRIPT_NAME', 'PHP_SELF', 'PATH_INFO', 'ORIG_PATH_INFO');
$ok_var = null; $ok_var = null;
foreach($possible_vars as $var) { foreach($possible_vars as $var) {
if(substr($_SERVER[$var], -4) == '.php') { if(substr($_SERVER[$var], -4) === '.php') {
$ok_var = $_SERVER[$var]; $ok_var = $_SERVER[$var];
break; break;
} }
} }
assert(!empty($ok_var)); assert(!empty($ok_var));
$dir = dirname($ok_var); $dir = dirname($ok_var);
if($dir == "/" || $dir == "\\") $dir = ""; if($dir === "/" || $dir === "\\") $dir = "";
return $dir; return $dir;
} }
@ -579,10 +583,10 @@ function warehouse_path($base, $hash, $create=true) {
$ab = substr($hash, 0, 2); $ab = substr($hash, 0, 2);
$cd = substr($hash, 2, 2); $cd = substr($hash, 2, 2);
if(WH_SPLITS == 2) { if(WH_SPLITS == 2) {
$pa = "$base/$ab/$cd/$hash"; $pa = $base.'/'.$ab.'/'.$cd.'/'.$hash;
} }
else { else {
$pa = "$base/$ab/$hash"; $pa = $base.'/'.$ab.'/'.$hash;
} }
if($create && !file_exists(dirname($pa))) mkdir(dirname($pa), 0755, true); if($create && !file_exists(dirname($pa))) mkdir(dirname($pa), 0755, true);
return $pa; return $pa;
@ -938,7 +942,8 @@ function _sanitise_environment() {
*/ */
function _decaret($str) { function _decaret($str) {
$out = ""; $out = "";
for($i=0; $i<strlen($str); $i++) { $length = strlen($str);
for($i=0; $i<$length; $i++) {
if($str[$i] == "^") { if($str[$i] == "^") {
$i++; $i++;
if($str[$i] == "^") $out .= "^"; if($str[$i] == "^") $out .= "^";
@ -985,7 +990,7 @@ function _get_page_request() {
global $config; global $config;
$args = _get_query_parts(); $args = _get_query_parts();
if(count($args) == 0 || strlen($args[0]) == 0) { if( empty($args) || strlen($args[0]) === 0) {
$args = explode('/', $config->get_string('front_page')); $args = explode('/', $config->get_string('front_page'));
} }
@ -1074,7 +1079,7 @@ function _start_cache() {
} }
else { else {
header("Content-type: text/html"); header("Content-type: text/html");
header("Last-Modified: $gmdate_mod"); header('Last-Modified: '.$gmdate_mod);
$zdata = @file_get_contents($_cache_filename); $zdata = @file_get_contents($_cache_filename);
if(CACHE_MEMCACHE) { if(CACHE_MEMCACHE) {
$_cache_memcache->set($_cache_hash, $zdata, 0, 600); $_cache_memcache->set($_cache_hash, $zdata, 0, 600);

View File

@ -114,7 +114,7 @@ class CommentList extends SimpleExtension {
public function onPageRequest(PageRequestEvent $event) { public function onPageRequest(PageRequestEvent $event) {
global $page, $user; global $page, $user;
if($event->page_matches("comment")) { if($event->page_matches("comment")) {
if($event->get_arg(0) == "add") { if($event->get_arg(0) === "add") {
if(isset($_POST['image_id']) && isset($_POST['comment'])) { if(isset($_POST['image_id']) && isset($_POST['comment'])) {
try { try {
$cpe = new CommentPostingEvent($_POST['image_id'], $user, $_POST['comment']); $cpe = new CommentPostingEvent($_POST['image_id'], $user, $_POST['comment']);
@ -127,10 +127,10 @@ class CommentList extends SimpleExtension {
} }
} }
} }
else if($event->get_arg(0) == "delete") { else if($event->get_arg(0) === "delete") {
if($user->is_admin()) { if($user->is_admin()) {
// FIXME: post, not args // FIXME: post, not args
if($event->count_args() == 3) { if($event->count_args() === 3) {
send_event(new CommentDeletionEvent($event->get_arg(1))); send_event(new CommentDeletionEvent($event->get_arg(1)));
$page->set_mode("redirect"); $page->set_mode("redirect");
if(!empty($_SERVER['HTTP_REFERER'])) { if(!empty($_SERVER['HTTP_REFERER'])) {
@ -145,7 +145,7 @@ class CommentList extends SimpleExtension {
$this->theme->display_permission_denied($page); $this->theme->display_permission_denied($page);
} }
} }
else if($event->get_arg(0) == "list") { else if($event->get_arg(0) === "list") {
$page_num = int_escape($event->get_arg(1)); $page_num = int_escape($event->get_arg(1));
$this->build_page($page_num); $this->build_page($page_num);
} }
@ -369,7 +369,7 @@ class CommentList extends SimpleExtension {
global $database; global $database;
// sqlite fails at intervals // sqlite fails at intervals
if($database->engine->name == "sqlite") return false; if($database->engine->name === "sqlite") return false;
$window = int_escape($config->get_int('comment_window')); $window = int_escape($config->get_int('comment_window'));
$max = int_escape($config->get_int('comment_limit')); $max = int_escape($config->get_int('comment_limit'));

View File

@ -21,12 +21,12 @@ class CommentListTheme extends Themelet {
$next = $page_number + 1; $next = $page_number + 1;
$h_prev = ($page_number <= 1) ? "Prev" : $h_prev = ($page_number <= 1) ? "Prev" :
"<a href='".make_link("comment/list/$prev")."'>Prev</a>"; '<a href="'.make_link('comment/list/'.$prev).'">Prev</a>';
$h_index = "<a href='".make_link()."'>Index</a>"; $h_index = "<a href='".make_link()."'>Index</a>";
$h_next = ($page_number >= $total_pages) ? "Next" : $h_next = ($page_number >= $total_pages) ? "Next" :
"<a href='".make_link("comment/list/$next")."'>Next</a>"; '<a href="'.make_link('comment/list/'.$next).'">Next</a>';
$nav = "$h_prev | $h_index | $h_next"; $nav = $h_prev.' | '.$h_index.' | '.$h_next;
$page->set_title("Comments"); $page->set_title("Comments");
$page->set_heading("Comments"); $page->set_heading("Comments");
@ -46,7 +46,7 @@ class CommentListTheme extends Themelet {
$comment_count = count($comments); $comment_count = count($comments);
if($comment_limit > 0 && $comment_count > $comment_limit) { if($comment_limit > 0 && $comment_count > $comment_limit) {
$hidden = $comment_count - $comment_limit; $hidden = $comment_count - $comment_limit;
$comment_html .= "<p>showing $comment_limit of $comment_count comments</p>"; $comment_html .= '<p>showing '.$comment_limit.' of '.$comment_count.' comments</p>';
$comments = array_slice($comments, -$comment_limit); $comments = array_slice($comments, -$comment_limit);
} }
$this->anon_id = 1; $this->anon_id = 1;
@ -68,14 +68,14 @@ class CommentListTheme extends Themelet {
} }
} }
$html = " $html = '
<table class='comment_list_table'><tr> <table class="comment_list_table"><tr>
<td>$thumb_html</td> <td>'.$thumb_html.'</td>
<td>$comment_html</td> <td>'.$comment_html.'</td>
</tr></table> </tr></table>
"; ';
$page->add_block(new Block("{$image->id}: ".($image->get_tag_list()), $html, "main", $position++)); $page->add_block(new Block( $image->id.': '.$image->get_tag_list(), $html, "main", $position++));
} }
} }
@ -146,23 +146,23 @@ class CommentListTheme extends Themelet {
$anoncode = ""; $anoncode = "";
if($h_name == "Anonymous" && $this->anon_id >= 0) { if($h_name == "Anonymous" && $this->anon_id >= 0) {
$anoncode = "<sup>{$this->anon_id}</sup>"; $anoncode = '<sup>'.$this->anon_id.'</sup>';
$this->anon_id++; $this->anon_id++;
} }
$h_userlink = "<a href='".make_link("user/$h_name")."'>$h_name</a>$anoncode"; $h_userlink = '<a href="'.make_link('user/'.$h_name).'">'.$h_name.'</a>'.$anoncode;
$stripped_nonl = str_replace("\n", "\\n", substr($tfe->stripped, 0, 50)); $stripped_nonl = str_replace("\n", "\\n", substr($tfe->stripped, 0, 50));
$stripped_nonl = str_replace("\r", "\\r", $stripped_nonl); $stripped_nonl = str_replace("\r", "\\r", $stripped_nonl);
$h_dellink = $user->is_admin() ? $h_dellink = $user->is_admin() ?
"<br>($h_poster_ip, $h_timestamp, <a ". '<br>('.$h_poster_ip.', '.$h_timestamp.', <a '.
"onclick=\"return confirm('Delete comment by $h_name:\\n$stripped_nonl');\" ". 'onclick="return confirm(\'Delete comment by '.$h_name.':\\n'.$stripped_nonl.'\');" '.
"href='".make_link("comment/delete/$i_comment_id/$i_image_id")."'>Del</a>)" : ""; 'href="'.make_link('comment/delete/'.$i_comment_id.'/'.$i_image_id).'">Del</a>)' : '';
if($trim) { if($trim) {
return " return '
$h_userlink: $h_comment '.$h_userlink.': '.$h_comment.'
<a href='".make_link("post/view/$i_image_id")."'>&gt;&gt;&gt;</a> <a href="'.make_link('post/view/'.$i_image_id).'">&gt;&gt;&gt;</a>
$h_dellink '.$h_dellink.'
"; ';
} }
else { else {
//$avatar = ""; //$avatar = "";
@ -171,14 +171,14 @@ class CommentListTheme extends Themelet {
// $avatar = "<img src=\"http://www.gravatar.com/avatar/$hash.jpg\"><br>"; // $avatar = "<img src=\"http://www.gravatar.com/avatar/$hash.jpg\"><br>";
//} //}
$oe = ($this->comments_shown++ % 2 == 0) ? "even" : "odd"; $oe = ($this->comments_shown++ % 2 == 0) ? "even" : "odd";
return " return '
<a name='$i_comment_id'></a> <a name="'.$i_comment_id.'"></a>
<div class='$oe comment'> <div class="'.$oe.' comment">
<!--<span class='timeago' style='float: right;'>$h_timestamp</span>--> <!--<span class="timeago" style="float: right;">'.$h_timestamp.'</span>-->
$h_userlink: $h_comment '.$h_userlink.': '.$h_comment.'
$h_dellink '.$h_dellink.'
</div> </div>
"; ';
} }
} }
@ -189,15 +189,15 @@ class CommentListTheme extends Themelet {
$hash = CommentList::get_hash(); $hash = CommentList::get_hash();
$captcha = $config->get_bool("comment_captcha") ? captcha_get_html() : ""; $captcha = $config->get_bool("comment_captcha") ? captcha_get_html() : "";
return " return '
".make_form(make_link("comment/add"))." '.make_form(make_link("comment/add")).'
<input type='hidden' name='image_id' value='$i_image_id' /> <input type="hidden" name="image_id" value="'.$i_image_id.'" />
<input type='hidden' name='hash' value='$hash' /> <input type="hidden" name="hash" value="'.$hash.'" />
<textarea name='comment' rows='5' cols='50'></textarea> <textarea name="comment" rows="5" cols="50"></textarea>
$captcha '.$captcha.'
<br><input type='submit' value='Post Comment' /> <br><input type="submit" value="Post Comment" />
</form> </form>
"; ';
} }
} }
?> ?>

View File

@ -25,12 +25,13 @@ class ExtensionInfo {
function ExtensionInfo($main) { function ExtensionInfo($main) {
$matches = array(); $matches = array();
$lines = file($main); $lines = file($main);
$number_of_lines = count($lines);
preg_match("#(ext|contrib)/(.*)/main.php#", $main, $matches); preg_match("#(ext|contrib)/(.*)/main.php#", $main, $matches);
$this->ext_name = $matches[2]; $this->ext_name = $matches[2];
$this->name = $this->ext_name; $this->name = $this->ext_name;
$this->enabled = $this->is_enabled($this->ext_name); $this->enabled = $this->is_enabled($this->ext_name);
for($i=0; $i<count($lines); $i++) { for($i=0; $i<$number_of_lines; $i++) {
$line = $lines[$i]; $line = $lines[$i];
if(preg_match("/Name: (.*)/", $line, $matches)) { if(preg_match("/Name: (.*)/", $line, $matches)) {
$this->name = $matches[1]; $this->name = $matches[1];

View File

@ -147,7 +147,7 @@ class Index extends SimpleExtension {
} }
else { else {
$page->set_mode("redirect"); $page->set_mode("redirect");
$page->set_redirect(make_link("post/list/$search/1")); $page->set_redirect(make_link('post/list/'.$search.'/1'));
} }
return; return;
} }
@ -171,7 +171,7 @@ class Index extends SimpleExtension {
} }
else if(count($search_terms) > 0 && count($images) == 1 && $page_number == 1) { else if(count($search_terms) > 0 && count($images) == 1 && $page_number == 1) {
$page->set_mode("redirect"); $page->set_mode("redirect");
$page->set_redirect(make_link("post/view/{$images[0]->id}")); $page->set_redirect(make_link('post/view/'.$images[0]->id));
} }
else { else {
send_event(new PostListBuildingEvent($search_terms)); send_event(new PostListBuildingEvent($search_terms));
@ -197,15 +197,16 @@ class Index extends SimpleExtension {
public function onSearchTermParse($event) { public function onSearchTermParse($event) {
$matches = array(); $matches = array();
if(preg_match("/^size(<|>|<=|>=|=)(\d+)x(\d+)$/", $event->term, $matches)) { // check for tags first as tag based searches are more common.
if(preg_match("/tags(<|>|<=|>=|=)(\d+)/", $event->term, $matches)) {
$cmp = $matches[1]; $cmp = $matches[1];
$args = array("width"=>int_escape($matches[2]), "height"=>int_escape($matches[3])); $tags = $matches[2];
$event->add_querylet(new Querylet("width $cmp :width AND height $cmp :height", $args)); $event->add_querylet(new Querylet('images.id IN (SELECT DISTINCT image_id FROM image_tags GROUP BY image_id HAVING count(image_id) '.$cmp.' '.$tags.')'));
} }
else if(preg_match("/^ratio(<|>|<=|>=|=)(\d+):(\d+)$/", $event->term, $matches)) { else if(preg_match("/^ratio(<|>|<=|>=|=)(\d+):(\d+)$/", $event->term, $matches)) {
$cmp = $matches[1]; $cmp = $matches[1];
$args = array("width"=>int_escape($matches[2]), "height"=>int_escape($matches[3])); $args = array("width"=>int_escape($matches[2]), "height"=>int_escape($matches[3]));
$event->add_querylet(new Querylet("width / height $cmp :width / :height", $args)); $event->add_querylet(new Querylet('width / height '.$cmp.' :width / :height', $args));
} }
else if(preg_match("/^(filesize|id)(<|>|<=|>=|=)(\d+[kmg]?b?)$/i", $event->term, $matches)) { else if(preg_match("/^(filesize|id)(<|>|<=|>=|=)(\d+[kmg]?b?)$/i", $event->term, $matches)) {
$col = $matches[1]; $col = $matches[1];
@ -215,24 +216,24 @@ class Index extends SimpleExtension {
} }
else if(preg_match("/^(hash|md5)=([0-9a-fA-F]*)$/i", $event->term, $matches)) { else if(preg_match("/^(hash|md5)=([0-9a-fA-F]*)$/i", $event->term, $matches)) {
$hash = strtolower($matches[2]); $hash = strtolower($matches[2]);
$event->add_querylet(new Querylet("images.hash = '$hash'")); $event->add_querylet(new Querylet('images.hash = "'.$hash.'"'));
} }
else if(preg_match("/^(filetype|ext)=([a-zA-Z0-9]*)$/i", $event->term, $matches)) { else if(preg_match("/^(filetype|ext)=([a-zA-Z0-9]*)$/i", $event->term, $matches)) {
$ext = strtolower($matches[2]); $ext = strtolower($matches[2]);
$event->add_querylet(new Querylet("images.ext = '$ext'")); $event->add_querylet(new Querylet('images.ext = "'.$ext.'"'));
} }
else if(preg_match("/^(filename|name)=([a-zA-Z0-9]*)$/i", $event->term, $matches)) { else if(preg_match("/^(filename|name)=([a-zA-Z0-9]*)$/i", $event->term, $matches)) {
$filename = strtolower($matches[2]); $filename = strtolower($matches[2]);
$event->add_querylet(new Querylet("images.filename LIKE '%$filename%'")); $event->add_querylet(new Querylet('images.filename LIKE "%'.$filename.'%"'));
} }
else if(preg_match("/^posted=(([0-9\*]*)?(-[0-9\*]*)?(-[0-9\*]*)?)$/", $event->term, $matches)) { else if(preg_match("/^posted=(([0-9\*]*)?(-[0-9\*]*)?(-[0-9\*]*)?)$/", $event->term, $matches)) {
$val = str_replace("*", "%", $matches[1]); $val = str_replace("*", "%", $matches[1]);
$event->add_querylet(new Querylet("images.posted LIKE '%$val%'")); $event->add_querylet(new Querylet('images.posted LIKE "%'.$val.'%"'));
} }
else if(preg_match("/tags(<|>|<=|>=|=)(\d+)/", $event->term, $matches)) { else if(preg_match("/^size(<|>|<=|>=|=)(\d+)x(\d+)$/", $event->term, $matches)) {
$cmp = $matches[1]; $cmp = $matches[1];
$tags = $matches[2]; $args = array("width"=>int_escape($matches[2]), "height"=>int_escape($matches[3]));
$event->add_querylet(new Querylet("images.id IN (SELECT DISTINCT image_id FROM image_tags GROUP BY image_id HAVING count(image_id) $cmp $tags)")); $event->add_querylet(new Querylet('width '.$cmp.' :width AND height '.$cmp.' :height', $args));
} }
} }
} }

View File

@ -69,12 +69,12 @@ EOD;
$next = $page_number + 1; $next = $page_number + 1;
$u_tags = url_escape(implode(" ", $search_terms)); $u_tags = url_escape(implode(" ", $search_terms));
$query = empty($u_tags) ? "" : "/$u_tags"; $query = empty($u_tags) ? "" : '/'.$u_tags;
$h_prev = ($page_number <= 1) ? "Prev" : "<a href='".make_link("post/list$query/$prev")."'>Prev</a>"; $h_prev = ($page_number <= 1) ? "Prev" : '<a href="'.make_link('post/list'.$query.'/'.$prev).'">Prev</a>';
$h_index = "<a href='".make_link()."'>Index</a>"; $h_index = "<a href='".make_link()."'>Index</a>";
$h_next = ($page_number >= $total_pages) ? "Next" : "<a href='".make_link("post/list$query/$next")."'>Next</a>"; $h_next = ($page_number >= $total_pages) ? "Next" : '<a href="'.make_link('post/list'.$query.'/'.$next).'">Next</a>';
$h_search_string = html_escape(implode(" ", $search_terms)); $h_search_string = html_escape(implode(" ", $search_terms));
$h_search_link = make_link(); $h_search_link = make_link();
@ -102,7 +102,7 @@ EOD;
</form> </form>
<div id='search_completions'></div>"; <div id='search_completions'></div>";
return "$h_prev | $h_index | $h_next<br>$h_search"; return $h_prev.' | '.$h_index.' | '.$h_next.'<br>'.$h_search;
} }
protected function build_table($images, $query) { protected function build_table($images, $query) {

View File

@ -16,7 +16,9 @@ class UploadTheme extends Themelet {
$tl_enabled = ($config->get_string("transload_engine", "none") != "none"); $tl_enabled = ($config->get_string("transload_engine", "none") != "none");
// Uploader 2.0! // Uploader 2.0!
$upload_list = ""; $upload_list = "";
for($i=0; $i<$config->get_int('upload_count'); $i++) $upload_count = $config->get_int('upload_count');
for($i=0; $i<$upload_count; $i++)
{ {
$a=$i+1; $a=$i+1;
$s=$i-1; $s=$i-1;
@ -243,7 +245,9 @@ class UploadTheme extends Themelet {
global $config; global $config;
$upload_list = ""; $upload_list = "";
for($i=0; $i<$config->get_int('upload_count'); $i++) { $upload_count = $config->get_int('upload_count');
for($i=0; $i<$upload_count; $i++) {
if($i == 0) $style = ""; // "style='display:visible'"; if($i == 0) $style = ""; // "style='display:visible'";
else $style = "style='display:none'"; else $style = "style='display:none'";
$upload_list .= "<input size='10' ". $upload_list .= "<input size='10' ".

View File

@ -30,9 +30,9 @@ class UserPageTheme extends Themelet {
public function display_user_block(Page $page, User $user, $parts) { public function display_user_block(Page $page, User $user, $parts) {
$h_name = html_escape($user->name); $h_name = html_escape($user->name);
$html = "Logged in as $h_name"; $html = 'Logged in as '.$h_name;
foreach($parts as $part) { foreach($parts as $part) {
$html .= "<br><a href='{$part["link"]}'>{$part["name"]}</a>"; $html .= '<br><a href="'.$part["link"].'">'.$part["name"].'</a>';
} }
$page->add_block(new Block("User Links", $html, "left", 90)); $page->add_block(new Block("User Links", $html, "left", 90));
} }
@ -48,12 +48,12 @@ class UserPageTheme extends Themelet {
} }
if(empty($tac)) {$html = "";} if(empty($tac)) {$html = "";}
else {$html = "<p>$tac</p>";} else {$html = '<p>'.$tac.'</p>';}
$reca = "<tr><td colspan='2'>".captcha_get_html()."</td></tr>"; $reca = "<tr><td colspan='2'>".captcha_get_html()."</td></tr>";
$html .= " $html .= '
".make_form(make_link("user_admin/create"))." '.make_form(make_link("user_admin/create"))."
<table style='width: 300px;'> <table style='width: 300px;'>
<tr><td>Name</td><td><input type='text' name='name'></td></tr> <tr><td>Name</td><td><input type='text' name='name'></td></tr>
<tr><td>Password</td><td><input type='password' name='pass1'></td></tr> <tr><td>Password</td><td><input type='password' name='pass1'></td></tr>
@ -81,8 +81,8 @@ class UserPageTheme extends Themelet {
public function display_login_block(Page $page) { public function display_login_block(Page $page) {
global $config; global $config;
$html = " $html = '
".make_form(make_link("user_admin/login"))." '.make_form(make_link("user_admin/login"))."
<table summary='Login Form'> <table summary='Login Form'>
<tr> <tr>
<td width='70'><label for='user'>Name</label></td> <td width='70'><label for='user'>Name</label></td>
@ -107,7 +107,7 @@ class UserPageTheme extends Themelet {
$html .= "<tr><td>Uploaded from: "; $html .= "<tr><td>Uploaded from: ";
$n = 0; $n = 0;
foreach($uploads as $ip => $count) { foreach($uploads as $ip => $count) {
$html .= "<br>$ip ($count)"; $html .= '<br>'.$ip.' ('.$count.')';
if(++$n >= 20) { if(++$n >= 20) {
$html .= "<br>..."; $html .= "<br>...";
break; break;
@ -117,7 +117,7 @@ class UserPageTheme extends Themelet {
$html .= "</td><td>Commented from:"; $html .= "</td><td>Commented from:";
$n = 0; $n = 0;
foreach($comments as $ip => $count) { foreach($comments as $ip => $count) {
$html .= "<br>$ip ($count)"; $html .= '<br>'.$ip.' ('.$count.')';
if(++$n >= 20) { if(++$n >= 20) {
$html .= "<br>..."; $html .= "<br>...";
break; break;
@ -133,10 +133,10 @@ class UserPageTheme extends Themelet {
public function display_user_page(User $duser, $stats) { public function display_user_page(User $duser, $stats) {
global $page, $user; global $page, $user;
assert(is_array($stats)); assert(is_array($stats));
$stats[] = "User ID: {$duser->id}"; $stats[] = 'User ID: '.$duser->id;
$page->set_title("{$duser->name}'s Page"); $page->set_title($duser->name."'s Page");
$page->set_heading("{$duser->name}'s Page"); $page->set_heading($duser->name."'s Page");
$page->add_block(new NavBlock()); $page->add_block(new NavBlock());
$page->add_block(new Block("Stats", join("<br>", $stats), "main", 0)); $page->add_block(new Block("Stats", join("<br>", $stats), "main", 0));

View File

@ -115,22 +115,22 @@ try {
ctx_log_start("Loading themelets"); ctx_log_start("Loading themelets");
// load the theme parts // load the theme parts
$_theme = $config->get_string("theme", "default"); $_theme = $config->get_string("theme", "default");
if(!file_exists("themes/$_theme")) $_theme = "default"; if(!file_exists('themes/'.$_theme)) $_theme = "default";
if(file_exists("themes/$_theme/custompage.class.php")) require_once "themes/$_theme/custompage.class.php"; if(file_exists('themes/'.$_theme.'/custompage.class.php')) require_once 'themes/'.$_theme.'/custompage.class.php';
require_once "themes/$_theme/layout.class.php"; require_once 'themes/'.$_theme.'/layout.class.php';
require_once "themes/$_theme/themelet.class.php"; require_once 'themes/'.$_theme.'/themelet.class.php';
$themelets = glob("ext/*/theme.php"); $themelets = glob("ext/*/theme.php");
foreach($themelets as $filename) { foreach($themelets as $filename) {
require_once $filename; require_once $filename;
} }
$custom_themelets = glob("themes/$_theme/*.theme.php"); $custom_themelets = glob('themes/'.$_theme.'/*.theme.php');
if($custom_themelets) { if($custom_themelets) {
$m = array(); $m = array();
foreach($custom_themelets as $filename) { foreach($custom_themelets as $filename) {
if(preg_match("/themes\/$_theme\/(.*)\.theme\.php/",$filename,$m) if(preg_match('/themes\/'.$_theme.'\/(.*)\.theme\.php/',$filename,$m)
&& in_array("ext/{$m[1]}/theme.php", $themelets)) { && in_array('ext/'.$m[1].'/theme.php', $themelets)) {
require_once $filename; require_once $filename;
} }
} }
@ -224,17 +224,17 @@ catch(Exception $e) {
$message = $e->getMessage(); $message = $e->getMessage();
//$trace = var_dump($e->getTrace()); //$trace = var_dump($e->getTrace());
header("HTTP/1.0 500 Internal Error"); header("HTTP/1.0 500 Internal Error");
print <<<EOD echo '
<html> <html>
<head> <head>
<title>Internal error - SCore-$version</title> <title>Internal error - SCore-'.$version.'</title>
</head> </head>
<body> <body>
<h1>Internal Error</h1> <h1>Internal Error</h1>
<p>$message <p>'.$message.'
</body> </body>
</html> </html>
EOD; ';
if($database && $database->db) $database->db->rollback(); if($database && $database->db) $database->db->rollback();
ctx_log_ender(); ctx_log_ender();
} }

View File

@ -904,7 +904,9 @@ class Securimage {
} }
$out_data = ''; $out_data = '';
for($i = 0; $i < sizeof($files); ++$i) { $file_size = sizeof($files);
for($i = 0; $i < $file_size; ++$i) {
if ($i == 0) { // output header if ($i == 0) { // output header
$out_data .= pack('C4VC8', ord('R'), ord('I'), ord('F'), ord('F'), $data_len + 36, ord('W'), ord('A'), ord('V'), ord('E'), ord('f'), ord('m'), ord('t'), ord(' ')); $out_data .= pack('C4VC8', ord('R'), ord('I'), ord('F'), ord('F'), $data_len + 36, ord('W'), ord('A'), ord('V'), ord('E'), ord('f'), ord('m'), ord('t'), ord(' '));

View File

@ -29,13 +29,13 @@ class Themelet {
*/ */
public function build_thumb_html(Image $image, $query=null) { public function build_thumb_html(Image $image, $query=null) {
global $config; global $config;
$i_id = int_escape($image->id); $i_id = (int) $image->id;
$h_view_link = make_link("post/view/$i_id", $query); $h_view_link = make_link('post/view/'.$i_id, $query);
$h_thumb_link = $image->get_thumb_link(); $h_thumb_link = $image->get_thumb_link();
// Removes the size tag if the file is an mp3 // Removes the size tag if the file is an mp3
if($image->ext == 'mp3'){ if($image->ext === 'mp3'){
$iitip = $image->get_tooltip(); $iitip = $image->get_tooltip();
$mp3tip = array("0x0"); $mp3tip = array("0x0");
$h_tip = str_replace($mp3tip, " ", $iitip); $h_tip = str_replace($mp3tip, " ", $iitip);
@ -45,29 +45,29 @@ class Themelet {
if(strstr($h_tip, " ")){ if(strstr($h_tip, " ")){
$h_tip = html_escape(str_replace($justincase, "", $h_tip)); $h_tip = html_escape(str_replace($justincase, "", $h_tip));
}else{ }else{
$h_tip = html_escape($h_tip); $h_tip = html_escape($h_tip);
} }
}else{ }else{
$h_tip = html_escape($image->get_tooltip()); $h_tip = html_escape($image->get_tooltip());
} }
// If file is flash or svg then sets thumbnail to max size. // If file is flash or svg then sets thumbnail to max size.
if($image->ext == 'swf' || $image->ext == 'svg'){ if($image->ext === 'swf' || $image->ext === 'svg'){
$tsize = get_thumbnail_size($config->get_int('thumb_width'), $config->get_int('thumb_height')); } $tsize = get_thumbnail_size($config->get_int('thumb_width'), $config->get_int('thumb_height')); }
else{ else{
$tsize = get_thumbnail_size($image->width, $image->height); } $tsize = get_thumbnail_size($image->width, $image->height); }
return " return '
<!-- cancel border --> <!-- cancel border -->
<div class='thumbblock'> <div class="thumbblock">
<div class='thumb'> <div class="thumb">
<a href='$h_view_link' style='position: relative; display: block; height: {$tsize[1]}px; width: {$tsize[0]}px;'> <a href="'.$h_view_link.'" style="position: relative; display: block; height: '.$tsize[1].'px; width: '.$tsize[0].'px;">
<img id='thumb_$i_id' title='$h_tip' alt='$h_tip' height='{$tsize[1]}' width='{$tsize[0]}' src='$h_thumb_link'> <img id="thumb_'.$i_id.'" title="'.$h_tip.'" alt="'.$h_tip.'" height="'.$tsize[1].'" width="'.$tsize[0].'" src="'.$h_thumb_link.'">
</a> </a>
</div> </div>
</div> </div>
"; ';
} }
@ -81,8 +81,8 @@ class Themelet {
} }
private function gen_page_link($base_url, $query, $page, $name) { private function gen_page_link($base_url, $query, $page, $name) {
$link = make_link("$base_url/$page", $query); $link = make_link($base_url.'/'.$page, $query);
return "<a href='$link'>$name</a>"; return '<a href="'.$link.'">'.$name.'</a>';
} }
private function gen_page_link_block($base_url, $query, $page, $current_page, $name) { private function gen_page_link_block($base_url, $query, $page, $current_page, $name) {
@ -116,8 +116,8 @@ class Themelet {
} }
$pages_html = implode(" | ", $pages); $pages_html = implode(" | ", $pages);
return "<p class='paginator'>$first_html | $prev_html | $random_html | $next_html | $last_html". return '<p class="paginator">'.$first_html.' | '.$prev_html.' | '.$random_html.' | '.$next_html.' | '.$last_html
"<br>&lt;&lt; $pages_html &gt;&gt;</p><!-- cancel border -->"; .'<br>&lt;&lt; '.$pages_html.' &gt;&gt;</p><!-- cancel border -->';
} }
} }
?> ?>