From 71616560638e368e84b0d94ba317c12037c040f9 Mon Sep 17 00:00:00 2001 From: shish Date: Mon, 16 Apr 2007 11:58:25 +0000 Subject: [PATCH] Initial import, 2.0rc1 git-svn-id: file:///home/shish/svn/shimmie2/trunk@1 7f39781d-f577-437e-ae19-be835c7a54ca --- README.txt | 78 + core/block.class.php | 11 + core/config.class.php | 128 + core/database.class.php | 342 ++ core/event.class.php | 8 + core/events/configsave.event.php | 14 + core/events/displayingimage.event.php | 21 + core/events/imagedeletion.event.php | 17 + core/events/initext.event.php | 10 + core/events/pagerequest.event.php | 31 + core/events/tagset.event.php | 17 + core/events/uploadingimage.event.php | 15 + core/ext/admin.ext.php | 77 + core/ext/image.ext.php | 285 ++ core/ext/index.ext.php | 147 + core/ext/setup.ext.php | 216 ++ core/ext/tag_edit.ext.php | 97 + core/ext/upload.ext.php | 131 + core/ext/user.ext.php | 401 +++ core/ext/view.ext.php | 124 + core/extension.class.php | 5 + core/image.class.php | 162 + core/navblock.class.php | 11 + core/page.class.php | 95 + core/paginator.class.php | 50 + core/user.class.php | 64 + core/util.inc.php | 197 ++ ext/alias_editor.ext.php | 91 + ext/autocomplete.ext.php.disabled | 73 + ext/bulk_add.ext.php | 102 + ext/comment.ext.php | 386 +++ ext/downtime.ext.php | 51 + ext/et.ext.php | 90 + ext/ipban.ext.php | 169 + ext/news.ext.php | 23 + ext/notes.ext.php.disabled | 52 + ext/rating.ext.php.disabled | 130 + ext/regen_thumb.ext.php | 170 + ext/tag_list.ext.php | 235 ++ ext/zoom.ext.php | 57 + favicon.ico | Bin 0 -> 1406 bytes index.php | 37 + install.php | 497 +++ lib/adodb/adodb-iterator.inc.php | 85 + lib/adodb/adodb-lib.inc.php | 1128 +++++++ lib/adodb/adodb-php4.inc.php | 16 + lib/adodb/adodb-time.inc.php | 1337 ++++++++ lib/adodb/adodb.inc.php | 4221 ++++++++++++++++++++++++ lib/adodb/drivers/adodb-mysql.inc.php | 782 +++++ lib/adodb/drivers/adodb-sqlite.inc.php | 398 +++ lib/adodb/license.txt | 182 + lib/akismet.class.php | 356 ++ scripts/libshish.js | 67 + scripts/shimmie.js | 131 + themes/default/default.php | 99 + themes/default/sidebar.js | 83 + themes/default/style.css | 146 + 57 files changed, 13948 insertions(+) create mode 100644 README.txt create mode 100644 core/block.class.php create mode 100644 core/config.class.php create mode 100644 core/database.class.php create mode 100644 core/event.class.php create mode 100644 core/events/configsave.event.php create mode 100644 core/events/displayingimage.event.php create mode 100644 core/events/imagedeletion.event.php create mode 100644 core/events/initext.event.php create mode 100644 core/events/pagerequest.event.php create mode 100644 core/events/tagset.event.php create mode 100644 core/events/uploadingimage.event.php create mode 100644 core/ext/admin.ext.php create mode 100644 core/ext/image.ext.php create mode 100644 core/ext/index.ext.php create mode 100644 core/ext/setup.ext.php create mode 100644 core/ext/tag_edit.ext.php create mode 100644 core/ext/upload.ext.php create mode 100644 core/ext/user.ext.php create mode 100644 core/ext/view.ext.php create mode 100644 core/extension.class.php create mode 100644 core/image.class.php create mode 100644 core/navblock.class.php create mode 100644 core/page.class.php create mode 100644 core/paginator.class.php create mode 100644 core/user.class.php create mode 100644 core/util.inc.php create mode 100644 ext/alias_editor.ext.php create mode 100644 ext/autocomplete.ext.php.disabled create mode 100644 ext/bulk_add.ext.php create mode 100644 ext/comment.ext.php create mode 100644 ext/downtime.ext.php create mode 100644 ext/et.ext.php create mode 100644 ext/ipban.ext.php create mode 100644 ext/news.ext.php create mode 100644 ext/notes.ext.php.disabled create mode 100644 ext/rating.ext.php.disabled create mode 100644 ext/regen_thumb.ext.php create mode 100644 ext/tag_list.ext.php create mode 100644 ext/zoom.ext.php create mode 100644 favicon.ico create mode 100644 index.php create mode 100644 install.php create mode 100644 lib/adodb/adodb-iterator.inc.php create mode 100644 lib/adodb/adodb-lib.inc.php create mode 100644 lib/adodb/adodb-php4.inc.php create mode 100644 lib/adodb/adodb-time.inc.php create mode 100644 lib/adodb/adodb.inc.php create mode 100644 lib/adodb/drivers/adodb-mysql.inc.php create mode 100644 lib/adodb/drivers/adodb-sqlite.inc.php create mode 100644 lib/adodb/license.txt create mode 100644 lib/akismet.class.php create mode 100644 scripts/libshish.js create mode 100644 scripts/shimmie.js create mode 100644 themes/default/default.php create mode 100644 themes/default/sidebar.js create mode 100644 themes/default/style.css diff --git a/README.txt b/README.txt new file mode 100644 index 00000000..467e600b --- /dev/null +++ b/README.txt @@ -0,0 +1,78 @@ + + _________.__ .__ .__ ________ + / _____/| |__ |__| _____ _____ |__| ____ \_____ \ + \_____ \ | | \| |/ \ / \| |/ __ \ / ____/ + / \| Y \ | Y Y \ Y Y \ \ ___// \ + /_______ /|___| /__|__|_| /__|_| /__|\___ >_______ \ + \/ \/ \/ \/ \/ \/ + +Shimmie2 Release Candidate +~~~~~~~~~~~~~~~~~~~~~~~~~~ +Okay, so maybe my estimate of "it should be done within the week" was a bit +optimistic... I did get the first 3.5k lines of code done in a week, then +another 1k of extensions in another week, but making it all work *properly* +took 3 months... + + +Requirements +~~~~~~~~~~~~ +MySQL 4.1+ +PHP 5.0+ +GD or ImageMagick + +PHP 4 support has currently been dropped, because +a) It's a pain in the ass to support +b) Nobody has told me they want it + +If you want PHP 4 support, mail me, and I'll see if I can get it working for +version 2.1... + + +Installation +~~~~~~~~~~~~ +1) Create a blank database +2) Unzip shimmie into a folder on the web host +3) Visit the install folder with a web browser +4) Enter the location of the database, and choose login details for the first + admin of the board +5) Click "install". Hopefully you'll end up at the configuration screen; if + not, you should be given instructions on how to fix any errors~ + + +Upgrade from 0.8.4 +~~~~~~~~~~~~~~~~~~ +BIG NOTE: 0.8.4 is the only version the upgrader supports; please upgrade to +that before going any further! Feel free to try other versions, just don't +complain when it doesn't work :P + +Upgrade process: +1) Make backups of everything. The most important things are your database + data, and your images folder. config.php and the thumbs folder are also + very helpful. +2) Check that your backups actually contain the important data, they aren't + just empty files with the right names... +3) Create a new, blank database, separate from the old one +4) Unzip shimmie2 into a different folder than shimmie1 +5) Visit the URL of shimmie2 +6) Full in the old database location, the new database location, and the full + path to the old installation folder (the folder where the old "images" and + "thumbs" can be found) +7) Click "upgrade" +8) Wait a couple of minutes while data is copied from the old install into the + new one. You may wish to spend these minutes in prayer :P +9) Log in with an existing admin account and set things up to taste + +The old installation can now be removed, but you may wish to keep it around +until you're sure everything in v2 is working properly~ + + +Contact +~~~~~~~ +http://forum.shishnet.org/viewforum.php?f=6 -- discussion forum +http://trac.shishnet.org/shimmie2/ -- bug tracker +webmaster at shishnet.org -- email +Shish on Freenode -- IRC + + + + diff --git a/core/block.class.php b/core/block.class.php new file mode 100644 index 00000000..0d144580 --- /dev/null +++ b/core/block.class.php @@ -0,0 +1,11 @@ +header = $header; + $this->body = $body; + } +} +?> diff --git a/core/config.class.php b/core/config.class.php new file mode 100644 index 00000000..a82e1bfc --- /dev/null +++ b/core/config.class.php @@ -0,0 +1,128 @@ + '/thumbs/$id.jpg', + 'image_ilink' => '/images/$id.$ext', + ); + var $defaults = array( + 'title' => 'Shimmie', # setup + 'version' => 'Shimmie2-0.0.9', // internal + 'db_version' => '2.0.0.9', // this should be managed by upgrade.php + 'base_href' => './index.php?q=', # setup + 'data_href' => './', # setup + 'theme' => 'default', # setup + 'debug_enabled' => true, # hidden + 'anon_id' => 0, # general + 'dir_images' => 'images', # general + 'dir_thumbs' => 'thumbs', # general + 'index_width' => 3, # index + 'index_height' => 4, # index + 'index_tips' => true, + 'thumb_width' => 192, # index + 'thumb_height' => 192, # index + 'thumb_quality' => 75, # index + 'thumb_gd_mem_limit' => '8MB', # upload + 'view_scale' => false, # view + 'tags_default' => 'map', # (ignored) + 'tags_min' => '2', # tags + 'upload_count' => 3, # upload + 'upload_size' => '256KB', # upload + 'upload_anon' => true, # upload + 'comment_anon' => true, # comment + 'comment_window' => 5, # comment + 'comment_limit' => 3, # comment + 'comment_count' => 5, # comment + 'popular_count' => 15, # popular + 'info_link' => 'http://tags.shishnet.org/wiki/$tag', # popular + 'login_signup_enabled' => true, # user + 'login_memory' => 7, # user + 'image_ilink' => '$base/image/$id.$ext', # view + 'image_slink' => '', # view + 'image_tlink' => '$base/thumb/$id.jpg', # view + 'image_tip' => '$tags // $size // $filesize' # view + ); + + public function Config() { + global $database; + $this->values = $database->db->GetAssoc("SELECT name, value FROM config"); + } + public function save($name=null) { + global $database; + + if(is_null($name)) { + foreach($this->values as $name => $value) { + // does "or update" work with sqlite / postgres? + $database->db->StartTrans(); + $database->db->Execute("DELETE FROM config WHERE name = ?", array($name)); + $database->db->Execute("INSERT INTO config VALUES (?, ?)", array($name, $value)); + $database->db->CommitTrans(); + } + } + else { + $database->db->StartTrans(); + $database->db->Execute("DELETE FROM config WHERE name = ?", array($name)); + $database->db->Execute("INSERT INTO config VALUES (?, ?)", array($name, $this->values[$name])); + $database->db->CommitTrans(); + } + } + + public function set_int($name, $value) { + $this->values[$name] = parse_shorthand_int($value); + $this->save($name); + } + public function set_string($name, $value) { + $this->values[$name] = $value; + $this->save($name); + } + public function set_bool($name, $value) { + $this->values[$name] = (($value == 'on' || $value === true) ? 'Y' : 'N'); + $this->save($name); + } + + public function set_int_from_post($name) { + if(isset($_POST[$name])) { + $this->values[$name] = $_POST[$name]; + $this->save($name); + } + } + public function set_string_from_post($name) { + if(isset($_POST[$name])) { + $this->values[$name] = $_POST[$name]; + $this->save($name); + } + } + public function set_bool_from_post($name) { + if(isset($_POST[$name]) && ($_POST[$name] == 'on')) { + $this->values[$name] = 'Y'; + } + else { + $this->values[$name] = 'N'; + } + $this->save($name); + } + + public function get_int($name) { + // deprecated -- ints should be stored as ints now + return parse_shorthand_int($this->get($name)); + } + public function get_string($name) { + return $this->get($name); + } + public function get_bool($name) { + // deprecated -- bools should be stored as Y/N now + return ($this->get($name) == 'Y' || $this->get($name) == '1'); + } + + public function get($name) { + if(isset($this->values[$name])) { + return $this->values[$name]; + } + else if(isset($this->defaults[$name])) { + return $this->defaults[$name]; + } + else { + return null; + } + } +} +?> diff --git a/core/database.class.php b/core/database.class.php new file mode 100644 index 00000000..de943714 --- /dev/null +++ b/core/database.class.php @@ -0,0 +1,342 @@ +sql = $sql; + $this->variables = $variables; + } + + public function append($querylet) { + $this->sql .= $querylet->sql; + $this->variables = array_merge($this->variables, $querylet->variables); + } + + public function append_sql($sql) { + $this->sql .= $sql; + } + + public function add_variable($var) { + $this->variables[] = $var; + } +} // }}} + +class Database { + var $db; + var $extensions; + + public function Database() { + if(is_readable("config.php")) { + require_once "config.php"; + $this->db = NewADOConnection($database_dsn); + $this->db->SetFetchMode(ADODB_FETCH_ASSOC); + $this->extensions = $this->db->GetAssoc("SELECT name, version FROM extensions"); + } + else { + header("Location: install.php"); + exit; + } + } + +// misc {{{ + public function count_pages($tags=array()) { + global $config; + $images_per_page = $config->get_int('index_width') * $config->get_int('index_height'); + if(count($tags) == 0) { + return ceil($this->db->GetOne("SELECT COUNT(*) FROM images") / $images_per_page); + } + else { + $querylet = $this->build_search_querylet($tags); + $result = $this->db->Execute($querylet->sql, $querylet->variables); + return ceil($result->RecordCount() / $images_per_page); + } + } +// }}} +// extensions {{{ + public function set_extension_version($name, $version) { + $this->extensions[$name] = $version; + $this->db->GetRow("INSERT INTO extensions(name, version) VALUES (?, ?)", array($name, $version)); + } + public function get_extension_version($name) { + return (isset($this->extensions[$name]) ? $this->extensions[$name] : -1); + } +// }}} +// tags {{{ + public function resolve_alias($tag) { + $newtag = $this->db->GetOne("SELECT newtag FROM aliases WHERE oldtag=?", array($tag)); + if(!empty($newtag)) { + return $newtag; + } else { + return $tag; + } + } + + public function sanitise($tag) { + return preg_replace("/[\s?*]/", "", $tag); + } + + private function build_search_querylet($terms) { + $tag_search = new Querylet("0"); + $positive_tag_count = 0; + $img_search = new Querylet(""); + + foreach($terms as $term) { + $negative = false; + if((strlen($term) > 0) && ($term[0] == '-')) { + $negative = true; + $term = substr($term, 1); + } + + $term = $this->resolve_alias($term); + + if(substr($term, 0, 5) == "size=") { + $dim = substr($term, 5); + $parts = explode('x', $dim); + $args = array(int_escape($parts[0]), int_escape($parts[1])); + $img_search->append(new Querylet("AND (width = ? AND height = ?)", $args)); + } + else if(substr($term, 0, 5) == "size>") { + $dim = substr($term, 5); + $parts = explode('x', $dim); + $args = array(int_escape($parts[0]), int_escape($parts[1])); + $img_search->append(new Querylet("AND (width > ? AND height > ?)", $args)); + } + else if(substr($term, 0, 5) == "size<") { + $dim = substr($term, 5); + $parts = explode('x', $dim); + $args = array(int_escape($parts[0]), int_escape($parts[1])); + $img_search->append(new Querylet("AND (width < ? AND height < ?)", $args)); + } + else if(substr($term, 0, 6) == "ratio=") { + $dim = substr($term, 6); + $parts = explode(':', $dim); + $args = array(int_escape($parts[0]), int_escape($parts[1])); + $img_search->append(new Querylet("AND (width / height = ? / ?)", $args)); + } + else if(substr($term, 0, 3) == "id<") { + $img_search->append(new Querylet("AND (id < ?)", array(int_escape(substr($term, 3))))); + } + else if(substr($term, 0, 3) == "id>") { + $img_search->append(new Querylet("AND (id > ?)", array(int_escape(substr($term, 3))))); + } + else if(substr($term, 0, 9) == "filesize<") { + $img_search->append(new Querylet("AND (filesize < ?)", array(parse_shorthand_int(substr($term, 9))))); + } + else if(substr($term, 0, 9) == "filesize>") { + $img_search->append(new Querylet("AND (filesize > ?)", array(parse_shorthand_int(substr($term, 9))))); + } + else { + $term = str_replace("*", "%", $term); + $term = str_replace("?", "_", $term); + $sign = $negative ? "-" : "+"; + if($sign == "+") $positive_tag_count++; + $tag_search->append(new Querylet(" $sign (tag LIKE ?)", array($term))); + } + } + + $database_fails = false; // MySQL 4.0 fails at subqueries + if(count($tag_search->variables) == 0 || $database_fails) { + $query = new Querylet("SELECT * FROM images "); + } + else { + $subquery = new Querylet(" + SELECT *, SUM({$tag_search->sql}) AS score + FROM images + LEFT JOIN tags ON tags.image_id = images.id + GROUP BY images.id + HAVING score = ?", + array_merge( + $tag_search->variables, + array($positive_tag_count) + ) + ); + $query = new Querylet("SELECT * FROM ({$subquery->sql}) AS images ", $subquery->variables); + } + + if(count($img_search->variables) > 0) { + $query->append_sql("WHERE 1=1 "); + $query->append($img_search); + } + + return $query; + } + + private function build_search_querylet_old($tags) { // {{{ + $querylet = new Querylet("SELECT images.*, SUM("); + + $tnum = 0; + foreach($tags as $tag) { + if(($tag != "") && ($tag[0] == '-')) continue; + $querylet->append_sql($tnum == 0 ? "(" : " OR "); + $querylet->append($this->term_to_querylet($tag)); + $tnum++; + } + $min_score = $tnum; + if($tnum > 0) $querylet->append_sql(")"); + + $tnum = 0; + foreach($tags as $tag) { + if(($tag == "") || ($tag[0] != '-')) continue; + $querylet->append_sql($tnum == 0 ? "-(" : " OR "); + $querylet->append($this->term_to_querylet(substr($tag, 1))); + $tnum++; + } + if($tnum > 0) $querylet->append_sql(")"); + + $querylet->append_sql(") AS score + FROM tags + LEFT JOIN images ON image_id=images.id + GROUP BY images.id + HAVING score >= ? + "); + $querylet->add_variable($min_score); + + return $querylet; + } + + private function term_to_querylet($term) { + $term = $this->resolve_alias($term); + + if(substr($term, 0, 5) == "size:") { + $dim = substr($term, 5); + $parts = explode('x', $dim); + return new Querylet("(width = ? AND height = ?)", array(int_escape($parts[0]), int_escape($parts[1]))); + } + else if(substr($term, 0, 9) == "size-min:") { + $dim = substr($term, 9); + $parts = explode('x', $dim); + return new Querylet("(width >= ? AND height >= ?)", array(int_escape($parts[0]), int_escape($parts[1]))); + } + else if(substr($term, 0, 9) == "size-max:") { + $dim = substr($term, 9); + $parts = explode('x', $dim); + return new Querylet("(width <= ? AND height <= ?)", array(int_escape($parts[0]), int_escape($parts[1]))); + } + else { + $term = str_replace("*", "%", $term); + $term = str_replace("?", "_", $term); + return new Querylet("(tag LIKE ?)", array($term)); + } + } // }}} + + public function delete_tags_from_image($image_id) { + $this->db->Execute("DELETE FROM tags WHERE image_id=?", array($image_id)); + } + + public function set_tags($image_id, $tags) { + $tags = tag_explode($tags); + + $tags = array_map(array($this, 'resolve_alias'), $tags); + $tags = array_map(array($this, 'sanitise'), $tags); + $tags = array_unique($tags); // remove any duplicate tags + + // delete old + $this->delete_tags_from_image($image_id); + + // insert each new tag + foreach($tags as $tag) { + $this->db->Execute("INSERT INTO tags(image_id, tag) VALUES(?, ?)", array($image_id, $tag)); + } + } +// }}} +// images {{{ + public function get_images($start, $limit, $tags=array()) { + $images = array(); + + assert($start >= 0); + assert($limit > 0); + if($start < 0) $start = 0; + if($limit < 1) $limit = 1; + + if(count($tags) == 0) { + $result = $this->db->Execute("SELECT * FROM images ORDER BY id DESC LIMIT ?,?", array($start, $limit)); + } + else { + $querylet = $this->build_search_querylet($tags); + $querylet->append(new Querylet("ORDER BY images.id DESC LIMIT ?,?", array($start, $limit))); + $result = $this->db->Execute($querylet->sql, $querylet->variables); + } + + while(!$result->EOF) { + $images[] = new Image($result->fields); + $result->MoveNext(); + } + return $images; + } + + public function get_next_image($id, $tags=array(), $next=true) { + if($next) { + $gtlt = "<"; + $dir = "DESC"; + } + else { + $gtlt = ">"; + $dir = "ASC"; + } + + if(count($tags) == 0) { + $row = $this->db->GetRow("SELECT * FROM images WHERE id $gtlt ? ORDER BY id $dir", array((int)$id)); + } + else { + $tags[] = ($next ? "id<$id" : "id>$id"); + $dir = ($next ? "DESC" : "ASC"); + $querylet = $this->build_search_querylet($tags); + $querylet->append_sql("ORDER BY id $dir"); + $row = $this->db->GetRow($querylet->sql, $querylet->variables); + } + + return ($row ? new Image($row) : null); + } + + public function get_prev_image($id, $tags=array()) { + return $this->get_next_image($id, $tags, false); + } + + public function get_image($id) { + $image = null; + $row = $this->db->GetRow("SELECT * FROM images WHERE id=?", array($id)); + return ($row ? new Image($row) : null); + } + + public function remove_image($id) { + $this->db->Execute("DELETE FROM images WHERE id=?", array($id)); + } +// }}} +// users {{{ + var $SELECT_USER = "SELECT *,time_to_sec(timediff(now(), joindate))/(60*60*24) AS days_old FROM users "; + + public function get_user($a=false, $b=false) { + if($b == false) { + return $this->get_user_by_id($a); + } + else { + return $this->get_user_by_name_and_hash($a, $b); + } + } + + public function get_user_session($name, $session) { + $row = $this->db->GetRow("{$this->SELECT_USER} WHERE name LIKE ? AND md5(concat(pass, ?)) = ?", + array($name, $_SERVER['REMOTE_ADDR'], $session)); + return $row ? new User($row) : null; + } + + public function get_user_by_id($id) { + $row = $this->db->GetRow("{$this->SELECT_USER} WHERE id=?", array($id)); + return $row ? new User($row) : null; + } + + public function get_user_by_name($name) { + $row = $this->db->GetRow("{$this->SELECT_USER} WHERE name=?", array($name)); + return $row ? new User($row) : null; + } + + public function get_user_by_name_and_hash($name, $hash) { + $row = $this->db->GetRow("{$this->SELECT_USER} WHERE name LIKE ? AND pass = ?", array($name, $hash)); + return $row ? new User($row) : null; + } +// }}} +} +?> diff --git a/core/event.class.php b/core/event.class.php new file mode 100644 index 00000000..351fa8a4 --- /dev/null +++ b/core/event.class.php @@ -0,0 +1,8 @@ + diff --git a/core/events/configsave.event.php b/core/events/configsave.event.php new file mode 100644 index 00000000..cc8f5bf1 --- /dev/null +++ b/core/events/configsave.event.php @@ -0,0 +1,14 @@ +config = $config; + } +} +?> diff --git a/core/events/displayingimage.event.php b/core/events/displayingimage.event.php new file mode 100644 index 00000000..bdf1f99f --- /dev/null +++ b/core/events/displayingimage.event.php @@ -0,0 +1,21 @@ +image = $image; + } + + public function get_image() { + return $this->image; + } +} +?> diff --git a/core/events/imagedeletion.event.php b/core/events/imagedeletion.event.php new file mode 100644 index 00000000..9c30aa94 --- /dev/null +++ b/core/events/imagedeletion.event.php @@ -0,0 +1,17 @@ +image = $image; + } +} +?> diff --git a/core/events/initext.event.php b/core/events/initext.event.php new file mode 100644 index 00000000..7c01f5df --- /dev/null +++ b/core/events/initext.event.php @@ -0,0 +1,10 @@ + diff --git a/core/events/pagerequest.event.php b/core/events/pagerequest.event.php new file mode 100644 index 00000000..c4600954 --- /dev/null +++ b/core/events/pagerequest.event.php @@ -0,0 +1,31 @@ + an event is generated with + * $page="view" and $args=array("42"); + * + * Used for initial page generation triggers + */ +class PageRequestEvent extends Event { + var $page; + var $args; + + public function PageRequestEvent($page, $args) { + $this->page = $page; + $this->args = $args; + } + + public function get_arg($n) { + return isset($this->args[$n]) ? $this->args[$n] : null; + } + + public function count_args() { + return isset($this->args) ? count($this->args) : 0; + } +} +?> diff --git a/core/events/tagset.event.php b/core/events/tagset.event.php new file mode 100644 index 00000000..8ea3b8f5 --- /dev/null +++ b/core/events/tagset.event.php @@ -0,0 +1,17 @@ +image_id = $image_id; + $this->tags = $tags; + } +} +?> diff --git a/core/events/uploadingimage.event.php b/core/events/uploadingimage.event.php new file mode 100644 index 00000000..aa9ea662 --- /dev/null +++ b/core/events/uploadingimage.event.php @@ -0,0 +1,15 @@ +image = $image; + } +} +?> diff --git a/core/ext/admin.ext.php b/core/ext/admin.ext.php new file mode 100644 index 00000000..573bfe5d --- /dev/null +++ b/core/ext/admin.ext.php @@ -0,0 +1,77 @@ +page == "admin")) { + global $user; + if(!$user->is_admin()) { + global $page; + $page->set_title("Error"); + $page->set_heading("Error"); + $page->add_side_block(new NavBlock(), 0); + $page->add_main_block(new Block("Permission Denied", "This page is for admins only"), 0); + } + else { + if($event->get_arg(0) == "delete_image") { + // FIXME: missing lots of else {complain} + if(isset($_POST['image_id'])) { + global $database; + $image = $database->get_image($_POST['image_id']); + if($image) { + send_event(new ImageDeletionEvent($image)); + global $page; + $page->set_mode("redirect"); + $page->set_redirect(make_link("index")); + } + } + } + else { + send_event(new AdminBuildingEvent()); + } + } + } + + if(is_a($event, 'DisplayingImageEvent')) { + global $user; + if($user->is_admin()) { + global $page; + $page->add_side_block(new Block("Admin", $this->build_del_block($event->image->id))); + } + } + + if(is_a($event, 'AdminBuildingEvent')) { + $this->build_page(); + } + } +// }}} +// block HTML {{{ + private function build_del_block($image_id) { + $i_image_id = int_escape($image_id); + return " +
+ + +
+ "; + } +// }}} +// admin page HTML {{{ + private function build_page() { + global $page; + $page->set_title("Admin Tools"); + $page->set_heading("Admin Tools"); + $page->add_side_block(new NavBlock(), 0); + } +// }}} +} +add_event_listener(new AdminPage()); +?> diff --git a/core/ext/image.ext.php b/core/ext/image.ext.php new file mode 100644 index 00000000..172f630e --- /dev/null +++ b/core/ext/image.ext.php @@ -0,0 +1,285 @@ +page == "image")) { + $this->send_file($event->get_arg(0), "image"); + } + if(is_a($event, 'PageRequestEvent') && ($event->page == "thumb")) { + $this->send_file($event->get_arg(0), "thumb"); + } + + if(is_a($event, 'UploadingImageEvent')) { + $this->add_image($event->image); + } + + if(is_a($event, 'ImageDeletionEvent')) { + $this->remove_image($event->image); + } + + if(is_a($event, 'SetupBuildingEvent')) { + $thumbers = array(); + $thumbers['Built-in GD'] = "gd"; + $thumbers['ImageMagick'] = "convert"; + + $sb = new SetupBlock("Thumbnailing"); + $sb->add_label("Engine: "); + $sb->add_choice_option("thumb_engine", $thumbers); + + $sb->add_label("
Size "); + $sb->add_int_option("thumb_width"); + $sb->add_label(" x "); + $sb->add_int_option("thumb_height"); + $sb->add_label(" px at "); + $sb->add_int_option("thumb_quality"); + $sb->add_label(" % quality "); + + $sb->add_label("
Max GD memory use: "); + $sb->add_shorthand_int_option("thumb_gd_mem_limit"); + + $event->panel->add_main_block($sb); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_string("thumb_engine", $_POST['thumb_engine']); + $event->config->set_int("thumb_width", $_POST['thumb_width']); + $event->config->set_int("thumb_height", $_POST['thumb_height']); + $event->config->set_int("thumb_quality", $_POST['thumb_quality']); + $event->config->set_int("thumb_gd_mem_limit", $_POST['thumb_gd_mem_limit']); + } + } +// }}} +// add image {{{ + private function is_dupe($hash) { + global $database; + return $database->db->GetRow("SELECT * FROM images WHERE hash=?", array($hash)); + } + + private function read_file($fname) { + $fp = fopen($fname, "r"); + if(!$fp) return false; + + $data = fread($fp, filesize($fname)); + fclose($fp); + + return $data; + } + + private function make_thumb($inname, $outname) { + global $config; + + $ok = false; + + switch($config->get_string("thumb_engine")) { + default: + case 'gd': + $ok = $this->make_thumb_gd($inname, $outname); + break; + case 'convert': + $ok = $this->make_thumb_convert($inname, $outname); + break; + } + + return $ok; + } + +// IM thumber {{{ + private function make_thumb_convert($inname, $outname) { + global $config; + + $w = $config->get_int("thumb_width"); + $h = $config->get_int("thumb_height"); + $q = $config->get_int("thumb_quality"); + + exec("convert $inname -geometry {$w}x{$h} -quality {$q} $outname"); + + return true; + } +// }}} +// GD thumber {{{ + private function make_thumb_gd($inname, $outname) { + global $config; + $thumb = $this->get_thumb($inname); + return imagejpeg($thumb, $outname, $config->get_int('thumb_quality')); + } + + private function get_memory_limit() { + global $config; + + // thumbnail generation requires lots of memory + $default_limit = 8*1024*1024; + $shimmie_limit = parse_shorthand_int($config->get_int("thumb_gd_mem_limit")); + if($shimmie_limit < 3*1024*1024) { + // we aren't going to fit, override + $shimmie_limit = $default_limit; + } + + ini_set("memory_limit", $shimmie_limit); + $memory = parse_shorthand_int(ini_get("memory_limit")); + + // changing of memory limit is disabled / failed + if($memory == -1) { + $memory = $default_limit; + } + + return $memory; + } + + private function get_thumb($tmpname) { + global $config; + + $info = getimagesize($tmpname); + $width = $info[0]; + $height = $info[1]; + + $max_width = $config->get_int('thumb_width'); + $max_height = $config->get_int('thumb_height'); + + $memory_use = (filesize($tmpname)*2) + ($width*$height*4) + (4*1024*1024); + $memory_limit = $this->get_memory_limit(); + + if($memory_use > $memory_limit) { + $thumb = imagecreatetruecolor($max_width, min($max_height, 64)); + $white = imagecolorallocate($thumb, 255, 255, 255); + $black = imagecolorallocate($thumb, 0, 0, 0); + imagefill($thumb, 0, 0, $white); + imagestring($thumb, 5, 10, 24, "Image Too Large :(", $black); + return $thumb; + } + else { + $image = imagecreatefromstring($this->read_file($tmpname)); + + $xscale = ($max_height / $height); + $yscale = ($max_width / $width); + $scale = ($xscale < $yscale) ? $xscale : $yscale; + + if($scale >= 1) { + $thumb = $image; + } + else { + $thumb = imagecreatetruecolor($width*$scale, $height*$scale); + imagecopyresampled( + $thumb, $image, 0, 0, 0, 0, + $width*$scale, $height*$scale, $width, $height + ); + } + return $thumb; + } + } +// }}} + + private function add_image($image) { + global $page; + global $user; + global $database; + global $config; + + /* + * Check for an existing image + */ + if($row = $this->is_dupe($image->hash)) { + $iid = $row['id']; + $page->add_main_block(new Block( + "Error uploading {$image->filename}", + "Image $iid ". + "already has hash {$image->hash}")); + return false; + } + + // actually insert the info + $database->db->Execute( + "INSERT INTO images(owner_id, owner_ip, filename, filesize, hash, ext, width, height, posted) ". + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, now())", + array($user->id, $_SERVER['REMOTE_ADDR'], $image->filename, $image->filesize, + $image->hash, $image->ext, $image->width, $image->height)); + $image->id = $database->db->Insert_ID(); + + /* + * If no errors: move the file from the temporary upload + * area to the main file store, create a thumbnail, and + * insert the image info into the database + */ + if(!copy($image->temp_filename, $image->get_image_filename())) { + $page->add_main_block(new Block("Error uploading {$image->filename}", + "The image couldn't be moved from the temporary area to the + main data store -- is the web server allowed to write to '". + ($image->get_image_filename())."'?")); + send_event(new ImageDeletionEvent($image->id)); + return false; + } + chmod($image->get_image_filename(), 0644); + + if(!$this->make_thumb($image->get_image_filename(), $image->get_thumb_filename())) { + $page->add_main_block(new Block("Error uploading {$image->filename}", + "The image thumbnail couldn't be generated -- is the web + server allowed to write to '".($image->get_thumb_filename())."'?")); + send_event(new ImageDeletionEvent($image->id)); + return false; + } + chmod($image->get_thumb_filename(), 0644); + + send_event(new TagSetEvent($image->id, $image->get_tag_array())); + + return true; + } +// }}} +// fetch image {{{ + private function send_file($image_id, $type) { + global $database; + $image = $database->get_image($image_id); + + global $page; + if(!is_null($image)) { + $page->set_mode("data"); + if($type == "thumb") { + $page->set_type("image/jpeg"); + $file = $image->get_thumb_filename(); + } + else { + $page->set_type($image->get_mime_type()); + $file = $image->get_image_filename(); + } + + $page->set_data(file_get_contents($file)); + + if(isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) { + $if_modified_since = preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]); + } + else { + $if_modified_since = ""; + } + $gmdate_mod = gmdate('D, d M Y H:i:s', filemtime($file)) . ' GMT'; + + // FIXME: should be $page->blah + if($if_modified_since == $gmdate_mod) { + header("HTTP/1.0 304 Not Modified"); + } + else { + header("Last-Modified: $gmdate_mod"); + header("Expires: Fri, 2 Sep 2101 12:42:42 GMT"); // War was beginning + } + } + else { + $page->set_title("Not Found"); + $page->set_heading("Not Found"); + $page->add_side_block(new Block("Navigation", "Index"), 0); + $page->add_main_block(new Block("Image not in database", + "The requested image was not found in the database")); + } + } +// }}} +// delete image {{{ + private function remove_image($image) { + global $database; + $database->remove_image($image->id); + + unlink($image->get_image_filename()); + unlink($image->get_thumb_filename()); + } +// }}} +} +add_event_listener(new ImageIO()); +?> diff --git a/core/ext/index.ext.php b/core/ext/index.ext.php new file mode 100644 index 00000000..958a1aad --- /dev/null +++ b/core/ext/index.ext.php @@ -0,0 +1,147 @@ +page == "index")) { + if($event->get_arg(0) == 'rss') { + $this->do_rss(); + } + else { + $search_terms = array(); + $page_number = 1; + + if($event->count_args() > 0) { + $page_number = int_escape($event->get_arg(0)); + } + + if(isset($_GET['search'])) { + $search_terms = explode(' ', $_GET['search']); + $query = "search=".html_escape($_GET['search']); + } + else { + $query = null; + } + + global $page; + global $config; + global $database; + + $total_pages = $database->count_pages($search_terms); + $count = $config->get_int('index_width') * $config->get_int('index_height'); + $images = $database->get_images(($page_number-1)*$count, $count, $search_terms); + + if(count($search_terms) == 0) { + $page_title = $config->get_string('title'); + } + else { + $page_title = html_escape($_GET['search']); + /* + $page_title = ""; + foreach($search_terms as $term) { + $h_term = html_escape($term); + $page_title .= "$h_term"; + } + */ + $page->set_subheading("Page $page_number / $total_pages"); + } + if($page_number > 1 || count($search_terms) > 0) { + // $page_title .= " / $page_number"; + } + + $page->set_title($page_title); + $page->set_heading($page_title); + $page->add_side_block(new Block("Navigation", $this->build_navigation($page_number, $total_pages, $search_terms)), 0); + $page->add_main_block(new Block("Images", $this->build_table($images, $query)), 10); + $page->add_main_block(new Paginator("index", $query, $page_number, $total_pages), 90); + } + } + + if(is_a($event, 'SetupBuildingEvent')) { + $sb = new SetupBlock("Index Options"); + + $sb->add_label("Index table size "); + $sb->add_int_option("index_width"); + $sb->add_label(" x "); + $sb->add_int_option("index_height"); + $sb->add_label(" images"); + + $sb->add_label("
Image tooltip "); + $sb->add_text_option("image_tip"); + + $event->panel->add_main_block($sb, 20); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_int("index_width", $_POST['index_width']); + $event->config->set_int("index_height", $_POST['index_height']); + $event->config->set_string("image_tip", $_POST['image_tip']); + } + } +// }}} +// HTML generation {{{ + private function build_navigation($page_number, $total_pages, $search_terms) { + $prev = $page_number - 1; + $next = $page_number + 1; + + $h_tags = html_escape(implode("%20", $search_terms)); + $query = empty($h_tags) ? null : "search=$h_tags"; + + + $h_prev = ($page_number <= 1) ? "Prev" : "Prev"; + $h_index = "Index"; + $h_next = ($page_number >= $total_pages) ? "Next" : "Next"; + + $h_search_string = count($search_terms) == 0 ? "Search" : html_escape(implode(" ", $search_terms)); + $h_search_link = make_link("index"); + $h_search = " +

+ + +
+
"; + + return "$h_prev | $h_index | $h_next
$h_search"; + } + + private function build_table($images, $query) { + global $config; + + $width = $config->get_int('index_width'); + $height = $config->get_int('index_height'); + + $table = "\n"; + for($i=0; $i<$height; $i++) { + $table .= "\n"; + for($j=0; $j<$width; $j++) { + $image = isset($images[$i*$width+$j]) ? $images[$i*$width+$j] : null; + if(!is_null($image)) { + $table .= $this->build_thumb($image, $query); + } + else { + $table .= "\t\n"; + } + } + $table .= "\n"; + } + $table .= "
 
\n"; + + return $table; + } + + private function build_thumb($image, $query=null) { + global $config; + $h_view_link = make_link("post/view/{$image->id}", $query); + $h_tip = html_escape($image->get_tooltip()); + $h_thumb_link = $image->get_thumb_link(); + return "$h_tip\n"; + } +// }}} +// rss {{{ + private function do_rss() { + // TODO: this function + } +// }}} +} +add_event_listener(new Index()); +?> diff --git a/core/ext/setup.ext.php b/core/ext/setup.ext.php new file mode 100644 index 00000000..ebc77d12 --- /dev/null +++ b/core/ext/setup.ext.php @@ -0,0 +1,216 @@ +panel = $panel; + } + + public function get_panel() { + return $this->panel; + } +} +// }}} +/* SetupPanel {{{ + * + */ +class SetupPanel extends Page { +} +// }}} +/* SetupBlock {{{ + * + */ +class SetupBlock extends Block { + var $header; + var $body; + + public function SetupBlock($title) { + $this->header = $title; + } + + public function add_label($text) { + $this->body .= $text; + } + public function add_text_option($name) { + global $config; + $val = $config->get_string($name); + $this->body .= "\n"; + } + public function add_longtext_option($name) { + global $config; + $val = $config->get_string($name); + $this->body .= "\n"; + $this->body .= "\n"; // setup page auto-layout counts
tags + } + public function add_bool_option($name) { + global $config; + $checked = $config->get_bool($name) ? " checked" : ""; + $this->body .= "\n"; + } + public function add_hidden_option($name) { + global $config; + $val = $config->get_string($name); + $this->body .= ""; + } + public function add_int_option($name) { + global $config; + $val = $config->get_string($name); + $this->body .= "\n"; + } + public function add_shorthand_int_option($name) { + global $config; + $val = to_shorthand_int($config->get_string($name)); + $this->body .= "\n"; + } + public function add_choice_option($name, $options) { + global $config; + $current = $config->get_string($name); + + $html = ""; + + $this->body .= $html; + } +} +// }}} + +class Setup extends Extension { +// event handling {{{ + public function receive_event($event) { + if(is_a($event, 'PageRequestEvent') && ($event->page == "setup")) { + global $user; + if(!$user->is_admin()) { + global $page; + $page->set_title("Error"); + $page->set_heading("Error"); + $page->add_side_block(new NavBlock(), 0); + $page->add_main_block(new Block("Permission Denied", "This page is for admins only"), 0); + } + else { + if($event->get_arg(0) == "save") { + global $config; + send_event(new ConfigSaveEvent($config)); + $config->save(); + + global $page; + $page->set_mode("redirect"); + $page->set_redirect(make_link("setup")); + } + else { + $panel = new SetupPanel(); + send_event(new SetupBuildingEvent($panel)); + $this->build_page($panel); + } + } + } + + if(is_a($event, 'SetupBuildingEvent')) { + $themes = array(); + foreach(glob("themes/*") as $theme_dirname) { + $name = str_replace("themes/", "", $theme_dirname); + $themes[ucfirst($name)] = $name; + } + + $sb = new SetupBlock("General"); + $sb->add_label("Site title: "); + $sb->add_text_option("title"); + $sb->add_label("
Base URL: "); + $sb->add_text_option("base_href"); + $sb->add_label("
Data URL: "); + $sb->add_text_option("data_href"); + $sb->add_label("
Contact URL: "); + $sb->add_text_option("contact_link"); + $sb->add_label("
Theme: "); + $sb->add_choice_option("theme", $themes); + // $sb->add_label("
Anonymous ID: "); + // $sb->add_int_option("anon_id", 0, 100000); + $sb->add_hidden_option("anon_id"); + $event->panel->add_main_block($sb, 0); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_string("title", $_POST['title']); + $event->config->set_string("base_href", $_POST['base_href']); + $event->config->set_string("data_href", $_POST['data_href']); + $event->config->set_string("contact_link", $_POST['contact_link']); + $event->config->set_string("theme", $_POST['theme']); + $event->config->set_int("anon_id", $_POST['anon_id']); + } + } +// }}} +// HTML building {{{ + private function build_page($panel) { + $setupblock_html1 = ""; + $setupblock_html2 = ""; + + ksort($panel->mainblocks); + + /* + $flip = true; + foreach($panel->mainblocks as $block) { + if(is_a($block, 'SetupBlock')) { + if($flip) $setupblock_html1 .= $this->sb_to_html($block); + else $setupblock_html2 .= $this->sb_to_html($block); + $flip = !$flip; + } + } + */ + + /* + * Try and keep the two columns even; count the line breaks in + * each an calculate where a block would work best + */ + $len1 = 0; + $len2 = 0; + foreach($panel->mainblocks as $block) { + if(is_a($block, 'SetupBlock')) { + $html = $this->sb_to_html($block); + $len = count(explode("
", $html)); + if($len1 <= $len2) { + $setupblock_html1 .= $this->sb_to_html($block); + $len1 += $len; + } + else { + $setupblock_html2 .= $this->sb_to_html($block); + $len2 += $len; + } + } + } + + $table = " +
+ + +
$setupblock_html1$setupblock_html2
+ "; + + global $page; + $page->set_title("Shimmie Setup"); + $page->set_heading("Shimmie Setup"); + $page->add_side_block(new Block("Navigation", $this->build_navigation()), 0); + $page->add_main_block(new Block("Setup", $table)); + } + + private function build_navigation() { + return " + Index +
Help + "; + } + + private function sb_to_html($block) { + return "
{$block->header}
{$block->body}
\n"; + } +// }}} +} +add_event_listener(new Setup()); +?> diff --git a/core/ext/tag_edit.ext.php b/core/ext/tag_edit.ext.php new file mode 100644 index 00000000..85161a85 --- /dev/null +++ b/core/ext/tag_edit.ext.php @@ -0,0 +1,97 @@ +page == "tags")) { + global $page; + if($event->get_arg(0) == "set") { + global $database; + $i_image_id = int_escape($_POST['image_id']); + $query = $_POST['query']; + $database->set_tags($i_image_id, $_POST['tags']); + $page->set_mode("redirect"); + $page->set_redirect(make_link("post/view/$i_image_id", $query)); + } + else if($event->get_arg(0) == "replace") { + global $user; + if($user->is_admin() && isset($_POST['search']) && isset($_POST['replace'])) { + global $page; + $this->mass_tag_edit($_POST['search'], $_POST['replace']); + $page->set_mode("redirect"); + $page->set_redirect(make_link("admin")); + } + } + } + + if(is_a($event, 'DisplayingImageEvent')) { + global $page; + $page->add_main_block(new Block(null, $this->build_tag_editor($event->image)), 5); + } + + if(is_a($event, 'TagSetEvent')) { + global $database; + $database->set_tags($event->image_id, $event->tags); + } + + if(is_a($event, 'ImageDeletionEvent')) { + global $database; + $database->delete_tags_from_image($event->image->id); + } + + if(is_a($event, 'AdminBuildingEvent')) { + global $page; + $page->add_main_block(new Block("Mass Tag Edit", $this->build_mass_tag_edit())); + } + + // When an alias is added, oldtag becomes inaccessable + if(is_a($event, 'AddAliasEvent')) { + $this->mass_tag_edit($event->oldtag, $event->newtag); + } + } +// }}} +// edit {{{ + private function mass_tag_edit($search, $replace) { + // FIXME: deal with collisions + global $database; + $database->db->Execute("UPDATE tags SET tag=? WHERE tag=?", Array($replace, $search)); + } +// }}} +// HTML {{{ + private function build_tag_editor($image) { + global $database; + + if(isset($_GET['search'])) { + $h_query = "search=".html_escape($_GET['search']); + } + else { + $h_query = ""; + } + + $h_tags = html_escape($image->get_tag_list()); + $i_image_id = int_escape($image->id); + + return " +

+ + + + +
+ "; + } + private function build_mass_tag_edit() { + return " +
+ + + + +
Search
Replace
+
+ "; + } +// }}} +} +add_event_listener(new TagEdit()); +?> diff --git a/core/ext/upload.ext.php b/core/ext/upload.ext.php new file mode 100644 index 00000000..f85f0505 --- /dev/null +++ b/core/ext/upload.ext.php @@ -0,0 +1,131 @@ +page == "index")) { + if($this->can_upload()) { + $page->add_side_block(new Block("Upload", $this->build_upload_block()), 20); + } + } + if(is_a($event, 'PageRequestEvent') && ($event->page == "upload")) { + if($this->can_upload()) { + global $config; + global $page; + + $ok = true; + foreach($_FILES as $file) { + $ok = $ok & $this->try_upload($file); + } + + $this->show_result($ok); + } + else { + $page->set_title("Upload Denied"); + $page->set_heading("Upload Denied"); + $page->add_side_block(new NavBlock()); + $page->add_main_block(new Block("Error", "Anonymous posting is disabled")); + } + } + + if(is_a($event, 'SetupBuildingEvent')) { + $sb = new SetupBlock("Upload"); + $sb->add_label("Max Uploads: "); + $sb->add_int_option("upload_count"); + $sb->add_label("
Max size per file: "); + $sb->add_shorthand_int_option("upload_size"); + $sb->add_label("
Allow anonymous upoads: "); + $sb->add_bool_option("upload_anon"); + $event->panel->add_main_block($sb, 10); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_int("upload_count", $_POST['upload_count']); + $event->config->set_int("upload_size", $_POST['upload_size']); + $event->config->set_bool("upload_anon", $_POST['upload_anon']); + } + } +// }}} +// do things {{{ + private function can_upload() { + global $config, $user; + return $config->get_bool("upload_anon") || ($user->id != $config->get_int("anon_id")); + } + + private function try_upload($file) { + global $page; + global $config; + + $ok = false; + + if(!file_exists($file['tmp_name'])) { + // this happens normally with blank file boxes + } + else if(filesize($file['tmp_name']) > $config->get_int('upload_size')) { + $page->add_main_block(new Block("Error with ".html_escape($file['name']), + "File too large (".filesize($file['tmp_name'])." > ". + ($config->get_int('upload_size')).")")); + } + else if(!($info = getimagesize($file['tmp_name']))) { + $page->add_main_block(new Block("Error with ".html_escape($file['name']), + "PHP doesn't recognise this as an image file")); + } + else { + $image = new Image($file['tmp_name'], $file['name'], $_POST['tags']); + + if($image->is_ok()) { + send_event(new UploadingImageEvent($image)); + $ok = true; + } + else { + $page->add_main_block(new Block("Error with ".html_escape($file['name']), + "Something is not right!")); + } + } + + return $ok; + } + + private function show_result($ok) { + global $page; + + if($ok) { + $page->set_mode("redirect"); + $page->set_redirect(make_link("index")); + } + else { + $page->set_title("Upload Status"); + $page->set_heading("Upload Status"); + $page->add_side_block(new NavBlock()); + $page->add_main_block(new Block("OK?", + "If there are no errors here, things should be OK \\o/")); + } + } +// }}} +// HTML {{{ + private function build_upload_block() { + global $config; + + $upload_list = ""; + for($i=0; $i<$config->get_int('upload_count'); $i++) { + if($i == 0) $style = ""; // "style='display:visible'"; + else $style = "style='display:none'"; + $upload_list .= "\n"; + } + $max_size = $config->get_int('upload_size'); + $max_kb = (int)($max_size / 1024); + // + return " +
+ $upload_list + + +
+
(Max file size is {$max_kb}KB)
+ "; + } +// }}} +} +add_event_listener(new Upload()); +?> diff --git a/core/ext/user.ext.php b/core/ext/user.ext.php new file mode 100644 index 00000000..087a7a6e --- /dev/null +++ b/core/ext/user.ext.php @@ -0,0 +1,401 @@ +page == "user")) { + global $page; + global $user; + global $database; + global $config; + + if($event->get_arg(0) == "login") { + if(isset($_POST['user']) && isset($_POST['pass'])) { + $this->login(); + } + else { + $page->set_title("Login"); + $page->set_heading("Login"); + $page->add_side_block(new NavBlock()); + $page->add_main_block(new Block("Login There", + "There should be a login box to the left")); + } + } + else if($event->get_arg(0) == "logout") { + setcookie("shm_session", "", time()+60*60*24*$config->get_int('login_memory'), "/"); + $page->set_mode("redirect"); + $page->set_redirect(make_link("index")); + } + else if($event->get_arg(0) == "changepass") { + $this->change_password_wrapper(); + } + else if($event->get_arg(0) == "create") { + $this->create_user_wrapper(); + } + else if($event->get_arg(0) == "set_more") { + $this->set_more_wrapper(); + } + else { // view + $duser = ($event->count_args() == 0) ? $user : $database->get_user_by_name($event->get_arg(0)); + $this->build_user_page($duser); + } + } + + // user info is shown on all pages + if(is_a($event, 'PageRequestEvent')) { + global $user; + global $page; + + if($user->is_anonymous()) { + $page->add_side_block(new Block("Login", $this->build_login_block()), 90); + } + else { + $page->add_side_block(new Block("User Links", $this->build_links_block()), 90); + } + } + + if(is_a($event, 'SetupBuildingEvent')) { + $sb = new SetupBlock("User Options"); + $sb->add_label("Login memory: "); + $sb->add_int_option("login_memory"); + $sb->add_label(" days"); + $sb->add_label("
Allow new signups: "); + $sb->add_bool_option("login_signup_enabled"); + $sb->add_label("
Terms & Conditions:
"); + $sb->add_longtext_option("login_tac"); + $event->panel->add_main_block($sb); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_int("login_memory", $_POST['login_memory']); + $event->config->set_bool("login_signup_enabled", $_POST['login_signup_enabled']); + $event->config->set_string("login_tac", $_POST['login_tac']); + } + } +// }}} +// Things done *with* the user {{{ + private function login() { + global $page; + global $database; + global $config; + global $user; + + $name = $_POST['user']; + $pass = $_POST['pass']; + $addr = $_SERVER['REMOTE_ADDR']; + $hash = md5( strtolower($name) . $pass ); + + $duser = $database->get_user($name, $hash); + if(!is_null($duser)) { + $user = $duser; + + setcookie( + "shm_user", $name, + time()+60*60*24*365, "/" + ); + setcookie( + "shm_session", md5($hash.$addr), + time()+60*60*24*$config->get_int('login_memory'), "/" + ); + + $page->set_mode("redirect"); + $page->set_redirect(make_link("user")); + } + else { + $page->set_title("Permission Denied"); + $page->set_heading("Permission Denied"); + $page->add_side_block(new NavBlock(), 0); + $page->add_main_block(new Block("Error", "No user with those details was found")); + } + } + + private function create_user_wrapper() { + global $page; + global $database; + global $config; + + if(!$config->get_bool("login_signup_enabled")) { + $page->set_title("Signups Disabled"); + $page->set_heading("Signups Disabled"); + $page->add_side_block(new NavBlock()); + $page->add_main_block(new Block("Signups Disabled", + "The board admin has disabled the ability to create new accounts~")); + } + else if(isset($_POST['name']) && isset($_POST['pass1']) && isset($_POST['pass2'])) { + $name = trim($_POST['name']); + $pass1 = $_POST['pass1']; + $pass2 = $_POST['pass2']; + + $page->set_title("Error"); + $page->set_heading("Error"); + $page->add_side_block(new NavBlock()); + if(strlen($name) < 1) { + $page->add_main_block(new Block("Error", "Username must be at least 1 character")); + } + else if($pass1 != $pass2) { + $page->add_main_block(new Block("Error", "Passwords don't match")); + } + else if($database->db->GetRow("SELECT * FROM users WHERE name = ?", array($name))) { + $page->add_main_block(new Block("Error", "That username is already taken")); + } + else { + $addr = $_SERVER['REMOTE_ADDR']; + $hash = md5( strtolower($name) . $pass1 ); + $email = isset($_POST['email']) ? $_POST['email'] : null; + + // FIXME: send_event() + $database->db->Execute( + "INSERT INTO users (name, pass, joindate, email) VALUES (?, ?, now(), ?)", + array($name, $hash, $email)); + + setcookie("shm_user", $name, + time()+60*60*24*365, '/'); + setcookie("shm_session", md5($hash.$addr), + time()+60*60*24*$config->get_int('login_memory'), '/'); + $page->set_mode("redirect"); + $page->set_redirect(make_link("user")); + } + } + else { + $page->set_title("Create Account"); + $page->set_heading("Create Account"); + $page->add_side_block(new NavBlock()); + $page->add_main_block(new Block("Signup", $this->build_signup_form())); + } + } +//}}} +// Things do ne *to* the user {{{ + private function change_password_wrapper() { + global $user; + global $page; + global $database; + + $page->set_title("Error"); + $page->set_heading("Error"); + $page->add_side_block(new NavBlock()); + if($user->is_anonymous()) { + $page->add_main_block(new Block("Error", "You aren't logged in")); + } + else if(isset($_POST['id']) && isset($_POST['name']) && + isset($_POST['pass1']) && isset($_POST['pass2'])) { + $name = $_POST['name']; + $id = $_POST['id']; + $pass1 = $_POST['pass1']; + $pass2 = $_POST['pass2']; + + if((!$user->is_admin()) && ($name != $user->name)) { + $page->add_main_block(new Block("Error", + "You need to be an admin to change other people's passwords")); + } + else if($pass1 != $pass2) { + $page->add_main_block(new Block("Error", "Passwords don't match")); + } + else { + global $config; + $addr = $_SERVER['REMOTE_ADDR']; + $hash = md5( strtolower($name) . $pass1 ); + + // FIXME: send_event() + // FIXME: $duser->set_pass(); + $database->db->Execute( + "UPDATE users SET pass = ? WHERE id = ?", + array($hash, $id)); + + if($id == $user->id) { + setcookie("shm_user", $name, + time()+60*60*24*365, '/'); + setcookie("shm_session", md5($hash.$addr), + time()+60*60*24*$config->get_int('login_memory'), '/'); + $page->set_mode("redirect"); + $page->set_redirect(make_link("user")); + } + else { + $page->set_mode("redirect"); + $page->set_redirect(make_link("user/{$user->name}")); + } + } + } + } + + private function set_more_wrapper() { + global $page; + global $user; + global $database; + + $page->set_title("Error"); + $page->set_heading("Error"); + $page->add_side_block(new NavBlock()); + if(!$user->is_admin()) { + $page->add_main_block(new Block("Not Admin", "Only admins can edit accounts")); + } + else if(!isset($_POST['id']) || !is_numeric($_POST['id'])) { + $page->add_main_block(new Block("No ID Specified", + "You need to specify the account number to edit")); + } + else { + $admin = (isset($_POST['admin']) && ($_POST['admin'] == "on")); + $enabled = (isset($_POST['enabled']) && ($_POST['enabled'] == "on")); + + $duser = $database->get_user_by_id($_POST['id']); + $duser->set_admin($admin); + $duser->set_enabled($enabled); + + $page->set_mode("redirect"); + if($duser->id == $user->id) { + $page->set_redirect(make_link("user")); + } + else { + $page->set_redirect(make_link("user/{$duser->name}")); + } + } + } +// }}} +// HTML building {{{ + private function build_signup_form() { + global $config; + $tac = $config->get_string("login_tac"); + + if(empty($tac)) { + $html = ""; + } + else { + $html = "

$tac

"; + } + $html .= " +
+ + + + + + +
Name
Password
Repeat Password
Email (Optional)
+
+ "; + return $html; + } + + private function build_user_page($duser) { + global $page; + global $user; + if(!is_null($duser)) { + $page->set_title("{$duser->name}'s Page"); + $page->set_heading("{$duser->name}'s Page"); + $page->add_side_block(new NavBlock(), 0); + $page->add_main_block(new Block("Stats", $this->build_stats($duser))); + + if(!$user->is_anonymous()) { + if($user->id == $duser->id || $user->is_admin()) { + $page->add_main_block(new Block("Options", $this->build_options($duser))); + } + if($user->is_admin()) { + $page->add_main_block(new Block("More Options", $this->build_more_options($duser))); + } + } + } + else { + $page->set_title("No Such User"); + $page->set_heading("No Such User"); + $page->add_side_block(new NavBlock(), 0); + $page->add_main_block(new Block("No User By That ID", + "If you typed the ID by hand, try again; if you came from a link on this ". + "site, it might be bug report time...")); + } + } + + private function build_stats($duser) { + global $database; + global $config; + + $i_days_old = int_escape($duser->get_days_old()); + $h_join_date = html_escape($duser->join_date); + $i_image_count = int_escape($duser->get_image_count()); + $i_comment_count = int_escape($duser->get_comment_count()); + + $i_days_old2 = ($i_days_old == 0) ? 1 : $i_days_old; + + $h_image_rate = sprintf("%3.1f", ($i_image_count / $i_days_old2)); + $h_comment_rate = sprintf("%3.1f", ($i_comment_count / $i_days_old2)); + + return " + Join date: $h_join_date ($i_days_old days old) +
Images uploaded: $i_image_count ($h_image_rate / day) +
Comments made: $i_comment_count ($h_comment_rate / day) + "; + } + + private function build_options($duser) { + global $database; + global $config; + + $html = ""; + $html .= " +
+ + + + + + + +
Change Password
Password
Repeat Password
+
+ "; + return $html; + } + + private function build_more_options($duser) { + global $database; + global $config; + + $i_user_id = int_escape($duser->id); + $h_is_admin = $duser->is_admin() ? " checked" : ""; + $h_is_enabled = $duser->is_enabled() ? " checked" : ""; + + $html = " +
+ + Admin: +
Enabled: +

+

+ "; + return $html; + } + + private function build_links_block() { + global $user; + + $h_name = html_escape($user->name); + $html = "Logged in as $h_name"; + if($user->is_admin()) { + $html .= "
Board Config"; + $html .= "
Admin"; + } + $html .= "
User Config"; + $html .= "
Log Out"; + return $html; + } + + private function build_login_block() { + global $config; + $html = " +
+ + + + +
Name
Password
+
+ "; + if($config->get_bool("login_signup_enabled")) { + $html .= "Create Account"; + } + else { + $html .= "Account creation disabled"; + } + return $html; + } +// }}} +} +add_event_listener(new UserPage()); +?> diff --git a/core/ext/view.ext.php b/core/ext/view.ext.php new file mode 100644 index 00000000..d883be21 --- /dev/null +++ b/core/ext/view.ext.php @@ -0,0 +1,124 @@ +page == "post") && ($event->get_arg(0) == "view")) { + $image_id = int_escape($event->get_arg(1)); + + global $database; + $image = $database->get_image($image_id); + + if(!is_null($image)) { + send_event(new DisplayingImageEvent($image)); + } + else { + global $page; + $page->set_title("Image not found"); + $page->set_heading("Image not found"); + $page->add_side_block(new NavBlock(), 0); + $page->add_main_block(new Block("Image not found", + "No image in the database has the ID #$image_id"), 0); + } + } + + if(is_a($event, 'DisplayingImageEvent')) { + $image = $event->get_image(); + + global $page; + $page->set_title("Image {$image->id}: ".$image->get_tag_list()); + $page->set_heading($image->get_tag_list()); + $page->add_side_block(new Block("Navigation", $this->build_navigation($image->id)), 0); + $page->add_main_block(new Block("Image", $this->build_image_view($image)), 0); + $page->add_main_block(new Block(null, $this->build_info($image)), 10); + } + + if(is_a($event, 'SetupBuildingEvent')) { + $sb = new SetupBlock("View Options"); + $sb->add_label("Long link "); + $sb->add_text_option("image_ilink"); + $sb->add_label("
Short link "); + $sb->add_text_option("image_slink"); + $sb->add_label("
Thumbnail link "); + $sb->add_text_option("image_tlink"); + //$sb->add_label("
Zoom by default"); + //$sb->add_bool_option("view_scale"); + $event->panel->add_main_block($sb, 30); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_string("image_ilink", $_POST['image_ilink']); + $event->config->set_string("image_slink", $_POST['image_slink']); + $event->config->set_string("image_tlink", $_POST['image_tlink']); + //$event->config->set_bool("view_scale", $_POST['view_scale']); + } + } +// }}} +// HTML {{{ + var $pin = null; + + private function build_pin($image_id) { + if(!is_null($this->pin)) { + return $this->pin; + } + + global $database; + + // $next_img = $database->db->GetOne("SELECT id FROM images WHERE id < ? ORDER BY id DESC", array($image_id)); + // $prev_img = $database->db->GetOne("SELECT id FROM images WHERE id > ? ORDER BY id ASC ", array($image_id)); + if(isset($_GET['search'])) { + $search_terms = explode(' ', $_GET['search']); + $query = "search=".html_escape($_GET['search']); + } + else { + $search_terms = array(); + $query = null; + } + + $next = $database->get_next_image($image_id, $search_terms); + $prev = $database->get_prev_image($image_id, $search_terms); + + $h_prev = (!is_null($prev) ? "Prev" : "Prev"); + $h_index = "Index"; + $h_next = (!is_null($next) ? "Next" : "Next"); + + $this->pin = "$h_prev | $h_index | $h_next"; + return $this->pin; + } + + private function build_navigation($image_id) { + $h_pin = $this->build_pin($image_id); + $h_search = " +

+ + +
+
"; + + return "$h_pin
$h_search"; + } + + private function build_image_view($image) { + $ilink = $image->get_image_link(); + return ""; + } + + private function build_info($image) { + $owner = $image->get_owner(); + $h_owner = html_escape($owner->name); + $i_owner_id = int_escape($owner->id); + + $html = ""; + if(strlen($image->get_short_link()) > 0) { + $slink = $image->get_short_link(); + $html .= "

Link: "; + } + $html .= "

Uploaded by $h_owner"; + $html .= "

".$this->build_pin($image->id); + + return $html; + } +// }}} +} +add_event_listener(new ViewImage()); +?> diff --git a/core/extension.class.php b/core/extension.class.php new file mode 100644 index 00000000..be7d23c2 --- /dev/null +++ b/core/extension.class.php @@ -0,0 +1,5 @@ + diff --git a/core/image.class.php b/core/image.class.php new file mode 100644 index 00000000..ed77c92b --- /dev/null +++ b/core/image.class.php @@ -0,0 +1,162 @@ +create_from_row($a); + } + else { + $this->create_from_data($a, $b, $c); + } + } + + private function create_from_row($row) { + $this->id = $row['id']; + $this->owner_id = $row['owner_id']; + $this->filename = $row['filename']; + $this->filesize = $row['filesize']; + $this->hash = $row['hash']; + $this->ext = $row['ext']; + $this->width = $row['width']; + $this->height = $row['height']; + } + + private function mime_to_ext($mime) { + switch($mime) { + default: + case 'image/jpeg': return "jpg"; break; + case 'image/png': return "png"; break; + case 'image/gif': return "gif"; break; + } + } + + private function create_from_data($tmp, $filename, $tags) { + global $config; + + $this->ok = false; + $info = ""; + + if(!file_exists($tmp)) return; + if(filesize($tmp) > $config->get_int('upload_size')) return; + if(!($info = getimagesize($tmp))) return; + + $this->width = $info[0]; + $this->height = $info[1]; + $this->mime_type = $info['mime']; + $this->filename = str_replace("/", "_", $filename); // is this even possible? + $this->filesize = filesize($tmp); + $this->ext = $this->mime_to_ext($info['mime']); + $this->hash = md5_file($tmp); + $this->temp_filename = $tmp; + + $this->tag_array = tag_explode($tags); + + $this->ok = true; + } + + public function is_ok() { + return $this->ok; + } + + public function get_owner() { + global $database; + return $database->get_user($this->owner_id); + } + + public function get_tag_array() { + if(!isset($this->tag_array)) { + global $database; + $this->tag_array = Array(); + $row = $database->db->Execute("SELECT * FROM tags WHERE image_id=?", array($this->id)); + while(!$row->EOF) { + $this->tag_array[] = $row->fields['tag']; + $row->MoveNext(); + } + } + return $this->tag_array; + } + + public function get_tag_list() { + return implode(' ', $this->get_tag_array()); + } + + public function get_image_link() { + global $config; + return $this->parse_link_template($config->get_string('image_ilink'), $this); + } + + public function get_short_link() { + global $config; + return $this->parse_link_template($config->get_string('image_slink'), $this); + } + + public function get_thumb_link() { + global $config; + return $this->parse_link_template($config->get_string('image_tlink'), $this); + } + + public function get_tooltip() { + global $config; + return $this->parse_link_template($config->get_string('image_tip'), $this); + } + + public function get_image_filename() { + global $config; + $hash = $this->hash; + $ab = substr($hash, 0, 2); + $ext = $this->ext; + return "images/$ab/$hash"; + } + + public function get_thumb_filename() { + global $config; + $hash = $this->hash; + $ab = substr($hash, 0, 2); + return "thumbs/$ab/$hash"; + } + + public function get_filename() { + return $this->filename; + } + + public function get_mime_type() { + return "image/".($this->ext); + } + + public function get_ext() { + return $this->ext; + } + + private function parse_link_template($tmpl, $img) { + global $config; + + // don't bother hitting the database if it won't be used... + $safe_tags = ""; + if(strpos($tmpl, '$tags') !== false) { // * stabs dynamically typed languages with a rusty spoon * + $safe_tags = preg_replace( + "/[^a-zA-Z0-9_\- ]/", + "", $img->get_tag_list()); + } + + $base_href = $config->get_string('base_href'); + $fname = $img->get_filename(); + $base_fname = strpos($fname, '.') ? substr($fname, 0, strrpos($fname, '.')) : $fname; + + $tmpl = str_replace('$id', $img->id, $tmpl); + $tmpl = str_replace('$hash', $img->hash, $tmpl); + $tmpl = str_replace('$tags', $safe_tags, $tmpl); + $tmpl = str_replace('$base', $base_href, $tmpl); + $tmpl = str_replace('$ext', $img->ext, $tmpl); + $tmpl = str_replace('$size', "{$img->width}x{$img->height}", $tmpl); + $tmpl = str_replace('$filesize', to_shorthand_int($img->filesize), $tmpl); + $tmpl = str_replace('$filename', $base_fname, $tmpl); + + return $tmpl; + } +} +?> diff --git a/core/navblock.class.php b/core/navblock.class.php new file mode 100644 index 00000000..38be5693 --- /dev/null +++ b/core/navblock.class.php @@ -0,0 +1,11 @@ +header = "Navigation"; + $this->body = "Index"; + } +} +?> diff --git a/core/page.class.php b/core/page.class.php new file mode 100644 index 00000000..d51f9c9d --- /dev/null +++ b/core/page.class.php @@ -0,0 +1,95 @@ +mode = $mode; + } + + public function set_type($type) { + $this->type = $type; + } + + + // ============================================== + + // data + var $data = ""; + + public function set_data($data) { + $this->data = $data; + } + + + // ============================================== + + // redirect + var $redirect = ""; + + public function set_redirect($redirect) { + $this->redirect = $redirect; + } + + + // ============================================== + + // page + var $title = ""; + var $heading = ""; + var $subheading = ""; + var $quicknav = ""; + var $sideblocks = array(); + var $mainblocks = array(); + + public function set_title($title) { + $this->title = $title; + } + + public function set_heading($heading) { + $this->heading = $heading; + } + + public function set_subheading($subheading) { + $this->subheading = $subheading; + } + + public function add_side_block($block, $position=50) { + while(isset($this->sideblocks[$position])) $position++; + $this->sideblocks[$position] = $block; + } + + public function add_main_block($block, $position=50) { + while(isset($this->mainblocks[$position])) $position++; + $this->mainblocks[$position] = $block; + } + + // ============================================== + + public function display() { + global $config; + + header("Content-type: {$this->type}"); + + switch($this->mode) { + case "page": + header("Cache-control: no-cache"); + ksort($this->sideblocks); + ksort($this->mainblocks); + $theme = $config->get_string("theme"); + require_once "themes/$theme/default.php"; + break; + case "data": + print $this->data; + break; + case "redirect": + header("Location: {$this->redirect}"); + print "You should be redirected to {$this->redirect}"; + break; + default: + print "Invalid page mode"; + break; + } + } +} +?> diff --git a/core/paginator.class.php b/core/paginator.class.php new file mode 100644 index 00000000..f1974290 --- /dev/null +++ b/core/paginator.class.php @@ -0,0 +1,50 @@ +body = $this->build_paginator($page_number, $total_pages, $page, $query); + } + + private function gen_page_link($base_url, $query, $page, $name) { + $link = make_link("$base_url/$page", $query); + return "$name"; + } + + private function gen_page_link_block($base_url, $query, $page, $current_page, $name) { + $paginator = ""; + if($page == $current_page) $paginator .= ""; + $paginator .= $this->gen_page_link($base_url, $query, $page, $name); + if($page == $current_page) $paginator .= ""; + return $paginator; + } + + private function build_paginator($current_page, $total_pages, $base_url, $query) { + $next = $current_page + 1; + $prev = $current_page - 1; + $rand = rand(1, $total_pages); + + $at_start = ($current_page <= 1 || $total_pages <= 1); + $at_end = ($current_page >= $total_pages); + + $first_html = $at_start ? "First" : $this->gen_page_link($base_url, $query, 1, "First"); + $prev_html = $at_start ? "Prev" : $this->gen_page_link($base_url, $query, $prev, "Prev"); + $random_html = $this->gen_page_link($base_url, $query, $rand, "Random"); + $next_html = $at_end ? "Next" : $this->gen_page_link($base_url, $query, $next, "Next"); + $last_html = $at_end ? "Last" : $this->gen_page_link($base_url, $query, $total_pages, "Last"); + + $start = $current_page-5 > 1 ? $current_page-5 : 1; + $end = $start+10 < $total_pages ? $start+10 : $total_pages; + + $pages = array(); + foreach(range($start, $end) as $i) { + $pages[] = $this->gen_page_link_block($base_url, $query, $i, $current_page, $i); + } + $pages_html = implode(" | ", $pages); + + return "

$first_html | $prev_html | $random_html | $next_html | $last_html". + "
<< $pages_html >>

"; + } +} diff --git a/core/user.class.php b/core/user.class.php new file mode 100644 index 00000000..4259d9e0 --- /dev/null +++ b/core/user.class.php @@ -0,0 +1,64 @@ +id = int_escape($row['id']); + $this->name = $row['name']; + $this->email = $row['email']; + $this->join_date = $row['joindate']; + $this->days_old = $row['days_old']; + $this->enabled = ($row['enabled'] == 'Y'); + $this->admin = ($row['admin'] == 'Y'); + } + + public function is_anonymous() { + global $config; + return ($this->id == $config->get_int('anon_id')); + } + + public function is_enabled() { + return $this->enabled; + } + + public function set_enabled($enabled) { + global $database; + + $yn = $enabled ? 'Y' : 'N'; + $database->db->Execute("UPDATE users SET enabled=? WHERE id=?", + array($yn, $this->id)); + } + + public function is_admin() { + return $this->admin; + } + + public function set_admin($admin) { + global $database; + + $yn = $admin ? 'Y' : 'N'; + $database->db->Execute("UPDATE users SET admin=? WHERE id=?", + array($yn, $this->id)); + } + + public function get_days_old() { + return $this->days_old; + } + + public function get_image_count() { + global $database; + return $database->db->GetOne("SELECT COUNT(*) AS count FROM images WHERE owner_id=?", $this->id); + } + + public function get_comment_count() { + global $database; + return $database->db->GetOne("SELECT COUNT(*) AS count FROM comments WHERE owner_id=?", $this->id); + } +} +?> diff --git a/core/util.inc.php b/core/util.inc.php new file mode 100644 index 00000000..f1cf1b64 --- /dev/null +++ b/core/util.inc.php @@ -0,0 +1,197 @@ +db->Quote($input); +} + +function make_link($page, $query=null) { + global $config; + $base = $config->get_string('base_href'); + + if(is_null($query)) { + return "$base/$page"; + } + else { + if(strpos($base, "?")) { + return "$base/$page&$query"; + } + else { + return "$base/$page?$query"; + } + } +} + +function parse_shorthand_int($limit) { + if(is_numeric($limit)) { + return (int)$limit; + } + + if(preg_match('/^([\d\.]+)([gmk])?b?$/i', "$limit", $m)) { + $value = $m[1]; + if (isset($m[2])) { + switch(strtolower($m[2])) { + case 'g': $value *= 1024; # fallthrough + case 'm': $value *= 1024; # fallthrough + case 'k': $value *= 1024; break; + default: $value = -1; + } + } + return (int)$value; + } else { + return -1; + } +} + +function to_shorthand_int($int) { + if($int >= pow(1024, 3)) { + return sprintf("%.1fGB", $int / pow(1024, 3)); + } + else if($int >= pow(1024, 2)) { + return sprintf("%.1fMB", $int / pow(1024, 2)); + } + else if($int >= 1024) { + return sprintf("%.1fKB", $int / 1024); + } + else { + return "$int"; + } +} + +function bbcode2html($text) { + $text = trim($text); + $text = html_escape($text); +# $text = preg_replace("/\[b\](.*?)\[\/b\]/s", "\\1", $text); +# $text = preg_replace("/\[i\](.*?)\[\/i\]/s", "\\1", $text); +# $text = preg_replace("/\[u\](.*?)\[\/u\]/s", "\\1", $text); + $text = str_replace("\n", "\n
", $text); + return $text; +} + +function tag_explode($tags) { + if(is_string($tags)) { + $tags = explode(' ', $tags); + } + else if(is_array($tags)) { + // do nothing + } + else { + die("tag_explode only takes strings or arrays"); + } + + $tags = array_map("trim", $tags); + + foreach($tags as $tag) { + if(is_string($tag) && strlen($tag) > 0) { + $tag_array[] = $tag; + } + } + + if(count($tag_array) == 0) { + $tag_array = array("tagme"); + } + + return $tag_array; +} + + + + + +# $db is the connection object +function CountExecs($db, $sql, $inputarray) { + global $_execs; +# $fp = fopen("sql.log", "a"); +# fwrite($fp, preg_replace('/\s+/msi', ' ', $sql)."\n"); +# fclose($fp); + if (!is_array($inputarray)) $_execs++; + # handle 2-dimensional input arrays + else if (is_array(reset($inputarray))) $_execs += sizeof($inputarray); + else $_execs++; + # in PHP4.4 and PHP5, we need to return a value by reference + $null = null; return $null; +} + + +// internal things + +$_event_listeners = array(); + +function add_event_listener($block, $pos=50) { + global $_event_listeners; + while(isset($_event_listeners[$pos])) { + $pos++; + } + $_event_listeners[$pos] = $block; +} + +function send_event($event) { + global $_event_listeners; + foreach($_event_listeners as $listener) { + $listener->receive_event($event); + } +} + + +function _get_query_parts() { + if(isset($_GET["q"])) { + $path = $_GET["q"]; + } + else if(isset($_SERVER["PATH_INFO"])) { + $path = $_SERVER["PATH_INFO"]; + } + else { + $path = "index/1"; + } + + while(strlen($path) > 0 && $path[0] == '/') { + $path = substr($path, 1); + } + + return split('/', $path); +} +function get_page_request() { + $args = _get_query_parts(); + + if(count($args) == 0) { + $page = "index"; + $args = array(); + } + else if(count($args) == 1) { + $page = (strlen($args[0]) > 0 ? $args[0] : "index"); + $args = array(); + } + else { + $page = $args[0]; + $args = array_slice($args, 1); + } + + return new PageRequestEvent($page, $args); +} + +function get_user() { + global $database; + global $config; + + $user = null; + if(isset($_COOKIE["shm_user"]) && isset($_COOKIE["shm_session"])) { + $tmp_user = $database->get_user_session($_COOKIE["shm_user"], $_COOKIE["shm_session"]); + if(!is_null($tmp_user) && $tmp_user->is_enabled()) { + $user = $tmp_user; + } + + } + if(is_null($user)) { + $user = $database->get_user($config->get_int("anon_id")); + } + return $user; +} + +?> diff --git a/ext/alias_editor.ext.php b/ext/alias_editor.ext.php new file mode 100644 index 00000000..91883579 --- /dev/null +++ b/ext/alias_editor.ext.php @@ -0,0 +1,91 @@ +oldtag = $oldtag; + $this->newtag = $newtag; + } +} + +class AliasEditor extends Extension { +// event handler {{{ + public function receive_event($event) { + if(is_a($event, 'PageRequestEvent') && ($event->page == "alias")) { + global $user; + if($user->is_admin()) { + if($event->get_arg(0) == "add") { + if(isset($_POST['oldtag']) && isset($_POST['newtag'])) { + send_event(new AddAliasEvent($_POST['oldtag'], $_POST['newtag'])); + } + } + else if($event->get_arg(0) == "remove") { + if(isset($_POST['oldtag'])) { + global $database; + $database->db->Execute("DELETE FROM aliases WHERE oldtag=?", array($_POST['oldtag'])); + + global $page; + $page->set_mode("redirect"); + $page->set_redirect(make_link("admin")); + } + } + } + } + + if(is_a($event, 'AdminBuildingEvent')) { + global $page; + $page->add_main_block(new Block("Edit Aliases", $this->build_aliases())); + } + + if(is_a($event, 'AddAliasEvent')) { + global $database; + $database->db->Execute("INSERT INTO aliases(oldtag, newtag) VALUES(?, ?)", array($event->oldtag, $event->newtag)); + + global $page; + $page->set_mode("redirect"); + $page->set_redirect(make_link("admin")); + } + } +// }}} +// admin page HTML {{{ + private function build_aliases() { + global $database; + $h_aliases = ""; + $aliases = $database->db->GetAssoc("SELECT oldtag, newtag FROM aliases"); + foreach($aliases as $old => $new) { + $h_old = html_escape($old); + $h_new = html_escape($new); + $h_aliases .= " + + $h_old + $h_new + +
+ + +
+ + + "; + } + $html = " + + + $h_aliases + + + + + + + +
FromToAction
+ "; + return $html; + } +// }}} +} +add_event_listener(new AliasEditor()); +?> diff --git a/ext/autocomplete.ext.php.disabled b/ext/autocomplete.ext.php.disabled new file mode 100644 index 00000000..c758828b --- /dev/null +++ b/ext/autocomplete.ext.php.disabled @@ -0,0 +1,73 @@ +page == "index" || $event->page == "view")) { + global $page; + $page->add_side_block(new Block(null, $this->build_autocomplete_script())); + } + if(is_a($event, 'PageRequestEvent') && ($event->page == "autocomplete")) { + global $page; + $page->set_mode("data"); + $page->set_type("text/plain"); + $page->set_data($this->get_completions($event->get_arg(0))); + } + } +// }}} +// do things {{{ + private function get_completions($start) { + global $database; + $tags = $database->db->GetCol("SELECT tag,count(image_id) AS count FROM tags WHERE tag LIKE ? GROUP BY tag ORDER BY count DESC", array($start.'%')); + return implode("\n", $tags); + } +// }}} +// html {{{ + private function build_autocomplete_script() { + global $database; + $ac_url = html_escape(make_link("autocomplete")); + + return << +//completion_cache = new array(); + +input = byId("search_input"); +output = byId("search_completions"); + +function get_cached_completions(start) { +// if(completion_cache[start]) { +// return completion_cache[start]; +// } +// else { + return null; +// } +} +function get_completions(start) { + cached = get_cached_completions(start); + if(cached) { + output.innerHTML = cached; + } + else { + ajaxRequest("$ac_url/"+start, function(data) {set_completions(start, data);}); + } +} +function set_completions(start, data) { +// completion_cache[start] = data; + output.innerHTML = data; +} + +input.onkeyup = function() { + if(input.value.length < 3) { + output.innerHTML = ""; + } + else { + get_completions(input.value); + } +}; + +EOD; + } +// }}} +} +add_event_listener(new AutoComplete()); +?> diff --git a/ext/bulk_add.ext.php b/ext/bulk_add.ext.php new file mode 100644 index 00000000..981e198e --- /dev/null +++ b/ext/bulk_add.ext.php @@ -0,0 +1,102 @@ +page == "bulk_add")) { + global $user; + if($user->is_admin() && isset($_POST['dir'])) { + global $page; + $page->set_title("Adding folder"); + $page->set_heading("Adding folder"); + $page->add_side_block(new NavBlock()); + $this->add_dir($_POST['dir']); + } + } + + if(is_a($event, 'AdminBuildingEvent')) { + global $page; + $page->add_main_block(new Block("Bulk Add", $this->build_bulkadd())); + } + } +// }}} +// do the adding {{{ + private function add_image($tmpname, $filename, $tags) { + global $config; + + $ok = false; + + if(filesize($tmpname) > $config->get_int('upload_size')) { +// $page->add_main_block(new Block("Error with ".html_escape($filename), +// "File too large (".filesize($file['tmp_name'])." > ". +// ($config->get_int('upload_size')).")")); + } + else if(!($info = getimagesize($tmpname))) { +// $page->add_main_block(new Block("Error with ".html_escape($file['name']), +// "PHP doesn't recognise this as an image file")); + } + else { + $image = new Image($tmpname, $filename, $tags); + + if($image->is_ok()) { + send_event(new UploadingImageEvent($image)); + $ok = true; + } + } + + return $ok; + } + + private function add_dir($base, $subdir="") { + global $page; + + if(!is_dir($base)) { + $page->add_main_block(new Block("Error", "$base is not a directory")); + } + + $list = ""; + + $dir = opendir("$base/$subdir"); + while($filename = readdir($dir)) { + $fullpath = "$base/$subdir/$filename"; + + if(is_dir($fullpath)) { + if($filename[0] != ".") { + $this->add_dir($base, "$subdir/$filename"); + } + } + else { + $tmpfile = $fullpath; + $list .= "
".html_escape("$subdir/$filename (".str_replace("/", ",", $subdir).")..."); + if($this->add_image($tmpfile, $filename, str_replace("/", " ", $subdir))) { + $list .= "ok\n"; + } + else { + $list .= "failed\n"; + } + } + } + closedir($dir); + + $page->add_main_block(new Block("Adding $subdir", $list)); + } +// }}} +// admin page HTML {{{ + private function build_bulkadd() { + $html = " + Add a folder full of images; any subfolders will have their names + used as tags for the images within. +
Note: this is the folder as seen by the server -- you need to + upload via FTP or something first. + +

+ Directory to add: + +
+ "; + return $html; + } +// }}} +} +add_event_listener(new BulkAdd()); +?> diff --git a/ext/comment.ext.php b/ext/comment.ext.php new file mode 100644 index 00000000..aa1ba7dc --- /dev/null +++ b/ext/comment.ext.php @@ -0,0 +1,386 @@ +comment_id = $comment_id; + } +} +// }}} + +class Comment { // {{{ + public function Comment($row) { + $this->owner_id = $row['user_id']; + $this->owner_name = $row['user_name']; + $this->comment = $row['comment']; + $this->comment_id = $row['comment_id']; + $this->image_id = $row['image_id']; + $this->poster_ip = $row['poster_ip']; + } + + public function to_html($link_to_image = false) { + global $user; + + $i_uid = int_escape($this->owner_id); + $h_name = html_escape($this->owner_name); + $h_poster_ip = html_escape($this->poster_ip); + $h_comment = bbcode2html($this->comment); + $i_comment_id = int_escape($this->comment_id); + $i_image_id = int_escape($this->image_id); + + $h_userlink = "$h_name"; + $h_dellink = $user->is_admin() ? + "
($h_poster_ip, Del)" : ""; + $h_imagelink = $link_to_image ? ">>>\n" : ""; + return "

$h_userlink: $h_comment $h_imagelink $h_dellink

"; + } +} // }}} + +class CommentList extends Extension { +// event handler {{{ + public function receive_event($event) { + if(is_a($event, 'InitExtEvent')) { + global $config; + if($config->get_int("ext_comments_version") < 1) { + $this->install(); + } + } + + if(is_a($event, 'PageRequestEvent') && ($event->page == "comment")) { + if($event->get_arg(0) == "add") { + $this->add_comment_wrapper($_POST['image_id'], $_POST['comment']); + } + else if($event->get_arg(0) == "delete") { + global $user; + global $page; + if($user->is_admin()) { + // FIXME: post, not args + if($event->count_args() == 3) { + send_event(new CommentDeletionEvent($event->get_arg(1))); + $page->set_mode("redirect"); + $page->set_redirect(make_link("post/view/".$event->get_arg(2))); + } + } + else { + // FIXME: denied message + } + } + else if($event->get_arg(0) == "rss") { + $this->build_rss(); + } + else if($event->get_arg(0) == "list") { + $this->build_page($event->get_arg(1)); + } + } + if(is_a($event, 'PageRequestEvent') && ($event->page == "index")) { + global $page; + global $config; + if($config->get_int("comment_count") > 0) { + $page->add_side_block(new Block("Comments", $this->build_recent_comments()), 50); + // $page->add_quicknav("Comments", make_link("comments/list")); + } + } + + if(is_a($event, 'DisplayingImageEvent')) { + global $page; + $page->add_main_block(new Block("Comments", + $this->build_image_comments($event->image->id). + $this->build_postbox($event->image->id)), 50); + } + + if(is_a($event, 'ImageDeletionEvent')) { + $this->delete_comments($event->image->id); + } + if(is_a($event, 'CommentDeletionEvent')) { + $this->delete_comment($event->comment_id); + } + + if(is_a($event, 'SetupBuildingEvent')) { + $sb = new SetupBlock("Comment Options"); + $sb->add_label("Allow anonymous comments "); + $sb->add_bool_option("comment_anon"); + $sb->add_label("
Limit to "); + $sb->add_int_option("comment_limit"); + $sb->add_label(" comments per "); + $sb->add_int_option("comment_window"); + $sb->add_label(" minutes"); + $sb->add_label("
Show "); + $sb->add_int_option("comment_count"); + $sb->add_label(" recent comments on the index"); + $sb->add_label("
Akismet Key "); + $sb->add_text_option("comment_wordpress_key"); + $event->panel->add_main_block($sb); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_bool("comment_anon", $_POST['comment_anon']); + $event->config->set_int("comment_limit", $_POST['comment_limit']); + $event->config->set_int("comment_window", $_POST['comment_window']); + $event->config->set_int("comment_count", $_POST['comment_count']); + $event->config->set_string("comment_wordpress_key", $_POST['comment_wordpress_key']); + } + } +// }}} +// installer {{{ + protected function install() { + global $database; + global $config; + $database->db->Execute("CREATE TABLE `comments` ( + `id` int(11) NOT NULL auto_increment, + `image_id` int(11) NOT NULL, + `owner_id` int(11) NOT NULL, + `owner_ip` char(16) NOT NULL, + `posted` datetime default NULL, + `comment` text NOT NULL, + PRIMARY KEY (`id`), + KEY `comments_image_id` (`image_id`) + )"); + $config->set_int("ext_comments_version", 1); + } +// }}} +// page building {{{ + private function build_rss() { + global $page; + $page->set_mode("data"); + $page->set_type("application/rss+xml"); + + $rss = "moo"; // FIXME + + $page->set_data($rss); + } + + private function build_page($current_page) { + global $page; + global $database; + + if(is_null($current_page) || $current_page <= 0) { + $current_page = 1; + } + + $threads_per_page = 10; + $start = $threads_per_page * ($current_page - 1); + + $get_threads = " + SELECT image_id,MAX(posted) AS latest + FROM comments + GROUP BY image_id + ORDER BY latest DESC + LIMIT ?,? + "; + $result = $database->db->Execute($get_threads, array($start, $threads_per_page)); + + + $total_pages = (int)($database->db->GetOne("SELECT COUNT(distinct image_id) AS count FROM comments") / 10); + + $page->set_title("Comments"); + $page->set_heading("Comments"); + $page->add_side_block(new Block("Navigation", $this->build_navigation($current_page, $total_pages))); + $page->add_main_block(new Paginator("comment/list", null, $current_page, $total_pages), 90); + + $n = 10; + while(!$result->EOF) { + $image = $database->get_image($result->fields["image_id"]); + + $html = "
"; + $html .= ""; + $html .= ""; + $html .= $this->build_image_comments($image->id); + $html .= "
"; + $html .= "
".($this->build_postbox($image->id))."
"; + + $page->add_main_block(new Block("{$image->id}: ".($image->get_tag_list()), $html), $n); + $n += 1; + $result->MoveNext(); + } + + } + + private function build_navigation($page_number, $total_pages) { + $prev = $page_number - 1; + $next = $page_number + 1; + + $h_prev = ($page_number <= 1) ? "Prev" : + "Prev"; + $h_index = "Index"; + $h_next = ($page_number >= $total_pages) ? "Next" : + "Next"; + + return "$h_prev | $h_index | $h_next"; + } + + private function build_image_comments($image_id) { + global $config; + $i_image_id = int_escape($image_id); + $html = "
"; + $html .= $this->query_to_html(" + SELECT + users.id as user_id, users.name as user_name, + comments.comment as comment, comments.id as comment_id, + comments.image_id as image_id, comments.owner_ip as poster_ip + FROM comments + LEFT JOIN users ON comments.owner_id=users.id + WHERE comments.image_id=? + ORDER BY comments.id ASC + ", array($i_image_id)); + $html .= "
"; + return $html; + } + + private function build_recent_comments() { + global $config; + $html = $this->query_to_html(" + SELECT + users.id as user_id, users.name as user_name, + if( + length(comments.comment) > 50, + concat(substring(comments.comment, 1, 50), ' ...'), + comments.comment + ) as comment, + comments.id as comment_id, + comments.image_id as image_id, comments.owner_ip as poster_ip + FROM comments + LEFT JOIN users ON comments.owner_id=users.id + ORDER BY comments.id DESC + LIMIT ? + ", array($config->get_int('comment_count')), true); + $html .= "

Full List >>>"; + return $html; + } + + private function build_postbox($image_id) { + if($this->can_comment()) { + $i_image_id = int_escape($image_id); + return " +

+ + +
+
+ "; + } + else { + return "

You need to create an account before you can comment

"; + } + } + + private function query_to_html($query, $args, $link_to_image=false) { + global $database; + global $config; + + $html = ""; + $result = $database->db->Execute($query, $args); + while(!$result->EOF) { + $comment = new Comment($result->fields); + $html .= $comment->to_html($link_to_image); + $result->MoveNext(); + } + return $html; + } +// }}} +// add / remove / edit comments {{{ + private function is_comment_limit_hit() { + global $user; + global $config; + global $database; + + $window = int_escape($config->get_int('comment_window')); + $max = int_escape($config->get_int('comment_limit')); + + $result = $database->db->Execute("SELECT * FROM comments WHERE owner_ip = ? ". + "AND posted > date_sub(now(), interval ? minute)", + Array($_SERVER['REMOTE_ADDR'], $window)); + $recent_comments = $result->RecordCount(); + + return ($recent_comments >= $max); + } + + private function is_spam($text) { + global $user; + global $config; + + if(strlen($config->get_string('comment_wordpress_key')) == 0) { + return false; + } + else { + $comment = array( + 'author' => $user->name, + 'email' => $user->email, + 'website' => '', + 'body' => $text, + 'permalink' => '', + ); + + $akismet = new Akismet( + 'http://www.yourdomain.com/', + $config->get_string('comment_wordpress_key'), + $comment); + + if($akismet->errorsExist()) { + return false; + } + else { + return $akismet->isSpam(); + } + } + } + + private function can_comment() { + global $config; + return ($config->get_bool('comment_anon') || !$user->is_anonymous()); + } + + private function add_comment_wrapper($image_id, $comment) { + global $user; + global $database; + global $config; + global $page; + + $page->set_title("Error"); + $page->set_heading("Error"); + $page->add_side_block(new NavBlock()); + if(!$config->get_bool('comment_anon') && $user->is_anonymous()) { + $page->add_main_block(new Block("Permission Denied", "Anonymous posting has been disabled")); + } + else if(trim($comment) == "") { + $page->add_main_block(new Block("Comment Empty", "Comments need text...")); + } + else if($this->is_comment_limit_hit()) { + $page->add_main_block(new Block("Comment Limit Hit", + "You've posted several comments recently; wait a minute and try again...")); + } + else if($this->is_spam($comment)) { + $page->add_main_block(new Block("Spam Detected", + "Akismet thinks that your comment is spam. Try rewriting the comment?")); + } + else { + $database->db->Execute( + "INSERT INTO comments(image_id, owner_id, owner_ip, posted, comment) ". + "VALUES(?, ?, ?, now(), ?)", + array($image_id, $user->id, $_SERVER['REMOTE_ADDR'], $comment)); + $page->set_mode("redirect"); + $page->set_redirect(make_link("post/view/".int_escape($image_id))); + } + } + + private function delete_comments($image_id) { + global $database; + $database->db->Execute("DELETE FROM comments WHERE image_id=?", array($image_id)); + } + + private function delete_comment($comment_id) { + global $database; + $database->db->Execute("DELETE FROM comments WHERE id=?", array($comment_id)); + } +// }}} +} +add_event_listener(new CommentList()); +?> diff --git a/ext/downtime.ext.php b/ext/downtime.ext.php new file mode 100644 index 00000000..6a4edaea --- /dev/null +++ b/ext/downtime.ext.php @@ -0,0 +1,51 @@ +check_downtime($event); + + if(is_a($event, 'SetupBuildingEvent')) { + $sb = new SetupBlock("Downtime"); + $sb->add_label("Disable non-admin access: "); + $sb->add_bool_option("downtime"); + $sb->add_label("
"); + $sb->add_longtext_option("downtime_message"); + $event->panel->add_main_block($sb); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_bool("downtime", $_POST['downtime']); + $event->config->set_string("downtime_message", $_POST['downtime_message']); + } + } +// }}} +// do things {{{ + private function check_downtime($event) { + global $user; + global $config; + + if($config->get_bool("downtime") && !$user->is_admin() && + is_a($event, 'PageRequestEvent') && !$this->is_safe_page($event)) { + $msg = $config->get_string("downtime_message"); + print << + + Downtime + + + $msg + + +EOD; + exit; + } + } + + private function is_safe_page($event) { + if($event->page == "user" && $event->get_arg(0) == "login") return true; + else return false; + } +// }}} +} +add_event_listener(new Downtime(), 10); +?> diff --git a/ext/et.ext.php b/ext/et.ext.php new file mode 100644 index 00000000..70dc19a4 --- /dev/null +++ b/ext/et.ext.php @@ -0,0 +1,90 @@ +page == "phone_home")) { + global $user; + if($user->is_admin()) { + $this->phone_home(); + } + } + + if(is_a($event, 'AdminBuildingEvent')) { + global $page; + $page->add_main_block(new Block("Gather System Info", $this->build_phone_home()), 99); + } + } +// }}} +// do it {{{ + private function phone_home() { + global $page; + $page->set_title("System Info"); + $page->set_heading("System Info"); + $page->add_side_block(new NavBlock()); + $page->add_main_block(new Block("Data which is to be sent:", $this->build_data_form())); + } + private function build_data_form() { + global $database; + global $config; + + $data = ""; + + $data .= "Optional:\n"; + $data .= "Add this site to the public shimmie users list: No\n"; + $data .= "Site title: ".($config->get_string("title"))."\n"; + $data .= "Theme: ".($config->get_string("theme"))."\n"; + $data .= "Genre: [please write something here]\n"; + + $data .= "\nSystem stats:\n"; + $data .= "PHP: ".phpversion()."\n"; + $data .= "OS: ".php_uname()."\n"; + $data .= "Server: ".($_SERVER["SERVER_SOFTWARE"])."\n"; + + include "config.php"; + $proto = preg_replace("#(.*)://.*#", "$1", $database_dsn); + $db = $database->db->ServerInfo(); + $data .= "Database: $proto / {$db['version']}\n"; + + $data .= "\nShimmie stats:\n"; + $uri = isset($_SERVER['SCRIPT_URI']) ? dirname($_SERVER['SCRIPT_URI']) : "???"; + $data .= "URL: ".($uri)."\n"; + $data .= "Version: ".($config->get_string("version"))."\n"; + $data .= "Images: ".($database->db->GetOne("SELECT COUNT(*) FROM images"))."\n"; + $data .= "Comments: ".($database->db->GetOne("SELECT COUNT(*) FROM comments"))."\n"; + $data .= "Users: ".($database->db->GetOne("SELECT COUNT(*) FROM users"))."\n"; + $data .= "Tags: ".($database->db->GetOne("SELECT COUNT(*) FROM tags"))."\n"; + + $html = " +
+ + +
+
Your stats are useful so that I know which combinations + of web servers / databases / etc I need to support, +
and so + that I can get some idea of how people use shimmie generally +
+ "; + return $html; + } +// }}} +// admin page HTML {{{ + private function build_phone_home() { + global $database; + $h_bans = ""; + $html = " + This button will gather various bits of information about + your system (PHP version, database, etc) which will be + useful in debugging~ + +

+ +
+ "; + return $html; + } +// }}} +} +add_event_listener(new ET()); +?> diff --git a/ext/ipban.ext.php b/ext/ipban.ext.php new file mode 100644 index 00000000..1bf76bcd --- /dev/null +++ b/ext/ipban.ext.php @@ -0,0 +1,169 @@ +ip = $ip; + } +} +// }}} +// AddIPBanEvent {{{ +class AddIPBanEvent extends Event { + var $ip; + var $reason; + + public function AddIPBanEvent($ip, $reason) { + $this->ip = $ip; + $this->reason = $reason; + } +} +// }}} + +class IPBan extends Extension { +// event handler {{{ + public function receive_event($event) { + if(is_a($event, 'InitExtEvent')) { + global $config; + if($config->get_int("ext_ipban_version") < 1) { + $this->install(); + } + } + + $this->check_ip_ban(); + + if(is_a($event, 'PageRequestEvent') && ($event->page == "ip_ban")) { + global $user; + if($user->is_admin()) { + if($event->get_arg(0) == "add") { + if(isset($_POST['ip']) && isset($_POST['reason'])) { + send_event(new AddIPBanEvent($_POST['ip'], $_POST['reason'])); + + global $page; + $page->set_mode("redirect"); + $page->set_redirect(make_link("admin")); + } + } + else if($event->get_arg(0) == "remove") { + if(isset($_POST['ip'])) { + send_event(new RemoveIPBanEvent($_POST['ip'])); + + global $page; + $page->set_mode("redirect"); + $page->set_redirect(make_link("admin")); + } + } + } + } + + if(is_a($event, 'AddIPBanEvent')) { + $this->add_ip_ban($event->ip, $event->reason); + } + + if(is_a($event, 'RemoveIPBanEvent')) { + $this->remove_ip_ban($event->ip); + } + + if(is_a($event, 'AdminBuildingEvent')) { + global $page; + $page->add_main_block(new Block("Edit IP Bans", $this->build_ip_bans())); + } + } +// }}} +// installer {{{ + protected function install() { + global $database; + global $config; + $database->db->Execute("CREATE TABLE bans ( + id int(11) NOT NULL auto_increment, + ip char(15) default NULL, + date datetime default NULL, + end datetime default NULL, + reason varchar(255) default NULL, + PRIMARY KEY (id) + )"); + $config->set_int("ext_ipban_version", 1); + } +// }}} +// deal with banned person {{{ + private function check_ip_ban() { + $row = $this->get_ip_ban($_SERVER['REMOTE_ADDR']); + if($row) { + global $config; + + print "IP {$row['ip']} has been banned because of {$row['reason']}"; + + $contact_link = $config->get_string("contact_link"); + if(!empty($contact_link)) { + print "

Contact The Admin"; + } + exit; + } + } +// }}} +// database {{{ + public function get_bans() { + // FIXME: many + global $database; + $bans = $database->db->GetAll("SELECT * FROM bans"); + if($bans) {return $bans;} + else {return array();} + } + + public function get_ip_ban($ip) { + global $database; + // yes, this is "? LIKE var", because ? is the thing with matching tokens + return $database->db->GetRow("SELECT * FROM bans WHERE ? LIKE ip", array($ip)); + } + + public function add_ip_ban($ip, $reason) { + global $database; + $database->db->Execute( + "INSERT INTO bans (ip, reason, date) VALUES (?, ?, now())", + array($ip, $reason)); + } + + public function remove_ip_ban($ip) { + global $database; + $database->db->Execute("DELETE FROM bans WHERE ip = ?", array($ip)); + } +// }}} +// admin page HTML {{{ + private function build_ip_bans() { + global $database; + $h_bans = ""; + $bans = $this->get_bans(); + foreach($bans as $ban) { + $h_bans .= " + + {$ban['ip']} + {$ban['reason']} + +

+ + +
+ + + "; + } + $html = " + + + $h_bans + + + + + + + +
IPReasonAction
+ "; + return $html; + } +// }}} +} +add_event_listener(new IPBan(), 10); +?> diff --git a/ext/news.ext.php b/ext/news.ext.php new file mode 100644 index 00000000..1c48d019 --- /dev/null +++ b/ext/news.ext.php @@ -0,0 +1,23 @@ +page == "index")) { + global $config; + if(strlen($config->get_string("news_text")) > 0) { + $page->add_side_block(new Block("Note", $config->get_string("news_text")), 5); + } + } + if(is_a($event, 'SetupBuildingEvent')) { + $sb = new SetupBlock("News"); + $sb->add_longtext_option("news_text"); + $event->panel->add_main_block($sb); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_string("news_text", $_POST['news_text']); + } + } +} +add_event_listener(new News()); +?> diff --git a/ext/notes.ext.php.disabled b/ext/notes.ext.php.disabled new file mode 100644 index 00000000..195fb5b1 --- /dev/null +++ b/ext/notes.ext.php.disabled @@ -0,0 +1,52 @@ +get_int("ext_notes_version") < 1) { + $this->install(); + } + } + + if(is_a($event, 'DisplayingImageEvent')) { + global $page; + $page->add_main_block(new Block(null, $this->make_notes($event->image->id))); + } + } + + protected function install() { + global $database; + global $config; + $database->db->Execute("CREATE TABLE `image_notes` ( + `id` int(11) NOT NULL auto_increment, + `image_id` int(11) NOT NULL, + `user_id` int(11) NOT NULL, + `owner_ip` char(15) NOT NULL, + `created_at` datetime NOT NULL, + `updated_at` datetime NOT NULL, + `version` int(11) DEFAULT 1 NOT NULL, + `is_active` enum('Y', 'N') DEFAULT 'Y' NOT NULL, + `x` int(11) NOT NULL, + `y` int(11) NOT NULL, + `w` int(11) NOT NULL, + `h` int(11) NOT NULL, + `body` text NOT NULL, + PRIMARY KEY (`id`) + )"); + $config->set_int("ext_notes_version", 1); + } + + private function make_notes($image_id) { + global $database; + $notes = $database->db->GetAll("SELECT * FROM image_notes WHERE image_id = ?", array($image_id)); + + return << +img = byId("main_image"); + +EOD; + } +} +add_event_listener(new Notes()); +?> diff --git a/ext/rating.ext.php.disabled b/ext/rating.ext.php.disabled new file mode 100644 index 00000000..963dbf6f --- /dev/null +++ b/ext/rating.ext.php.disabled @@ -0,0 +1,130 @@ +get_int("ext_ratings_version") < 1) { + $this->install(); + } + } + +/* + if(is_a($event, 'ImageDeletionEvent')) { + $this->delete_comments($event->image->id); + } + if(is_a($event, 'CommentDeletionEvent')) { + $this->delete_comment($event->comment_id); + } + + if(is_a($event, 'SetupBuildingEvent')) { + $sb = new SetupBlock("Comment Options"); + $sb->add_label("Allow anonymous comments "); + $sb->add_bool_option("comment_anon"); + $sb->add_label("
Limit to "); + $sb->add_int_option("comment_limit", 1, 60); + $sb->add_label(" comments per "); + $sb->add_int_option("comment_window", 1, 60); + $sb->add_label(" minutes"); + $sb->add_label("
Show "); + $sb->add_int_option("comment_count", 0, 100); + $sb->add_label(" recent comments on the index"); + $event->panel->add_main_block($sb); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_bool("comment_anon", $_POST['comment_anon']); + $event->config->set_int("comment_limit", $_POST['comment_limit']); + $event->config->set_int("comment_window", $_POST['comment_window']); + $event->config->set_int("comment_count", $_POST['comment_count']); + } +*/ + } + + private function can_comment() { + global $config, $user; + return $config->get_bool("rate_anon") || ($user->id != $config->get_int("anon_id")); + } +// }}} +// installer {{{ + protected function install() { + global $database; + global $config; + $database->db->Execute("CREATE TABLE `image_voters` ( + `image_id` int(11) NOT NULL, + `user_id` int(11) NOT NULL, + `vote` tinyint(4) NOT NULL, + `voted` datetime NOT NULL, + PRIMARY KEY (`image_id`,`user_id`) + )"); + $config->set_int("ext_ratings_version", 1); + } +// }}} +// page building {{{ + + private function build_image_rating($image_id) { + global $config; + $i_image_id = int_escape($image_id); + return $this->query_to_html(" + SELECT + users.id as user_id, users.name as user_name, + comments.comment as comment, comments.id as comment_id, + comments.image_id as image_id, comments.owner_ip as poster_ip + FROM comments + LEFT JOIN users ON comments.owner_id=users.id + WHERE comments.image_id=? + ORDER BY comments.id ASC + LIMIT ? + ", array($i_image_id, $config->get_int('recent_count'))); + } + + private function build_rater($image_id) { + if($this->can_comment()) { + $i_image_id = int_escape($image_id); + return " +
+ + +
+
+ + +
+ "; + } + else { + return "You need to create an account before you can rate"; + } + } +// }}} +// add / remove / edit comments {{{ + private function add_rating($image_id, $rating) { + global $user; + global $database; + global $config; + global $page; + + $page->set_title("Error"); + $page->set_heading("Error"); + if(!$config->get_bool('rating_anon') && $user->is_anonymous()) { + $page->add_main_block(new Block("Permission Denied", "Anonymous rating has been disabled")); + } + else { + $i_rating = int_escape($rating); + $database->db->Execute( + "INSERT INTO image_ratings(image_id, user_id, rating, rated) ". + "VALUES(?, ?, ?, now())", + array($image_id, $user->id, $i_rating)); + $page->set_mode("redirect"); + $page->set_redirect(make_link("post/view/".int_escape($image_id))); + } + } + + private function delete_ratings($image_id) { + global $database; + $database->db->Execute("DELETE FROM image_voters WHERE image_id=?", array($image_id)); + } +// }}} +} +add_event_listener(new Ratings()); +?> diff --git a/ext/regen_thumb.ext.php b/ext/regen_thumb.ext.php new file mode 100644 index 00000000..13ca330b --- /dev/null +++ b/ext/regen_thumb.ext.php @@ -0,0 +1,170 @@ +page == "regen_thumb")) { + global $user; + if($user->is_admin() && isset($_POST['program']) && isset($_POST['image_id'])) { + $this->make_thumb($_POST['program'], $_POST['image_id']); + } + } + + if(is_a($event, 'DisplayingImageEvent')) { + global $page; + global $user; + if($user->is_admin()) { + $page->add_side_block(new Block("Regen Thumb", $this->build_regen_buttons($event->image))); + } + } + } +// }}} +// do things {{{ + // FIXME: make locations of convert / epeg config variables + private function make_thumb($program, $image_id) { + global $database; + global $config; + + $i_image_id = int_escape($image_id); + $image = $database->get_image($i_image_id); + + $f_image = $this->check_filename($image->get_image_filename()); + $f_thumb = $this->check_filename($image->get_thumb_filename()); + + $w = $config->get_int('thumb_width'); + $h = $config->get_int('thumb_height'); + $q = $config->get_int('thumb_quality'); + + switch($program) { + case 'convert': + unlink($f_thumb); + exec("convert $f_image -geometry {$w}x{$h} -quality {$q} $f_thumb"); + break; + case 'gd': + $this->make_thumb_gd($f_image, $f_thumb); + break; + default: + break; + } + + global $page; + $page->set_title("Thumbnail Regenerated"); + $page->set_heading("Thumbnail Regenerated"); + $page->add_side_block(new NavBlock()); + $page->add_main_block(new Block("Thumbnail", $this->build_thumb_html($image))); + } + + private function build_thumb_html($image) { + $link = make_link("post/view/".$image->id); + $img = $image->get_thumb_link(); + $html = ""; + return $html; + } + + private function check_filename($filename) { + $filename = preg_replace("#[^a-zA-Z0-9/\._]#", "", $filename); + return $filename; + } + +// }}} +// GD thumber {{{ + private function read_file($fname) { + $fp = fopen($fname, "r"); + if(!$fp) return false; + + $data = fread($fp, filesize($fname)); + fclose($fp); + + return $data; + } + private function make_thumb_gd($inname, $outname) { + global $config; + $thumb = $this->get_thumb($inname); + return imagejpeg($thumb, $outname, $config->get_int('thumb_quality')); + } + + private function get_memory_limit() { + global $config; + + // thumbnail generation requires lots of memory + $default_limit = 8*1024*1024; + $shimmie_limit = parse_shorthand_int($config->get_int("thumb_gd_mem_limit")); + if($shimmie_limit < 3*1024*1024) { + // we aren't going to fit, override + $shimmie_limit = $default_limit; + } + + ini_set("memory_limit", $shimmie_limit); + $memory = parse_shorthand_int(ini_get("memory_limit")); + + // changing of memory limit is disabled / failed + if($memory == -1) { + $memory = $default_limit; + } + + return $memory; + } + + private function get_thumb($tmpname) { + global $config; + + $info = getimagesize($tmpname); + $width = $info[0]; + $height = $info[1]; + + $max_width = $config->get_int('thumb_width'); + $max_height = $config->get_int('thumb_height'); + + $memory_use = (filesize($tmpname)*2) + ($width*$height*4) + (4*1024*1024); + $memory_limit = $this->get_memory_limit(); + + if($memory_use > $memory_limit) { + $thumb = imagecreatetruecolor($max_width, min($max_height, 64)); + $white = imagecolorallocate($thumb, 255, 255, 255); + $black = imagecolorallocate($thumb, 0, 0, 0); + imagefill($thumb, 0, 0, $white); + imagestring($thumb, 5, 10, 24, "Image Too Large :(", $black); + return $thumb; + } + else { + $image = imagecreatefromstring($this->read_file($tmpname)); + + $xscale = ($max_height / $height); + $yscale = ($max_width / $width); + $scale = ($xscale < $yscale) ? $xscale : $yscale; + + if($scale >= 1) { + $thumb = $image; + } + else { + $thumb = imagecreatetruecolor($width*$scale, $height*$scale); + imagecopyresampled( + $thumb, $image, 0, 0, 0, 0, + $width*$scale, $height*$scale, $width, $height + ); + } + return $thumb; + } + } +// }}} +// page building {{{ + private function build_regen_buttons($image) { + global $user; + if($user->is_admin()) { + return " +
+ + + +
+ "; + } + } +// }}} +} +add_event_listener(new RegenThumb()); +?> diff --git a/ext/tag_list.ext.php b/ext/tag_list.ext.php new file mode 100644 index 00000000..29ad68a7 --- /dev/null +++ b/ext/tag_list.ext.php @@ -0,0 +1,235 @@ +page == "tags")) { + global $page; + $page->set_title("Tag List"); + $page->add_side_block(new Block("Navigation", $this->build_navigation()), 0); + + switch($event->get_arg(0)) { + default: + case 'map': + $page->set_heading("Tag Map"); + $page->add_main_block(new Block("Tags", $this->build_tag_map())); + break; + case 'alphabetic': + $page->set_heading("Alphabetic Tag List"); + $page->add_main_block(new Block("Tags", $this->build_tag_alphabetic())); + break; + case 'popularity': + $page->set_heading("Tag List by Popularity"); + $page->add_main_block(new Block("Tags", $this->build_tag_popularity())); + break; + } + } + if(is_a($event, 'PageRequestEvent') && ($event->page == "index")) { + global $config; + global $page; + if($config->get_int('popular_count') > 0) { + $page->add_side_block(new Block("Popular Tags", $this->get_popular_tags()), 60); + // $page->add_quicknav("Tags", make_link("tags")); + } + } + + if(is_a($event, 'DisplayingImageEvent')) { + global $page; + $page->add_side_block(new Block("Related Tags", $this->get_related_tags($event->get_image())), 60); + } + + if(is_a($event, 'SetupBuildingEvent')) { + $sb = new SetupBlock("Tag Map Options"); + $sb->add_label("Ignore tags used fewer than "); + $sb->add_int_option("tags_min", 0, 99); + $sb->add_label(" times"); + $event->panel->add_main_block($sb); + + $sb = new SetupBlock("Popular Tag List"); + $sb->add_label("Show top "); + $sb->add_int_option("popular_count", 0, 60); + $sb->add_label(" tags"); + $sb->add_label("
Tag info link: "); + $sb->add_text_option("info_link", true); + $event->panel->add_main_block($sb); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_int("tags_min", $_POST['tags_min']); + + $event->config->set_int("popular_count", $_POST['popular_count']); + $event->config->set_string("info_link", $_POST['info_link']); + } + } +// }}} +// misc {{{ + private function tag_link($tag) { + $h_tag = html_escape($tag); + return make_link("index", "search=$h_tag"); + } +// }}} +// maps {{{ + private function build_navigation() { + $h_index = "Index"; + $h_map = "Map"; + $h_alphabetic = "Alphabetic"; + $h_popularity = "Popularity"; + return "$h_index
$h_map
$h_alphabetic
$h_popularity"; + } + + private function build_tag_map() { + global $database; + global $config; + + $tags_min = $config->get_int('tags_min'); + $result = $database->db->Execute( + "SELECT tag,COUNT(image_id) AS count FROM tags GROUP BY tag HAVING count > ? ORDER BY tag", + array($tags_min)); + + $html = ""; + while(!$result->EOF) { + $row = $result->fields; + $h_tag = html_escape($row['tag']); + $count = $row['count']; + if($count > 1) { + $size = floor(log(log($row['count'] - $tags_min + 1)+1)*1.5*100)/100; + $link = $this->tag_link($row['tag']); + $html .= " $h_tag \n"; + } + $result->MoveNext(); + } + return $html; + } + + private function build_tag_alphabetic() { + global $database; + global $config; + + $tags_min = $config->get_int('tags_min'); + $result = $database->db->Execute( + "SELECT tag,COUNT(image_id) AS count FROM tags GROUP BY tag HAVING count > ? ORDER BY tag", + array($tags_min)); + + $html = ""; + $lastLetter = 0; + while(!$result->EOF) { + $row = $result->fields; + $h_tag = html_escape($row['tag']); + $count = $row['count']; + if($lastLetter != strtolower(substr($h_tag, 0, 1))) { + $lastLetter = strtolower(substr($h_tag, 0, 1)); + $html .= "

$lastLetter
"; + } + $link = $this->tag_link($row['tag']); + $html .= "$h_tag ($count)\n"; + $result->MoveNext(); + } + + return $html; + } + + private function build_tag_popularity() { + global $database; + global $config; + + $tags_min = $config->get_int('tags_min'); + $result = $database->db->Execute( + "SELECT tag,COUNT(image_id) AS count FROM tags GROUP BY tag HAVING count > ? ORDER BY count DESC, tag ASC", + array($tags_min) + ); + + $html = "Results grouped by loge(n)"; + $lastLog = 0; + while(!$result->EOF) { + $row = $result->fields; + $h_tag = html_escape($row['tag']); + $count = $row['count']; + if($lastLog != floor(log($count))) { + $lastLog = floor(log($count)); + $html .= "

$lastLog
"; + } + $link = $this->tag_link($row['tag']); + $html .= "$h_tag ($count)\n"; + $result->MoveNext(); + } + + return $html; + } +// }}} +// get related {{{ + private function get_related_tags($image) { + global $database; + global $config; + + $query = " + SELECT COUNT(t3.image_id) as count, t3.tag + FROM + tags AS t1, + tags AS t2, + tags AS t3 + WHERE + t1.image_id=? + AND t1.tag=t2.tag + AND t2.image_id=t3.image_id + AND t1.tag != 'tagme' + AND t3.tag != 'tagme' + GROUP by t3.tag + ORDER by count DESC + LIMIT ? + "; + + $n = 0; + $html = ""; + $result = $database->db->Execute($query, array($image->id, $config->get_int('popular_count'))); + while(!$result->EOF) { + $row = $result->fields; + $h_tag = html_escape($row['tag']); + $count = $row['count']; + if($n++) $html .= "
"; + $link = $this->tag_link($row['tag']); + $html .= "$h_tag\n"; + $result->MoveNext(); + } + $result->Close(); + + return $html; + } +// }}} +// get popular {{{ + private function get_popular_tags() { + global $database; + global $config; + + $query = " + SELECT tag, COUNT(image_id) AS count + FROM tags + GROUP BY tag + ORDER BY count DESC + LIMIT ? + "; + + $n = 0; + $result = $database->db->Execute($query, array($config->get_int('popular_count'))); + $html = ""; + while(!$result->EOF) { + $row = $result->fields; + $tag = html_escape($row['tag']); + $count = $row['count']; + if($n++) $html .= "
"; + $link = $this->tag_link($row['tag']); + $html .= "$tag ($count)\n"; + if(!is_null($config->get_string('info_link'))) { + $link = str_replace('$tag', $tag, $config->get_string('info_link')); + $html .= "?\n"; + } + $result->MoveNext(); + } + $result->Close(); + + $html .= "

Full List >>>\n"; + + return $html; + } +// }}} +} +add_event_listener(new TagList()); +?> diff --git a/ext/zoom.ext.php b/ext/zoom.ext.php new file mode 100644 index 00000000..f4f94053 --- /dev/null +++ b/ext/zoom.ext.php @@ -0,0 +1,57 @@ +add_main_block(new Block(null, $this->make_zoomer())); + } + + if(is_a($event, 'SetupBuildingEvent')) { + $sb = new SetupBlock("Image Zoom"); + $sb->add_label("Zoom by default: "); + $sb->add_bool_option("image_zoom"); + $event->panel->add_main_block($sb); + } + if(is_a($event, 'ConfigSaveEvent')) { + $event->config->set_bool("image_zoom", $_POST['image_zoom']); + } + } + + private function make_zoomer() { + global $config; + $default = $config->get_bool("image_zoom") ? "scale(img);" : ""; + return << +img = byId("main_image"); + +img.onclick = function() {scale(img);}; + +msg_div = document.createElement("div"); +msg_div.id = "msg_div"; +msg_div.appendChild(document.createTextNode("Note: Image has been scaled to fit the screen; click to enlarge")); +msg_div.style.display="none"; + +img.parentNode.insertBefore(msg_div, img); + +orig_width = ""; + +function scale(img) { + if(img.style.width != "90%") { + origwidth = img.style.width; + img.style.width = "90%"; + msg_div.style.display = "block"; + } + else { + img.style.width = origwidth; + msg_div.style.display = "none"; + } +} + +$default + +EOD; + } +} +add_event_listener(new Zoom()); +?> diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..e9fb63219f1048084413de2cf157a9e0761bcf46 GIT binary patch literal 1406 zcmeH{O^Sm+5QRVE$0SKYnxV? z*ECH-+qQIFN8k6)S}*>xfn@`4zJc>!%;q%_)-OPfnYPrJYc>Aq&1U^!ucQeple@0F z-+wyJ7H6mRp26|xayU#{O#Ray`J|@-O|A`2V-NZ8%!H#7bDa1*y)e1fJTMFporGJV PEwo_O{j10n!zvZ literal 0 HcmV?d00001 diff --git a/index.php b/index.php new file mode 100644 index 00000000..28f5ca12 --- /dev/null +++ b/index.php @@ -0,0 +1,37 @@ + +EOD; + exit; +} + +$files = array_merge(glob("core/*.php"), glob("core/*/*.php"), glob("ext/*.php")); + +foreach($files as $filename) { + require_once $filename; +} + +$database = new Database(); +$database->db->fnExecute = 'CountExecs'; +$config = new Config(); +$page = new Page(); +$user = get_user(); +send_event(new InitExtEvent()); +send_event(get_page_request()); +$page->display(); +?> diff --git a/install.php b/install.php new file mode 100644 index 00000000..1ca7ca67 --- /dev/null +++ b/install.php @@ -0,0 +1,497 @@ +Error\nPHP's GD extension seems to be missing; ". + "you can live without it if you have imagemagick installed..."; + } + else { + $gd = ""; + } + + print << + Shimmie2 Installer + + +

Shimmie Installer

+ + $gd + +

Note

+ Shimmie is developed with MySQL, and support + for it is included. Other databases may work, + but you'll need to add the appropriate ADOdb + drivers yourself + +

Install

+
+
+ + + + + +
Database
Admin Name:
Admin Pass:
+ +

Databases should be specified like so: +
ie: protocol://username:password@host/database?options +
eg: mysql://shimmie:pw123@localhost/shimmie?persist +

+
+ +

Upgrade

+
+
+ + + + + +
Old Database:
New Database:
Old Data Folder:
+ +

Data folder is where the "images" and "thumbs" folders are stored +

+
+ + +EOD; +} +// }}} +// common {{{ +function set_admin_cookie($admin_name, $admin_pass) { // {{{ + $addr = $_SERVER['REMOTE_ADDR']; + $hash = md5(strtolower($admin_name) . $admin_pass); + setcookie("shm_user", $admin_name, time()+60*60*24*365); + setcookie("shm_session", md5($hash.$addr), time()+60*60*24*7, "/"); +} // }}} +function create_tables($dsn) { // {{{ + $db = NewADOConnection($dsn); + if(!$db) { + die("Couldn't connect to \"$dsn\""); + } + else { + if(create_tables_mysql($db)) { + $_SESSION['tables_created'] = true; + } + else { + die("Error creating tables"); + } + } + $db->Close(); +} // }}} +function build_dirs() { // {{{ + if(!file_exists("images")) @mkdir("images"); // *try* and make default dirs. Ignore any errors -- + if(!file_exists("thumbs")) @mkdir("thumbs"); // if something is amiss, we'll tell the user later + + if( + ((!file_exists("images") || !file_exists("thumbs")) && !is_writable("./")) || + (!is_writable("images") || !is_writable("thumbs")) + ) { + print "Shimmie needs two folders in it's directory, 'images' and 'thumbs', + and they need to be writable by the PHP user (if you see this error, + if probably means the folders are owned by you, and they need to be + writable by the web server). + +

Once you have created these folders, hit 'refresh' to continue."; + exit; + } + else { + assert(file_exists("images") && is_writable("images")); + assert(file_exists("thumbs") && is_writable("thumbs")); + + if(!file_exists("images/ff")) { + for($i=0; $i<256; $i++) { + mkdir(sprintf("images/%02x", $i)); + mkdir(sprintf("thumbs/%02x", $i)); + } + } + } +} // }}} +function write_config($dsn) { // {{{ + $file_content .= ""; + + if(is_writable("./") && installer_write_file("config.php", $file_content)) { + assert(file_exists("config.php")); + session_destroy(); + } + else { + $h_file_content = htmlentities($file_content); + print << + Shimmie2 Installer + + The web server isn't allowed to write to the config file; please copy + the text below, save it as 'config.php', and upload it into the shimmie + folder manually. Make sure that when you save it, there is no whitespace + before the "<?php" or after the "?>" + +

+ +

One done, Continue + + +EOD; + session_destroy(); + exit; + } +} // }}} +// }}} +// install {{{ +function install_process() { // {{{ + if(!isset($_POST['database_dsn']) || !isset($_POST["admin_name"]) || !isset($_POST["admin_pass"])) { + die("Install is missing some paramaters (database_dsn, admin_name, or admin_pass)"); + } + else if(strlen($_POST["admin_name"]) < 1 || strlen($_POST["admin_pass"]) < 1) { + die("Admin name and password must be at least one character each"); + } + else { + $database_dsn = $_POST['database_dsn']; + $admin_name = $_POST["admin_name"]; + $admin_pass = $_POST["admin_pass"]; + } + + set_admin_cookie($admin_name, $admin_pass); + create_tables($database_dsn); + insert_defaults($database_dsn, $admin_name, $admin_pass); + build_dirs(); + write_config($database_dsn); + + header("Location: index.php?q=setup"); +} // }}} +function insert_defaults($dsn, $admin_name, $admin_pass) { // {{{ + $db = NewADOConnection($dsn); + if(!$db) { + die("Couldn't connect to \"$dsn\""); + } + else { + $config_insert = $db->Prepare("INSERT INTO config(name, value) VALUES(?, ?)"); + $user_insert = $db->Prepare("INSERT INTO users(name, pass, joindate, admin) VALUES(?, ?, now(), ?)"); + + if(!$db->GetOne("SELECT * FROM users WHERE name=?", Array('Anonymous'))) { + $db->Execute($user_insert, Array('Anonymous', null, 'N')); + + $db->Execute("DELETE FROM config WHERE name=?", Array('anon_id')); + $db->Execute($config_insert, Array('anon_id', $db->Insert_ID())); + } + + # we can safely delete the user and recreate, hence changing the ID, + # because insert_defaults is only called during first installation + if($db->GetOne("SELECT * FROM users WHERE name=?", Array($admin_name))) { + $db->Execute("DELETE FROM users WHERE name=?", Array($admin_name)); + } + + $admin_pass = md5(strtolower($admin_name).$admin_pass); + $db->Execute($user_insert, Array($admin_name, $admin_pass, 'Y')); + + $db->Close(); + } +} // }}} +// }}} +// upgrade {{{ +function upgrade_process() { // {{{ + if(!isset($_POST['old_dsn']) || !isset($_POST["new_dsn"]) || !isset($_POST["old_data"])) { + die("Install is missing some paramaters (old_dsn, new_dsn, or old_data)"); + } + else { + $old_dsn = $_POST['old_dsn']; + $new_dsn = $_POST['new_dsn']; + $old_data = $_POST['old_data']; + } + + if(!is_readable($old_data)) {die("Can't find \"$old_data\"");} + if(!is_readable("$old_data/images")) {die("Can't find \"$old_data/images\"");} + if(!is_readable("$old_data/thumbs")) {die("Can't find \"$old_data/thumbs\"");} + + // set_admin_cookie($admin_name, $admin_pass); + create_tables($new_dsn); + build_dirs(); + move_data($old_dsn, $new_dsn, $old_data); + write_config($new_dsn); + +// header("Location: index.php?q=setup"); + print "

If everything looks OK, continue"; +} // }}} +function move_data($old_dsn, $new_dsn, $old_data) { + print("
Fetching old data..."); + $old_db = NewADOConnection($old_dsn); + $old_db->SetFetchMode(ADODB_FETCH_ASSOC); + # tmpfile & serialize? + $anon_id = -1; + $users = $old_db->GetAll("SELECT id, name, pass, joindate FROM users"); + $admins = $old_db->GetCol("SELECT owner_id FROM user_configs WHERE name='isadmin' AND value='true'"); + $images = $old_db->GetAll("SELECT id, owner_id, owner_ip, filename, hash, ext FROM images"); + $comments = $old_db->GetAll("SELECT id, image_id, owner_id, owner_ip, posted, comment FROM comments"); + $tags = $old_db->GetAll("SELECT image_id, tag FROM tags"); + $old_db->Close(); + + $new_db = NewADOConnection($new_dsn); + $new_db->SetFetchMode(ADODB_FETCH_ASSOC); + + if($users) { + print("
Moving users..."); + $new_db->Execute("DELETE FROM users"); + $new_db->Execute(" + INSERT INTO users(id, name, pass, joindate, enabled, admin, email) + VALUES(?, ?, ?, ?, 'Y', 'N', '')", $users); + } + + if($admins) { + print("
Setting account flags"); + $new_db->Execute("UPDATE users SET admin='Y' WHERE id=?", array($admins)); + } + + if(true) { + print("
Updating anonymous account..."); + $anon_id = $new_db->GetOne("SELECT id FROM users WHERE name='Anonymous'"); + if(!$anon_id) { + print("
Warning: 'Anonymous' not found; creating one"); + $new_db->Execute("INSERT INTO users(name, pass, joindate) VALUES ('Anonymous', NULL, now())"); + $anon_id = $new_db->Insert_ID(); + } + + $new_db->Execute("DELETE FROM config WHERE name=?", array("anon_id")); + $new_db->Execute("INSERT INTO config(name, value) VALUES(?, ?)", array('anon_id', $anon_id)); + } + + if($images) { + print("
Moving images..."); + $new_db->Execute("DELETE FROM images"); + $new_db->Execute(" + INSERT INTO images(id, owner_id, owner_ip, filename, hash, ext, filesize, width, height, source, posted) + VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, NULL, now())", $images); + } + + if($comments) { + print("
Moving comments..."); + + // HAAAAAAAX! + // the comments table is installed by an extension, so it won't be + // ready when we need it... + $new_db->Execute("DROP TABLE comments"); + $new_db->Execute("DELETE FROM config WHERE name=?", array('ext_comments_version')); + + $new_db->Execute("CREATE TABLE `comments` ( + `id` int(11) NOT NULL auto_increment, + `image_id` int(11) NOT NULL, + `owner_id` int(11) NOT NULL, + `owner_ip` char(16) NOT NULL, + `posted` datetime default NULL, + `comment` text NOT NULL, + PRIMARY KEY (`id`), + KEY `comments_image_id` (`image_id`) + )"); + $new_db->Execute("INSERT INTO config(name, value) VALUES(?, ?)", array("ext_comments_version", 1)); + + $new_db->Execute("DELETE FROM comments"); + $new_db->Execute(" + INSERT INTO comments(id, image_id, owner_id, owner_ip, posted, comment) + VALUES (?, ?, ?, ?, ?, ?)", $comments); + + print("
Setting orphan comments to anonymous..."); + $orphans = $new_db->GetCol(" + SELECT comments.id + FROM comments + LEFT JOIN users ON users.id = comments.owner_id + WHERE isnull(users.name)"); + if($orphans) { + foreach($orphans as $orphan) { + $new_db->Execute("UPDATE comments SET owner_id=? WHERE id=?", array($anon_id, $orphan)); + } + } + + print("
Setting orphan images to anonymous..."); + $orphans = $new_db->GetCol(" + SELECT images.id + FROM images + LEFT JOIN users ON users.id = images.owner_id + WHERE isnull(users.name)"); + if($orphans) { + foreach($orphans as $orphan) { + $new_db->Execute("UPDATE images SET owner_id=? WHERE id=?", array($anon_id, $orphan)); + } + } + } + + if($tags) { + print("
Moving tags.."); + $new_db->Execute("DELETE FROM tags"); + $new_db->Execute("INSERT INTO tags(image_id, tag) VALUES (?, ?)", $tags); + } + + print("
Moving files..."); + $result = $new_db->Execute("SELECT * FROM images"); + while(!$result->EOF) { + $fields = $result->fields; + + $id = $fields['id']; + $hash = $fields['hash']; + $ext = $fields['ext']; + $ab = substr($hash, 0, 2); + + if(file_exists("images/$ab/$hash")) { + unlink("images/$ab/$hash"); + } + + $fname = "$old_data/images/$id.$ext"; + if(file_exists($fname)) { + $size = filesize($fname); + $sizekb = (int)($size/1024); + $info = getimagesize($fname); + if($info) { + $width = $info[0]; + $height = $info[1]; + + // print "
{$id}: {$width}x{$height}, {$sizekb}KB\n"; // noise + $new_db->Execute("UPDATE images SET width=?, height=?, filesize=? WHERE id=?", + array($width, $height, $size, $id)); + } + + copy("$old_data/thumbs/$id.jpg", "thumbs/$ab/$hash"); + copy("$old_data/images/$id.$ext", "images/$ab/$hash"); + } + else { + print "
Warning: $fname not found; dropped from new database"; + $new_db->Execute("DELETE FROM images WHERE id=?", array($id)); + } + + $result->MoveNext(); + } + + $new_db->Close(); +} +// }}} + + +// table creation {{{ +/* + * Note: try and keep this as ANSI SQL compliant as possible, + * so that we can (in theory) support other databases + */ +function create_tables_mysql($db) { + $db->StartTrans(); + + $db->Execute("DROP TABLE IF EXISTS aliases"); + $db->Execute("CREATE TABLE aliases ( + oldtag varchar(255) NOT NULL, + newtag varchar(255) NOT NULL, + PRIMARY KEY (oldtag) + )"); + + $db->Execute("DROP TABLE IF EXISTS config"); + $db->Execute("CREATE TABLE config ( + name varchar(255) NOT NULL, + value text, + PRIMARY KEY (name) + )"); + + $db->Execute("DROP TABLE IF EXISTS images"); + $db->Execute("CREATE TABLE images ( + id int(11) NOT NULL auto_increment, + owner_id int(11) NOT NULL default '0', + owner_ip char(16) default NULL, + filename varchar(64) NOT NULL default '', + filesize int(11) NOT NULL default '0', + hash char(32) NOT NULL default '', + ext char(4) NOT NULL default '', + source varchar(255), + width int(11) NOT NULL, + height int(11) NOT NULL, + posted datetime NOT NULL, + PRIMARY KEY (id), + UNIQUE (hash) + )"); + + $db->Execute("DROP TABLE IF EXISTS tags"); + $db->Execute("CREATE TABLE tags ( + image_id int(11) NOT NULL default '0', + tag varchar(255) NOT NULL default '', + UNIQUE KEY image_id (image_id,tag), + KEY tags_tag (tag), + KEY tags_image_id (image_id) + )"); + + $db->Execute("DROP TABLE IF EXISTS users"); + $db->Execute("CREATE TABLE users ( + id int(11) NOT NULL auto_increment, + name varchar(32) NOT NULL, + pass char(32) default NULL, + joindate datetime NOT NULL, + enabled enum('N','Y') NOT NULL default 'Y', + admin enum('N','Y') NOT NULL default 'N', + email varchar(255) default NULL, + PRIMARY KEY (id), + UNIQUE (name) + )"); + + $db->Execute("INSERT INTO config(name, value) VALUES(?, ?)", Array('db_version', '2.0.0.9')); + + return $db->CommitTrans(); +} +// }}} +?> diff --git a/lib/adodb/adodb-iterator.inc.php b/lib/adodb/adodb-iterator.inc.php new file mode 100644 index 00000000..031c963d --- /dev/null +++ b/lib/adodb/adodb-iterator.inc.php @@ -0,0 +1,85 @@ +Execute("select * from adoxyz"); + foreach($rs as $k => $v) { + echo $k; print_r($v); echo "
"; + } + + + Iterator code based on http://cvs.php.net/cvs.php/php-src/ext/spl/examples/cachingiterator.inc?login=2 + */ + + + class ADODB_Iterator implements Iterator { + + private $rs; + + function __construct($rs) + { + $this->rs = $rs; + } + function rewind() + { + $this->rs->MoveFirst(); + } + + function valid() + { + return !$this->rs->EOF; + } + + function key() + { + return $this->rs->_currentRow; + } + + function current() + { + return $this->rs->fields; + } + + function next() + { + $this->rs->MoveNext(); + } + + function __call($func, $params) + { + return call_user_func_array(array($this->rs, $func), $params); + } + + + function hasMore() + { + return !$this->rs->EOF; + } + +} + + +class ADODB_BASE_RS implements IteratorAggregate { + function getIterator() { + return new ADODB_Iterator($this); + } + + /* this is experimental - i don't really know what to return... */ + function __toString() + { + include_once(ADODB_DIR.'/toexport.inc.php'); + return _adodb_export($this,',',',',false,true); + } +} + + +?> \ No newline at end of file diff --git a/lib/adodb/adodb-lib.inc.php b/lib/adodb/adodb-lib.inc.php new file mode 100644 index 00000000..bdda6498 --- /dev/null +++ b/lib/adodb/adodb-lib.inc.php @@ -0,0 +1,1128 @@ + sizeof($array)) $max = sizeof($array); + else $max = $probe; + + + for ($j=0;$j < $max; $j++) { + $row =& $array[$j]; + if (!$row) break; + $i = -1; + foreach($row as $v) { + $i += 1; + + if (isset($types[$i]) && $types[$i]=='C') continue; + + //print " ($i ".$types[$i]. "$v) "; + $v = trim($v); + + if (!preg_match('/^[+-]{0,1}[0-9\.]+$/',$v)) { + $types[$i] = 'C'; // once C, always C + + continue; + } + if ($j == 0) { + // If empty string, we presume is character + // test for integer for 1st row only + // after that it is up to testing other rows to prove + // that it is not an integer + if (strlen($v) == 0) $types[$i] = 'C'; + if (strpos($v,'.') !== false) $types[$i] = 'N'; + else $types[$i] = 'I'; + continue; + } + + if (strpos($v,'.') !== false) $types[$i] = 'N'; + + } + } +} + +function &adodb_transpose(&$arr, &$newarr, &$hdr) +{ + $oldX = sizeof(reset($arr)); + $oldY = sizeof($arr); + + if ($hdr) { + $startx = 1; + $hdr = array(); + for ($y = 0; $y < $oldY; $y++) { + $hdr[] = $arr[$y][0]; + } + } else + $startx = 0; + + for ($x = $startx; $x < $oldX; $x++) { + $newarr[] = array(); + for ($y = 0; $y < $oldY; $y++) { + $newarr[$x-$startx][] = $arr[$y][$x]; + } + } +} + +// Force key to upper. +// See also http://www.php.net/manual/en/function.array-change-key-case.php +function _array_change_key_case($an_array) +{ + if (is_array($an_array)) { + $new_array = array(); + foreach($an_array as $key=>$value) + $new_array[strtoupper($key)] = $value; + + return $new_array; + } + + return $an_array; +} + +function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc) +{ + if (count($fieldArray) == 0) return 0; + $first = true; + $uSet = ''; + + if (!is_array($keyCol)) { + $keyCol = array($keyCol); + } + foreach($fieldArray as $k => $v) { + if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,$zthis->null2null)!=0) { + $v = $zthis->qstr($v); + $fieldArray[$k] = $v; + } + if (in_array($k,$keyCol)) continue; // skip UPDATE if is key + + if ($first) { + $first = false; + $uSet = "$k=$v"; + } else + $uSet .= ",$k=$v"; + } + + $where = false; + foreach ($keyCol as $v) { + if (isset($fieldArray[$v])) { + if ($where) $where .= ' and '.$v.'='.$fieldArray[$v]; + else $where = $v.'='.$fieldArray[$v]; + } + } + + if ($uSet && $where) { + $update = "UPDATE $table SET $uSet WHERE $where"; + + $rs = $zthis->Execute($update); + + + if ($rs) { + if ($zthis->poorAffectedRows) { + /* + The Select count(*) wipes out any errors that the update would have returned. + http://phplens.com/lens/lensforum/msgs.php?id=5696 + */ + if ($zthis->ErrorNo()<>0) return 0; + + # affected_rows == 0 if update field values identical to old values + # for mysql - which is silly. + + $cnt = $zthis->GetOne("select count(*) from $table where $where"); + if ($cnt > 0) return 1; // record already exists + } else { + if (($zthis->Affected_Rows()>0)) return 1; + } + } else + return 0; + } + + // print "

Error=".$this->ErrorNo().'

'; + $first = true; + foreach($fieldArray as $k => $v) { + if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col + + if ($first) { + $first = false; + $iCols = "$k"; + $iVals = "$v"; + } else { + $iCols .= ",$k"; + $iVals .= ",$v"; + } + } + $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; + $rs = $zthis->Execute($insert); + return ($rs) ? 2 : 0; +} + +// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM +function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false, + $size=0, $selectAttr='',$compareFields0=true) +{ + $hasvalue = false; + + if ($multiple or is_array($defstr)) { + if ($size==0) $size=5; + $attr = ' multiple size="'.$size.'"'; + if (!strpos($name,'[]')) $name .= '[]'; + } else if ($size) $attr = ' size="'.$size.'"'; + else $attr =''; + + $s = '\n"; +} + +// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM +function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false, + $size=0, $selectAttr='',$compareFields0=true) +{ + $hasvalue = false; + + if ($multiple or is_array($defstr)) { + if ($size==0) $size=5; + $attr = ' multiple size="'.$size.'"'; + if (!strpos($name,'[]')) $name .= '[]'; + } else if ($size) $attr = ' size="'.$size.'"'; + else $attr =''; + + $s = '\n"; +} + + +/* + Count the number of records this sql statement will return by using + query rewriting heuristics... + + Does not work with UNIONs, except with postgresql and oracle. + + Usage: + + $conn->Connect(...); + $cnt = _adodb_getcount($conn, $sql); + +*/ +function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) +{ + $qryRecs = 0; + + if (!empty($zthis->_nestedSQL) || preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || + preg_match('/\s+GROUP\s+BY\s+/is',$sql) || + preg_match('/\s+UNION\s+/is',$sql)) { + // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias + // but this is only supported by oracle and postgresql... + if ($zthis->dataProvider == 'oci8') { + + $rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$sql); + + // Allow Oracle hints to be used for query optimization, Chris Wrye + if (preg_match('#/\\*+.*?\\*\\/#', $sql, $hint)) { + $rewritesql = "SELECT ".$hint[0]." COUNT(*) FROM (".$rewritesql.")"; + } else + $rewritesql = "SELECT COUNT(*) FROM (".$rewritesql.")"; + + } else if (strncmp($zthis->databaseType,'postgres',8) == 0) { + $rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$sql); + $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_"; + } + } else { + // now replace SELECT ... FROM with SELECT COUNT(*) FROM + $rewritesql = preg_replace( + '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql); + + + + // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails + // with mssql, access and postgresql. Also a good speedup optimization - skips sorting! + // also see http://phplens.com/lens/lensforum/msgs.php?id=12752 + if (preg_match('/\sORDER\s+BY\s*\(/i',$rewritesql)) + $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql); + else + $rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$rewritesql); + } + + + + if (isset($rewritesql) && $rewritesql != $sql) { + if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[1]; + + if ($secs2cache) { + // we only use half the time of secs2cache because the count can quickly + // become inaccurate if new records are added + $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr); + + } else { + $qryRecs = $zthis->GetOne($rewritesql,$inputarr); + } + if ($qryRecs !== false) return $qryRecs; + } + //-------------------------------------------- + // query rewrite failed - so try slower way... + + + // strip off unneeded ORDER BY if no UNION + if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql; + else $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); + + if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0]; + + $rstest = &$zthis->Execute($rewritesql,$inputarr); + if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr); + + if ($rstest) { + $qryRecs = $rstest->RecordCount(); + if ($qryRecs == -1) { + global $ADODB_EXTENSION; + // some databases will return -1 on MoveLast() - change to MoveNext() + if ($ADODB_EXTENSION) { + while(!$rstest->EOF) { + adodb_movenext($rstest); + } + } else { + while(!$rstest->EOF) { + $rstest->MoveNext(); + } + } + $qryRecs = $rstest->_currentRow; + } + $rstest->Close(); + if ($qryRecs == -1) return 0; + } + return $qryRecs; +} + +/* + Code originally from "Cornel G" + + This code might not work with SQL that has UNION in it + + Also if you are using CachePageExecute(), there is a strong possibility that + data will get out of synch. use CachePageExecute() only with tables that + rarely change. +*/ +function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, + $inputarr=false, $secs2cache=0) +{ + $atfirstpage = false; + $atlastpage = false; + $lastpageno=1; + + // If an invalid nrows is supplied, + // we assume a default value of 10 rows per page + if (!isset($nrows) || $nrows <= 0) $nrows = 10; + + $qryRecs = false; //count records for no offset + + $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache); + $lastpageno = (int) ceil($qryRecs / $nrows); + $zthis->_maxRecordCount = $qryRecs; + + + + // ***** Here we check whether $page is the last page or + // whether we are trying to retrieve + // a page number greater than the last page number. + if ($page >= $lastpageno) { + $page = $lastpageno; + $atlastpage = true; + } + + // If page number <= 1, then we are at the first page + if (empty($page) || $page <= 1) { + $page = 1; + $atfirstpage = true; + } + + // We get the data we want + $offset = $nrows * ($page-1); + if ($secs2cache > 0) + $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr); + else + $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); + + + // Before returning the RecordSet, we set the pagination properties we need + if ($rsreturn) { + $rsreturn->_maxRecordCount = $qryRecs; + $rsreturn->rowsPerPage = $nrows; + $rsreturn->AbsolutePage($page); + $rsreturn->AtFirstPage($atfirstpage); + $rsreturn->AtLastPage($atlastpage); + $rsreturn->LastPageNo($lastpageno); + } + return $rsreturn; +} + +// Iván Oliva version +function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0) +{ + + $atfirstpage = false; + $atlastpage = false; + + if (!isset($page) || $page <= 1) { // If page number <= 1, then we are at the first page + $page = 1; + $atfirstpage = true; + } + if ($nrows <= 0) $nrows = 10; // If an invalid nrows is supplied, we assume a default value of 10 rows per page + + // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than + // the last page number. + $pagecounter = $page + 1; + $pagecounteroffset = ($pagecounter * $nrows) - $nrows; + if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr); + else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache); + if ($rstest) { + while ($rstest && $rstest->EOF && $pagecounter>0) { + $atlastpage = true; + $pagecounter--; + $pagecounteroffset = $nrows * ($pagecounter - 1); + $rstest->Close(); + if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr); + else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache); + } + if ($rstest) $rstest->Close(); + } + if ($atlastpage) { // If we are at the last page or beyond it, we are going to retrieve it + $page = $pagecounter; + if ($page == 1) $atfirstpage = true; // We have to do this again in case the last page is the same as the first + //... page, that is, the recordset has only 1 page. + } + + // We get the data we want + $offset = $nrows * ($page-1); + if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr); + else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); + + // Before returning the RecordSet, we set the pagination properties we need + if ($rsreturn) { + $rsreturn->rowsPerPage = $nrows; + $rsreturn->AbsolutePage($page); + $rsreturn->AtFirstPage($atfirstpage); + $rsreturn->AtLastPage($atlastpage); + } + return $rsreturn; +} + +function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=2) +{ + if (!$rs) { + printf(ADODB_BAD_RS,'GetUpdateSQL'); + return false; + } + + $fieldUpdatedCount = 0; + $arrFields = _array_change_key_case($arrFields); + + $hasnumeric = isset($rs->fields[0]); + $setFields = ''; + + // Loop through all of the fields in the recordset + for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { + // Get the field from the recordset + $field = $rs->FetchField($i); + + // If the recordset field is one + // of the fields passed in then process. + $upperfname = strtoupper($field->name); + if (adodb_key_exists($upperfname,$arrFields,$force)) { + + // If the existing field value in the recordset + // is different from the value passed in then + // go ahead and append the field name and new value to + // the update query. + + if ($hasnumeric) $val = $rs->fields[$i]; + else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname]; + else if (isset($rs->fields[$field->name])) $val = $rs->fields[$field->name]; + else if (isset($rs->fields[strtolower($upperfname)])) $val = $rs->fields[strtolower($upperfname)]; + else $val = ''; + + + if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) { + // Set the counter for the number of fields that will be updated. + $fieldUpdatedCount++; + + // Based on the datatype of the field + // Format the value properly for the database + $type = $rs->MetaType($field->type); + + + if ($type == 'null') { + $type = 'C'; + } + + if (strpos($upperfname,' ') !== false) + $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote; + else + $fnameq = $upperfname; + + + // is_null requires php 4.0.4 + //********************************************************// + if (is_null($arrFields[$upperfname]) + || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0) + || $arrFields[$upperfname] === $zthis->null2null + ) + { + switch ($force) { + + //case 0: + // //Ignore empty values. This is allready handled in "adodb_key_exists" function. + //break; + + case 1: + //Set null + $setFields .= $field->name . " = null, "; + break; + + case 2: + //Set empty + $arrFields[$upperfname] = ""; + $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq); + break; + default: + case 3: + //Set the value that was given in array, so you can give both null and empty values + if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) { + $setFields .= $field->name . " = null, "; + } else { + $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq); + } + break; + } + //********************************************************// + } else { + //we do this so each driver can customize the sql for + //DB specific column types. + //Oracle needs BLOB types to be handled with a returning clause + //postgres has special needs as well + $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq, + $arrFields, $magicq); + } + } + } + } + + // If there were any modified fields then build the rest of the update query. + if ($fieldUpdatedCount > 0 || $forceUpdate) { + // Get the table name from the existing query. + if (!empty($rs->tableName)) $tableName = $rs->tableName; + else { + preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName); + $tableName = $tableName[1]; + } + // Get the full where clause excluding the word "WHERE" from + // the existing query. + preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause); + + $discard = false; + // not a good hack, improvements? + if ($whereClause) { + #var_dump($whereClause); + if (preg_match('/\s(ORDER\s.*)/is', $whereClause[1], $discard)); + else if (preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard)); + else if (preg_match('/\s(FOR UPDATE.*)/is', $whereClause[1], $discard)); + else preg_match('/\s.*(\) WHERE .*)/is', $whereClause[1], $discard); # see http://sourceforge.net/tracker/index.php?func=detail&aid=1379638&group_id=42718&atid=433976 + } else + $whereClause = array(false,false); + + if ($discard) + $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1])); + + $sql = 'UPDATE '.$tableName.' SET '.substr($setFields, 0, -2); + if (strlen($whereClause[1]) > 0) + $sql .= ' WHERE '.$whereClause[1]; + + return $sql; + + } else { + return false; + } +} + +function adodb_key_exists($key, &$arr,$force=2) +{ + if ($force<=0) { + // the following is the old behaviour where null or empty fields are ignored + return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0); + } + + if (isset($arr[$key])) return true; + ## null check below + if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr); + return false; +} + +/** + * There is a special case of this function for the oci8 driver. + * The proper way to handle an insert w/ a blob in oracle requires + * a returning clause with bind variables and a descriptor blob. + * + * + */ +function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2) +{ +static $cacheRS = false; +static $cacheSig = 0; +static $cacheCols; + + $tableName = ''; + $values = ''; + $fields = ''; + $recordSet = null; + $arrFields = _array_change_key_case($arrFields); + $fieldInsertedCount = 0; + + if (is_string($rs)) { + //ok we have a table name + //try and get the column info ourself. + $tableName = $rs; + + //we need an object for the recordSet + //because we have to call MetaType. + //php can't do a $rsclass::MetaType() + $rsclass = $zthis->rsPrefix.$zthis->databaseType; + $recordSet = new $rsclass(-1,$zthis->fetchMode); + $recordSet->connection = &$zthis; + + if (is_string($cacheRS) && $cacheRS == $rs) { + $columns =& $cacheCols; + } else { + $columns = $zthis->MetaColumns( $tableName ); + $cacheRS = $tableName; + $cacheCols = $columns; + } + } else if (is_subclass_of($rs, 'adorecordset')) { + if (isset($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) { + $columns =& $cacheCols; + } else { + for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) + $columns[] = $rs->FetchField($i); + $cacheRS = $cacheSig; + $cacheCols = $columns; + $rs->insertSig = $cacheSig++; + } + $recordSet =& $rs; + + } else { + printf(ADODB_BAD_RS,'GetInsertSQL'); + return false; + } + + // Loop through all of the fields in the recordset + foreach( $columns as $field ) { + $upperfname = strtoupper($field->name); + if (adodb_key_exists($upperfname,$arrFields,$force)) { + $bad = false; + if (strpos($upperfname,' ') !== false) + $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote; + else + $fnameq = $upperfname; + + $type = $recordSet->MetaType($field->type); + + /********************************************************/ + if (is_null($arrFields[$upperfname]) + || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0) + || $arrFields[$upperfname] === $zthis->null2null + ) + { + switch ($force) { + + case 0: // we must always set null if missing + $bad = true; + break; + + case 1: + $values .= "null, "; + break; + + case 2: + //Set empty + $arrFields[$upperfname] = ""; + $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,$arrFields, $magicq); + break; + + default: + case 3: + //Set the value that was given in array, so you can give both null and empty values + if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) { + $values .= "null, "; + } else { + $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, $arrFields, $magicq); + } + break; + } // switch + + /*********************************************************/ + } else { + //we do this so each driver can customize the sql for + //DB specific column types. + //Oracle needs BLOB types to be handled with a returning clause + //postgres has special needs as well + $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, + $arrFields, $magicq); + } + + if ($bad) continue; + // Set the counter for the number of fields that will be inserted. + $fieldInsertedCount++; + + + // Get the name of the fields to insert + $fields .= $fnameq . ", "; + } + } + + + // If there were any inserted fields then build the rest of the insert query. + if ($fieldInsertedCount <= 0) return false; + + // Get the table name from the existing query. + if (!$tableName) { + if (!empty($rs->tableName)) $tableName = $rs->tableName; + else if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName)) + $tableName = $tableName[1]; + else + return false; + } + + // Strip off the comma and space on the end of both the fields + // and their values. + $fields = substr($fields, 0, -2); + $values = substr($values, 0, -2); + + // Append the fields and their values to the insert query. + return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )'; +} + + +/** + * This private method is used to help construct + * the update/sql which is generated by GetInsertSQL and GetUpdateSQL. + * It handles the string construction of 1 column -> sql string based on + * the column type. We want to do 'safe' handling of BLOBs + * + * @param string the type of sql we are trying to create + * 'I' or 'U'. + * @param string column data type from the db::MetaType() method + * @param string the column name + * @param array the column value + * + * @return string + * + */ +function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFields, $magicq) +{ + $sql = ''; + + // Based on the datatype of the field + // Format the value properly for the database + switch($type) { + case 'B': + //in order to handle Blobs correctly, we need + //to do some magic for Oracle + + //we need to create a new descriptor to handle + //this properly + if (!empty($zthis->hasReturningInto)) { + if ($action == 'I') { + $sql = 'empty_blob(), '; + } else { + $sql = $fnameq. '=empty_blob(), '; + } + //add the variable to the returning clause array + //so the user can build this later in + //case they want to add more to it + $zthis->_returningArray[$fname] = ':xx'.$fname.'xx'; + } else if (empty($arrFields[$fname])){ + if ($action == 'I') { + $sql = 'empty_blob(), '; + } else { + $sql = $fnameq. '=empty_blob(), '; + } + } else { + //this is to maintain compatibility + //with older adodb versions. + $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false); + } + break; + + case "X": + //we need to do some more magic here for long variables + //to handle these correctly in oracle. + + //create a safe bind var name + //to avoid conflicts w/ dupes. + if (!empty($zthis->hasReturningInto)) { + if ($action == 'I') { + $sql = ':xx'.$fname.'xx, '; + } else { + $sql = $fnameq.'=:xx'.$fname.'xx, '; + } + //add the variable to the returning clause array + //so the user can build this later in + //case they want to add more to it + $zthis->_returningArray[$fname] = ':xx'.$fname.'xx'; + } else { + //this is to maintain compatibility + //with older adodb versions. + $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false); + } + break; + + default: + $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false); + break; + } + + return $sql; +} + +function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq, $recurse=true) +{ + + if ($recurse) { + switch($zthis->dataProvider) { + case 'postgres': + if ($type == 'L') $type = 'C'; + break; + case 'oci8': + return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq); + + } + } + + switch($type) { + case "C": + case "X": + case 'B': + $val = $zthis->qstr($arrFields[$fname],$magicq); + break; + + case "D": + $val = $zthis->DBDate($arrFields[$fname]); + break; + + case "T": + $val = $zthis->DBTimeStamp($arrFields[$fname]); + break; + + default: + $val = $arrFields[$fname]; + if (empty($val)) $val = '0'; + break; + } + + if ($action == 'I') return $val . ", "; + + + return $fnameq . "=" . $val . ", "; + +} + + + +function _adodb_debug_execute(&$zthis, $sql, $inputarr) +{ + $ss = ''; + if ($inputarr) { + foreach($inputarr as $kk=>$vv) { + if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...'; + $ss .= "($kk=>'$vv') "; + } + $ss = "[ $ss ]"; + } + $sqlTxt = is_array($sql) ? $sql[0] : $sql; + /*str_replace(', ','##1#__^LF',is_array($sql) ? $sql[0] : $sql); + $sqlTxt = str_replace(',',', ',$sqlTxt); + $sqlTxt = str_replace('##1#__^LF', ', ' ,$sqlTxt); + */ + // check if running from browser or command-line + $inBrowser = isset($_SERVER['HTTP_USER_AGENT']); + + $dbt = $zthis->databaseType; + if (isset($zthis->dsnType)) $dbt .= '-'.$zthis->dsnType; + if ($inBrowser) { + if ($ss) { + $ss = ''.htmlspecialchars($ss).''; + } + if ($zthis->debug === -1) + ADOConnection::outp( "
\n($dbt): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); + else + ADOConnection::outp( "


\n($dbt): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); + } else { + ADOConnection::outp("-----\n($dbt): ".$sqlTxt."\n-----\n",false); + } + + $qID = $zthis->_query($sql,$inputarr); + + /* + Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql + because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion + */ + if ($zthis->databaseType == 'mssql') { + // ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6 + if($emsg = $zthis->ErrorMsg()) { + if ($err = $zthis->ErrorNo()) ADOConnection::outp($err.': '.$emsg); + } + } else if (!$qID) { + ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg()); + } + + if ($zthis->debug === 99) _adodb_backtrace(true,9999,2); + return $qID; +} + +# pretty print the debug_backtrace function +function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0) +{ + if (!function_exists('debug_backtrace')) return ''; + + $html = (isset($_SERVER['HTTP_USER_AGENT'])); + $fmt = ($html) ? " %% line %4d, file: %s" : "%% line %4d, file: %s"; + + $MAXSTRLEN = 128; + + $s = ($html) ? '
' : '';
+	
+	if (is_array($printOrArr)) $traceArr = $printOrArr;
+	else $traceArr = debug_backtrace();
+	array_shift($traceArr);
+	array_shift($traceArr);
+	$tabs = sizeof($traceArr)-2;
+	
+	foreach ($traceArr as $arr) {
+		if ($skippy) {$skippy -= 1; continue;}
+		$levels -= 1;
+		if ($levels < 0) break;
+		
+		$args = array();
+		for ($i=0; $i < $tabs; $i++) $s .=  ($html) ? '   ' : "\t";
+		$tabs -= 1;
+		if ($html) $s .= '';
+		if (isset($arr['class'])) $s .= $arr['class'].'.';
+		if (isset($arr['args']))
+		 foreach($arr['args'] as $v) {
+			if (is_null($v)) $args[] = 'null';
+			else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
+			else if (is_object($v)) $args[] = 'Object:'.get_class($v);
+			else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
+			else {
+				$v = (string) @$v;
+				$str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
+				if (strlen($v) > $MAXSTRLEN) $str .= '...';
+				$args[] = $str;
+			}
+		}
+		$s .= $arr['function'].'('.implode(', ',$args).')';
+		
+		
+		$s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
+			
+		$s .= "\n";
+	}	
+	if ($html) $s .= '
'; + if ($printOrArr) print $s; + + return $s; +} +/* +function _adodb_find_from($sql) +{ + + $sql = str_replace(array("\n","\r"), ' ', $sql); + $charCount = strlen($sql); + + $inString = false; + $quote = ''; + $parentheseCount = 0; + $prevChars = ''; + $nextChars = ''; + + + for($i = 0; $i < $charCount; $i++) { + + $char = substr($sql,$i,1); + $prevChars = substr($sql,0,$i); + $nextChars = substr($sql,$i+1); + + if((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === false) { + $quote = $char; + $inString = true; + } + + elseif((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === true && $quote == $char) { + $quote = ""; + $inString = false; + } + + elseif($char == "(" && $inString === false) + $parentheseCount++; + + elseif($char == ")" && $inString === false && $parentheseCount > 0) + $parentheseCount--; + + elseif($parentheseCount <= 0 && $inString === false && $char == " " && strtoupper(substr($prevChars,-5,5)) == " FROM") + return $i; + + } +} +*/ + +?> \ No newline at end of file diff --git a/lib/adodb/adodb-php4.inc.php b/lib/adodb/adodb-php4.inc.php new file mode 100644 index 00000000..a23dc170 --- /dev/null +++ b/lib/adodb/adodb-php4.inc.php @@ -0,0 +1,16 @@ + \ No newline at end of file diff --git a/lib/adodb/adodb-time.inc.php b/lib/adodb/adodb-time.inc.php new file mode 100644 index 00000000..51f69f76 --- /dev/null +++ b/lib/adodb/adodb-time.inc.php @@ -0,0 +1,1337 @@ + 4 digit year conversion. The maximum is billions of years in the +future, but this is a theoretical limit as the computation of that year +would take too long with the current implementation of adodb_mktime(). + +This library replaces native functions as follows: + +
	
+	getdate()  with  adodb_getdate()
+	date()     with  adodb_date() 
+	gmdate()   with  adodb_gmdate()
+	mktime()   with  adodb_mktime()
+	gmmktime() with  adodb_gmmktime()
+	strftime() with  adodb_strftime()
+	strftime() with  adodb_gmstrftime()
+
+ +The parameters are identical, except that adodb_date() accepts a subset +of date()'s field formats. Mktime() will convert from local time to GMT, +and date() will convert from GMT to local time, but daylight savings is +not handled currently. + +This library is independant of the rest of ADOdb, and can be used +as standalone code. + +PERFORMANCE + +For high speed, this library uses the native date functions where +possible, and only switches to PHP code when the dates fall outside +the 32-bit signed integer range. + +GREGORIAN CORRECTION + +Pope Gregory shortened October of A.D. 1582 by ten days. Thursday, +October 4, 1582 (Julian) was followed immediately by Friday, October 15, +1582 (Gregorian). + +Since 0.06, we handle this correctly, so: + +adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582) + == 24 * 3600 (1 day) + +============================================================================= + +COPYRIGHT + +(c) 2003-2005 John Lim and released under BSD-style license except for code by +jackbbs, which includes adodb_mktime, adodb_get_gmt_diff, adodb_is_leap_year +and originally found at http://www.php.net/manual/en/function.mktime.php + +============================================================================= + +BUG REPORTS + +These should be posted to the ADOdb forums at + + http://phplens.com/lens/lensforum/topics.php?id=4 + +============================================================================= + +FUNCTION DESCRIPTIONS + + +** FUNCTION adodb_getdate($date=false) + +Returns an array containing date information, as getdate(), but supports +dates greater than 1901 to 2038. The local date/time format is derived from a +heuristic the first time adodb_getdate is called. + + +** FUNCTION adodb_date($fmt, $timestamp = false) + +Convert a timestamp to a formatted local date. If $timestamp is not defined, the +current timestamp is used. Unlike the function date(), it supports dates +outside the 1901 to 2038 range. + +The format fields that adodb_date supports: + +
+	a - "am" or "pm" 
+	A - "AM" or "PM" 
+	d - day of the month, 2 digits with leading zeros; i.e. "01" to "31" 
+	D - day of the week, textual, 3 letters; e.g. "Fri" 
+	F - month, textual, long; e.g. "January" 
+	g - hour, 12-hour format without leading zeros; i.e. "1" to "12" 
+	G - hour, 24-hour format without leading zeros; i.e. "0" to "23" 
+	h - hour, 12-hour format; i.e. "01" to "12" 
+	H - hour, 24-hour format; i.e. "00" to "23" 
+	i - minutes; i.e. "00" to "59" 
+	j - day of the month without leading zeros; i.e. "1" to "31" 
+	l (lowercase 'L') - day of the week, textual, long; e.g. "Friday"  
+	L - boolean for whether it is a leap year; i.e. "0" or "1" 
+	m - month; i.e. "01" to "12" 
+	M - month, textual, 3 letters; e.g. "Jan" 
+	n - month without leading zeros; i.e. "1" to "12" 
+	O - Difference to Greenwich time in hours; e.g. "+0200" 
+	Q - Quarter, as in 1, 2, 3, 4 
+	r - RFC 2822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200" 
+	s - seconds; i.e. "00" to "59" 
+	S - English ordinal suffix for the day of the month, 2 characters; 
+	   			i.e. "st", "nd", "rd" or "th" 
+	t - number of days in the given month; i.e. "28" to "31"
+	T - Timezone setting of this machine; e.g. "EST" or "MDT" 
+	U - seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)  
+	w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday) 
+	Y - year, 4 digits; e.g. "1999" 
+	y - year, 2 digits; e.g. "99" 
+	z - day of the year; i.e. "0" to "365" 
+	Z - timezone offset in seconds (i.e. "-43200" to "43200"). 
+	   			The offset for timezones west of UTC is always negative, 
+				and for those east of UTC is always positive. 
+
+ +Unsupported: +
+	B - Swatch Internet time 
+	I (capital i) - "1" if Daylight Savings Time, "0" otherwise.
+	W - ISO-8601 week number of year, weeks starting on Monday 
+
+
+ + +** FUNCTION adodb_date2($fmt, $isoDateString = false) +Same as adodb_date, but 2nd parameter accepts iso date, eg. + + adodb_date2('d-M-Y H:i','2003-12-25 13:01:34'); + + +** FUNCTION adodb_gmdate($fmt, $timestamp = false) + +Convert a timestamp to a formatted GMT date. If $timestamp is not defined, the +current timestamp is used. Unlike the function date(), it supports dates +outside the 1901 to 2038 range. + + +** FUNCTION adodb_mktime($hr, $min, $sec[, $month, $day, $year]) + +Converts a local date to a unix timestamp. Unlike the function mktime(), it supports +dates outside the 1901 to 2038 range. All parameters are optional. + + +** FUNCTION adodb_gmmktime($hr, $min, $sec [, $month, $day, $year]) + +Converts a gmt date to a unix timestamp. Unlike the function gmmktime(), it supports +dates outside the 1901 to 2038 range. Differs from gmmktime() in that all parameters +are currently compulsory. + +** FUNCTION adodb_gmstrftime($fmt, $timestamp = false) +Convert a timestamp to a formatted GMT date. + +** FUNCTION adodb_strftime($fmt, $timestamp = false) + +Convert a timestamp to a formatted local date. Internally converts $fmt into +adodb_date format, then echo result. + +For best results, you can define the local date format yourself. Define a global +variable $ADODB_DATE_LOCALE which is an array, 1st element is date format using +adodb_date syntax, and 2nd element is the time format, also in adodb_date syntax. + + eg. $ADODB_DATE_LOCALE = array('d/m/Y','H:i:s'); + + Supported format codes: + +
+	%a - abbreviated weekday name according to the current locale 
+	%A - full weekday name according to the current locale 
+	%b - abbreviated month name according to the current locale 
+	%B - full month name according to the current locale 
+	%c - preferred date and time representation for the current locale 
+	%d - day of the month as a decimal number (range 01 to 31) 
+	%D - same as %m/%d/%y 
+	%e - day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31') 
+	%h - same as %b
+	%H - hour as a decimal number using a 24-hour clock (range 00 to 23) 
+	%I - hour as a decimal number using a 12-hour clock (range 01 to 12) 
+	%m - month as a decimal number (range 01 to 12) 
+	%M - minute as a decimal number 
+	%n - newline character 
+	%p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale 
+	%r - time in a.m. and p.m. notation 
+	%R - time in 24 hour notation 
+	%S - second as a decimal number 
+	%t - tab character 
+	%T - current time, equal to %H:%M:%S 
+	%x - preferred date representation for the current locale without the time 
+	%X - preferred time representation for the current locale without the date 
+	%y - year as a decimal number without a century (range 00 to 99) 
+	%Y - year as a decimal number including the century 
+	%Z - time zone or name or abbreviation 
+	%% - a literal `%' character 
+
+ + Unsupported codes: +
+	%C - century number (the year divided by 100 and truncated to an integer, range 00 to 99) 
+	%g - like %G, but without the century. 
+	%G - The 4-digit year corresponding to the ISO week number (see %V). 
+	     This has the same format and value as %Y, except that if the ISO week number belongs 
+		 to the previous or next year, that year is used instead. 
+	%j - day of the year as a decimal number (range 001 to 366) 
+	%u - weekday as a decimal number [1,7], with 1 representing Monday 
+	%U - week number of the current year as a decimal number, starting 
+	    with the first Sunday as the first day of the first week 
+	%V - The ISO 8601:1988 week number of the current year as a decimal number, 
+	     range 01 to 53, where week 1 is the first week that has at least 4 days in the 
+		 current year, and with Monday as the first day of the week. (Use %G or %g for 
+		 the year component that corresponds to the week number for the specified timestamp.) 
+	%w - day of the week as a decimal, Sunday being 0 
+	%W - week number of the current year as a decimal number, starting with the 
+	     first Monday as the first day of the first week 
+
+ +============================================================================= + +NOTES + +Useful url for generating test timestamps: + http://www.4webhelp.net/us/timestamp.php + +Possible future optimizations include + +a. Using an algorithm similar to Plauger's in "The Standard C Library" +(page 428, xttotm.c _Ttotm() function). Plauger's algorithm will not +work outside 32-bit signed range, so i decided not to implement it. + +b. Implement daylight savings, which looks awfully complicated, see + http://webexhibits.org/daylightsaving/ + + +CHANGELOG +- 19 March 2006 0.24 +Changed strftime() locale detection, because some locales prepend the day of week to the date when %c is used. + +- 10 Feb 2006 0.23 +PHP5 compat: when we detect PHP5, the RFC2822 format for gmt 0000hrs is changed from -0000 to +0000. + In PHP4, we will still use -0000 for 100% compat with PHP4. + +- 08 Sept 2005 0.22 +In adodb_date2(), $is_gmt not supported properly. Fixed. + +- 18 July 2005 0.21 +In PHP 4.3.11, the 'r' format has changed. Leading 0 in day is added. Changed for compat. +Added support for negative months in adodb_mktime(). + +- 24 Feb 2005 0.20 +Added limited strftime/gmstrftime support. x10 improvement in performance of adodb_date(). + +- 21 Dec 2004 0.17 +In adodb_getdate(), the timestamp was accidentally converted to gmt when $is_gmt is false. +Also adodb_mktime(0,0,0) did not work properly. Both fixed thx Mauro. + +- 17 Nov 2004 0.16 +Removed intval typecast in adodb_mktime() for secs, allowing: + adodb_mktime(0,0,0 + 2236672153,1,1,1934); +Suggested by Ryan. + +- 18 July 2004 0.15 +All params in adodb_mktime were formerly compulsory. Now only the hour, min, secs is compulsory. +This brings it more in line with mktime (still not identical). + +- 23 June 2004 0.14 + +Allow you to define your own daylights savings function, adodb_daylight_sv. +If the function is defined (somewhere in an include), then you can correct for daylights savings. + +In this example, we apply daylights savings in June or July, adding one hour. This is extremely +unrealistic as it does not take into account time-zone, geographic location, current year. + +function adodb_daylight_sv(&$arr, $is_gmt) +{ + if ($is_gmt) return; + $m = $arr['mon']; + if ($m == 6 || $m == 7) $arr['hours'] += 1; +} + +This is only called by adodb_date() and not by adodb_mktime(). + +The format of $arr is +Array ( + [seconds] => 0 + [minutes] => 0 + [hours] => 0 + [mday] => 1 # day of month, eg 1st day of the month + [mon] => 2 # month (eg. Feb) + [year] => 2102 + [yday] => 31 # days in current year + [leap] => # true if leap year + [ndays] => 28 # no of days in current month + ) + + +- 28 Apr 2004 0.13 +Fixed adodb_date to properly support $is_gmt. Thx to Dimitar Angelov. + +- 20 Mar 2004 0.12 +Fixed month calculation error in adodb_date. 2102-June-01 appeared as 2102-May-32. + +- 26 Oct 2003 0.11 +Because of daylight savings problems (some systems apply daylight savings to +January!!!), changed adodb_get_gmt_diff() to ignore daylight savings. + +- 9 Aug 2003 0.10 +Fixed bug with dates after 2038. +See http://phplens.com/lens/lensforum/msgs.php?id=6980 + +- 1 July 2003 0.09 +Added support for Q (Quarter). +Added adodb_date2(), which accepts ISO date in 2nd param + +- 3 March 2003 0.08 +Added support for 'S' adodb_date() format char. Added constant ADODB_ALLOW_NEGATIVE_TS +if you want PHP to handle negative timestamps between 1901 to 1969. + +- 27 Feb 2003 0.07 +All negative numbers handled by adodb now because of RH 7.3+ problems. +See http://bugs.php.net/bug.php?id=20048&edit=2 + +- 4 Feb 2003 0.06 +Fixed a typo, 1852 changed to 1582! This means that pre-1852 dates +are now correctly handled. + +- 29 Jan 2003 0.05 + +Leap year checking differs under Julian calendar (pre 1582). Also +leap year code optimized by checking for most common case first. + +We also handle month overflow correctly in mktime (eg month set to 13). + +Day overflow for less than one month's days is supported. + +- 28 Jan 2003 0.04 + +Gregorian correction handled. In PHP5, we might throw an error if +mktime uses invalid dates around 5-14 Oct 1582. Released with ADOdb 3.10. +Added limbo 5-14 Oct 1582 check, when we set to 15 Oct 1582. + +- 27 Jan 2003 0.03 + +Fixed some more month problems due to gmt issues. Added constant ADODB_DATE_VERSION. +Fixed calculation of days since start of year for <1970. + +- 27 Jan 2003 0.02 + +Changed _adodb_getdate() to inline leap year checking for better performance. +Fixed problem with time-zones west of GMT +0000. + +- 24 Jan 2003 0.01 + +First implementation. +*/ + + +/* Initialization */ + +/* + Version Number +*/ +define('ADODB_DATE_VERSION',0.24); + +/* + This code was originally for windows. But apparently this problem happens + also with Linux, RH 7.3 and later! + + glibc-2.2.5-34 and greater has been changed to return -1 for dates < + 1970. This used to work. The problem exists with RedHat 7.3 and 8.0 + echo (mktime(0, 0, 0, 1, 1, 1960)); // prints -1 + + References: + http://bugs.php.net/bug.php?id=20048&edit=2 + http://lists.debian.org/debian-glibc/2002/debian-glibc-200205/msg00010.html +*/ + +if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1); + +function adodb_date_test_date($y1,$m,$d=13) +{ + $t = adodb_mktime(0,0,0,$m,$d,$y1); + $rez = adodb_date('Y-n-j H:i:s',$t); + if ("$y1-$m-$d 00:00:00" != $rez) { + print "$y1 error, expected=$y1-$m-$d 00:00:00, adodb=$rez
"; + return false; + } + return true; +} + +function adodb_date_test_strftime($fmt) +{ + $s1 = strftime($fmt); + $s2 = adodb_strftime($fmt); + + if ($s1 == $s2) return true; + + echo "error for $fmt, strftime=$s1, $adodb=$s2
"; + return false; +} + +/** + Test Suite +*/ +function adodb_date_test() +{ + + error_reporting(E_ALL); + print "

Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION.' PHP='.PHP_VERSION."

"; + @set_time_limit(0); + $fail = false; + + // This flag disables calling of PHP native functions, so we can properly test the code + if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES',1); + + adodb_date_test_strftime('%Y %m %x %X'); + adodb_date_test_strftime("%A %d %B %Y"); + adodb_date_test_strftime("%H %M S"); + + $t = adodb_mktime(0,0,0); + if (!(adodb_date('Y-m-d') == date('Y-m-d'))) print 'Error in '.adodb_mktime(0,0,0).'
'; + + $t = adodb_mktime(0,0,0,6,1,2102); + if (!(adodb_date('Y-m-d',$t) == '2102-06-01')) print 'Error in '.adodb_date('Y-m-d',$t).'
'; + + $t = adodb_mktime(0,0,0,2,1,2102); + if (!(adodb_date('Y-m-d',$t) == '2102-02-01')) print 'Error in '.adodb_date('Y-m-d',$t).'
'; + + + print "

Testing gregorian <=> julian conversion

"; + $t = adodb_mktime(0,0,0,10,11,1492); + //http://www.holidayorigins.com/html/columbus_day.html - Friday check + if (!(adodb_date('D Y-m-d',$t) == 'Fri 1492-10-11')) print 'Error in Columbus landing
'; + + $t = adodb_mktime(0,0,0,2,29,1500); + if (!(adodb_date('Y-m-d',$t) == '1500-02-29')) print 'Error in julian leap years
'; + + $t = adodb_mktime(0,0,0,2,29,1700); + if (!(adodb_date('Y-m-d',$t) == '1700-03-01')) print 'Error in gregorian leap years
'; + + print adodb_mktime(0,0,0,10,4,1582).' '; + print adodb_mktime(0,0,0,10,15,1582); + $diff = (adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582)); + if ($diff != 3600*24) print " Error in gregorian correction = ".($diff/3600/24)." days
"; + + print " 15 Oct 1582, Fri=".(adodb_dow(1582,10,15) == 5 ? 'Fri' : 'Error')."
"; + print " 4 Oct 1582, Thu=".(adodb_dow(1582,10,4) == 4 ? 'Thu' : 'Error')."
"; + + print "

Testing overflow

"; + + $t = adodb_mktime(0,0,0,3,33,1965); + if (!(adodb_date('Y-m-d',$t) == '1965-04-02')) print 'Error in day overflow 1
'; + $t = adodb_mktime(0,0,0,4,33,1971); + if (!(adodb_date('Y-m-d',$t) == '1971-05-03')) print 'Error in day overflow 2
'; + $t = adodb_mktime(0,0,0,1,60,1965); + if (!(adodb_date('Y-m-d',$t) == '1965-03-01')) print 'Error in day overflow 3 '.adodb_date('Y-m-d',$t).'
'; + $t = adodb_mktime(0,0,0,12,32,1965); + if (!(adodb_date('Y-m-d',$t) == '1966-01-01')) print 'Error in day overflow 4 '.adodb_date('Y-m-d',$t).'
'; + $t = adodb_mktime(0,0,0,12,63,1965); + if (!(adodb_date('Y-m-d',$t) == '1966-02-01')) print 'Error in day overflow 5 '.adodb_date('Y-m-d',$t).'
'; + $t = adodb_mktime(0,0,0,13,3,1965); + if (!(adodb_date('Y-m-d',$t) == '1966-01-03')) print 'Error in mth overflow 1
'; + + print "Testing 2-digit => 4-digit year conversion

"; + if (adodb_year_digit_check(00) != 2000) print "Err 2-digit 2000
"; + if (adodb_year_digit_check(10) != 2010) print "Err 2-digit 2010
"; + if (adodb_year_digit_check(20) != 2020) print "Err 2-digit 2020
"; + if (adodb_year_digit_check(30) != 2030) print "Err 2-digit 2030
"; + if (adodb_year_digit_check(40) != 1940) print "Err 2-digit 1940
"; + if (adodb_year_digit_check(50) != 1950) print "Err 2-digit 1950
"; + if (adodb_year_digit_check(90) != 1990) print "Err 2-digit 1990
"; + + // Test string formating + print "

Testing date formating

"; + $fmt = '\d\a\t\e T Y-m-d H:i:s a A d D F g G h H i j l L m M n O \R\F\C2822 r s t U w y Y z Z 2003'; + $s1 = date($fmt,0); + $s2 = adodb_date($fmt,0); + if ($s1 != $s2) { + print " date() 0 failed
$s1
$s2
"; + } + flush(); + for ($i=100; --$i > 0; ) { + + $ts = 3600.0*((rand()%60000)+(rand()%60000))+(rand()%60000); + $s1 = date($fmt,$ts); + $s2 = adodb_date($fmt,$ts); + //print "$s1
$s2

"; + $pos = strcmp($s1,$s2); + + if (($s1) != ($s2)) { + for ($j=0,$k=strlen($s1); $j < $k; $j++) { + if ($s1[$j] != $s2[$j]) { + print substr($s1,$j).' '; + break; + } + } + print "Error date(): $ts

 
+  \"$s1\" (date len=".strlen($s1).")
+  \"$s2\" (adodb_date len=".strlen($s2).")

"; + $fail = true; + } + + $a1 = getdate($ts); + $a2 = adodb_getdate($ts); + $rez = array_diff($a1,$a2); + if (sizeof($rez)>0) { + print "Error getdate() $ts
"; + print_r($a1); + print "
"; + print_r($a2); + print "

"; + $fail = true; + } + } + + // Test generation of dates outside 1901-2038 + print "

Testing random dates between 100 and 4000

"; + adodb_date_test_date(100,1); + for ($i=100; --$i >= 0;) { + $y1 = 100+rand(0,1970-100); + $m = rand(1,12); + adodb_date_test_date($y1,$m); + + $y1 = 3000-rand(0,3000-1970); + adodb_date_test_date($y1,$m); + } + print '

'; + $start = 1960+rand(0,10); + $yrs = 12; + $i = 365.25*86400*($start-1970); + $offset = 36000+rand(10000,60000); + $max = 365*$yrs*86400; + $lastyear = 0; + + // we generate a timestamp, convert it to a date, and convert it back to a timestamp + // and check if the roundtrip broke the original timestamp value. + print "Testing $start to ".($start+$yrs).", or $max seconds, offset=$offset: "; + $cnt = 0; + for ($max += $i; $i < $max; $i += $offset) { + $ret = adodb_date('m,d,Y,H,i,s',$i); + $arr = explode(',',$ret); + if ($lastyear != $arr[2]) { + $lastyear = $arr[2]; + print " $lastyear "; + flush(); + } + $newi = adodb_mktime($arr[3],$arr[4],$arr[5],$arr[0],$arr[1],$arr[2]); + if ($i != $newi) { + print "Error at $i, adodb_mktime returned $newi ($ret)"; + $fail = true; + break; + } + $cnt += 1; + } + echo "Tested $cnt dates
"; + if (!$fail) print "

Passed !

"; + else print "

Failed :-(

"; +} + +/** + Returns day of week, 0 = Sunday,... 6=Saturday. + Algorithm from PEAR::Date_Calc +*/ +function adodb_dow($year, $month, $day) +{ +/* +Pope Gregory removed 10 days - October 5 to October 14 - from the year 1582 and +proclaimed that from that time onwards 3 days would be dropped from the calendar +every 400 years. + +Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 15, 1582 (Gregorian). +*/ + if ($year <= 1582) { + if ($year < 1582 || + ($year == 1582 && ($month < 10 || ($month == 10 && $day < 15)))) $greg_correction = 3; + else + $greg_correction = 0; + } else + $greg_correction = 0; + + if($month > 2) + $month -= 2; + else { + $month += 10; + $year--; + } + + $day = floor((13 * $month - 1) / 5) + + $day + ($year % 100) + + floor(($year % 100) / 4) + + floor(($year / 100) / 4) - 2 * + floor($year / 100) + 77 + $greg_correction; + + return $day - 7 * floor($day / 7); +} + + +/** + Checks for leap year, returns true if it is. No 2-digit year check. Also + handles julian calendar correctly. +*/ +function _adodb_is_leap_year($year) +{ + if ($year % 4 != 0) return false; + + if ($year % 400 == 0) { + return true; + // if gregorian calendar (>1582), century not-divisible by 400 is not leap + } else if ($year > 1582 && $year % 100 == 0 ) { + return false; + } + + return true; +} + + +/** + checks for leap year, returns true if it is. Has 2-digit year check +*/ +function adodb_is_leap_year($year) +{ + return _adodb_is_leap_year(adodb_year_digit_check($year)); +} + +/** + Fix 2-digit years. Works for any century. + Assumes that if 2-digit is more than 30 years in future, then previous century. +*/ +function adodb_year_digit_check($y) +{ + if ($y < 100) { + + $yr = (integer) date("Y"); + $century = (integer) ($yr /100); + + if ($yr%100 > 50) { + $c1 = $century + 1; + $c0 = $century; + } else { + $c1 = $century; + $c0 = $century - 1; + } + $c1 *= 100; + // if 2-digit year is less than 30 years in future, set it to this century + // otherwise if more than 30 years in future, then we set 2-digit year to the prev century. + if (($y + $c1) < $yr+30) $y = $y + $c1; + else $y = $y + $c0*100; + } + return $y; +} + +/** + get local time zone offset from GMT +*/ +function adodb_get_gmt_diff() +{ +static $TZ; + if (isset($TZ)) return $TZ; + + $TZ = mktime(0,0,0,1,2,1970,0) - gmmktime(0,0,0,1,2,1970,0); + return $TZ; +} + +/** + Returns an array with date info. +*/ +function adodb_getdate($d=false,$fast=false) +{ + if ($d === false) return getdate(); + if (!defined('ADODB_TEST_DATES')) { + if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range + if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer + return @getdate($d); + } + } + return _adodb_getdate($d); +} + +/* +// generate $YRS table for _adodb_getdate() +function adodb_date_gentable($out=true) +{ + + for ($i=1970; $i >= 1600; $i-=10) { + $s = adodb_gmmktime(0,0,0,1,1,$i); + echo "$i => $s,
"; + } +} +adodb_date_gentable(); + +for ($i=1970; $i > 1500; $i--) { + +echo "
$i "; + adodb_date_test_date($i,1,1); +} + +*/ + + +$_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); +$_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); + +function adodb_validdate($y,$m,$d) +{ +global $_month_table_normal,$_month_table_leaf; + + if (_adodb_is_leap_year($y)) $marr =& $_month_table_leaf; + else $marr =& $_month_table_normal; + + if ($m > 12 || $m < 1) return false; + + if ($d > 31 || $d < 1) return false; + + if ($marr[$m] < $d) return false; + + if ($y < 1000 && $y > 3000) return false; + + return true; +} + +/** + Low-level function that returns the getdate() array. We have a special + $fast flag, which if set to true, will return fewer array values, + and is much faster as it does not calculate dow, etc. +*/ +function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) +{ +static $YRS; +global $_month_table_normal,$_month_table_leaf; + + $d = $origd - ($is_gmt ? 0 : adodb_get_gmt_diff()); + + $_day_power = 86400; + $_hour_power = 3600; + $_min_power = 60; + + if ($d < -12219321600) $d -= 86400*10; // if 15 Oct 1582 or earlier, gregorian correction + + $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); + $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); + + $d366 = $_day_power * 366; + $d365 = $_day_power * 365; + + if ($d < 0) { + + if (empty($YRS)) $YRS = array( + 1970 => 0, + 1960 => -315619200, + 1950 => -631152000, + 1940 => -946771200, + 1930 => -1262304000, + 1920 => -1577923200, + 1910 => -1893456000, + 1900 => -2208988800, + 1890 => -2524521600, + 1880 => -2840140800, + 1870 => -3155673600, + 1860 => -3471292800, + 1850 => -3786825600, + 1840 => -4102444800, + 1830 => -4417977600, + 1820 => -4733596800, + 1810 => -5049129600, + 1800 => -5364662400, + 1790 => -5680195200, + 1780 => -5995814400, + 1770 => -6311347200, + 1760 => -6626966400, + 1750 => -6942499200, + 1740 => -7258118400, + 1730 => -7573651200, + 1720 => -7889270400, + 1710 => -8204803200, + 1700 => -8520336000, + 1690 => -8835868800, + 1680 => -9151488000, + 1670 => -9467020800, + 1660 => -9782640000, + 1650 => -10098172800, + 1640 => -10413792000, + 1630 => -10729324800, + 1620 => -11044944000, + 1610 => -11360476800, + 1600 => -11676096000); + + if ($is_gmt) $origd = $d; + // The valid range of a 32bit signed timestamp is typically from + // Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT + // + + # old algorithm iterates through all years. new algorithm does it in + # 10 year blocks + + /* + # old algo + for ($a = 1970 ; --$a >= 0;) { + $lastd = $d; + + if ($leaf = _adodb_is_leap_year($a)) $d += $d366; + else $d += $d365; + + if ($d >= 0) { + $year = $a; + break; + } + } + */ + + $lastsecs = 0; + $lastyear = 1970; + foreach($YRS as $year => $secs) { + if ($d >= $secs) { + $a = $lastyear; + break; + } + $lastsecs = $secs; + $lastyear = $year; + } + + $d -= $lastsecs; + if (!isset($a)) $a = $lastyear; + + //echo ' yr=',$a,' ', $d,'.'; + + for (; --$a >= 0;) { + $lastd = $d; + + if ($leaf = _adodb_is_leap_year($a)) $d += $d366; + else $d += $d365; + + if ($d >= 0) { + $year = $a; + break; + } + } + /**/ + + $secsInYear = 86400 * ($leaf ? 366 : 365) + $lastd; + + $d = $lastd; + $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; + for ($a = 13 ; --$a > 0;) { + $lastd = $d; + $d += $mtab[$a] * $_day_power; + if ($d >= 0) { + $month = $a; + $ndays = $mtab[$a]; + break; + } + } + + $d = $lastd; + $day = $ndays + ceil(($d+1) / ($_day_power)); + + $d += ($ndays - $day+1)* $_day_power; + $hour = floor($d/$_hour_power); + + } else { + for ($a = 1970 ;; $a++) { + $lastd = $d; + + if ($leaf = _adodb_is_leap_year($a)) $d -= $d366; + else $d -= $d365; + if ($d < 0) { + $year = $a; + break; + } + } + $secsInYear = $lastd; + $d = $lastd; + $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; + for ($a = 1 ; $a <= 12; $a++) { + $lastd = $d; + $d -= $mtab[$a] * $_day_power; + if ($d < 0) { + $month = $a; + $ndays = $mtab[$a]; + break; + } + } + $d = $lastd; + $day = ceil(($d+1) / $_day_power); + $d = $d - ($day-1) * $_day_power; + $hour = floor($d /$_hour_power); + } + + $d -= $hour * $_hour_power; + $min = floor($d/$_min_power); + $secs = $d - $min * $_min_power; + if ($fast) { + return array( + 'seconds' => $secs, + 'minutes' => $min, + 'hours' => $hour, + 'mday' => $day, + 'mon' => $month, + 'year' => $year, + 'yday' => floor($secsInYear/$_day_power), + 'leap' => $leaf, + 'ndays' => $ndays + ); + } + + + $dow = adodb_dow($year,$month,$day); + + return array( + 'seconds' => $secs, + 'minutes' => $min, + 'hours' => $hour, + 'mday' => $day, + 'wday' => $dow, + 'mon' => $month, + 'year' => $year, + 'yday' => floor($secsInYear/$_day_power), + 'weekday' => gmdate('l',$_day_power*(3+$dow)), + 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)), + 0 => $origd + ); +} + +function adodb_gmdate($fmt,$d=false) +{ + return adodb_date($fmt,$d,true); +} + +// accepts unix timestamp and iso date format in $d +function adodb_date2($fmt, $d=false, $is_gmt=false) +{ + if ($d !== false) { + if (!preg_match( + "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", + ($d), $rr)) return adodb_date($fmt,false,$is_gmt); + + if ($rr[1] <= 100 && $rr[2]<= 1) return adodb_date($fmt,false,$is_gmt); + + // h-m-s-MM-DD-YY + if (!isset($rr[5])) $d = adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1],false,$is_gmt); + else $d = @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1],false,$is_gmt); + } + + return adodb_date($fmt,$d,$is_gmt); +} + + +/** + Return formatted date based on timestamp $d +*/ +function adodb_date($fmt,$d=false,$is_gmt=false) +{ +static $daylight; + + if ($d === false) return ($is_gmt)? @gmdate($fmt): @date($fmt); + if (!defined('ADODB_TEST_DATES')) { + if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range + if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer + return ($is_gmt)? @gmdate($fmt,$d): @date($fmt,$d); + + } + } + $_day_power = 86400; + + $arr = _adodb_getdate($d,true,$is_gmt); + + if (!isset($daylight)) $daylight = function_exists('adodb_daylight_sv'); + if ($daylight) adodb_daylight_sv($arr, $is_gmt); + + $year = $arr['year']; + $month = $arr['mon']; + $day = $arr['mday']; + $hour = $arr['hours']; + $min = $arr['minutes']; + $secs = $arr['seconds']; + + $max = strlen($fmt); + $dates = ''; + + $isphp5 = PHP_VERSION >= 5; + + /* + at this point, we have the following integer vars to manipulate: + $year, $month, $day, $hour, $min, $secs + */ + for ($i=0; $i < $max; $i++) { + switch($fmt[$i]) { + case 'T': $dates .= date('T');break; + // YEAR + case 'L': $dates .= $arr['leap'] ? '1' : '0'; break; + case 'r': // Thu, 21 Dec 2000 16:01:07 +0200 + + // 4.3.11 uses '04 Jun 2004' + // 4.3.8 uses ' 4 Jun 2004' + $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))).', ' + . ($day<10?'0'.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' '; + + if ($hour < 10) $dates .= '0'.$hour; else $dates .= $hour; + + if ($min < 10) $dates .= ':0'.$min; else $dates .= ':'.$min; + + if ($secs < 10) $dates .= ':0'.$secs; else $dates .= ':'.$secs; + + $gmt = adodb_get_gmt_diff(); + if ($isphp5) + $dates .= sprintf(' %s%04d',($gmt<=0)?'+':'-',abs($gmt)/36); + else + $dates .= sprintf(' %s%04d',($gmt<0)?'+':'-',abs($gmt)/36); + break; + + case 'Y': $dates .= $year; break; + case 'y': $dates .= substr($year,strlen($year)-2,2); break; + // MONTH + case 'm': if ($month<10) $dates .= '0'.$month; else $dates .= $month; break; + case 'Q': $dates .= ($month+3)>>2; break; + case 'n': $dates .= $month; break; + case 'M': $dates .= date('M',mktime(0,0,0,$month,2,1971)); break; + case 'F': $dates .= date('F',mktime(0,0,0,$month,2,1971)); break; + // DAY + case 't': $dates .= $arr['ndays']; break; + case 'z': $dates .= $arr['yday']; break; + case 'w': $dates .= adodb_dow($year,$month,$day); break; + case 'l': $dates .= gmdate('l',$_day_power*(3+adodb_dow($year,$month,$day))); break; + case 'D': $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))); break; + case 'j': $dates .= $day; break; + case 'd': if ($day<10) $dates .= '0'.$day; else $dates .= $day; break; + case 'S': + $d10 = $day % 10; + if ($d10 == 1) $dates .= 'st'; + else if ($d10 == 2 && $day != 12) $dates .= 'nd'; + else if ($d10 == 3) $dates .= 'rd'; + else $dates .= 'th'; + break; + + // HOUR + case 'Z': + $dates .= ($is_gmt) ? 0 : -adodb_get_gmt_diff(); break; + case 'O': + $gmt = ($is_gmt) ? 0 : adodb_get_gmt_diff(); + + if ($isphp5) + $dates .= sprintf('%s%04d',($gmt<=0)?'+':'-',abs($gmt)/36); + else + $dates .= sprintf('%s%04d',($gmt<0)?'+':'-',abs($gmt)/36); + break; + + case 'H': + if ($hour < 10) $dates .= '0'.$hour; + else $dates .= $hour; + break; + case 'h': + if ($hour > 12) $hh = $hour - 12; + else { + if ($hour == 0) $hh = '12'; + else $hh = $hour; + } + + if ($hh < 10) $dates .= '0'.$hh; + else $dates .= $hh; + break; + + case 'G': + $dates .= $hour; + break; + + case 'g': + if ($hour > 12) $hh = $hour - 12; + else { + if ($hour == 0) $hh = '12'; + else $hh = $hour; + } + $dates .= $hh; + break; + // MINUTES + case 'i': if ($min < 10) $dates .= '0'.$min; else $dates .= $min; break; + // SECONDS + case 'U': $dates .= $d; break; + case 's': if ($secs < 10) $dates .= '0'.$secs; else $dates .= $secs; break; + // AM/PM + // Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM + case 'a': + if ($hour>=12) $dates .= 'pm'; + else $dates .= 'am'; + break; + case 'A': + if ($hour>=12) $dates .= 'PM'; + else $dates .= 'AM'; + break; + default: + $dates .= $fmt[$i]; break; + // ESCAPE + case "\\": + $i++; + if ($i < $max) $dates .= $fmt[$i]; + break; + } + } + return $dates; +} + +/** + Returns a timestamp given a GMT/UTC time. + Note that $is_dst is not implemented and is ignored. +*/ +function adodb_gmmktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false) +{ + return adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst,true); +} + +/** + Return a timestamp given a local time. Originally by jackbbs. + Note that $is_dst is not implemented and is ignored. + + Not a very fast algorithm - O(n) operation. Could be optimized to O(1). +*/ +function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false,$is_gmt=false) +{ + if (!defined('ADODB_TEST_DATES')) { + + if ($mon === false) { + return $is_gmt? @gmmktime($hr,$min,$sec): @mktime($hr,$min,$sec); + } + + // for windows, we don't check 1970 because with timezone differences, + // 1 Jan 1970 could generate negative timestamp, which is illegal + if (1971 < $year && $year < 2038 + || !defined('ADODB_NO_NEGATIVE_TS') && (1901 < $year && $year < 2038) + ) { + return $is_gmt ? + @gmmktime($hr,$min,$sec,$mon,$day,$year): + @mktime($hr,$min,$sec,$mon,$day,$year); + } + } + + $gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_diff(); + + /* + # disabled because some people place large values in $sec. + # however we need it for $mon because we use an array... + $hr = intval($hr); + $min = intval($min); + $sec = intval($sec); + */ + $mon = intval($mon); + $day = intval($day); + $year = intval($year); + + + $year = adodb_year_digit_check($year); + + if ($mon > 12) { + $y = floor($mon / 12); + $year += $y; + $mon -= $y*12; + } else if ($mon < 1) { + $y = ceil((1-$mon) / 12); + $year -= $y; + $mon += $y*12; + } + + $_day_power = 86400; + $_hour_power = 3600; + $_min_power = 60; + + $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); + $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); + + $_total_date = 0; + if ($year >= 1970) { + for ($a = 1970 ; $a <= $year; $a++) { + $leaf = _adodb_is_leap_year($a); + if ($leaf == true) { + $loop_table = $_month_table_leaf; + $_add_date = 366; + } else { + $loop_table = $_month_table_normal; + $_add_date = 365; + } + if ($a < $year) { + $_total_date += $_add_date; + } else { + for($b=1;$b<$mon;$b++) { + $_total_date += $loop_table[$b]; + } + } + } + $_total_date +=$day-1; + $ret = $_total_date * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different; + + } else { + for ($a = 1969 ; $a >= $year; $a--) { + $leaf = _adodb_is_leap_year($a); + if ($leaf == true) { + $loop_table = $_month_table_leaf; + $_add_date = 366; + } else { + $loop_table = $_month_table_normal; + $_add_date = 365; + } + if ($a > $year) { $_total_date += $_add_date; + } else { + for($b=12;$b>$mon;$b--) { + $_total_date += $loop_table[$b]; + } + } + } + $_total_date += $loop_table[$mon] - $day; + + $_day_time = $hr * $_hour_power + $min * $_min_power + $sec; + $_day_time = $_day_power - $_day_time; + $ret = -( $_total_date * $_day_power + $_day_time - $gmt_different); + if ($ret < -12220185600) $ret += 10*86400; // if earlier than 5 Oct 1582 - gregorian correction + else if ($ret < -12219321600) $ret = -12219321600; // if in limbo, reset to 15 Oct 1582. + } + //print " dmy=$day/$mon/$year $hr:$min:$sec => " .$ret; + return $ret; +} + +function adodb_gmstrftime($fmt, $ts=false) +{ + return adodb_strftime($fmt,$ts,true); +} + +// hack - convert to adodb_date +function adodb_strftime($fmt, $ts=false,$is_gmt=false) +{ +global $ADODB_DATE_LOCALE; + + if (!defined('ADODB_TEST_DATES')) { + if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range + if (!defined('ADODB_NO_NEGATIVE_TS') || $ts >= 0) // if windows, must be +ve integer + return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts); + + } + } + + if (empty($ADODB_DATE_LOCALE)) { + /* + $tstr = strtoupper(gmstrftime('%c',31366800)); // 30 Dec 1970, 1 am + $sep = substr($tstr,2,1); + $hasAM = strrpos($tstr,'M') !== false; + */ + # see http://phplens.com/lens/lensforum/msgs.php?id=14865 for reasoning, and changelog for version 0.24 + $dstr = gmstrftime('%x',31366800); // 30 Dec 1970, 1 am + $sep = substr($dstr,2,1); + $tstr = strtoupper(gmstrftime('%X',31366800)); // 30 Dec 1970, 1 am + $hasAM = strrpos($tstr,'M') !== false; + + $ADODB_DATE_LOCALE = array(); + $ADODB_DATE_LOCALE[] = strncmp($tstr,'30',2) == 0 ? 'd'.$sep.'m'.$sep.'y' : 'm'.$sep.'d'.$sep.'y'; + $ADODB_DATE_LOCALE[] = ($hasAM) ? 'h:i:s a' : 'H:i:s'; + + } + $inpct = false; + $fmtdate = ''; + for ($i=0,$max = strlen($fmt); $i < $max; $i++) { + $ch = $fmt[$i]; + if ($ch == '%') { + if ($inpct) { + $fmtdate .= '%'; + $inpct = false; + } else + $inpct = true; + } else if ($inpct) { + + $inpct = false; + switch($ch) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case 'E': + case 'O': + /* ignore format modifiers */ + $inpct = true; + break; + + case 'a': $fmtdate .= 'D'; break; + case 'A': $fmtdate .= 'l'; break; + case 'h': + case 'b': $fmtdate .= 'M'; break; + case 'B': $fmtdate .= 'F'; break; + case 'c': $fmtdate .= $ADODB_DATE_LOCALE[0].$ADODB_DATE_LOCALE[1]; break; + case 'C': $fmtdate .= '\C?'; break; // century + case 'd': $fmtdate .= 'd'; break; + case 'D': $fmtdate .= 'm/d/y'; break; + case 'e': $fmtdate .= 'j'; break; + case 'g': $fmtdate .= '\g?'; break; //? + case 'G': $fmtdate .= '\G?'; break; //? + case 'H': $fmtdate .= 'H'; break; + case 'I': $fmtdate .= 'h'; break; + case 'j': $fmtdate .= '?z'; $parsej = true; break; // wrong as j=1-based, z=0-basd + case 'm': $fmtdate .= 'm'; break; + case 'M': $fmtdate .= 'i'; break; + case 'n': $fmtdate .= "\n"; break; + case 'p': $fmtdate .= 'a'; break; + case 'r': $fmtdate .= 'h:i:s a'; break; + case 'R': $fmtdate .= 'H:i:s'; break; + case 'S': $fmtdate .= 's'; break; + case 't': $fmtdate .= "\t"; break; + case 'T': $fmtdate .= 'H:i:s'; break; + case 'u': $fmtdate .= '?u'; $parseu = true; break; // wrong strftime=1-based, date=0-based + case 'U': $fmtdate .= '?U'; $parseU = true; break;// wrong strftime=1-based, date=0-based + case 'x': $fmtdate .= $ADODB_DATE_LOCALE[0]; break; + case 'X': $fmtdate .= $ADODB_DATE_LOCALE[1]; break; + case 'w': $fmtdate .= '?w'; $parseu = true; break; // wrong strftime=1-based, date=0-based + case 'W': $fmtdate .= '?W'; $parseU = true; break;// wrong strftime=1-based, date=0-based + case 'y': $fmtdate .= 'y'; break; + case 'Y': $fmtdate .= 'Y'; break; + case 'Z': $fmtdate .= 'T'; break; + } + } else if (('A' <= ($ch) && ($ch) <= 'Z' ) || ('a' <= ($ch) && ($ch) <= 'z' )) + $fmtdate .= "\\".$ch; + else + $fmtdate .= $ch; + } + //echo "fmt=",$fmtdate,"
"; + if ($ts === false) $ts = time(); + $ret = adodb_date($fmtdate, $ts, $is_gmt); + return $ret; +} + + +?> \ No newline at end of file diff --git a/lib/adodb/adodb.inc.php b/lib/adodb/adodb.inc.php new file mode 100644 index 00000000..d8c1b590 --- /dev/null +++ b/lib/adodb/adodb.inc.php @@ -0,0 +1,4221 @@ +fields is available on EOF + $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default... + + //============================================================================================== + // GLOBAL SETUP + //============================================================================================== + + $ADODB_EXTENSION = defined('ADODB_EXTENSION'); + + //********************************************************// + /* + Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3). + Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi + + 0 = ignore empty fields. All empty fields in array are ignored. + 1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values. + 2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values. + 3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and empty fields '' are set to empty '' sql values. + */ + define('ADODB_FORCE_IGNORE',0); + define('ADODB_FORCE_NULL',1); + define('ADODB_FORCE_EMPTY',2); + define('ADODB_FORCE_VALUE',3); + //********************************************************// + + + if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) { + + define('ADODB_BAD_RS','

Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;

'); + + // allow [ ] @ ` " and . in table names + define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)'); + + // prefetching used by oracle + if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10); + + + /* + Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names. + This currently works only with mssql, odbc, oci8po and ibase derived drivers. + + 0 = assoc lowercase field names. $rs->fields['orderid'] + 1 = assoc uppercase field names. $rs->fields['ORDERID'] + 2 = use native-case field names. $rs->fields['OrderID'] + */ + + define('ADODB_FETCH_DEFAULT',0); + define('ADODB_FETCH_NUM',1); + define('ADODB_FETCH_ASSOC',2); + define('ADODB_FETCH_BOTH',3); + + if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100); + + // PHP's version scheme makes converting to numbers difficult - workaround + $_adodb_ver = (float) PHP_VERSION; + if ($_adodb_ver >= 5.2) { + define('ADODB_PHPVER',0x5200); + } else if ($_adodb_ver >= 5.0) { + define('ADODB_PHPVER',0x5000); + } else if ($_adodb_ver > 4.299999) { # 4.3 + define('ADODB_PHPVER',0x4300); + } else if ($_adodb_ver > 4.199999) { # 4.2 + define('ADODB_PHPVER',0x4200); + } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) { + define('ADODB_PHPVER',0x4050); + } else { + define('ADODB_PHPVER',0x4000); + } + } + + //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); + + + /** + Accepts $src and $dest arrays, replacing string $data + */ + function ADODB_str_replace($src, $dest, $data) + { + if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data); + + $s = reset($src); + $d = reset($dest); + while ($s !== false) { + $data = str_replace($s,$d,$data); + $s = next($src); + $d = next($dest); + } + return $data; + } + + function ADODB_Setup() + { + GLOBAL + $ADODB_vers, // database version + $ADODB_COUNTRECS, // count number of records returned - slows down query + $ADODB_CACHE_DIR, // directory to cache recordsets + $ADODB_FETCH_MODE, + $ADODB_FORCE_TYPE; + + $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT; + $ADODB_FORCE_TYPE = ADODB_FORCE_VALUE; + + + if (!isset($ADODB_CACHE_DIR)) { + $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp'; + } else { + // do not accept url based paths, eg. http:/ or ftp:/ + if (strpos($ADODB_CACHE_DIR,'://') !== false) + die("Illegal path http:// or ftp://"); + } + + + // Initialize random number generator for randomizing cache flushes + // -- note Since PHP 4.2.0, the seed becomes optional and defaults to a random value if omitted. + srand(((double)microtime())*1000000); + + /** + * ADODB version as a string. + */ + $ADODB_vers = 'V4.93 10 Oct 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.'; + + /** + * Determines whether recordset->RecordCount() is used. + * Set to false for highest performance -- RecordCount() will always return -1 then + * for databases that provide "virtual" recordcounts... + */ + if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true; + } + + + //============================================================================================== + // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB + //============================================================================================== + + ADODB_Setup(); + + //============================================================================================== + // CLASS ADOFieldObject + //============================================================================================== + /** + * Helper class for FetchFields -- holds info on a column + */ + class ADOFieldObject { + var $name = ''; + var $max_length=0; + var $type=""; +/* + // additional fields by dannym... (danny_milo@yahoo.com) + var $not_null = false; + // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^ + // so we can as well make not_null standard (leaving it at "false" does not harm anyways) + + var $has_default = false; // this one I have done only in mysql and postgres for now ... + // others to come (dannym) + var $default_value; // default, if any, and supported. Check has_default first. +*/ + } + + + + function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) + { + //print "Errorno ($fn errno=$errno m=$errmsg) "; + $thisConnection->_transOK = false; + if ($thisConnection->_oldRaiseFn) { + $fn = $thisConnection->_oldRaiseFn; + $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection); + } + } + + //============================================================================================== + // CLASS ADOConnection + //============================================================================================== + + /** + * Connection object. For connecting to databases, and executing queries. + */ + class ADOConnection { + // + // PUBLIC VARS + // + var $dataProvider = 'native'; + var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql + var $database = ''; /// Name of database to be used. + var $host = ''; /// The hostname of the database server + var $user = ''; /// The username which is used to connect to the database server. + var $password = ''; /// Password for the username. For security, we no longer store it. + var $debug = false; /// if set to true will output sql statements + var $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro + var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase + var $substr = 'substr'; /// substring operator + var $length = 'length'; /// string length ofperator + var $random = 'rand()'; /// random function + var $upperCase = 'upper'; /// uppercase function + var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database + var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt. + var $true = '1'; /// string that represents TRUE for a database + var $false = '0'; /// string that represents FALSE for a database + var $replaceQuote = "\\'"; /// string to use to replace quotes + var $nameQuote = '"'; /// string to use to quote identifiers and names + var $charSet=false; /// character set to use - only for interbase, postgres and oci8 + var $metaDatabasesSQL = ''; + var $metaTablesSQL = ''; + var $uniqueOrderBy = false; /// All order by columns have to be unique + var $emptyDate = ' '; + var $emptyTimeStamp = ' '; + var $lastInsID = false; + //-- + var $hasInsertID = false; /// supports autoincrement ID? + var $hasAffectedRows = false; /// supports affected rows for update/delete? + var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE + var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10 + var $readOnly = false; /// this is a readonly database - used by phpLens + var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards + var $hasGenID = false; /// can generate sequences using GenID(); + var $hasTransactions = true; /// has transactions + //-- + var $genID = 0; /// sequence id used by GenID(); + var $raiseErrorFn = false; /// error function to call + var $isoDates = false; /// accepts dates in ISO format + var $cacheSecs = 3600; /// cache for 1 hour + + // memcache + var $memCache = false; /// should we use memCache instead of caching in files + var $memCacheHost; /// memCache host + var $memCachePort = 11211; /// memCache port + var $memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib) + + var $sysDate = false; /// name of function that returns the current date + var $sysTimeStamp = false; /// name of function that returns the current timestamp + var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets + + var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' ' + var $numCacheHits = 0; + var $numCacheMisses = 0; + var $pageExecuteCountRows = true; + var $uniqueSort = false; /// indicates that all fields in order by must be unique + var $leftOuter = false; /// operator to use for left outer join in WHERE clause + var $rightOuter = false; /// operator to use for right outer join in WHERE clause + var $ansiOuter = false; /// whether ansi outer join syntax supported + var $autoRollback = false; // autoRollback on PConnect(). + var $poorAffectedRows = false; // affectedRows not working or unreliable + + var $fnExecute = false; + var $fnCacheExecute = false; + var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char + var $rsPrefix = "ADORecordSet_"; + + var $autoCommit = true; /// do not modify this yourself - actually private + var $transOff = 0; /// temporarily disable transactions + var $transCnt = 0; /// count of nested transactions + + var $fetchMode=false; + + var $null2null = 'null'; // in autoexecute/getinsertsql/getupdatesql, this value will be converted to a null + // + // PRIVATE VARS + // + var $_oldRaiseFn = false; + var $_transOK = null; + var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made. + var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will + /// then returned by the errorMsg() function + var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8 + var $_queryID = false; /// This variable keeps the last created result link identifier + + var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */ + var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters. + var $_evalAll = false; + var $_affected = false; + var $_logsql = false; + var $_transmode = ''; // transaction mode + + + + /** + * Constructor + */ + function ADOConnection() + { + die('Virtual Class -- cannot instantiate'); + } + + function Version() + { + global $ADODB_vers; + + return (float) substr($ADODB_vers,1); + } + + /** + Get server version info... + + @returns An array with 2 elements: $arr['string'] is the description string, + and $arr[version] is the version (also a string). + */ + function ServerInfo() + { + return array('description' => '', 'version' => ''); + } + + function IsConnected() + { + return !empty($this->_connectionID); + } + + function _findvers($str) + { + if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1]; + else return ''; + } + + /** + * All error messages go through this bottleneck function. + * You can define your own handler by defining the function name in ADODB_OUTP. + */ + function outp($msg,$newline=true) + { + global $ADODB_FLUSH,$ADODB_OUTP; + + if (defined('ADODB_OUTP')) { + $fn = ADODB_OUTP; + $fn($msg,$newline); + return; + } else if (isset($ADODB_OUTP)) { + $fn = $ADODB_OUTP; + $fn($msg,$newline); + return; + } + + if ($newline) $msg .= "
\n"; + + if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg; + else echo strip_tags($msg); + + + if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan + + } + + function Time() + { + $rs =& $this->_Execute("select $this->sysTimeStamp"); + if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields)); + + return false; + } + + /** + * Connect to database + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * @param [forceNew] force new connection + * + * @return true or false + */ + function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) + { + if ($argHostname != "") $this->host = $argHostname; + if ($argUsername != "") $this->user = $argUsername; + if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons + if ($argDatabaseName != "") $this->database = $argDatabaseName; + + $this->_isPersistentConnection = false; + if ($forceNew) { + if ($rez=$this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true; + } else { + if ($rez=$this->_connect($this->host, $this->user, $this->password, $this->database)) return true; + } + if (isset($rez)) { + $err = $this->ErrorMsg(); + if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; + $ret = false; + } else { + $err = "Missing extension for ".$this->dataProvider; + $ret = 0; + } + if ($fn = $this->raiseErrorFn) + $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); + + + $this->_connectionID = false; + if ($this->debug) ADOConnection::outp( $this->host.': '.$err); + return $ret; + } + + function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) + { + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName); + } + + + /** + * Always force a new connection to database - currently only works with oracle + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * + * @return true or false + */ + function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") + { + return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true); + } + + /** + * Establish persistent connect to database + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * + * @return return true or false + */ + function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") + { + if (defined('ADODB_NEVER_PERSIST')) + return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName); + + if ($argHostname != "") $this->host = $argHostname; + if ($argUsername != "") $this->user = $argUsername; + if ($argPassword != "") $this->password = $argPassword; + if ($argDatabaseName != "") $this->database = $argDatabaseName; + + $this->_isPersistentConnection = true; + if ($rez = $this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true; + if (isset($rez)) { + $err = $this->ErrorMsg(); + if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; + $ret = false; + } else { + $err = "Missing extension for ".$this->dataProvider; + $ret = 0; + } + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); + } + + $this->_connectionID = false; + if ($this->debug) ADOConnection::outp( $this->host.': '.$err); + return $ret; + } + + // Format date column in sql string given an input format that understands Y M D + function SQLDate($fmt, $col=false) + { + if (!$col) $col = $this->sysDate; + return $col; // child class implement + } + + /** + * Should prepare the sql statement and return the stmt resource. + * For databases that do not support this, we return the $sql. To ensure + * compatibility with databases that do not support prepare: + * + * $stmt = $db->Prepare("insert into table (id, name) values (?,?)"); + * $db->Execute($stmt,array(1,'Jill')) or die('insert failed'); + * $db->Execute($stmt,array(2,'Joe')) or die('insert failed'); + * + * @param sql SQL to send to database + * + * @return return FALSE, or the prepared statement, or the original sql if + * if the database does not support prepare. + * + */ + function Prepare($sql) + { + return $sql; + } + + /** + * Some databases, eg. mssql require a different function for preparing + * stored procedures. So we cannot use Prepare(). + * + * Should prepare the stored procedure and return the stmt resource. + * For databases that do not support this, we return the $sql. To ensure + * compatibility with databases that do not support prepare: + * + * @param sql SQL to send to database + * + * @return return FALSE, or the prepared statement, or the original sql if + * if the database does not support prepare. + * + */ + function PrepareSP($sql,$param=true) + { + return $this->Prepare($sql,$param); + } + + /** + * PEAR DB Compat + */ + function Quote($s) + { + return $this->qstr($s,false); + } + + /** + Requested by "Karsten Dambekalns" + */ + function QMagic($s) + { + return $this->qstr($s,get_magic_quotes_gpc()); + } + + function q(&$s) + { + #if (!empty($this->qNull)) if ($s == 'null') return $s; + $s = $this->qstr($s,false); + } + + /** + * PEAR DB Compat - do not use internally. + */ + function ErrorNative() + { + return $this->ErrorNo(); + } + + + /** + * PEAR DB Compat - do not use internally. + */ + function nextId($seq_name) + { + return $this->GenID($seq_name); + } + + /** + * Lock a row, will escalate and lock the table if row locking not supported + * will normally free the lock at the end of the transaction + * + * @param $table name of table to lock + * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock + */ + function RowLock($table,$where) + { + return false; + } + + function CommitLock($table) + { + return $this->CommitTrans(); + } + + function RollbackLock($table) + { + return $this->RollbackTrans(); + } + + /** + * PEAR DB Compat - do not use internally. + * + * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical + * for easy porting :-) + * + * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM + * @returns The previous fetch mode + */ + function SetFetchMode($mode) + { + $old = $this->fetchMode; + $this->fetchMode = $mode; + + if ($old === false) { + global $ADODB_FETCH_MODE; + return $ADODB_FETCH_MODE; + } + return $old; + } + + + /** + * PEAR DB Compat - do not use internally. + */ + function &Query($sql, $inputarr=false) + { + $rs = &$this->Execute($sql, $inputarr); + if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + return $rs; + } + + + /** + * PEAR DB Compat - do not use internally + */ + function &LimitQuery($sql, $offset, $count, $params=false) + { + $rs = &$this->SelectLimit($sql, $count, $offset, $params); + if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + return $rs; + } + + + /** + * PEAR DB Compat - do not use internally + */ + function Disconnect() + { + return $this->Close(); + } + + /* + Returns placeholder for parameter, eg. + $DB->Param('a') + + will return ':a' for Oracle, and '?' for most other databases... + + For databases that require positioned params, eg $1, $2, $3 for postgresql, + pass in Param(false) before setting the first parameter. + */ + function Param($name,$type='C') + { + return '?'; + } + + /* + InParameter and OutParameter are self-documenting versions of Parameter(). + */ + function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) + { + return $this->Parameter($stmt,$var,$name,false,$maxLen,$type); + } + + /* + */ + function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) + { + return $this->Parameter($stmt,$var,$name,true,$maxLen,$type); + + } + + + /* + Usage in oracle + $stmt = $db->Prepare('select * from table where id =:myid and group=:group'); + $db->Parameter($stmt,$id,'myid'); + $db->Parameter($stmt,$group,'group',64); + $db->Execute(); + + @param $stmt Statement returned by Prepare() or PrepareSP(). + @param $var PHP variable to bind to + @param $name Name of stored procedure variable name to bind to. + @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8. + @param [$maxLen] Holds an maximum length of the variable. + @param [$type] The data type of $var. Legal values depend on driver. + + */ + function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false) + { + return false; + } + + + function IgnoreErrors($saveErrs=false) + { + if (!$saveErrs) { + $saveErrs = array($this->raiseErrorFn,$this->_transOK); + $this->raiseErrorFn = false; + return $saveErrs; + } else { + $this->raiseErrorFn = $saveErrs[0]; + $this->_transOK = $saveErrs[1]; + } + } + + /** + Improved method of initiating a transaction. Used together with CompleteTrans(). + Advantages include: + + a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans. + Only the outermost block is treated as a transaction.
+ b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.
+ c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block + are disabled, making it backward compatible. + */ + function StartTrans($errfn = 'ADODB_TransMonitor') + { + if ($this->transOff > 0) { + $this->transOff += 1; + return; + } + + $this->_oldRaiseFn = $this->raiseErrorFn; + $this->raiseErrorFn = $errfn; + $this->_transOK = true; + + if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans"); + $this->BeginTrans(); + $this->transOff = 1; + } + + + /** + Used together with StartTrans() to end a transaction. Monitors connection + for sql errors, and will commit or rollback as appropriate. + + @autoComplete if true, monitor sql errors and commit and rollback as appropriate, + and if set to false force rollback even if no SQL error detected. + @returns true on commit, false on rollback. + */ + function CompleteTrans($autoComplete = true) + { + if ($this->transOff > 1) { + $this->transOff -= 1; + return true; + } + $this->raiseErrorFn = $this->_oldRaiseFn; + + $this->transOff = 0; + if ($this->_transOK && $autoComplete) { + if (!$this->CommitTrans()) { + $this->_transOK = false; + if ($this->debug) ADOConnection::outp("Smart Commit failed"); + } else + if ($this->debug) ADOConnection::outp("Smart Commit occurred"); + } else { + $this->_transOK = false; + $this->RollbackTrans(); + if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred"); + } + + return $this->_transOK; + } + + /* + At the end of a StartTrans/CompleteTrans block, perform a rollback. + */ + function FailTrans() + { + if ($this->debug) + if ($this->transOff == 0) { + ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans"); + } else { + ADOConnection::outp("FailTrans was called"); + adodb_backtrace(); + } + $this->_transOK = false; + } + + /** + Check if transaction has failed, only for Smart Transactions. + */ + function HasFailedTrans() + { + if ($this->transOff > 0) return $this->_transOK == false; + return false; + } + + /** + * Execute SQL + * + * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text) + * @param [inputarr] holds the input data to bind to. Null elements will be set to null. + * @return RecordSet or false + */ + function &Execute($sql,$inputarr=false) + { + if ($this->fnExecute) { + $fn = $this->fnExecute; + $ret =& $fn($this,$sql,$inputarr); + if (isset($ret)) return $ret; + } + if ($inputarr) { + if (!is_array($inputarr)) $inputarr = array($inputarr); + + $element0 = reset($inputarr); + # is_object check because oci8 descriptors can be passed in + $array_2d = is_array($element0) && !is_object(reset($element0)); + //remove extra memory copy of input -mikefedyk + unset($element0); + + if (!is_array($sql) && !$this->_bindInputArray) { + $sqlarr = explode('?',$sql); + + if (!$array_2d) $inputarr = array($inputarr); + foreach($inputarr as $arr) { + $sql = ''; $i = 0; + //Use each() instead of foreach to reduce memory usage -mikefedyk + while(list(, $v) = each($arr)) { + $sql .= $sqlarr[$i]; + // from Ron Baldwin + // Only quote string types + $typ = gettype($v); + if ($typ == 'string') + //New memory copy of input created here -mikefedyk + $sql .= $this->qstr($v); + else if ($typ == 'double') + $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1 + else if ($typ == 'boolean') + $sql .= $v ? $this->true : $this->false; + else if ($typ == 'object') { + if (method_exists($v, '__toString')) $sql .= $this->qstr($v->__toString()); + else $sql .= $this->qstr((string) $v); + } else if ($v === null) + $sql .= 'NULL'; + else + $sql .= $v; + $i += 1; + } + if (isset($sqlarr[$i])) { + $sql .= $sqlarr[$i]; + if ($i+1 != sizeof($sqlarr)) ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql)); + } else if ($i != sizeof($sqlarr)) + ADOConnection::outp( "Input array does not match ?: ".htmlspecialchars($sql)); + + $ret =& $this->_Execute($sql); + if (!$ret) return $ret; + } + } else { + if ($array_2d) { + if (is_string($sql)) + $stmt = $this->Prepare($sql); + else + $stmt = $sql; + + foreach($inputarr as $arr) { + $ret =& $this->_Execute($stmt,$arr); + if (!$ret) return $ret; + } + } else { + $ret =& $this->_Execute($sql,$inputarr); + } + } + } else { + $ret =& $this->_Execute($sql,false); + } + + return $ret; + } + + + function &_Execute($sql,$inputarr=false) + { + if ($this->debug) { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); + $this->_queryID = _adodb_debug_execute($this, $sql,$inputarr); + } else { + $this->_queryID = @$this->_query($sql,$inputarr); + } + + /************************ + // OK, query executed + *************************/ + + if ($this->_queryID === false) { // error handling if query fails + if ($this->debug == 99) adodb_backtrace(true,5); + $fn = $this->raiseErrorFn; + if ($fn) { + $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this); + } + $false = false; + return $false; + } + + if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead + $rs =& new ADORecordSet_empty(); + return $rs; + } + + // return real recordset from select statement + $rsclass = $this->rsPrefix.$this->databaseType; + $rs = new $rsclass($this->_queryID,$this->fetchMode); + $rs->connection = &$this; // Pablo suggestion + $rs->Init(); + if (is_array($sql)) $rs->sql = $sql[0]; + else $rs->sql = $sql; + if ($rs->_numOfRows <= 0) { + global $ADODB_COUNTRECS; + if ($ADODB_COUNTRECS) { + if (!$rs->EOF) { + $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql)); + $rs->_queryID = $this->_queryID; + } else + $rs->_numOfRows = 0; + } + } + return $rs; + } + + function CreateSequence($seqname='adodbseq',$startID=1) + { + if (empty($this->_genSeqSQL)) return false; + return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); + } + + function DropSequence($seqname='adodbseq') + { + if (empty($this->_dropSeqSQL)) return false; + return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); + } + + /** + * Generates a sequence id and stores it in $this->genID; + * GenID is only available if $this->hasGenID = true; + * + * @param seqname name of sequence to use + * @param startID if sequence does not exist, start at this ID + * @return 0 if not supported, otherwise a sequence id + */ + function GenID($seqname='adodbseq',$startID=1) + { + if (!$this->hasGenID) { + return 0; // formerly returns false pre 1.60 + } + + $getnext = sprintf($this->_genIDSQL,$seqname); + + $holdtransOK = $this->_transOK; + + $save_handler = $this->raiseErrorFn; + $this->raiseErrorFn = ''; + @($rs = $this->Execute($getnext)); + $this->raiseErrorFn = $save_handler; + + if (!$rs) { + $this->_transOK = $holdtransOK; //if the status was ok before reset + $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); + $rs = $this->Execute($getnext); + } + if ($rs && !$rs->EOF) $this->genID = reset($rs->fields); + else $this->genID = 0; // false + + if ($rs) $rs->Close(); + + return $this->genID; + } + + /** + * @param $table string name of the table, not needed by all databases (eg. mysql), default '' + * @param $column string name of the column, not needed by all databases (eg. mysql), default '' + * @return the last inserted ID. Not all databases support this. + */ + function Insert_ID($table='',$column='') + { + if ($this->_logsql && $this->lastInsID) return $this->lastInsID; + if ($this->hasInsertID) return $this->_insertid($table,$column); + if ($this->debug) { + ADOConnection::outp( '

Insert_ID error

'); + adodb_backtrace(); + } + return false; + } + + + /** + * Portable Insert ID. Pablo Roca + * + * @return the last inserted ID. All databases support this. But aware possible + * problems in multiuser environments. Heavy test this before deploying. + */ + function PO_Insert_ID($table="", $id="") + { + if ($this->hasInsertID){ + return $this->Insert_ID($table,$id); + } else { + return $this->GetOne("SELECT MAX($id) FROM $table"); + } + } + + /** + * @return # rows affected by UPDATE/DELETE + */ + function Affected_Rows() + { + if ($this->hasAffectedRows) { + if ($this->fnExecute === 'adodb_log_sql') { + if ($this->_logsql && $this->_affected !== false) return $this->_affected; + } + $val = $this->_affectedrows(); + return ($val < 0) ? false : $val; + } + + if ($this->debug) ADOConnection::outp( '

Affected_Rows error

',false); + return false; + } + + + /** + * @return the last error message + */ + function ErrorMsg() + { + if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg; + else return ''; + } + + + /** + * @return the last error number. Normally 0 means no error. + */ + function ErrorNo() + { + return ($this->_errorMsg) ? -1 : 0; + } + + function MetaError($err=false) + { + include_once(ADODB_DIR."/adodb-error.inc.php"); + if ($err === false) $err = $this->ErrorNo(); + return adodb_error($this->dataProvider,$this->databaseType,$err); + } + + function MetaErrorMsg($errno) + { + include_once(ADODB_DIR."/adodb-error.inc.php"); + return adodb_errormsg($errno); + } + + /** + * @returns an array with the primary key columns in it. + */ + function MetaPrimaryKeys($table, $owner=false) + { + // owner not used in base class - see oci8 + $p = array(); + $objs =& $this->MetaColumns($table); + if ($objs) { + foreach($objs as $v) { + if (!empty($v->primary_key)) + $p[] = $v->name; + } + } + if (sizeof($p)) return $p; + if (function_exists('ADODB_VIEW_PRIMARYKEYS')) + return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner); + return false; + } + + /** + * @returns assoc array where keys are tables, and values are foreign keys + */ + function MetaForeignKeys($table, $owner=false, $upper=false) + { + return false; + } + /** + * Choose a database to connect to. Many databases do not support this. + * + * @param dbName is the name of the database to select + * @return true or false + */ + function SelectDB($dbName) + {return false;} + + + /** + * Will select, getting rows from $offset (1-based), for $nrows. + * This simulates the MySQL "select * from table limit $offset,$nrows" , and + * the PostgreSQL "select * from table limit $nrows offset $offset". Note that + * MySQL and PostgreSQL parameter ordering is the opposite of the other. + * eg. + * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based) + * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based) + * + * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set) + * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set + * + * @param sql + * @param [offset] is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to get + * @param [inputarr] array of bind variables + * @param [secs2cache] is a private parameter only used by jlim + * @return the recordset ($rs->databaseType == 'array') + */ + function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) + { + if ($this->hasTop && $nrows > 0) { + // suggested by Reinhard Balling. Access requires top after distinct + // Informix requires first before distinct - F Riosa + $ismssql = (strpos($this->databaseType,'mssql') !== false); + if ($ismssql) $isaccess = false; + else $isaccess = (strpos($this->databaseType,'access') !== false); + + if ($offset <= 0) { + + // access includes ties in result + if ($isaccess) { + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql); + + if ($secs2cache != 0) { + $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr); + } else { + $ret =& $this->Execute($sql,$inputarr); + } + return $ret; // PHP5 fix + } else if ($ismssql){ + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql); + } else { + $sql = preg_replace( + '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql); + } + } else { + $nn = $nrows + $offset; + if ($isaccess || $ismssql) { + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); + } else { + $sql = preg_replace( + '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); + } + } + } + + // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows + // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS. + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + if ($offset>0){ + if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); + else $rs = &$this->Execute($sql,$inputarr); + } else { + if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); + else $rs = &$this->Execute($sql,$inputarr); + } + $ADODB_COUNTRECS = $savec; + if ($rs && !$rs->EOF) { + $rs =& $this->_rs2rs($rs,$nrows,$offset); + } + //print_r($rs); + return $rs; + } + + /** + * Create serializable recordset. Breaks rs link to connection. + * + * @param rs the recordset to serialize + */ + function &SerializableRS(&$rs) + { + $rs2 =& $this->_rs2rs($rs); + $ignore = false; + $rs2->connection =& $ignore; + + return $rs2; + } + + /** + * Convert database recordset to an array recordset + * input recordset's cursor should be at beginning, and + * old $rs will be closed. + * + * @param rs the recordset to copy + * @param [nrows] number of rows to retrieve (optional) + * @param [offset] offset by number of rows (optional) + * @return the new recordset + */ + function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true) + { + if (! $rs) { + $false = false; + return $false; + } + $dbtype = $rs->databaseType; + if (!$dbtype) { + $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ? + return $rs; + } + if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) { + $rs->MoveFirst(); + $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ? + return $rs; + } + $flds = array(); + for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { + $flds[] = $rs->FetchField($i); + } + + $arr =& $rs->GetArrayLimit($nrows,$offset); + //print_r($arr); + if ($close) $rs->Close(); + + $arrayClass = $this->arrayClass; + + $rs2 = new $arrayClass(); + $rs2->connection = &$this; + $rs2->sql = $rs->sql; + $rs2->dataProvider = $this->dataProvider; + $rs2->InitArrayFields($arr,$flds); + $rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode; + return $rs2; + } + + /* + * Return all rows. Compat with PEAR DB + */ + function &GetAll($sql, $inputarr=false) + { + $arr =& $this->GetArray($sql,$inputarr); + return $arr; + } + + function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false) + { + $rs =& $this->Execute($sql, $inputarr); + if (!$rs) { + $false = false; + return $false; + } + $arr =& $rs->GetAssoc($force_array,$first2cols); + return $arr; + } + + function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false) + { + if (!is_numeric($secs2cache)) { + $first2cols = $force_array; + $force_array = $inputarr; + } + $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr); + if (!$rs) { + $false = false; + return $false; + } + $arr =& $rs->GetAssoc($force_array,$first2cols); + return $arr; + } + + /** + * Return first element of first row of sql statement. Recordset is disposed + * for you. + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function GetOne($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + $crecs = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + $ret = false; + $rs = &$this->Execute($sql,$inputarr); + if ($rs) { + if (!$rs->EOF) $ret = reset($rs->fields); + $rs->Close(); + } + $ADODB_COUNTRECS = $crecs; + return $ret; + } + + function CacheGetOne($secs2cache,$sql=false,$inputarr=false) + { + $ret = false; + $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); + if ($rs) { + if (!$rs->EOF) $ret = reset($rs->fields); + $rs->Close(); + } + + return $ret; + } + + function GetCol($sql, $inputarr = false, $trim = false) + { + $rv = false; + $rs = &$this->Execute($sql, $inputarr); + if ($rs) { + $rv = array(); + if ($trim) { + while (!$rs->EOF) { + $rv[] = trim(reset($rs->fields)); + $rs->MoveNext(); + } + } else { + while (!$rs->EOF) { + $rv[] = reset($rs->fields); + $rs->MoveNext(); + } + } + $rs->Close(); + } + return $rv; + } + + function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false) + { + $rv = false; + $rs = &$this->CacheExecute($secs, $sql, $inputarr); + if ($rs) { + if ($trim) { + while (!$rs->EOF) { + $rv[] = trim(reset($rs->fields)); + $rs->MoveNext(); + } + } else { + while (!$rs->EOF) { + $rv[] = reset($rs->fields); + $rs->MoveNext(); + } + } + $rs->Close(); + } + return $rv; + } + + function &Transpose(&$rs) + { + $rs2 =& $this->_rs2rs($rs); + $false = false; + if (!$rs2) return $false; + + $rs2->_transpose(); + return $rs2; + } + + /* + Calculate the offset of a date for a particular database and generate + appropriate SQL. Useful for calculating future/past dates and storing + in a database. + + If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour. + */ + function OffsetDate($dayFraction,$date=false) + { + if (!$date) $date = $this->sysDate; + return '('.$date.'+'.$dayFraction.')'; + } + + + /** + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function &GetArray($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + $rs =& $this->Execute($sql,$inputarr); + $ADODB_COUNTRECS = $savec; + if (!$rs) + if (defined('ADODB_PEAR')) { + $cls = ADODB_PEAR_Error(); + return $cls; + } else { + $false = false; + return $false; + } + $arr =& $rs->GetArray(); + $rs->Close(); + return $arr; + } + + function &CacheGetAll($secs2cache,$sql=false,$inputarr=false) + { + $arr =& $this->CacheGetArray($secs2cache,$sql,$inputarr); + return $arr; + } + + function &CacheGetArray($secs2cache,$sql=false,$inputarr=false) + { + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr); + $ADODB_COUNTRECS = $savec; + + if (!$rs) + if (defined('ADODB_PEAR')) { + $cls = ADODB_PEAR_Error(); + return $cls; + } else { + $false = false; + return $false; + } + $arr =& $rs->GetArray(); + $rs->Close(); + return $arr; + } + + + + /** + * Return one row of sql statement. Recordset is disposed for you. + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function &GetRow($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + $crecs = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + $rs =& $this->Execute($sql,$inputarr); + + $ADODB_COUNTRECS = $crecs; + if ($rs) { + if (!$rs->EOF) $arr = $rs->fields; + else $arr = array(); + $rs->Close(); + return $arr; + } + + $false = false; + return $false; + } + + function &CacheGetRow($secs2cache,$sql=false,$inputarr=false) + { + $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr); + if ($rs) { + $arr = false; + if (!$rs->EOF) $arr = $rs->fields; + $rs->Close(); + return $arr; + } + $false = false; + return $false; + } + + /** + * Insert or replace a single record. Note: this is not the same as MySQL's replace. + * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL. + * Also note that no table locking is done currently, so it is possible that the + * record be inserted twice by two programs... + * + * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname'); + * + * $table table name + * $fieldArray associative array of data (you must quote strings yourself). + * $keyCol the primary key field name or if compound key, array of field names + * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers + * but does not work with dates nor SQL functions. + * has_autoinc the primary key is an auto-inc field, so skip in insert. + * + * Currently blob replace not supported + * + * returns 0 = fail, 1 = update, 2 = insert + */ + + function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); + + return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc); + } + + + /** + * Will select, getting rows from $offset (1-based), for $nrows. + * This simulates the MySQL "select * from table limit $offset,$nrows" , and + * the PostgreSQL "select * from table limit $nrows offset $offset". Note that + * MySQL and PostgreSQL parameter ordering is the opposite of the other. + * eg. + * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based) + * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based) + * + * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set + * + * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional + * @param sql + * @param [offset] is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to get + * @param [inputarr] array of bind variables + * @return the recordset ($rs->databaseType == 'array') + */ + function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false) + { + if (!is_numeric($secs2cache)) { + if ($sql === false) $sql = -1; + if ($offset == -1) $offset = false; + // sql, nrows, offset,inputarr + $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs); + } else { + if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()"); + $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + } + return $rs; + } + + + /** + * Flush cached recordsets that match a particular $sql statement. + * If $sql == false, then we purge all files in the cache. + */ + + /** + * Flush cached recordsets that match a particular $sql statement. + * If $sql == false, then we purge all files in the cache. + */ + function CacheFlush($sql=false,$inputarr=false) + { + global $ADODB_CACHE_DIR; + + if ($this->memCache) { + global $ADODB_INCLUDED_MEMCACHE; + + $key = false; + if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php'); + if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true); + FlushMemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug); + return; + } + + if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) { + /*if (strncmp(PHP_OS,'WIN',3) === 0) + $dir = str_replace('/', '\\', $ADODB_CACHE_DIR); + else */ + $dir = $ADODB_CACHE_DIR; + + if ($this->debug) { + ADOConnection::outp( "CacheFlush: $dir
\n", $this->_dirFlush($dir),"
"); + } else { + $this->_dirFlush($dir); + } + return; + } + + global $ADODB_INCLUDED_CSV; + if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php'); + + $f = $this->_gencachename($sql.serialize($inputarr),false); + adodb_write_file($f,''); // is adodb_write_file needed? + if (!@unlink($f)) { + if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f"); + } + } + + /** + * Private function to erase all of the files and subdirectories in a directory. + * + * Just specify the directory, and tell it if you want to delete the directory or just clear it out. + * Note: $kill_top_level is used internally in the function to flush subdirectories. + */ + function _dirFlush($dir, $kill_top_level = false) { + if(!$dh = @opendir($dir)) return; + + while (($obj = readdir($dh))) { + if($obj=='.' || $obj=='..') + continue; + + if (!@unlink($dir.'/'.$obj)) + $this->_dirFlush($dir.'/'.$obj, true); + } + if ($kill_top_level === true) + @rmdir($dir); + return true; + } + + + function xCacheFlush($sql=false,$inputarr=false) + { + global $ADODB_CACHE_DIR; + + if ($this->memCache) { + global $ADODB_INCLUDED_MEMCACHE; + $key = false; + if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php'); + if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true); + flushmemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug); + return; + } + + if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) { + if (strncmp(PHP_OS,'WIN',3) === 0) { + $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache'; + } else { + //$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f'; + $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/'; + // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`'; + } + if ($this->debug) { + ADOConnection::outp( "CacheFlush: $cmd
\n", system($cmd),"
"); + } else { + exec($cmd); + } + return; + } + + global $ADODB_INCLUDED_CSV; + if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php'); + + $f = $this->_gencachename($sql.serialize($inputarr),false); + adodb_write_file($f,''); // is adodb_write_file needed? + if (!@unlink($f)) { + if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f"); + } + } + + /** + * Private function to generate filename for caching. + * Filename is generated based on: + * + * - sql statement + * - database type (oci8, ibase, ifx, etc) + * - database name + * - userid + * - setFetchMode (adodb 4.23) + * + * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). + * Assuming that we can have 50,000 files per directory with good performance, + * then we can scale to 12.8 million unique cached recordsets. Wow! + */ + function _gencachename($sql,$createdir,$memcache=false) + { + global $ADODB_CACHE_DIR; + static $notSafeMode; + + if ($this->fetchMode === false) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } else { + $mode = $this->fetchMode; + } + $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode); + if ($memcache) return $m; + + if (!isset($notSafeMode)) $notSafeMode = !ini_get('safe_mode'); + $dir = ($notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($m,0,2) : $ADODB_CACHE_DIR; + + if ($createdir && $notSafeMode && !file_exists($dir)) { + $oldu = umask(0); + if (!mkdir($dir,0771)) + if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql"); + umask($oldu); + } + return $dir.'/adodb_'.$m.'.cache'; + } + + + /** + * Execute SQL, caching recordsets. + * + * @param [secs2cache] seconds to cache data, set to 0 to force query. + * This is an optional parameter. + * @param sql SQL statement to execute + * @param [inputarr] holds the input data to bind to + * @return RecordSet or false + */ + function &CacheExecute($secs2cache,$sql=false,$inputarr=false) + { + + + if (!is_numeric($secs2cache)) { + $inputarr = $sql; + $sql = $secs2cache; + $secs2cache = $this->cacheSecs; + } + + if (is_array($sql)) { + $sqlparam = $sql; + $sql = $sql[0]; + } else + $sqlparam = $sql; + + if ($this->memCache) { + global $ADODB_INCLUDED_MEMCACHE; + if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php'); + $md5file = $this->_gencachename($sql.serialize($inputarr),false,true); + } else { + global $ADODB_INCLUDED_CSV; + if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php'); + $md5file = $this->_gencachename($sql.serialize($inputarr),true); + } + + $err = ''; + + if ($secs2cache > 0){ + if ($this->memCache) + $rs = &getmemCache($md5file,$err,$secs2cache, $this->memCacheHost, $this->memCachePort); + else + $rs = &csv2rs($md5file,$err,$secs2cache,$this->arrayClass); + $this->numCacheHits += 1; + } else { + $err='Timeout 1'; + $rs = false; + $this->numCacheMisses += 1; + } + if (!$rs) { + // no cached rs found + if ($this->debug) { + if (get_magic_quotes_runtime() && !$this->memCache) { + ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :("); + } + if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)"); + } + + $rs = &$this->Execute($sqlparam,$inputarr); + + if ($rs && $this->memCache) { + $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately + if(!putmemCache($md5file, $rs, $this->memCacheHost, $this->memCachePort, $this->memCacheCompress, $this->debug)) { + if ($fn = $this->raiseErrorFn) + $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this); + if ($this->debug) ADOConnection::outp( " Cache write error"); + } + } else + if ($rs) { + $eof = $rs->EOF; + $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately + $txt = _rs2serialize($rs,false,$sql); // serialize + + if (!adodb_write_file($md5file,$txt,$this->debug)) { + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this); + } + if ($this->debug) ADOConnection::outp( " Cache write error"); + } + if ($rs->EOF && !$eof) { + $rs->MoveFirst(); + //$rs = &csv2rs($md5file,$err); + $rs->connection = &$this; // Pablo suggestion + } + + } else + if (!$this->memCache) + @unlink($md5file); + } else { + $this->_errorMsg = ''; + $this->_errorCode = 0; + + if ($this->fnCacheExecute) { + $fn = $this->fnCacheExecute; + $fn($this, $secs2cache, $sql, $inputarr); + } + // ok, set cached object found + $rs->connection = &$this; // Pablo suggestion + if ($this->debug){ + + $inBrowser = isset($_SERVER['HTTP_USER_AGENT']); + $ttl = $rs->timeCreated + $secs2cache - time(); + $s = is_array($sql) ? $sql[0] : $sql; + if ($inBrowser) $s = ''.htmlspecialchars($s).''; + + ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]"); + } + } + return $rs; + } + + + /* + Similar to PEAR DB's autoExecute(), except that + $mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE + If $mode == 'UPDATE', then $where is compulsory as a safety measure. + + $forceUpdate means that even if the data has not changed, perform update. + */ + function& AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false) + { + $false = false; + $sql = 'SELECT * FROM '.$table; + if ($where!==FALSE) $sql .= ' WHERE '.$where; + else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) { + ADOConnection::outp('AutoExecute: Illegal mode=UPDATE with empty WHERE clause'); + return $false; + } + + $rs =& $this->SelectLimit($sql,1); + if (!$rs) return $false; // table does not exist + $rs->tableName = $table; + + switch((string) $mode) { + case 'UPDATE': + case '2': + $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq); + break; + case 'INSERT': + case '1': + $sql = $this->GetInsertSQL($rs, $fields_values, $magicq); + break; + default: + ADOConnection::outp("AutoExecute: Unknown mode=$mode"); + return $false; + } + $ret = false; + if ($sql) $ret = $this->Execute($sql); + if ($ret) $ret = true; + return $ret; + } + + + /** + * Generates an Update Query based on an existing recordset. + * $arrFields is an associative array of fields with the value + * that should be assigned. + * + * Note: This function should only be used on a recordset + * that is run against a single table and sql should only + * be a simple select stmt with no groupby/orderby/limit + * + * "Jonathan Younger" + */ + function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null) + { + global $ADODB_INCLUDED_LIB; + + //********************************************************// + //This is here to maintain compatibility + //with older adodb versions. Sets force type to force nulls if $forcenulls is set. + if (!isset($force)) { + global $ADODB_FORCE_TYPE; + $force = $ADODB_FORCE_TYPE; + } + //********************************************************// + + if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force); + } + + /** + * Generates an Insert Query based on an existing recordset. + * $arrFields is an associative array of fields with the value + * that should be assigned. + * + * Note: This function should only be used on a recordset + * that is run against a single table. + */ + function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null) + { + global $ADODB_INCLUDED_LIB; + if (!isset($force)) { + global $ADODB_FORCE_TYPE; + $force = $ADODB_FORCE_TYPE; + + } + if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force); + } + + + /** + * Update a blob column, given a where clause. There are more sophisticated + * blob handling functions that we could have implemented, but all require + * a very complex API. Instead we have chosen something that is extremely + * simple to understand and use. + * + * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course. + * + * Usage to update a $blobvalue which has a primary key blob_id=1 into a + * field blobtable.blobcolumn: + * + * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1'); + * + * Insert example: + * + * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); + * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); + */ + + function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') + { + return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false; + } + + /** + * Usage: + * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1'); + * + * $blobtype supports 'BLOB' and 'CLOB' + * + * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); + * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1'); + */ + function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') + { + $fd = fopen($path,'rb'); + if ($fd === false) return false; + $val = fread($fd,filesize($path)); + fclose($fd); + return $this->UpdateBlob($table,$column,$val,$where,$blobtype); + } + + function BlobDecode($blob) + { + return $blob; + } + + function BlobEncode($blob) + { + return $blob; + } + + function SetCharSet($charset) + { + return false; + } + + function IfNull( $field, $ifNull ) + { + return " CASE WHEN $field is null THEN $ifNull ELSE $field END "; + } + + function LogSQL($enable=true) + { + include_once(ADODB_DIR.'/adodb-perf.inc.php'); + + if ($enable) $this->fnExecute = 'adodb_log_sql'; + else $this->fnExecute = false; + + $old = $this->_logsql; + $this->_logsql = $enable; + if ($enable && !$old) $this->_affected = false; + return $old; + } + + function GetCharSet() + { + return false; + } + + /** + * Usage: + * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB'); + * + * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)'); + * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1'); + */ + function UpdateClob($table,$column,$val,$where) + { + return $this->UpdateBlob($table,$column,$val,$where,'CLOB'); + } + + // not the fastest implementation - quick and dirty - jlim + // for best performance, use the actual $rs->MetaType(). + function MetaType($t,$len=-1,$fieldobj=false) + { + + if (empty($this->_metars)) { + $rsclass = $this->rsPrefix.$this->databaseType; + $this->_metars =& new $rsclass(false,$this->fetchMode); + $this->_metars->connection =& $this; + } + return $this->_metars->MetaType($t,$len,$fieldobj); + } + + + /** + * Change the SQL connection locale to a specified locale. + * This is used to get the date formats written depending on the client locale. + */ + function SetDateLocale($locale = 'En') + { + $this->locale = $locale; + switch (strtoupper($locale)) + { + case 'EN': + $this->fmtDate="'Y-m-d'"; + $this->fmtTimeStamp = "'Y-m-d H:i:s'"; + break; + + case 'US': + $this->fmtDate = "'m-d-Y'"; + $this->fmtTimeStamp = "'m-d-Y H:i:s'"; + break; + + case 'NL': + case 'FR': + case 'RO': + case 'IT': + $this->fmtDate="'d-m-Y'"; + $this->fmtTimeStamp = "'d-m-Y H:i:s'"; + break; + + case 'GE': + $this->fmtDate="'d.m.Y'"; + $this->fmtTimeStamp = "'d.m.Y H:i:s'"; + break; + + default: + $this->fmtDate="'Y-m-d'"; + $this->fmtTimeStamp = "'Y-m-d H:i:s'"; + break; + } + } + + function &GetActiveRecordsClass($class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false) + { + global $_ADODB_ACTIVE_DBS; + + $save = $this->SetFetchMode(ADODB_FETCH_NUM); + if (empty($whereOrderBy)) $whereOrderBy = '1=1'; + $rows = $this->GetAll("select * from ".$table.' WHERE '.$whereOrderBy,$bindarr); + $this->SetFetchMode($save); + + $false = false; + + if ($rows === false) { + return $false; + } + + + if (!isset($_ADODB_ACTIVE_DBS)) { + include(ADODB_DIR.'/adodb-active-record.inc.php'); + } + if (!class_exists($class)) { + ADOConnection::outp("Unknown class $class in GetActiveRcordsClass()"); + return $false; + } + $arr = array(); + foreach($rows as $row) { + + $obj =& new $class($table,$primkeyArr,$this); + if ($obj->ErrorMsg()){ + $this->_errorMsg = $obj->ErrorMsg(); + return $false; + } + $obj->Set($row); + $arr[] =& $obj; + } + return $arr; + } + + function &GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false) + { + $arr =& $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr); + return $arr; + } + + /** + * Close Connection + */ + function Close() + { + $rez = $this->_close(); + $this->_connectionID = false; + return $rez; + } + + /** + * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans(). + * + * @return true if succeeded or false if database does not support transactions + */ + function BeginTrans() {return false;} + + /* set transaction mode */ + function SetTransactionMode( $transaction_mode ) + { + $transaction_mode = $this->MetaTransaction($transaction_mode, $this->dataProvider); + $this->_transmode = $transaction_mode; + } +/* +http://msdn2.microsoft.com/en-US/ms173763.aspx +http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-isolation.html +http://www.postgresql.org/docs/8.1/interactive/sql-set-transaction.html +http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_10005.htm +*/ + function MetaTransaction($mode,$db) + { + $mode = strtoupper($mode); + $mode = str_replace('ISOLATION LEVEL ','',$mode); + + switch($mode) { + + case 'READ UNCOMMITTED': + switch($db) { + case 'oci8': + case 'oracle': + return 'ISOLATION LEVEL READ COMMITTED'; + default: + return 'ISOLATION LEVEL READ UNCOMMITTED'; + } + break; + + case 'READ COMMITTED': + return 'ISOLATION LEVEL READ COMMITTED'; + break; + + case 'REPEATABLE READ': + switch($db) { + case 'oci8': + case 'oracle': + return 'ISOLATION LEVEL SERIALIZABLE'; + default: + return 'ISOLATION LEVEL REPEATABLE READ'; + } + break; + + case 'SERIALIZABLE': + return 'ISOLATION LEVEL SERIALIZABLE'; + break; + + default: + return $mode; + } + } + + /** + * If database does not support transactions, always return true as data always commited + * + * @param $ok set to false to rollback transaction, true to commit + * + * @return true/false. + */ + function CommitTrans($ok=true) + { return true;} + + + /** + * If database does not support transactions, rollbacks always fail, so return false + * + * @return true/false. + */ + function RollbackTrans() + { return false;} + + + /** + * return the databases that the driver can connect to. + * Some databases will return an empty array. + * + * @return an array of database names. + */ + function MetaDatabases() + { + global $ADODB_FETCH_MODE; + + if ($this->metaDatabasesSQL) { + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + + $arr = $this->GetCol($this->metaDatabasesSQL); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + return $arr; + } + + return false; + } + + + /** + * @param ttype can either be 'VIEW' or 'TABLE' or false. + * If false, both views and tables are returned. + * "VIEW" returns only views + * "TABLE" returns only tables + * @param showSchema returns the schema/user with the table name, eg. USER.TABLE + * @param mask is the input mask - only supported by oci8 and postgresql + * + * @return array of tables for current database. + */ + function &MetaTables($ttype=false,$showSchema=false,$mask=false) + { + global $ADODB_FETCH_MODE; + + + $false = false; + if ($mask) { + return $false; + } + if ($this->metaTablesSQL) { + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + + $rs = $this->Execute($this->metaTablesSQL); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + if ($rs === false) return $false; + $arr =& $rs->GetArray(); + $arr2 = array(); + + if ($hast = ($ttype && isset($arr[0][1]))) { + $showt = strncmp($ttype,'T',1); + } + + for ($i=0; $i < sizeof($arr); $i++) { + if ($hast) { + if ($showt == 0) { + if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]); + } else { + if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]); + } + } else + $arr2[] = trim($arr[$i][0]); + } + $rs->Close(); + return $arr2; + } + return $false; + } + + + function _findschema(&$table,&$schema) + { + if (!$schema && ($at = strpos($table,'.')) !== false) { + $schema = substr($table,0,$at); + $table = substr($table,$at+1); + } + } + + /** + * List columns in a database as an array of ADOFieldObjects. + * See top of file for definition of object. + * + * @param $table table name to query + * @param $normalize makes table name case-insensitive (required by some databases) + * @schema is optional database schema to use - not supported by all databases. + * + * @return array of ADOFieldObjects for current table. + */ + function &MetaColumns($table,$normalize=true) + { + global $ADODB_FETCH_MODE; + + $false = false; + + if (!empty($this->metaColumnsSQL)) { + + $schema = false; + $this->_findschema($table,$schema); + + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + $rs = $this->Execute(sprintf($this->metaColumnsSQL,($normalize)?strtoupper($table):$table)); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if ($rs === false || $rs->EOF) return $false; + + $retarr = array(); + while (!$rs->EOF) { //print_r($rs->fields); + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $fld->type = $rs->fields[1]; + if (isset($rs->fields[3]) && $rs->fields[3]) { + if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3]; + $fld->scale = $rs->fields[4]; + if ($fld->scale>0) $fld->max_length += 1; + } else + $fld->max_length = $rs->fields[2]; + + if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; + else $retarr[strtoupper($fld->name)] = $fld; + $rs->MoveNext(); + } + $rs->Close(); + return $retarr; + } + return $false; + } + + /** + * List indexes on a table as an array. + * @param table table name to query + * @param primary true to only show primary keys. Not actually used for most databases + * + * @return array of indexes on current table. Each element represents an index, and is itself an associative array. + + Array ( + [name_of_index] => Array + ( + [unique] => true or false + [columns] => Array + ( + [0] => firstname + [1] => lastname + ) + ) + */ + function &MetaIndexes($table, $primary = false, $owner = false) + { + $false = false; + return $false; + } + + /** + * List columns names in a table as an array. + * @param table table name to query + * + * @return array of column names for current table. + */ + function &MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */) + { + $objarr =& $this->MetaColumns($table); + if (!is_array($objarr)) { + $false = false; + return $false; + } + $arr = array(); + if ($numIndexes) { + $i = 0; + if ($useattnum) { + foreach($objarr as $v) + $arr[$v->attnum] = $v->name; + + } else + foreach($objarr as $v) $arr[$i++] = $v->name; + } else + foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name; + + return $arr; + } + + /** + * Different SQL databases used different methods to combine strings together. + * This function provides a wrapper. + * + * param s variable number of string parameters + * + * Usage: $db->Concat($str1,$str2); + * + * @return concatenated string + */ + function Concat() + { + $arr = func_get_args(); + return implode($this->concat_operator, $arr); + } + + + /** + * Converts a date "d" to a string that the database can understand. + * + * @param d a date in Unix date time format. + * + * @return date string in database date format + */ + function DBDate($d) + { + if (empty($d) && $d !== 0) return 'null'; + + if (is_string($d) && !is_numeric($d)) { + if ($d === 'null' || strncmp($d,"'",1) === 0) return $d; + if ($this->isoDates) return "'$d'"; + $d = ADOConnection::UnixDate($d); + } + + return adodb_date($this->fmtDate,$d); + } + + function BindDate($d) + { + $d = $this->DBDate($d); + if (strncmp($d,"'",1)) return $d; + + return substr($d,1,strlen($d)-2); + } + + function BindTimeStamp($d) + { + $d = $this->DBTimeStamp($d); + if (strncmp($d,"'",1)) return $d; + + return substr($d,1,strlen($d)-2); + } + + + /** + * Converts a timestamp "ts" to a string that the database can understand. + * + * @param ts a timestamp in Unix date time format. + * + * @return timestamp string in database timestamp format + */ + function DBTimeStamp($ts) + { + if (empty($ts) && $ts !== 0) return 'null'; + + # strlen(14) allows YYYYMMDDHHMMSS format + if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) + return adodb_date($this->fmtTimeStamp,$ts); + + if ($ts === 'null') return $ts; + if ($this->isoDates && strlen($ts) !== 14) return "'$ts'"; + + $ts = ADOConnection::UnixTimeStamp($ts); + return adodb_date($this->fmtTimeStamp,$ts); + } + + /** + * Also in ADORecordSet. + * @param $v is a date string in YYYY-MM-DD format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixDate($v) + { + if (is_object($v)) { + // odbtp support + //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 ) + return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year); + } + + if (is_numeric($v) && strlen($v) !== 8) return $v; + if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", + ($v), $rr)) return false; + + if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0; + // h-m-s-MM-DD-YY + return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); + } + + + /** + * Also in ADORecordSet. + * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixTimeStamp($v) + { + if (is_object($v)) { + // odbtp support + //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 ) + return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year); + } + + if (!preg_match( + "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", + ($v), $rr)) return false; + + if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0; + + // h-m-s-MM-DD-YY + if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); + return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); + } + + /** + * Also in ADORecordSet. + * + * Format database date based on user defined format. + * + * @param v is the character date in YYYY-MM-DD format, returned by database + * @param fmt is the format to apply to it, using date() + * + * @return a date formated as user desires + */ + + function UserDate($v,$fmt='Y-m-d',$gmt=false) + { + $tt = $this->UnixDate($v); + + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + else if ($tt == 0) return $this->emptyDate; + else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR + } + + return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt); + + } + + /** + * + * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format + * @param fmt is the format to apply to it, using date() + * + * @return a timestamp formated as user desires + */ + function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false) + { + if (!isset($v)) return $this->emptyTimeStamp; + # strlen(14) allows YYYYMMDDHHMMSS format + if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v); + $tt = $this->UnixTimeStamp($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + if ($tt == 0) return $this->emptyTimeStamp; + return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt); + } + + function escape($s,$magic_quotes=false) + { + return $this->addq($s,$magic_quotes); + } + + /** + * Quotes a string, without prefixing nor appending quotes. + */ + function addq($s,$magic_quotes=false) + { + if (!$magic_quotes) { + + if ($this->replaceQuote[0] == '\\'){ + // only since php 4.0.5 + $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); + //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); + } + return str_replace("'",$this->replaceQuote,$s); + } + + // undo magic quotes for " + $s = str_replace('\\"','"',$s); + + if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything + return $s; + else {// change \' to '' for sybase/mssql + $s = str_replace('\\\\','\\',$s); + return str_replace("\\'",$this->replaceQuote,$s); + } + } + + /** + * Correctly quotes a string so that all strings are escaped. We prefix and append + * to the string single-quotes. + * An example is $db->qstr("Don't bother",magic_quotes_runtime()); + * + * @param s the string to quote + * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc(). + * This undoes the stupidity of magic quotes for GPC. + * + * @return quoted string to be sent back to database + */ + function qstr($s,$magic_quotes=false) + { + if (!$magic_quotes) { + + if ($this->replaceQuote[0] == '\\'){ + // only since php 4.0.5 + $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); + //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); + } + return "'".str_replace("'",$this->replaceQuote,$s)."'"; + } + + // undo magic quotes for " + $s = str_replace('\\"','"',$s); + + if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything + return "'$s'"; + else {// change \' to '' for sybase/mssql + $s = str_replace('\\\\','\\',$s); + return "'".str_replace("\\'",$this->replaceQuote,$s)."'"; + } + } + + + /** + * Will select the supplied $page number from a recordset, given that it is paginated in pages of + * $nrows rows per page. It also saves two boolean values saying if the given page is the first + * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. + * + * See readme.htm#ex8 for an example of usage. + * + * @param sql + * @param nrows is the number of rows per page to get + * @param page is the page number to get (1-based) + * @param [inputarr] array of bind variables + * @param [secs2cache] is a private parameter only used by jlim + * @return the recordset ($rs->databaseType == 'array') + * + * NOTE: phpLens uses a different algorithm and does not use PageExecute(). + * + */ + function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); + if ($this->pageExecuteCountRows) $rs =& _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache); + else $rs =& _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache); + return $rs; + } + + + /** + * Will select the supplied $page number from a recordset, given that it is paginated in pages of + * $nrows rows per page. It also saves two boolean values saying if the given page is the first + * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. + * + * @param secs2cache seconds to cache data, set to 0 to force query + * @param sql + * @param nrows is the number of rows per page to get + * @param page is the page number to get (1-based) + * @param [inputarr] array of bind variables + * @return the recordset ($rs->databaseType == 'array') + */ + function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) + { + /*switch($this->dataProvider) { + case 'postgres': + case 'mysql': + break; + default: $secs2cache = 0; break; + }*/ + $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache); + return $rs; + } + +} // end class ADOConnection + + + + //============================================================================================== + // CLASS ADOFetchObj + //============================================================================================== + + /** + * Internal placeholder for record objects. Used by ADORecordSet->FetchObj(). + */ + class ADOFetchObj { + }; + + //============================================================================================== + // CLASS ADORecordSet_empty + //============================================================================================== + + /** + * Lightweight recordset when there are no records to be returned + */ + class ADORecordSet_empty + { + var $dataProvider = 'empty'; + var $databaseType = false; + var $EOF = true; + var $_numOfRows = 0; + var $fields = false; + var $connection = false; + function RowCount() {return 0;} + function RecordCount() {return 0;} + function PO_RecordCount(){return 0;} + function Close(){return true;} + function FetchRow() {return false;} + function FieldCount(){ return 0;} + function Init() {} + } + + //============================================================================================== + // DATE AND TIME FUNCTIONS + //============================================================================================== + if (!defined('ADODB_DATE_VERSION')) include(ADODB_DIR.'/adodb-time.inc.php'); + + //============================================================================================== + // CLASS ADORecordSet + //============================================================================================== + + if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php'); + else include_once(ADODB_DIR.'/adodb-iterator.inc.php'); + /** + * RecordSet class that represents the dataset returned by the database. + * To keep memory overhead low, this class holds only the current row in memory. + * No prefetching of data is done, so the RecordCount() can return -1 ( which + * means recordcount not known). + */ + class ADORecordSet extends ADODB_BASE_RS { + /* + * public variables + */ + var $dataProvider = "native"; + var $fields = false; /// holds the current row data + var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob + /// in other words, we use a text area for editing. + var $canSeek = false; /// indicates that seek is supported + var $sql; /// sql text + var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object. + + var $emptyTimeStamp = ' '; /// what to display when $time==0 + var $emptyDate = ' '; /// what to display when $time==0 + var $debug = false; + var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets + + var $bind = false; /// used by Fields() to hold array - should be private? + var $fetchMode; /// default fetch mode + var $connection = false; /// the parent connection + /* + * private variables + */ + var $_numOfRows = -1; /** number of rows, or -1 */ + var $_numOfFields = -1; /** number of fields in recordset */ + var $_queryID = -1; /** This variable keeps the result link identifier. */ + var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */ + var $_closed = false; /** has recordset been closed */ + var $_inited = false; /** Init() should only be called once */ + var $_obj; /** Used by FetchObj */ + var $_names; /** Used by FetchObj */ + + var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */ + var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */ + var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */ + var $_lastPageNo = -1; + var $_maxRecordCount = 0; + var $datetime = false; + + /** + * Constructor + * + * @param queryID this is the queryID returned by ADOConnection->_query() + * + */ + function ADORecordSet($queryID) + { + $this->_queryID = $queryID; + } + + + + function Init() + { + if ($this->_inited) return; + $this->_inited = true; + if ($this->_queryID) @$this->_initrs(); + else { + $this->_numOfRows = 0; + $this->_numOfFields = 0; + } + if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) { + + $this->_currentRow = 0; + if ($this->EOF = ($this->_fetch() === false)) { + $this->_numOfRows = 0; // _numOfRows could be -1 + } + } else { + $this->EOF = true; + } + } + + + /** + * Generate a SELECT tag string from a recordset, and return the string. + * If the recordset has 2 cols, we treat the 1st col as the containing + * the text to display to the user, and 2nd col as the return value. Default + * strings are compared with the FIRST column. + * + * @param name name of SELECT tag + * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox. + * @param [blank1stItem] true to leave the 1st item in list empty + * @param [multiple] true for listbox, false for popup + * @param [size] #rows to show for listbox. not used by popup + * @param [selectAttr] additional attributes to defined for SELECT tag. + * useful for holding javascript onChange='...' handlers. + & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with + * column 0 (1st col) if this is true. This is not documented. + * + * @return HTML + * + * changes by glen.davies@cce.ac.nz to support multiple hilited items + */ + function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false, + $size=0, $selectAttr='',$compareFields0=true) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple, + $size, $selectAttr,$compareFields0); + } + + + + /** + * Generate a SELECT tag string from a recordset, and return the string. + * If the recordset has 2 cols, we treat the 1st col as the containing + * the text to display to the user, and 2nd col as the return value. Default + * strings are compared with the SECOND column. + * + */ + function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='') + { + return $this->GetMenu($name,$defstr,$blank1stItem,$multiple, + $size, $selectAttr,false); + } + + /* + Grouped Menu + */ + function GetMenu3($name,$defstr='',$blank1stItem=true,$multiple=false, + $size=0, $selectAttr='') + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getmenu_gp($this, $name,$defstr,$blank1stItem,$multiple, + $size, $selectAttr,false); + } + + /** + * return recordset as a 2-dimensional array. + * + * @param [nRows] is the number of rows to return. -1 means every row. + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function &GetArray($nRows = -1) + { + global $ADODB_EXTENSION; if ($ADODB_EXTENSION) { + $results = adodb_getall($this,$nRows); + return $results; + } + $results = array(); + $cnt = 0; + while (!$this->EOF && $nRows != $cnt) { + $results[] = $this->fields; + $this->MoveNext(); + $cnt++; + } + return $results; + } + + function &GetAll($nRows = -1) + { + $arr =& $this->GetArray($nRows); + return $arr; + } + + /* + * Some databases allow multiple recordsets to be returned. This function + * will return true if there is a next recordset, or false if no more. + */ + function NextRecordSet() + { + return false; + } + + /** + * return recordset as a 2-dimensional array. + * Helper function for ADOConnection->SelectLimit() + * + * @param offset is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to return + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function &GetArrayLimit($nrows,$offset=-1) + { + if ($offset <= 0) { + $arr =& $this->GetArray($nrows); + return $arr; + } + + $this->Move($offset); + + $results = array(); + $cnt = 0; + while (!$this->EOF && $nrows != $cnt) { + $results[$cnt++] = $this->fields; + $this->MoveNext(); + } + + return $results; + } + + + /** + * Synonym for GetArray() for compatibility with ADO. + * + * @param [nRows] is the number of rows to return. -1 means every row. + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function &GetRows($nRows = -1) + { + $arr =& $this->GetArray($nRows); + return $arr; + } + + /** + * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. + * The first column is treated as the key and is not included in the array. + * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless + * $force_array == true. + * + * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional + * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing, + * read the source. + * + * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and + * instead of returning array[col0] => array(remaining cols), return array[col0] => col1 + * + * @return an associative array indexed by the first column of the array, + * or false if the data has less than 2 cols. + */ + function &GetAssoc($force_array = false, $first2cols = false) + { + global $ADODB_EXTENSION; + + $cols = $this->_numOfFields; + if ($cols < 2) { + $false = false; + return $false; + } + $numIndex = isset($this->fields[0]); + $results = array(); + + if (!$first2cols && ($cols > 2 || $force_array)) { + if ($ADODB_EXTENSION) { + if ($numIndex) { + while (!$this->EOF) { + $results[trim($this->fields[0])] = array_slice($this->fields, 1); + adodb_movenext($this); + } + } else { + while (!$this->EOF) { + // Fix for array_slice re-numbering numeric associative keys + $keys = array_slice(array_keys($this->fields), 1); + $sliced_array = array(); + + foreach($keys as $key) { + $sliced_array[$key] = $this->fields[$key]; + } + + $results[trim(reset($this->fields))] = $sliced_array; + adodb_movenext($this); + } + } + } else { + if ($numIndex) { + while (!$this->EOF) { + $results[trim($this->fields[0])] = array_slice($this->fields, 1); + $this->MoveNext(); + } + } else { + while (!$this->EOF) { + // Fix for array_slice re-numbering numeric associative keys + $keys = array_slice(array_keys($this->fields), 1); + $sliced_array = array(); + + foreach($keys as $key) { + $sliced_array[$key] = $this->fields[$key]; + } + + $results[trim(reset($this->fields))] = $sliced_array; + $this->MoveNext(); + } + } + } + } else { + if ($ADODB_EXTENSION) { + // return scalar values + if ($numIndex) { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $results[trim(($this->fields[0]))] = $this->fields[1]; + adodb_movenext($this); + } + } else { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $v1 = trim(reset($this->fields)); + $v2 = ''.next($this->fields); + $results[$v1] = $v2; + adodb_movenext($this); + } + } + } else { + if ($numIndex) { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $results[trim(($this->fields[0]))] = $this->fields[1]; + $this->MoveNext(); + } + } else { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $v1 = trim(reset($this->fields)); + $v2 = ''.next($this->fields); + $results[$v1] = $v2; + $this->MoveNext(); + } + } + } + } + + $ref =& $results; # workaround accelerator incompat with PHP 4.4 :( + return $ref; + } + + + /** + * + * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format + * @param fmt is the format to apply to it, using date() + * + * @return a timestamp formated as user desires + */ + function UserTimeStamp($v,$fmt='Y-m-d H:i:s') + { + if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v); + $tt = $this->UnixTimeStamp($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + if ($tt === 0) return $this->emptyTimeStamp; + return adodb_date($fmt,$tt); + } + + + /** + * @param v is the character date in YYYY-MM-DD format, returned by database + * @param fmt is the format to apply to it, using date() + * + * @return a date formated as user desires + */ + function UserDate($v,$fmt='Y-m-d') + { + $tt = $this->UnixDate($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + else if ($tt == 0) return $this->emptyDate; + else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR + } + return adodb_date($fmt,$tt); + } + + + /** + * @param $v is a date string in YYYY-MM-DD format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixDate($v) + { + return ADOConnection::UnixDate($v); + } + + + /** + * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixTimeStamp($v) + { + return ADOConnection::UnixTimeStamp($v); + } + + + /** + * PEAR DB Compat - do not use internally + */ + function Free() + { + return $this->Close(); + } + + + /** + * PEAR DB compat, number of rows + */ + function NumRows() + { + return $this->_numOfRows; + } + + + /** + * PEAR DB compat, number of cols + */ + function NumCols() + { + return $this->_numOfFields; + } + + /** + * Fetch a row, returning false if no more rows. + * This is PEAR DB compat mode. + * + * @return false or array containing the current record + */ + function &FetchRow() + { + if ($this->EOF) { + $false = false; + return $false; + } + $arr = $this->fields; + $this->_currentRow++; + if (!$this->_fetch()) $this->EOF = true; + return $arr; + } + + + /** + * Fetch a row, returning PEAR_Error if no more rows. + * This is PEAR DB compat mode. + * + * @return DB_OK or error object + */ + function FetchInto(&$arr) + { + if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false; + $arr = $this->fields; + $this->MoveNext(); + return 1; // DB_OK + } + + + /** + * Move to the first row in the recordset. Many databases do NOT support this. + * + * @return true or false + */ + function MoveFirst() + { + if ($this->_currentRow == 0) return true; + return $this->Move(0); + } + + + /** + * Move to the last row in the recordset. + * + * @return true or false + */ + function MoveLast() + { + if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1); + if ($this->EOF) return false; + while (!$this->EOF) { + $f = $this->fields; + $this->MoveNext(); + } + $this->fields = $f; + $this->EOF = false; + return true; + } + + + /** + * Move to next record in the recordset. + * + * @return true if there still rows available, or false if there are no more rows (EOF). + */ + function MoveNext() + { + if (!$this->EOF) { + $this->_currentRow++; + if ($this->_fetch()) return true; + } + $this->EOF = true; + /* -- tested error handling when scrolling cursor -- seems useless. + $conn = $this->connection; + if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) { + $fn = $conn->raiseErrorFn; + $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database); + } + */ + return false; + } + + + /** + * Random access to a specific row in the recordset. Some databases do not support + * access to previous rows in the databases (no scrolling backwards). + * + * @param rowNumber is the row to move to (0-based) + * + * @return true if there still rows available, or false if there are no more rows (EOF). + */ + function Move($rowNumber = 0) + { + $this->EOF = false; + if ($rowNumber == $this->_currentRow) return true; + if ($rowNumber >= $this->_numOfRows) + if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2; + + if ($this->canSeek) { + + if ($this->_seek($rowNumber)) { + $this->_currentRow = $rowNumber; + if ($this->_fetch()) { + return true; + } + } else { + $this->EOF = true; + return false; + } + } else { + if ($rowNumber < $this->_currentRow) return false; + global $ADODB_EXTENSION; + if ($ADODB_EXTENSION) { + while (!$this->EOF && $this->_currentRow < $rowNumber) { + adodb_movenext($this); + } + } else { + + while (! $this->EOF && $this->_currentRow < $rowNumber) { + $this->_currentRow++; + + if (!$this->_fetch()) $this->EOF = true; + } + } + return !($this->EOF); + } + + $this->fields = false; + $this->EOF = true; + return false; + } + + + /** + * Get the value of a field in the current row by column name. + * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM. + * + * @param colname is the field to access + * + * @return the value of $colname column + */ + function Fields($colname) + { + return $this->fields[$colname]; + } + + function GetAssocKeys($upper=true) + { + $this->bind = array(); + for ($i=0; $i < $this->_numOfFields; $i++) { + $o = $this->FetchField($i); + if ($upper === 2) $this->bind[$o->name] = $i; + else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i; + } + } + + /** + * Use associative array to get fields array for databases that do not support + * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it + * + * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC + * before you execute your SQL statement, and access $rs->fields['col'] directly. + * + * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField + */ + function &GetRowAssoc($upper=1) + { + $record = array(); + // if (!$this->fields) return $record; + + if (!$this->bind) { + $this->GetAssocKeys($upper); + } + + foreach($this->bind as $k => $v) { + $record[$k] = $this->fields[$v]; + } + + return $record; + } + + + /** + * Clean up recordset + * + * @return true or false + */ + function Close() + { + // free connection object - this seems to globally free the object + // and not merely the reference, so don't do this... + // $this->connection = false; + if (!$this->_closed) { + $this->_closed = true; + return $this->_close(); + } else + return true; + } + + /** + * synonyms RecordCount and RowCount + * + * @return the number of rows or -1 if this is not supported + */ + function RecordCount() {return $this->_numOfRows;} + + + /* + * If we are using PageExecute(), this will return the maximum possible rows + * that can be returned when paging a recordset. + */ + function MaxRecordCount() + { + return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount(); + } + + /** + * synonyms RecordCount and RowCount + * + * @return the number of rows or -1 if this is not supported + */ + function RowCount() {return $this->_numOfRows;} + + + /** + * Portable RecordCount. Pablo Roca + * + * @return the number of records from a previous SELECT. All databases support this. + * + * But aware possible problems in multiuser environments. For better speed the table + * must be indexed by the condition. Heavy test this before deploying. + */ + function PO_RecordCount($table="", $condition="") { + + $lnumrows = $this->_numOfRows; + // the database doesn't support native recordcount, so we do a workaround + if ($lnumrows == -1 && $this->connection) { + IF ($table) { + if ($condition) $condition = " WHERE " . $condition; + $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition"); + if ($resultrows) $lnumrows = reset($resultrows->fields); + } + } + return $lnumrows; + } + + + /** + * @return the current row in the recordset. If at EOF, will return the last row. 0-based. + */ + function CurrentRow() {return $this->_currentRow;} + + /** + * synonym for CurrentRow -- for ADO compat + * + * @return the current row in the recordset. If at EOF, will return the last row. 0-based. + */ + function AbsolutePosition() {return $this->_currentRow;} + + /** + * @return the number of columns in the recordset. Some databases will set this to 0 + * if no records are returned, others will return the number of columns in the query. + */ + function FieldCount() {return $this->_numOfFields;} + + + /** + * Get the ADOFieldObject of a specific column. + * + * @param fieldoffset is the column position to access(0-based). + * + * @return the ADOFieldObject for that column, or false. + */ + function &FetchField($fieldoffset) + { + // must be defined by child class + } + + /** + * Get the ADOFieldObjects of all columns in an array. + * + */ + function& FieldTypesArray() + { + $arr = array(); + for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) + $arr[] = $this->FetchField($i); + return $arr; + } + + /** + * Return the fields array of the current row as an object for convenience. + * The default case is lowercase field names. + * + * @return the object with the properties set to the fields of the current row + */ + function &FetchObj() + { + $o =& $this->FetchObject(false); + return $o; + } + + /** + * Return the fields array of the current row as an object for convenience. + * The default case is uppercase. + * + * @param $isupper to set the object property names to uppercase + * + * @return the object with the properties set to the fields of the current row + */ + function &FetchObject($isupper=true) + { + if (empty($this->_obj)) { + $this->_obj = new ADOFetchObj(); + $this->_names = array(); + for ($i=0; $i <$this->_numOfFields; $i++) { + $f = $this->FetchField($i); + $this->_names[] = $f->name; + } + } + $i = 0; + if (PHP_VERSION >= 5) $o = clone($this->_obj); + else $o = $this->_obj; + + for ($i=0; $i <$this->_numOfFields; $i++) { + $name = $this->_names[$i]; + if ($isupper) $n = strtoupper($name); + else $n = $name; + + $o->$n = $this->Fields($name); + } + return $o; + } + + /** + * Return the fields array of the current row as an object for convenience. + * The default is lower-case field names. + * + * @return the object with the properties set to the fields of the current row, + * or false if EOF + * + * Fixed bug reported by tim@orotech.net + */ + function &FetchNextObj() + { + $o =& $this->FetchNextObject(false); + return $o; + } + + + /** + * Return the fields array of the current row as an object for convenience. + * The default is upper case field names. + * + * @param $isupper to set the object property names to uppercase + * + * @return the object with the properties set to the fields of the current row, + * or false if EOF + * + * Fixed bug reported by tim@orotech.net + */ + function &FetchNextObject($isupper=true) + { + $o = false; + if ($this->_numOfRows != 0 && !$this->EOF) { + $o = $this->FetchObject($isupper); + $this->_currentRow++; + if ($this->_fetch()) return $o; + } + $this->EOF = true; + return $o; + } + + /** + * Get the metatype of the column. This is used for formatting. This is because + * many databases use different names for the same type, so we transform the original + * type to our standardised version which uses 1 character codes: + * + * @param t is the type passed in. Normally is ADOFieldObject->type. + * @param len is the maximum length of that field. This is because we treat character + * fields bigger than a certain size as a 'B' (blob). + * @param fieldobj is the field object returned by the database driver. Can hold + * additional info (eg. primary_key for mysql). + * + * @return the general type of the data: + * C for character < 250 chars + * X for teXt (>= 250 chars) + * B for Binary + * N for numeric or floating point + * D for date + * T for timestamp + * L for logical/Boolean + * I for integer + * R for autoincrement counter/integer + * + * + */ + function MetaType($t,$len=-1,$fieldobj=false) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } + // changed in 2.32 to hashing instead of switch stmt for speed... + static $typeMap = array( + 'VARCHAR' => 'C', + 'VARCHAR2' => 'C', + 'CHAR' => 'C', + 'C' => 'C', + 'STRING' => 'C', + 'NCHAR' => 'C', + 'NVARCHAR' => 'C', + 'VARYING' => 'C', + 'BPCHAR' => 'C', + 'CHARACTER' => 'C', + 'INTERVAL' => 'C', # Postgres + 'MACADDR' => 'C', # postgres + ## + 'LONGCHAR' => 'X', + 'TEXT' => 'X', + 'NTEXT' => 'X', + 'M' => 'X', + 'X' => 'X', + 'CLOB' => 'X', + 'NCLOB' => 'X', + 'LVARCHAR' => 'X', + ## + 'BLOB' => 'B', + 'IMAGE' => 'B', + 'BINARY' => 'B', + 'VARBINARY' => 'B', + 'LONGBINARY' => 'B', + 'B' => 'B', + ## + 'YEAR' => 'D', // mysql + 'DATE' => 'D', + 'D' => 'D', + ## + 'UNIQUEIDENTIFIER' => 'C', # MS SQL Server + ## + 'TIME' => 'T', + 'TIMESTAMP' => 'T', + 'DATETIME' => 'T', + 'TIMESTAMPTZ' => 'T', + 'T' => 'T', + 'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql + ## + 'BOOL' => 'L', + 'BOOLEAN' => 'L', + 'BIT' => 'L', + 'L' => 'L', + ## + 'COUNTER' => 'R', + 'R' => 'R', + 'SERIAL' => 'R', // ifx + 'INT IDENTITY' => 'R', + ## + 'INT' => 'I', + 'INT2' => 'I', + 'INT4' => 'I', + 'INT8' => 'I', + 'INTEGER' => 'I', + 'INTEGER UNSIGNED' => 'I', + 'SHORT' => 'I', + 'TINYINT' => 'I', + 'SMALLINT' => 'I', + 'I' => 'I', + ## + 'LONG' => 'N', // interbase is numeric, oci8 is blob + 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers + 'DECIMAL' => 'N', + 'DEC' => 'N', + 'REAL' => 'N', + 'DOUBLE' => 'N', + 'DOUBLE PRECISION' => 'N', + 'SMALLFLOAT' => 'N', + 'FLOAT' => 'N', + 'NUMBER' => 'N', + 'NUM' => 'N', + 'NUMERIC' => 'N', + 'MONEY' => 'N', + + ## informix 9.2 + 'SQLINT' => 'I', + 'SQLSERIAL' => 'I', + 'SQLSMINT' => 'I', + 'SQLSMFLOAT' => 'N', + 'SQLFLOAT' => 'N', + 'SQLMONEY' => 'N', + 'SQLDECIMAL' => 'N', + 'SQLDATE' => 'D', + 'SQLVCHAR' => 'C', + 'SQLCHAR' => 'C', + 'SQLDTIME' => 'T', + 'SQLINTERVAL' => 'N', + 'SQLBYTES' => 'B', + 'SQLTEXT' => 'X', + ## informix 10 + "SQLINT8" => 'I8', + "SQLSERIAL8" => 'I8', + "SQLNCHAR" => 'C', + "SQLNVCHAR" => 'C', + "SQLLVARCHAR" => 'X', + "SQLBOOL" => 'L' + ); + + $tmap = false; + $t = strtoupper($t); + $tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N'; + switch ($tmap) { + case 'C': + + // is the char field is too long, return as text field... + if ($this->blobSize >= 0) { + if ($len > $this->blobSize) return 'X'; + } else if ($len > 250) { + return 'X'; + } + return 'C'; + + case 'I': + if (!empty($fieldobj->primary_key)) return 'R'; + return 'I'; + + case false: + return 'N'; + + case 'B': + if (isset($fieldobj->binary)) + return ($fieldobj->binary) ? 'B' : 'X'; + return 'B'; + + case 'D': + if (!empty($this->connection) && !empty($this->connection->datetime)) return 'T'; + return 'D'; + + default: + if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B'; + return $tmap; + } + } + + + function _close() {} + + /** + * set/returns the current recordset page when paginating + */ + function AbsolutePage($page=-1) + { + if ($page != -1) $this->_currentPage = $page; + return $this->_currentPage; + } + + /** + * set/returns the status of the atFirstPage flag when paginating + */ + function AtFirstPage($status=false) + { + if ($status != false) $this->_atFirstPage = $status; + return $this->_atFirstPage; + } + + function LastPageNo($page = false) + { + if ($page != false) $this->_lastPageNo = $page; + return $this->_lastPageNo; + } + + /** + * set/returns the status of the atLastPage flag when paginating + */ + function AtLastPage($status=false) + { + if ($status != false) $this->_atLastPage = $status; + return $this->_atLastPage; + } + +} // end class ADORecordSet + + //============================================================================================== + // CLASS ADORecordSet_array + //============================================================================================== + + /** + * This class encapsulates the concept of a recordset created in memory + * as an array. This is useful for the creation of cached recordsets. + * + * Note that the constructor is different from the standard ADORecordSet + */ + + class ADORecordSet_array extends ADORecordSet + { + var $databaseType = 'array'; + + var $_array; // holds the 2-dimensional data array + var $_types; // the array of types of each column (C B I L M) + var $_colnames; // names of each column in array + var $_skiprow1; // skip 1st row because it holds column names + var $_fieldobjects; // holds array of field objects + var $canSeek = true; + var $affectedrows = false; + var $insertid = false; + var $sql = ''; + var $compat = false; + /** + * Constructor + * + */ + function ADORecordSet_array($fakeid=1) + { + global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH; + + // fetch() on EOF does not delete $this->fields + $this->compat = !empty($ADODB_COMPAT_FETCH); + $this->ADORecordSet($fakeid); // fake queryID + $this->fetchMode = $ADODB_FETCH_MODE; + } + + function _transpose() + { + global $ADODB_INCLUDED_LIB; + + if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); + $hdr = true; + + adodb_transpose($this->_array, $newarr, $hdr); + //adodb_pr($newarr); + + $this->_skiprow1 = false; + $this->_array =& $newarr; + $this->_colnames = $hdr; + + adodb_probetypes($newarr,$this->_types); + + $this->_fieldobjects = array(); + + foreach($hdr as $k => $name) { + $f = new ADOFieldObject(); + $f->name = $name; + $f->type = $this->_types[$k]; + $f->max_length = -1; + $this->_fieldobjects[] = $f; + + } + $this->fields = reset($this->_array); + + $this->_initrs(); + + } + + /** + * Setup the array. + * + * @param array is a 2-dimensional array holding the data. + * The first row should hold the column names + * unless paramter $colnames is used. + * @param typearr holds an array of types. These are the same types + * used in MetaTypes (C,B,L,I,N). + * @param [colnames] array of column names. If set, then the first row of + * $array should not hold the column names. + */ + function InitArray($array,$typearr,$colnames=false) + { + $this->_array = $array; + $this->_types = $typearr; + if ($colnames) { + $this->_skiprow1 = false; + $this->_colnames = $colnames; + } else { + $this->_skiprow1 = true; + $this->_colnames = $array[0]; + } + $this->Init(); + } + /** + * Setup the Array and datatype file objects + * + * @param array is a 2-dimensional array holding the data. + * The first row should hold the column names + * unless paramter $colnames is used. + * @param fieldarr holds an array of ADOFieldObject's. + */ + function InitArrayFields(&$array,&$fieldarr) + { + $this->_array =& $array; + $this->_skiprow1= false; + if ($fieldarr) { + $this->_fieldobjects =& $fieldarr; + } + $this->Init(); + } + + function &GetArray($nRows=-1) + { + if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) { + return $this->_array; + } else { + $arr =& ADORecordSet::GetArray($nRows); + return $arr; + } + } + + function _initrs() + { + $this->_numOfRows = sizeof($this->_array); + if ($this->_skiprow1) $this->_numOfRows -= 1; + + $this->_numOfFields =(isset($this->_fieldobjects)) ? + sizeof($this->_fieldobjects):sizeof($this->_types); + } + + /* Use associative array to get fields array */ + function Fields($colname) + { + $mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode; + + if ($mode & ADODB_FETCH_ASSOC) { + if (!isset($this->fields[$colname])) $colname = strtolower($colname); + return $this->fields[$colname]; + } + if (!$this->bind) { + $this->bind = array(); + for ($i=0; $i < $this->_numOfFields; $i++) { + $o = $this->FetchField($i); + $this->bind[strtoupper($o->name)] = $i; + } + } + return $this->fields[$this->bind[strtoupper($colname)]]; + } + + function &FetchField($fieldOffset = -1) + { + if (isset($this->_fieldobjects)) { + return $this->_fieldobjects[$fieldOffset]; + } + $o = new ADOFieldObject(); + $o->name = $this->_colnames[$fieldOffset]; + $o->type = $this->_types[$fieldOffset]; + $o->max_length = -1; // length not known + + return $o; + } + + function _seek($row) + { + if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) { + $this->_currentRow = $row; + if ($this->_skiprow1) $row += 1; + $this->fields = $this->_array[$row]; + return true; + } + return false; + } + + function MoveNext() + { + if (!$this->EOF) { + $this->_currentRow++; + + $pos = $this->_currentRow; + + if ($this->_numOfRows <= $pos) { + if (!$this->compat) $this->fields = false; + } else { + if ($this->_skiprow1) $pos += 1; + $this->fields = $this->_array[$pos]; + return true; + } + $this->EOF = true; + } + + return false; + } + + function _fetch() + { + $pos = $this->_currentRow; + + if ($this->_numOfRows <= $pos) { + if (!$this->compat) $this->fields = false; + return false; + } + if ($this->_skiprow1) $pos += 1; + $this->fields = $this->_array[$pos]; + return true; + } + + function _close() + { + return true; + } + + } // ADORecordSet_array + + //============================================================================================== + // HELPER FUNCTIONS + //============================================================================================== + + /** + * Synonym for ADOLoadCode. Private function. Do not use. + * + * @deprecated + */ + function ADOLoadDB($dbType) + { + return ADOLoadCode($dbType); + } + + /** + * Load the code for a specific database driver. Private function. Do not use. + */ + function ADOLoadCode($dbType) + { + global $ADODB_LASTDB; + + if (!$dbType) return false; + $db = strtolower($dbType); + switch ($db) { + case 'ado': + if (PHP_VERSION >= 5) $db = 'ado5'; + $class = 'ado'; + break; + case 'ifx': + case 'maxsql': $class = $db = 'mysqlt'; break; + case 'postgres': + case 'postgres8': + case 'pgsql': $class = $db = 'postgres7'; break; + default: + $class = $db; break; + } + + $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php"; + @include_once($file); + $ADODB_LASTDB = $class; + if (class_exists("ADODB_" . $class)) return $class; + + //ADOConnection::outp(adodb_pr(get_declared_classes(),true)); + if (!file_exists($file)) ADOConnection::outp("Missing file: $file"); + else ADOConnection::outp("Syntax error in file: $file"); + return false; + } + + /** + * synonym for ADONewConnection for people like me who cannot remember the correct name + */ + function &NewADOConnection($db='') + { + $tmp =& ADONewConnection($db); + return $tmp; + } + + /** + * Instantiate a new Connection class for a specific database driver. + * + * @param [db] is the database Connection object to create. If undefined, + * use the last database driver that was loaded by ADOLoadCode(). + * + * @return the freshly created instance of the Connection class. + */ + function &ADONewConnection($db='') + { + GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB; + + if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); + $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false; + $false = false; + if ($at = strpos($db,'://')) { + $origdsn = $db; + if (PHP_VERSION < 5) $dsna = @parse_url($db); + else { + $fakedsn = 'fake'.substr($db,$at); + $dsna = @parse_url($fakedsn); + $dsna['scheme'] = substr($db,0,$at); + + if (strncmp($db,'pdo',3) == 0) { + $sch = explode('_',$dsna['scheme']); + if (sizeof($sch)>1) { + $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : ''; + $dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host'])); + $dsna['scheme'] = 'pdo'; + } + } + } + + if (!$dsna) { + // special handling of oracle, which might not have host + $db = str_replace('@/','@adodb-fakehost/',$db); + $dsna = parse_url($db); + if (!$dsna) return $false; + $dsna['host'] = ''; + } + $db = @$dsna['scheme']; + if (!$db) return $false; + $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : ''; + $dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : ''; + $dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : ''; + $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; # strip off initial / + + if (isset($dsna['query'])) { + $opt1 = explode('&',$dsna['query']); + foreach($opt1 as $k => $v) { + $arr = explode('=',$v); + $opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1; + } + } else $opt = array(); + } + /* + * phptype: Database backend used in PHP (mysql, odbc etc.) + * dbsyntax: Database used with regards to SQL syntax etc. + * protocol: Communication protocol to use (tcp, unix etc.) + * hostspec: Host specification (hostname[:port]) + * database: Database to use on the DBMS server + * username: User name for login + * password: Password for login + */ + if (!empty($ADODB_NEWCONNECTION)) { + $obj = $ADODB_NEWCONNECTION($db); + + } else { + + if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = ''; + if (empty($db)) $db = $ADODB_LASTDB; + + if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db); + + if (!$db) { + if (isset($origdsn)) $db = $origdsn; + if ($errorfn) { + // raise an error + $ignore = false; + $errorfn('ADONewConnection', 'ADONewConnection', -998, + "could not load the database driver for '$db'", + $db,false,$ignore); + } else + ADOConnection::outp( "

ADONewConnection: Unable to load database driver '$db'

",false); + + return $false; + } + + $cls = 'ADODB_'.$db; + if (!class_exists($cls)) { + adodb_backtrace(); + return $false; + } + + $obj = new $cls(); + } + + # constructor should not fail + if ($obj) { + if ($errorfn) $obj->raiseErrorFn = $errorfn; + if (isset($dsna)) { + if (isset($dsna['port'])) $obj->port = $dsna['port']; + foreach($opt as $k => $v) { + switch(strtolower($k)) { + case 'new': + $nconnect = true; $persist = true; break; + case 'persist': + case 'persistent': $persist = $v; break; + case 'debug': $obj->debug = (integer) $v; break; + #ibase + case 'role': $obj->role = $v; break; + case 'dialect': $obj->dialect = (integer) $v; break; + case 'charset': $obj->charset = $v; $obj->charSet=$v; break; + case 'buffers': $obj->buffers = $v; break; + case 'fetchmode': $obj->SetFetchMode($v); break; + #ado + case 'charpage': $obj->charPage = $v; break; + #mysql, mysqli + case 'clientflags': $obj->clientFlags = $v; break; + #mysql, mysqli, postgres + case 'port': $obj->port = $v; break; + #mysqli + case 'socket': $obj->socket = $v; break; + #oci8 + case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break; + } + } + if (empty($persist)) + $ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); + else if (empty($nconnect)) + $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); + else + $ok = $obj->NConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); + + if (!$ok) return $false; + } + } + return $obj; + } + + + + // $perf == true means called by NewPerfMonitor(), otherwise for data dictionary + function _adodb_getdriver($provider,$drivername,$perf=false) + { + switch ($provider) { + case 'odbtp': if (strncmp('odbtp_',$drivername,6)==0) return substr($drivername,6); + case 'odbc' : if (strncmp('odbc_',$drivername,5)==0) return substr($drivername,5); + case 'ado' : if (strncmp('ado_',$drivername,4)==0) return substr($drivername,4); + case 'native': break; + default: + return $provider; + } + + switch($drivername) { + case 'mysqlt': + case 'mysqli': + $drivername='mysql'; + break; + case 'postgres7': + case 'postgres8': + $drivername = 'postgres'; + break; + case 'firebird15': $drivername = 'firebird'; break; + case 'oracle': $drivername = 'oci8'; break; + case 'access': if ($perf) $drivername = ''; break; + case 'db2' : break; + case 'sapdb' : break; + default: + $drivername = 'generic'; + break; + } + return $drivername; + } + + function &NewPerfMonitor(&$conn) + { + $false = false; + $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true); + if (!$drivername || $drivername == 'generic') return $false; + include_once(ADODB_DIR.'/adodb-perf.inc.php'); + @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php"); + $class = "Perf_$drivername"; + if (!class_exists($class)) return $false; + $perf = new $class($conn); + + return $perf; + } + + function &NewDataDictionary(&$conn,$drivername=false) + { + $false = false; + if (!$drivername) $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType); + + include_once(ADODB_DIR.'/adodb-lib.inc.php'); + include_once(ADODB_DIR.'/adodb-datadict.inc.php'); + $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php"; + + if (!file_exists($path)) { + ADOConnection::outp("Dictionary driver '$path' not available"); + return $false; + } + include_once($path); + $class = "ADODB2_$drivername"; + $dict = new $class(); + $dict->dataProvider = $conn->dataProvider; + $dict->connection = &$conn; + $dict->upperName = strtoupper($drivername); + $dict->quote = $conn->nameQuote; + if (!empty($conn->_connectionID)) + $dict->serverInfo = $conn->ServerInfo(); + + return $dict; + } + + + + /* + Perform a print_r, with pre tags for better formatting. + */ + function adodb_pr($var,$as_string=false) + { + if ($as_string) ob_start(); + + if (isset($_SERVER['HTTP_USER_AGENT'])) { + echo "
\n";print_r($var);echo "
\n"; + } else + print_r($var); + + if ($as_string) { + $s = ob_get_contents(); + ob_end_clean(); + return $s; + } + } + + /* + Perform a stack-crawl and pretty print it. + + @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then). + @param levels Number of levels to display + */ + function adodb_backtrace($printOrArr=true,$levels=9999) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_backtrace($printOrArr,$levels); + } + + +} +?> diff --git a/lib/adodb/drivers/adodb-mysql.inc.php b/lib/adodb/drivers/adodb-mysql.inc.php new file mode 100644 index 00000000..8e79d4a7 --- /dev/null +++ b/lib/adodb/drivers/adodb-mysql.inc.php @@ -0,0 +1,782 @@ +rsPrefix .= 'ext_'; + } + + function ServerInfo() + { + $arr['description'] = ADOConnection::GetOne("select version()"); + $arr['version'] = ADOConnection::_findvers($arr['description']); + return $arr; + } + + function IfNull( $field, $ifNull ) + { + return " IFNULL($field, $ifNull) "; // if MySQL + } + + + function &MetaTables($ttype=false,$showSchema=false,$mask=false) + { + $save = $this->metaTablesSQL; + if ($showSchema && is_string($showSchema)) { + $this->metaTablesSQL .= " from $showSchema"; + } + + if ($mask) { + $mask = $this->qstr($mask); + $this->metaTablesSQL .= " like $mask"; + } + $ret =& ADOConnection::MetaTables($ttype,$showSchema); + + $this->metaTablesSQL = $save; + return $ret; + } + + + function &MetaIndexes ($table, $primary = FALSE, $owner=false) + { + // save old fetch mode + global $ADODB_FETCH_MODE; + + $false = false; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } + + // get index details + $rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table)); + + // restore fetchmode + if (isset($savem)) { + $this->SetFetchMode($savem); + } + $ADODB_FETCH_MODE = $save; + + if (!is_object($rs)) { + return $false; + } + + $indexes = array (); + + // parse index data into array + while ($row = $rs->FetchRow()) { + if ($primary == FALSE AND $row[2] == 'PRIMARY') { + continue; + } + + if (!isset($indexes[$row[2]])) { + $indexes[$row[2]] = array( + 'unique' => ($row[1] == 0), + 'columns' => array() + ); + } + + $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4]; + } + + // sort columns by order in the index + foreach ( array_keys ($indexes) as $index ) + { + ksort ($indexes[$index]['columns']); + } + + return $indexes; + } + + + // if magic quotes disabled, use mysql_real_escape_string() + function qstr($s,$magic_quotes=false) + { + if (!$magic_quotes) { + + if (ADODB_PHPVER >= 0x4300) { + if (is_resource($this->_connectionID)) + return "'".mysql_real_escape_string($s,$this->_connectionID)."'"; + } + if ($this->replaceQuote[0] == '\\'){ + $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); + } + return "'".str_replace("'",$this->replaceQuote,$s)."'"; + } + + // undo magic quotes for " + $s = str_replace('\\"','"',$s); + return "'$s'"; + } + + function _insertid() + { + return ADOConnection::GetOne('SELECT LAST_INSERT_ID()'); + //return mysql_insert_id($this->_connectionID); + } + + function GetOne($sql,$inputarr=false) + { + if ($this->compat323 == false && strncasecmp($sql,'sele',4) == 0) { + $rs =& $this->SelectLimit($sql,1,-1,$inputarr); + if ($rs) { + $rs->Close(); + if ($rs->EOF) return false; + return reset($rs->fields); + } + } else { + return ADOConnection::GetOne($sql,$inputarr); + } + return false; + } + + function BeginTrans() + { + if ($this->debug) ADOConnection::outp("Transactions not supported in 'mysql' driver. Use 'mysqlt' or 'mysqli' driver"); + } + + function _affectedrows() + { + return mysql_affected_rows($this->_connectionID); + } + + // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html + // Reference on Last_Insert_ID on the recommended way to simulate sequences + var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);"; + var $_genSeqSQL = "create table %s (id int not null)"; + var $_genSeq2SQL = "insert into %s values (%s)"; + var $_dropSeqSQL = "drop table %s"; + + function CreateSequence($seqname='adodbseq',$startID=1) + { + if (empty($this->_genSeqSQL)) return false; + $u = strtoupper($seqname); + + $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); + if (!$ok) return false; + return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); + } + + + function GenID($seqname='adodbseq',$startID=1) + { + // post-nuke sets hasGenID to false + if (!$this->hasGenID) return false; + + $savelog = $this->_logsql; + $this->_logsql = false; + $getnext = sprintf($this->_genIDSQL,$seqname); + $holdtransOK = $this->_transOK; // save the current status + $rs = @$this->Execute($getnext); + if (!$rs) { + if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset + $u = strtoupper($seqname); + $this->Execute(sprintf($this->_genSeqSQL,$seqname)); + $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); + $rs = $this->Execute($getnext); + } + $this->genID = mysql_insert_id($this->_connectionID); + + if ($rs) $rs->Close(); + + $this->_logsql = $savelog; + return $this->genID; + } + + function &MetaDatabases() + { + $qid = mysql_list_dbs($this->_connectionID); + $arr = array(); + $i = 0; + $max = mysql_num_rows($qid); + while ($i < $max) { + $db = mysql_tablename($qid,$i); + if ($db != 'mysql') $arr[] = $db; + $i += 1; + } + return $arr; + } + + + // Format date column in sql string given an input format that understands Y M D + function SQLDate($fmt, $col=false) + { + if (!$col) $col = $this->sysTimeStamp; + $s = 'DATE_FORMAT('.$col.",'"; + $concat = false; + $len = strlen($fmt); + for ($i=0; $i < $len; $i++) { + $ch = $fmt[$i]; + switch($ch) { + + default: + if ($ch == '\\') { + $i++; + $ch = substr($fmt,$i,1); + } + /** FALL THROUGH */ + case '-': + case '/': + $s .= $ch; + break; + + case 'Y': + case 'y': + $s .= '%Y'; + break; + case 'M': + $s .= '%b'; + break; + + case 'm': + $s .= '%m'; + break; + case 'D': + case 'd': + $s .= '%d'; + break; + + case 'Q': + case 'q': + $s .= "'),Quarter($col)"; + + if ($len > $i+1) $s .= ",DATE_FORMAT($col,'"; + else $s .= ",('"; + $concat = true; + break; + + case 'H': + $s .= '%H'; + break; + + case 'h': + $s .= '%I'; + break; + + case 'i': + $s .= '%i'; + break; + + case 's': + $s .= '%s'; + break; + + case 'a': + case 'A': + $s .= '%p'; + break; + + case 'w': + $s .= '%w'; + break; + + case 'W': + $s .= '%U'; + break; + + case 'l': + $s .= '%W'; + break; + } + } + $s.="')"; + if ($concat) $s = "CONCAT($s)"; + return $s; + } + + + // returns concatenated string + // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator + function Concat() + { + $s = ""; + $arr = func_get_args(); + + // suggestion by andrew005@mnogo.ru + $s = implode(',',$arr); + if (strlen($s) > 0) return "CONCAT($s)"; + else return ''; + } + + function OffsetDate($dayFraction,$date=false) + { + if (!$date) $date = $this->sysDate; + + $fraction = $dayFraction * 24 * 3600; + return $date . ' + INTERVAL ' . $fraction.' SECOND'; + +// return "from_unixtime(unix_timestamp($date)+$fraction)"; + } + + // returns true or false + function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + if (!empty($this->port)) $argHostname .= ":".$this->port; + + if (ADODB_PHPVER >= 0x4300) + $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword, + $this->forceNewConnect,$this->clientFlags); + else if (ADODB_PHPVER >= 0x4200) + $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword, + $this->forceNewConnect); + else + $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword); + + if ($this->_connectionID === false) return false; + if ($argDatabasename) return $this->SelectDB($argDatabasename); + return true; + } + + // returns true or false + function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + if (!empty($this->port)) $argHostname .= ":".$this->port; + + if (ADODB_PHPVER >= 0x4300) + $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags); + else + $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword); + if ($this->_connectionID === false) return false; + if ($this->autoRollback) $this->RollbackTrans(); + if ($argDatabasename) return $this->SelectDB($argDatabasename); + return true; + } + + function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + $this->forceNewConnect = true; + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); + } + + function &MetaColumns($table) + { + $this->_findschema($table,$schema); + if ($schema) { + $dbName = $this->database; + $this->SelectDB($schema); + } + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); + + if ($schema) { + $this->SelectDB($dbName); + } + + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if (!is_object($rs)) { + $false = false; + return $false; + } + + $retarr = array(); + while (!$rs->EOF){ + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $type = $rs->fields[1]; + + // split type into type(length): + $fld->scale = null; + if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1; + } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + } elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) { + $fld->type = $query_array[1]; + $arr = explode(",",$query_array[2]); + $fld->enums = $arr; + $zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6 + $fld->max_length = ($zlen > 0) ? $zlen : 1; + } else { + $fld->type = $type; + $fld->max_length = -1; + } + $fld->not_null = ($rs->fields[2] != 'YES'); + $fld->primary_key = ($rs->fields[3] == 'PRI'); + $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false); + $fld->binary = (strpos($type,'blob') !== false); + $fld->unsigned = (strpos($type,'unsigned') !== false); + + if (!$fld->binary) { + $d = $rs->fields[4]; + if ($d != '' && $d != 'NULL') { + $fld->has_default = true; + $fld->default_value = $d; + } else { + $fld->has_default = false; + } + } + + if ($save == ADODB_FETCH_NUM) { + $retarr[] = $fld; + } else { + $retarr[strtoupper($fld->name)] = $fld; + } + $rs->MoveNext(); + } + + $rs->Close(); + return $retarr; + } + + // returns true or false + function SelectDB($dbName) + { + $this->database = $dbName; + $this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions + if ($this->_connectionID) { + return @mysql_select_db($dbName,$this->_connectionID); + } + else return false; + } + + // parameters use PostgreSQL convention, not MySQL + function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0) + { + $offsetStr =($offset>=0) ? ((integer)$offset)."," : ''; + // jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220 + if ($nrows < 0) $nrows = '18446744073709551615'; + + if ($secs) + $rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr".((integer)$nrows),$inputarr); + else + $rs =& $this->Execute($sql." LIMIT $offsetStr".((integer)$nrows),$inputarr); + return $rs; + } + + // returns queryID or false + function _query($sql,$inputarr) + { + //global $ADODB_COUNTRECS; + //if($ADODB_COUNTRECS) + return mysql_query($sql,$this->_connectionID); + //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6 + } + + /* Returns: the last error message from previous database operation */ + function ErrorMsg() + { + + if ($this->_logsql) return $this->_errorMsg; + if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error(); + else $this->_errorMsg = @mysql_error($this->_connectionID); + return $this->_errorMsg; + } + + /* Returns: the last error number from previous database operation */ + function ErrorNo() + { + if ($this->_logsql) return $this->_errorCode; + if (empty($this->_connectionID)) return @mysql_errno(); + else return @mysql_errno($this->_connectionID); + } + + // returns true or false + function _close() + { + @mysql_close($this->_connectionID); + $this->_connectionID = false; + } + + + /* + * Maximum size of C field + */ + function CharMax() + { + return 255; + } + + /* + * Maximum size of X field + */ + function TextMax() + { + return 4294967295; + } + + // "Innox - Juan Carlos Gonzalez" + function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $associative = FALSE ) + { + global $ADODB_FETCH_MODE; + if ($ADODB_FETCH_MODE == ADODB_FETCH_ASSOC || $this->fetchMode == ADODB_FETCH_ASSOC) $associative = true; + + if ( !empty($owner) ) { + $table = "$owner.$table"; + } + $a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table)); + if ($associative) $create_sql = $a_create_table["Create Table"]; + else $create_sql = $a_create_table[1]; + + $matches = array(); + + if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false; + $foreign_keys = array(); + $num_keys = count($matches[0]); + for ( $i = 0; $i < $num_keys; $i ++ ) { + $my_field = explode('`, `', $matches[1][$i]); + $ref_table = $matches[2][$i]; + $ref_field = explode('`, `', $matches[3][$i]); + + if ( $upper ) { + $ref_table = strtoupper($ref_table); + } + + $foreign_keys[$ref_table] = array(); + $num_fields = count($my_field); + for ( $j = 0; $j < $num_fields; $j ++ ) { + if ( $associative ) { + $foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j]; + } else { + $foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}"; + } + } + } + + return $foreign_keys; + } + + +} + +/*-------------------------------------------------------------------------------------- + Class Name: Recordset +--------------------------------------------------------------------------------------*/ + + +class ADORecordSet_mysql extends ADORecordSet{ + + var $databaseType = "mysql"; + var $canSeek = true; + + function ADORecordSet_mysql($queryID,$mode=false) + { + if ($mode === false) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } + switch ($mode) + { + case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; + case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + default: + $this->fetchMode = MYSQL_BOTH; break; + } + $this->adodbFetchMode = $mode; + $this->ADORecordSet($queryID); + } + + function _initrs() + { + //GLOBAL $ADODB_COUNTRECS; + // $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1; + $this->_numOfRows = @mysql_num_rows($this->_queryID); + $this->_numOfFields = @mysql_num_fields($this->_queryID); + } + + function &FetchField($fieldOffset = -1) + { + if ($fieldOffset != -1) { + $o = @mysql_fetch_field($this->_queryID, $fieldOffset); + $f = @mysql_field_flags($this->_queryID,$fieldOffset); + $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com) + //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable + $o->binary = (strpos($f,'binary')!== false); + } + else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ + $o = @mysql_fetch_field($this->_queryID); + $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com) + //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable + } + + return $o; + } + + function &GetRowAssoc($upper=true) + { + if ($this->fetchMode == MYSQL_ASSOC && !$upper) $row = $this->fields; + else $row =& ADORecordSet::GetRowAssoc($upper); + return $row; + } + + /* Use associative array to get fields array */ + function Fields($colname) + { + // added @ by "Michael William Miller" + if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname]; + + if (!$this->bind) { + $this->bind = array(); + for ($i=0; $i < $this->_numOfFields; $i++) { + $o = $this->FetchField($i); + $this->bind[strtoupper($o->name)] = $i; + } + } + return $this->fields[$this->bind[strtoupper($colname)]]; + } + + function _seek($row) + { + if ($this->_numOfRows == 0) return false; + return @mysql_data_seek($this->_queryID,$row); + } + + function MoveNext() + { + //return adodb_movenext($this); + //if (defined('ADODB_EXTENSION')) return adodb_movenext($this); + if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) { + $this->_currentRow += 1; + return true; + } + if (!$this->EOF) { + $this->_currentRow += 1; + $this->EOF = true; + } + return false; + } + + function _fetch() + { + $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode); + return is_array($this->fields); + } + + function _close() { + @mysql_free_result($this->_queryID); + $this->_queryID = false; + } + + function MetaType($t,$len=-1,$fieldobj=false) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } + + $len = -1; // mysql max_length is not accurate + switch (strtoupper($t)) { + case 'STRING': + case 'CHAR': + case 'VARCHAR': + case 'TINYBLOB': + case 'TINYTEXT': + case 'ENUM': + case 'SET': + if ($len <= $this->blobSize) return 'C'; + + case 'TEXT': + case 'LONGTEXT': + case 'MEDIUMTEXT': + return 'X'; + + // php_mysql extension always returns 'blob' even if 'text' + // so we have to check whether binary... + case 'IMAGE': + case 'LONGBLOB': + case 'BLOB': + case 'MEDIUMBLOB': + return !empty($fieldobj->binary) ? 'B' : 'X'; + + case 'YEAR': + case 'DATE': return 'D'; + + case 'TIME': + case 'DATETIME': + case 'TIMESTAMP': return 'T'; + + case 'INT': + case 'INTEGER': + case 'BIGINT': + case 'TINYINT': + case 'MEDIUMINT': + case 'SMALLINT': + + if (!empty($fieldobj->primary_key)) return 'R'; + else return 'I'; + + default: return 'N'; + } + } + +} + +class ADORecordSet_ext_mysql extends ADORecordSet_mysql { + function ADORecordSet_ext_mysql($queryID,$mode=false) + { + if ($mode === false) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } + switch ($mode) + { + case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; + case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + default: + $this->fetchMode = MYSQL_BOTH; break; + } + $this->adodbFetchMode = $mode; + $this->ADORecordSet($queryID); + } + + function MoveNext() + { + return @adodb_movenext($this); + } +} + + +} +?> \ No newline at end of file diff --git a/lib/adodb/drivers/adodb-sqlite.inc.php b/lib/adodb/drivers/adodb-sqlite.inc.php new file mode 100644 index 00000000..665cc543 --- /dev/null +++ b/lib/adodb/drivers/adodb-sqlite.inc.php @@ -0,0 +1,398 @@ +fmtDate)."'"; + case 'sysTimeStamp' : return "'".date($this->sysTimeStamp)."'"; + } + }*/ + + function ServerInfo() + { + $arr['version'] = sqlite_libversion(); + $arr['description'] = 'SQLite '; + $arr['encoding'] = sqlite_libencoding(); + return $arr; + } + + function BeginTrans() + { + if ($this->transOff) return true; + $ret = $this->Execute("BEGIN TRANSACTION"); + $this->transCnt += 1; + return true; + } + + function CommitTrans($ok=true) + { + if ($this->transOff) return true; + if (!$ok) return $this->RollbackTrans(); + $ret = $this->Execute("COMMIT"); + if ($this->transCnt>0)$this->transCnt -= 1; + return !empty($ret); + } + + function RollbackTrans() + { + if ($this->transOff) return true; + $ret = $this->Execute("ROLLBACK"); + if ($this->transCnt>0)$this->transCnt -= 1; + return !empty($ret); + } + + // mark newnham + function &MetaColumns($tab) + { + global $ADODB_FETCH_MODE; + $false = false; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + $rs = $this->Execute("PRAGMA table_info('$tab')"); + if (isset($savem)) $this->SetFetchMode($savem); + if (!$rs) { + $ADODB_FETCH_MODE = $save; + return $false; + } + $arr = array(); + while ($r = $rs->FetchRow()) { + $type = explode('(',$r['type']); + $size = ''; + if (sizeof($type)==2) + $size = trim($type[1],')'); + $fn = strtoupper($r['name']); + $fld = new ADOFieldObject; + $fld->name = $r['name']; + $fld->type = $type[0]; + $fld->max_length = $size; + $fld->not_null = $r['notnull']; + $fld->default_value = $r['dflt_value']; + $fld->scale = 0; + if ($save == ADODB_FETCH_NUM) $arr[] = $fld; + else $arr[strtoupper($fld->name)] = $fld; + } + $rs->Close(); + $ADODB_FETCH_MODE = $save; + return $arr; + } + + function _init($parentDriver) + { + + $parentDriver->hasTransactions = false; + $parentDriver->hasInsertID = true; + } + + function _insertid() + { + return sqlite_last_insert_rowid($this->_connectionID); + } + + function _affectedrows() + { + return sqlite_changes($this->_connectionID); + } + + function ErrorMsg() + { + if ($this->_logsql) return $this->_errorMsg; + return ($this->_errorNo) ? sqlite_error_string($this->_errorNo) : ''; + } + + function ErrorNo() + { + return $this->_errorNo; + } + + function SQLDate($fmt, $col=false) + { + $fmt = $this->qstr($fmt); + return ($col) ? "adodb_date2($fmt,$col)" : "adodb_date($fmt)"; + } + + + function _createFunctions() + { + @sqlite_create_function($this->_connectionID, 'adodb_date', 'adodb_date', 1); + @sqlite_create_function($this->_connectionID, 'adodb_date2', 'adodb_date2', 2); + } + + + // returns true or false + function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + if (!function_exists('sqlite_open')) return null; + if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename; + + $this->_connectionID = sqlite_open($argHostname); + if ($this->_connectionID === false) return false; + $this->_createFunctions(); + return true; + } + + // returns true or false + function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + if (!function_exists('sqlite_open')) return null; + if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename; + + $this->_connectionID = sqlite_popen($argHostname); + if ($this->_connectionID === false) return false; + $this->_createFunctions(); + return true; + } + + // returns query ID if successful, otherwise false + function _query($sql,$inputarr=false) + { + $rez = sqlite_query($sql,$this->_connectionID); + if (!$rez) { + $this->_errorNo = sqlite_last_error($this->_connectionID); + } + + return $rez; + } + + function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) + { + $offsetStr = ($offset >= 0) ? " OFFSET $offset" : ''; + $limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : ''); + if ($secs2cache) + $rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr); + else + $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr); + + return $rs; + } + + /* + This algorithm is not very efficient, but works even if table locking + is not available. + + Will return false if unable to generate an ID after $MAXLOOPS attempts. + */ + var $_genSeqSQL = "create table %s (id integer)"; + + function GenID($seq='adodbseq',$start=1) + { + // if you have to modify the parameter below, your database is overloaded, + // or you need to implement generation of id's yourself! + $MAXLOOPS = 100; + //$this->debug=1; + while (--$MAXLOOPS>=0) { + @($num = $this->GetOne("select id from $seq")); + if ($num === false) { + $this->Execute(sprintf($this->_genSeqSQL ,$seq)); + $start -= 1; + $num = '0'; + $ok = $this->Execute("insert into $seq values($start)"); + if (!$ok) return false; + } + $this->Execute("update $seq set id=id+1 where id=$num"); + + if ($this->affected_rows() > 0) { + $num += 1; + $this->genID = $num; + return $num; + } + } + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num); + } + return false; + } + + function CreateSequence($seqname='adodbseq',$start=1) + { + if (empty($this->_genSeqSQL)) return false; + $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); + if (!$ok) return false; + $start -= 1; + return $this->Execute("insert into $seqname values($start)"); + } + + var $_dropSeqSQL = 'drop table %s'; + function DropSequence($seqname) + { + if (empty($this->_dropSeqSQL)) return false; + return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); + } + + // returns true or false + function _close() + { + return @sqlite_close($this->_connectionID); + } + + function &MetaIndexes($table, $primary = FALSE, $owner=false) + { + $false = false; + // save old fetch mode + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } + $SQL=sprintf("SELECT name,sql FROM sqlite_master WHERE type='index' AND tbl_name='%s'", strtolower($table)); + $rs = $this->Execute($SQL); + if (!is_object($rs)) { + if (isset($savem)) + $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + return $false; + } + + $indexes = array (); + while ($row = $rs->FetchRow()) { + if ($primary && preg_match("/primary/i",$row[1]) == 0) continue; + if (!isset($indexes[$row[0]])) { + + $indexes[$row[0]] = array( + 'unique' => preg_match("/unique/i",$row[1]), + 'columns' => array()); + } + /** + * There must be a more elegant way of doing this, + * the index elements appear in the SQL statement + * in cols[1] between parentheses + * e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse) + */ + $cols = explode("(",$row[1]); + $cols = explode(")",$cols[1]); + array_pop($cols); + $indexes[$row[0]]['columns'] = $cols; + } + if (isset($savem)) { + $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + } + return $indexes; + } + +} + +/*-------------------------------------------------------------------------------------- + Class Name: Recordset +--------------------------------------------------------------------------------------*/ + +class ADORecordset_sqlite extends ADORecordSet { + + var $databaseType = "sqlite"; + var $bind = false; + + function ADORecordset_sqlite($queryID,$mode=false) + { + + if ($mode === false) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } + switch($mode) { + case ADODB_FETCH_NUM: $this->fetchMode = SQLITE_NUM; break; + case ADODB_FETCH_ASSOC: $this->fetchMode = SQLITE_ASSOC; break; + default: $this->fetchMode = SQLITE_BOTH; break; + } + $this->adodbFetchMode = $mode; + + $this->_queryID = $queryID; + + $this->_inited = true; + $this->fields = array(); + if ($queryID) { + $this->_currentRow = 0; + $this->EOF = !$this->_fetch(); + @$this->_initrs(); + } else { + $this->_numOfRows = 0; + $this->_numOfFields = 0; + $this->EOF = true; + } + + return $this->_queryID; + } + + + function &FetchField($fieldOffset = -1) + { + $fld = new ADOFieldObject; + $fld->name = sqlite_field_name($this->_queryID, $fieldOffset); + $fld->type = 'VARCHAR'; + $fld->max_length = -1; + return $fld; + } + + function _initrs() + { + $this->_numOfRows = @sqlite_num_rows($this->_queryID); + $this->_numOfFields = @sqlite_num_fields($this->_queryID); + } + + function Fields($colname) + { + if ($this->fetchMode != SQLITE_NUM) return $this->fields[$colname]; + if (!$this->bind) { + $this->bind = array(); + for ($i=0; $i < $this->_numOfFields; $i++) { + $o = $this->FetchField($i); + $this->bind[strtoupper($o->name)] = $i; + } + } + + return $this->fields[$this->bind[strtoupper($colname)]]; + } + + function _seek($row) + { + return sqlite_seek($this->_queryID, $row); + } + + function _fetch($ignore_fields=false) + { + $this->fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode); + return !empty($this->fields); + } + + function _close() + { + } + +} +?> \ No newline at end of file diff --git a/lib/adodb/license.txt b/lib/adodb/license.txt new file mode 100644 index 00000000..2353871c --- /dev/null +++ b/lib/adodb/license.txt @@ -0,0 +1,182 @@ +ADOdb is dual licensed using BSD and LGPL. + +In plain English, you do not need to distribute your application in source code form, nor do you need to distribute ADOdb source code, provided you follow the rest of terms of the BSD license. + +For more info about ADOdb, visit http://adodb.sourceforge.net/ + +BSD Style-License +================= + +Copyright (c) 2000, 2001, 2002, 2003, 2004 John Lim +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list +of conditions and the following disclaimer in the documentation and/or other materials +provided with the distribution. + +Neither the name of the John Lim nor the names of its contributors may be used to +endorse or promote products derived from this software without specific prior written +permission. + +DISCLAIMER: +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +JOHN LIM OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +========================================================== +GNU LESSER GENERAL PUBLIC LICENSE +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + +Preamble +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + +a) The modified work must itself be a software library. +b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. +c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. +d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + +a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) +b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. +c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. +d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. +e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + +a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. +b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/lib/akismet.class.php b/lib/akismet.class.php new file mode 100644 index 00000000..5c676f83 --- /dev/null +++ b/lib/akismet.class.php @@ -0,0 +1,356 @@ +Usage + * + * $comment = array( + * 'author' => 'viagra-test-123', + * 'email' => 'test@example.com', + * 'website' => 'http://www.example.com/', + * 'body' => 'This is a test comment', + * 'permalink' => 'http://yourdomain.com/yourblogpost.url', + * ); + * + * $akismet = new Akismet('http://www.yourdomain.com/', 'YOUR_WORDPRESS_API_KEY', $comment); + * + * if($akismet->isError()) { + * echo"Couldn't connected to Akismet server!"; + * } else { + * if($akismet->isSpam()) { + * echo"Spam detected"; + * } else { + * echo"yay, no spam!"; + * } + * } + * + * + * @author Bret Kuhns {@link www.miphp.net} + * @link http://www.miphp.net/blog/view/php4_akismet_class/ + * @version 0.3.3 + * @license http://www.opensource.org/licenses/mit-license.php MIT License + */ + + + +// Error constants +define("AKISMET_SERVER_NOT_FOUND", 0); +define("AKISMET_RESPONSE_FAILED", 1); +define("AKISMET_INVALID_KEY", 2); + + + +// Base class to assist in error handling between Akismet classes +class AkismetObject { + var $errors = array(); + + + /** + * Add a new error to the errors array in the object + * + * @param String $name A name (array key) for the error + * @param String $string The error message + * @return void + */ + // Set an error in the object + function setError($name, $message) { + $this->errors[$name] = $message; + } + + + /** + * Return a specific error message from the errors array + * + * @param String $name The name of the error you want + * @return mixed Returns a String if the error exists, a false boolean if it does not exist + */ + function getError($name) { + if($this->isError($name)) { + return $this->errors[$name]; + } else { + return false; + } + } + + + /** + * Return all errors in the object + * + * @return String[] + */ + function getErrors() { + return (array)$this->errors; + } + + + /** + * Check if a certain error exists + * + * @param String $name The name of the error you want + * @return boolean + */ + function isError($name) { + return isset($this->errors[$name]); + } + + + /** + * Check if any errors exist + * + * @return boolean + */ + function errorsExist() { + return (count($this->errors) > 0); + } + + +} + + + + + +// Used by the Akismet class to communicate with the Akismet service +class AkismetHttpClient extends AkismetObject { + var $akismetVersion = '1.1'; + var $con; + var $host; + var $port; + var $apiKey; + var $blogUrl; + var $errors = array(); + + + // Constructor + function AkismetHttpClient($host, $blogUrl, $apiKey, $port = 80) { + $this->host = $host; + $this->port = $port; + $this->blogUrl = $blogUrl; + $this->apiKey = $apiKey; + } + + + // Use the connection active in $con to get a response from the server and return that response + function getResponse($request, $path, $type = "post", $responseLength = 1160) { + $this->_connect(); + + if($this->con && !$this->isError(AKISMET_SERVER_NOT_FOUND)) { + $request = + strToUpper($type)." /{$this->akismetVersion}/$path HTTP/1.1\r\n" . + "Host: ".((!empty($this->apiKey)) ? $this->apiKey."." : null)."{$this->host}\r\n" . + "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n" . + "Content-Length: ".strlen($request)."\r\n" . + "User-Agent: Akismet PHP4 Class\r\n" . + "\r\n" . + $request + ; + $response = ""; + + @fwrite($this->con, $request); + + while(!feof($this->con)) { + $response .= @fgets($this->con, $responseLength); + } + + $response = explode("\r\n\r\n", $response, 2); + return $response[1]; + } else { + $this->setError(AKISMET_RESPONSE_FAILED, "The response could not be retrieved."); + } + + $this->_disconnect(); + } + + + // Connect to the Akismet server and store that connection in the instance variable $con + function _connect() { + if(!($this->con = @fsockopen($this->host, $this->port))) { + $this->setError(AKISMET_SERVER_NOT_FOUND, "Could not connect to akismet server."); + } + } + + + // Close the connection to the Akismet server + function _disconnect() { + @fclose($this->con); + } + + +} + + + + + +// The controlling class. This is the ONLY class the user should instantiate in +// order to use the Akismet service! +class Akismet extends AkismetObject { + var $apiPort = 80; + var $akismetServer = 'rest.akismet.com'; + var $akismetVersion = '1.1'; + var $http; + + var $ignore = array( + 'HTTP_COOKIE', + 'HTTP_X_FORWARDED_FOR', + 'HTTP_X_FORWARDED_HOST', + 'HTTP_MAX_FORWARDS', + 'HTTP_X_FORWARDED_SERVER', + 'REDIRECT_STATUS', + 'SERVER_PORT', + 'PATH', + 'DOCUMENT_ROOT', + 'SERVER_ADMIN', + 'QUERY_STRING', + 'PHP_SELF' + ); + + var $blogUrl = ""; + var $apiKey = ""; + var $comment = array(); + + + /** + * Constructor + * + * Set instance variables, connect to Akismet, and check API key + * + * @param String $blogUrl The URL to your own blog + * @param String $apiKey Your wordpress API key + * @param String[] $comment A formatted comment array to be examined by the Akismet service + */ + function Akismet($blogUrl, $apiKey, $comment) { + $this->blogUrl = $blogUrl; + $this->apiKey = $apiKey; + + // Populate the comment array with information needed by Akismet + $this->comment = $comment; + $this->_formatCommentArray(); + + if(!isset($this->comment['user_ip'])) { + $this->comment['user_ip'] = ($_SERVER['REMOTE_ADDR'] != getenv('SERVER_ADDR')) ? $_SERVER['REMOTE_ADDR'] : getenv('HTTP_X_FORWARDED_FOR'); + } + if(!isset($this->comment['user_agent'])) { + $this->comment['user_agent'] = $_SERVER['HTTP_USER_AGENT']; + } + if(!isset($this->comment['referrer'])) { + $this->comment['referrer'] = $_SERVER['HTTP_REFERER']; + } + $this->comment['blog'] = $blogUrl; + + // Connect to the Akismet server and populate errors if they exist + $this->http = new AkismetHttpClient($this->akismetServer, $blogUrl, $apiKey); + if($this->http->errorsExist()) { + $this->errors = array_merge($this->errors, $this->http->getErrors()); + } + + // Check if the API key is valid + if(!$this->_isValidApiKey($apiKey)) { + $this->setError(AKISMET_INVALID_KEY, "Your Akismet API key is not valid."); + } + } + + + /** + * Query the Akismet and determine if the comment is spam or not + * + * @return boolean + */ + function isSpam() { + $response = $this->http->getResponse($this->_getQueryString(), 'comment-check'); + + return ($response == "true"); + } + + + /** + * Submit this comment as an unchecked spam to the Akismet server + * + * @return void + */ + function submitSpam() { + $this->http->getResponse($this->_getQueryString(), 'submit-spam'); + } + + + /** + * Submit a false-positive comment as "ham" to the Akismet server + * + * @return void + */ + function submitHam() { + $this->http->getResponse($this->_getQueryString(), 'submit-ham'); + } + + + /** + * Check with the Akismet server to determine if the API key is valid + * + * @access Protected + * @param String $key The Wordpress API key passed from the constructor argument + * @return boolean + */ + function _isValidApiKey($key) { + $keyCheck = $this->http->getResponse("key=".$this->apiKey."&blog=".$this->blogUrl, 'verify-key'); + + return ($keyCheck == "valid"); + } + + + /** + * Format the comment array in accordance to the Akismet API + * + * @access Protected + * @return void + */ + function _formatCommentArray() { + $format = array( + 'type' => 'comment_type', + 'author' => 'comment_author', + 'email' => 'comment_author_email', + 'website' => 'comment_author_url', + 'body' => 'comment_content' + ); + + foreach($format as $short => $long) { + if(isset($this->comment[$short])) { + $this->comment[$long] = $this->comment[$short]; + unset($this->comment[$short]); + } + } + } + + + /** + * Build a query string for use with HTTP requests + * + * @access Protected + * @return String + */ + function _getQueryString() { + foreach($_SERVER as $key => $value) { + if(!in_array($key, $this->ignore)) { + if($key == 'REMOTE_ADDR') { + $this->comment[$key] = $this->comment['user_ip']; + } else { + $this->comment[$key] = $value; + } + } + } + + $query_string = ''; + + foreach($this->comment as $key => $data) { + if(is_string($data)) { + $query_string .= $key . '=' . urlencode(stripslashes($data)) . '&'; + } + } + + return $query_string; + } + + +} +?> diff --git a/scripts/libshish.js b/scripts/libshish.js new file mode 100644 index 00000000..80cdcc58 --- /dev/null +++ b/scripts/libshish.js @@ -0,0 +1,67 @@ +function addEvent(obj, event, func, capture){ + if (obj.addEventListener){ + obj.addEventListener(event, func, capture); + } else if (obj.attachEvent){ + obj.attachEvent("on"+event, func); + } +} + + +function byId(id) { + return document.getElementById(id); +} + + +function getHTTPObject() { + if (window.XMLHttpRequest){ + return new XMLHttpRequest(); + } + else if(window.ActiveXObject){ + return new ActiveXObject("Microsoft.XMLHTTP"); + } +} + +function ajaxRequest(url, callback) { + var http = getHTTPObject(); + http.open("GET", url, true); + http.onreadystatechange = function() { + if(http.readyState == 4) callback(http.responseText); + } + http.send(null); +} + + +/* get, set, and delete cookies */ +function getCookie( name ) { + var start = document.cookie.indexOf( name + "=" ); + var len = start + name.length + 1; + if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) { + return null; + } + if ( start == -1 ) return null; + var end = document.cookie.indexOf( ";", len ); + if ( end == -1 ) end = document.cookie.length; + return unescape( document.cookie.substring( len, end ) ); +} + +function setCookie( name, value, expires, path, domain, secure ) { + var today = new Date(); + today.setTime( today.getTime() ); + if ( expires ) { + expires = expires * 1000 * 60 * 60 * 24; + } + var expires_date = new Date( today.getTime() + (expires) ); + document.cookie = name+"="+escape( value ) + + ( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString() + ( ( path ) ? ";path=" + path : "" ) + + ( ( domain ) ? ";domain=" + domain : "" ) + + ( ( secure ) ? ";secure" : "" ); +} + +function deleteCookie( name, path, domain ) { + if ( getCookie( name ) ) document.cookie = name + "=" + + ( ( path ) ? ";path=" + path : "") + + ( ( domain ) ? ";domain=" + domain : "" ) + + ";expires=Thu, 01-Jan-1970 00:00:01 GMT"; +} + diff --git a/scripts/shimmie.js b/scripts/shimmie.js new file mode 100644 index 00000000..cdbed93f --- /dev/null +++ b/scripts/shimmie.js @@ -0,0 +1,131 @@ +var defaultTexts = new Array(); + +window.onload = function(e) { + var sections=get_sections(); + for(var i=0;i"+results[i]+""; + } +} + +function initAjax(boxname, areaname) { + var box = byId(boxname); + if(!box) return; + + addEvent( + box, + "keyup", + function f() { + starter = endWord(box.value); + + if(resultCache[starter]) { + fillCompletionZone(boxname, areaname, resultCache[starter]); + } + else { + ajaxRequest( + "ajax.php?start="+starter, + function g(text) { + resultCache[starter] = text.split("\n"); + fillCompletionZone(boxname, areaname, resultCache[starter]); + } + ); + } + }, + false + ); +} + +function initGray(boxname, text) { + var box = byId(boxname); + if(!box) return; + + addEvent(box, "focus", function f() {cleargray(box, text);}, false); + addEvent(box, "blur", function f() {setgray(box, text);}, false); + + if(box.value == text) { + box.style.color = "#999"; + box.style.textAlign = "center"; + } + else { + box.style.color = "#000"; + box.style.textAlign = "left"; + } +} + +function cleargray(box, text) { + if(box.value == text) { + box.value = ""; + box.style.color = "#000"; + box.style.textAlign = "left"; + } +} +function setgray(box, text) { + if(box.value == "") { + box.style.textAlign = "center"; + box.style.color = "gray"; + box.value = text; + } +} + +function showUp(elem) { + e = document.getElementById(elem) + if(!e) return; + e.style.display = ""; +// alert(e.type+": "+e.value); + if(e.value.match(/^http|^ftp/)) { + e.type = "text"; + alert("Box is web upload"); + } +} + + +function check_int(box, min, max) { + check(box, (box.value >= min && box.value <= max)); +} + +function check(box, bool) { + if(bool) { + box.style.background = "#AFA"; + } + else { + box.style.background = "#FAA"; + } +} + diff --git a/themes/default/default.php b/themes/default/default.php new file mode 100644 index 00000000..0499a2a1 --- /dev/null +++ b/themes/default/default.php @@ -0,0 +1,99 @@ +get_string('base_href'); +$data_href = $config->get_string('data_href'); +$contact_link = $config->get_string('contact_link'); + +function block_to_html($block) { + $h = $block->header; + $b = $block->body; + $i = str_replace(' ', '_', $h); + $html = ""; + if(!is_null($h)) $html .= "\n

$h

\n"; + if(!is_null($b)) $html .= "
$b
\n"; + return $html; +} + +$sideblock_html = ""; +foreach($this->sideblocks as $block) { + $sideblock_html .= block_to_html($block); +} + +$mainblock_html = ""; +foreach($this->mainblocks as $block) { + $mainblock_html .= block_to_html($block); +} + +$scripts = glob("scripts/*.js"); +$script_html = ""; +foreach($scripts as $script) { + $script_html .= "\t\t\n"; +} + +if($config->get_bool('debug_enabled')) { + if(function_exists('memory_get_usage')) { + $i_mem = sprintf("%5.2f", ((memory_get_usage()+512)/1024)/1024); + } + else { + $i_mem = "???"; + } + if(function_exists('getrusage')) { + $ru = getrusage(); + $i_utime = sprintf("%5.2f", ($ru["ru_utime.tv_sec"]*1e6+$ru["ru_utime.tv_usec"])/1000000); + $i_stime = sprintf("%5.2f", ($ru["ru_stime.tv_sec"]*1e6+$ru["ru_stime.tv_usec"])/1000000); + } + else { + $i_utime = "???"; + $i_stime = "???"; + } + $i_files = count(get_included_files()); + global $_execs; + $debug = "
Took $i_utime + $i_stime seconds and {$i_mem}MB of RAM"; + $debug .= "; Used $i_files files and $_execs queries"; +} +else { + $debug = ""; +} + +global $config; +$version = $config->get_string('version'); + +$contact = empty($contact_link) ? "" : "
Contact"; + +if(empty($this->subheading)) { + $subheading = ""; +} +else { + $subheading = "
{$this->subheading}
"; +} + +print << + + + {$this->title} + + +$script_html + + + +

{$this->heading}

+ $subheading + + +
$mainblock_html
+ + + + +EOD; +?> diff --git a/themes/default/sidebar.js b/themes/default/sidebar.js new file mode 100644 index 00000000..585f8ca8 --- /dev/null +++ b/themes/default/sidebar.js @@ -0,0 +1,83 @@ +/* + * This script shamelessly stolen from wakachan.org d(^_^)b + */ + +var cookie_name="shimmie_sidebar"; +var default_sections=["upload", "edit_tags"]; + +function toggle(id) +{ + var e=document.getElementById(id); + if(!e) return; + if(e.style.display) + { + remove_section(id); + e.style.display=""; + + var e2 = document.getElementById(id+"-toggle"); + if(e2) { + e2.style.color = "#000"; + } + } + else + { + add_section(id); + e.style.display="none"; + + var e2 = document.getElementById(id+"-toggle"); + if(e2) { + e2.style.color = "#AAA"; + } + } +} + +function add_section(id) +{ + var sections=get_sections(); + for(var i=0;i