Merge branch 'pdo'

This commit is contained in:
Shish 2011-01-01 18:47:55 +00:00
commit 06a3be4941
41 changed files with 278 additions and 10847 deletions

View File

@ -39,9 +39,15 @@ Installation
not, you should be given instructions on how to fix any errors~
Upgrade from 2.2.X
Upgrade from 2.3.X
~~~~~~~~~~~~~~~~~~
Should be automatic, just unzip into a clean folder and copy across
The database connection setting in config.php has changed; now using
PDO DSN format [1] rather than ADODB URI [2]
[1] <proto>:user=<username>;password=<password>;host=<host>;dbname=<database>
[2] <proto>://<username>:<password>@<host>/<database>
The rest should be automatic, just unzip into a clean folder and copy across
config.php, images and thumbs folders from the old version. This
includes automatically messing with the database -- back it up first!
@ -66,7 +72,7 @@ Contact
~~~~~~~
#shimmie on Freenode -- IRC
webmaster at shishnet.org -- email
http://redmine.shishnet.org/projects/show/shimmie2 -- bug tracker
https://github.com/shish/shimmie2 -- bug tracker
Licence

View File

@ -52,8 +52,8 @@ class UploadS3 extends SimpleExtension {
S3::ACL_PUBLIC_READ,
array(),
array(
"Content-Type" => "image/" . $event->image->type,
"Content-Disposition" => "inline; filename=image-" . $event->image->id . "." . $event->image->type,
"Content-Type" => $event->image->get_mime_type(),
"Content-Disposition" => "inline; filename=image-" . $event->image->id . "." . $event->image->ext,
)
);
}

View File

@ -434,7 +434,7 @@ class Artists implements Extension {
{
global $database;
$result = $database->db->GetOne("SELECT COUNT(1) FROM artist_urls WHERE url = ?", array(mysql_real_escape_string($url)));
$result = $database->get_one("SELECT COUNT(1) FROM artist_urls WHERE url = ?", array(mysql_real_escape_string($url)));
return ($result != 0);
}
@ -442,7 +442,7 @@ class Artists implements Extension {
{
global $database;
$result = $database->db->GetOne("SELECT COUNT(1) FROM artist_members WHERE name = ?", array(mysql_real_escape_string($member)));
$result = $database->get_one("SELECT COUNT(1) FROM artist_members WHERE name = ?", array(mysql_real_escape_string($member)));
return ($result != 0);
}
@ -450,7 +450,7 @@ class Artists implements Extension {
{
global $database;
$result = $database->db->GetOne("SELECT COUNT(1) FROM artist_alias WHERE alias = ?", array(mysql_real_escape_string($alias)));
$result = $database->get_one("SELECT COUNT(1) FROM artist_alias WHERE alias = ?", array(mysql_real_escape_string($alias)));
return ($result != 0);
}
@ -459,7 +459,7 @@ class Artists implements Extension {
global $database;
$result = $database->db->GetOne("SELECT COUNT(1) FROM artist_alias WHERE artist_id = ? AND alias = ?", array(
$result = $database->get_one("SELECT COUNT(1) FROM artist_alias WHERE artist_id = ? AND alias = ?", array(
$artistID
, mysql_real_escape_string($alias)
));
@ -870,7 +870,7 @@ class Artists implements Extension {
private function artist_exists($name){
global $database;
$result = $database->db->GetOne("SELECT COUNT(1) FROM artists WHERE name = ?"
$result = $database->get_one("SELECT COUNT(1) FROM artists WHERE name = ?"
, array(
mysql_real_escape_string($name)
));
@ -1046,7 +1046,7 @@ class Artists implements Extension {
$listing[$i]["artist_name"] = stripslashes($listing[$i]["artist_name"]);
}
$count = $database->db->GetOne(
$count = $database->get_one(
"SELECT COUNT(1)
FROM artists AS a
LEFT OUTER JOIN artist_members AS am
@ -1170,7 +1170,7 @@ class Artists implements Extension {
global $database;
$result = $database->db->GetOne("SELECT COUNT(1) FROM artist_members WHERE artist_id = ? AND name = ?"
$result = $database->get_one("SELECT COUNT(1) FROM artist_members WHERE artist_id = ? AND name = ?"
, array(
$artistID
, mysql_real_escape_string($member)
@ -1184,7 +1184,7 @@ class Artists implements Extension {
global $database;
$result = $database->db->GetOne("SELECT COUNT(1) FROM artist_urls WHERE artist_id = ? AND url = ?"
$result = $database->get_one("SELECT COUNT(1) FROM artist_urls WHERE artist_id = ? AND url = ?"
, array(
$artistID
, mysql_real_escape_string($url)

View File

@ -50,14 +50,14 @@ class ET implements Extension {
$info['sys_server'] = $_SERVER["SERVER_SOFTWARE"];
include "config.php"; // more magical hax
$proto = preg_replace("#(.*)://.*#", "$1", $database_dsn);
$db = $database->db->ServerInfo();
$info['sys_db'] = "$proto / {$db['version']}";
#$db = $database->db->ServerInfo();
#$info['sys_db'] = "$proto / {$db['version']}";
$info['stat_images'] = $database->db->GetOne("SELECT COUNT(*) FROM images");
$info['stat_comments'] = $database->db->GetOne("SELECT COUNT(*) FROM comments");
$info['stat_users'] = $database->db->GetOne("SELECT COUNT(*) FROM users");
$info['stat_tags'] = $database->db->GetOne("SELECT COUNT(*) FROM tags");
$info['stat_image_tags'] = $database->db->GetOne("SELECT COUNT(*) FROM image_tags");
$info['stat_images'] = $database->get_one("SELECT COUNT(*) FROM images");
$info['stat_comments'] = $database->get_one("SELECT COUNT(*) FROM comments");
$info['stat_users'] = $database->get_one("SELECT COUNT(*) FROM users");
$info['stat_tags'] = $database->get_one("SELECT COUNT(*) FROM tags");
$info['stat_image_tags'] = $database->get_one("SELECT COUNT(*) FROM image_tags");
$els = array();
foreach($_event_listeners as $el) {

View File

@ -14,6 +14,8 @@ class ETTheme extends Themelet {
}
protected function build_data_form($info) {
global $user;
$data = <<<EOD
Optional:
Site title: {$info['site_title']}
@ -27,7 +29,6 @@ Schema: {$info['sys_schema']}
PHP: {$info['sys_php']}
OS: {$info['sys_os']}
Server: {$info['sys_server']}
Database: {$info['sys_db']}
Disk use: {$info['sys_disk']}
Shimmie stats:

View File

@ -40,7 +40,7 @@ class Favorites extends SimpleExtension {
$user_id = $user->id;
$image_id = $event->image->id;
$is_favorited = $database->db->GetOne(
$is_favorited = $database->get_one(
"SELECT COUNT(*) AS ct FROM user_favorites WHERE user_id = ? AND image_id = ?",
array($user_id, $image_id)) > 0;

View File

@ -60,8 +60,8 @@ class Forum extends SimpleExtension {
public function onUserPageBuilding($event) {
global $page, $user, $database;
$threads_count = $database->db->GetOne("SELECT COUNT(*) FROM forum_threads WHERE user_id=?", array($event->display_user->id));
$posts_count = $database->db->GetOne("SELECT COUNT(*) FROM forum_posts WHERE user_id=?", array($event->display_user->id));
$threads_count = $database->get_one("SELECT COUNT(*) FROM forum_threads WHERE user_id=?", array($event->display_user->id));
$posts_count = $database->get_one("SELECT COUNT(*) FROM forum_posts WHERE user_id=?", array($event->display_user->id));
$days_old = ((time() - strtotime($event->display_user->join_date)) / 86400) + 1;
@ -278,7 +278,7 @@ class Forum extends SimpleExtension {
, array($pageNumber * $threadsPerPage, $threadsPerPage)
);
$totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM forum_threads") / $threadsPerPage);
$totalPages = ceil($database->get_one("SELECT COUNT(*) FROM forum_threads") / $threadsPerPage);
$this->theme->display_thread_list($page, $threads, $showAdminOptions, $pageNumber + 1, $totalPages);
}
@ -309,7 +309,7 @@ class Forum extends SimpleExtension {
, array($threadID, $pageNumber * $postsPerPage, $postsPerPage)
);
$totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM forum_posts WHERE thread_id = ?", array($threadID)) / $postsPerPage);
$totalPages = ceil($database->get_one("SELECT COUNT(*) FROM forum_posts WHERE thread_id = ?", array($threadID)) / $postsPerPage);
$threadTitle = $this->get_thread_title($threadID);

View File

@ -45,7 +45,7 @@ class ImageBan extends SimpleExtension {
public function onDataUpload(DataUploadEvent $event) {
global $database;
$row = $database->db->GetRow("SELECT * FROM image_bans WHERE hash = ?", $event->hash);
$row = $database->get_row("SELECT * FROM image_bans WHERE hash = :hash", array("hash"=>$event->hash));
if($row) {
log_info("image_hash_ban", "Blocked image ({$event->hash})");
throw new UploadException("Image ".html_escape($row["hash"])." has been banned, reason: ".format_text($row["reason"]));
@ -87,7 +87,7 @@ class ImageBan extends SimpleExtension {
$page_num = int_escape($event->get_arg(1));
}
$page_size = 100;
$page_count = ceil($database->db->getone("SELECT COUNT(id) FROM image_bans")/$page_size);
$page_count = ceil($database->get_one("SELECT COUNT(id) FROM image_bans")/$page_size);
$this->theme->display_Image_hash_Bans($page, $page_num, $page_count, $this->get_image_hash_bans($page_num, $page_size));
}
}

View File

@ -89,7 +89,7 @@ class IPBan implements Extension {
}
if($event instanceof RemoveIPBanEvent) {
$database->Execute("DELETE FROM bans WHERE id = ?", array($event->id));
$database->Execute("DELETE FROM bans WHERE id = :id", array("id"=>$event->id));
$database->cache->delete("ip_bans");
}
}
@ -211,9 +211,9 @@ class IPBan implements Extension {
SELECT bans.*, users.name as banner_name
FROM bans
JOIN users ON banner_id = users.id
WHERE (end_timestamp > ?) OR (end_timestamp IS NULL)
WHERE (end_timestamp > :end_timestamp) OR (end_timestamp IS NULL)
ORDER BY end_timestamp, bans.id
", array(time()));
", array("end_timestamp"=>time()));
$database->cache->set("ip_bans", $bans, 600);

View File

@ -49,38 +49,34 @@ class LogDatabase extends SimpleExtension {
$page_num = int_escape($event->get_arg(0));
if($page_num <= 0) $page_num = 1;
if(!empty($_GET["time"])) {
$wheres[] = "date_sent LIKE ?";
$args[] = $_GET["time"]."%";
$wheres[] = "date_sent LIKE :time";
$args["time"] = $_GET["time"]."%";
}
if(!empty($_GET["module"])) {
$wheres[] = "section = ?";
$args[] = $_GET["module"];
$wheres[] = "section = :module";
$args["module"] = $_GET["module"];
}
if(!empty($_GET["user"])) {
if($database->engine->name == "pgsql") {
if(preg_match("#\d+\.\d+\.\d+\.\d+(/\d+)?#", $_GET["user"])) {
$wheres[] = "(username = ? OR address << ?)";
$args[] = $_GET["user"];
$args[] = $_GET["user"];
$wheres[] = "(username = :user OR address << :user)";
}
else {
$wheres[] = "lower(username) = lower(?)";
$args[] = $_GET["user"];
$wheres[] = "lower(username) = lower(:user)";
}
}
else {
$wheres[] = "(username = ? OR address = ?)";
$args[] = $_GET["user"];
$args[] = $_GET["user"];
$wheres[] = "(username = :user OR address = :user)";
}
$args["user"] = $_GET["user"];
}
if(!empty($_GET["priority"])) {
$wheres[] = "priority >= ?";
$args[] = int_escape($_GET["priority"]);
$wheres[] = "priority >= :priority";
$args["priority"] = int_escape($_GET["priority"]);
}
else {
$wheres[] = "priority >= ?";
$args[] = 20;
$wheres[] = "priority >= :priority";
$args["priority"] = 20;
}
$where = "";
if(count($wheres) > 0) {
@ -92,16 +88,16 @@ class LogDatabase extends SimpleExtension {
$offset = ($page_num-1) * $limit;
$page_total = $database->cache->get("event_log_length");
if(!$page_total) {
$page_total = $database->db->GetOne("SELECT count(*) FROM score_log $where", $args);
$page_total = $database->get_one("SELECT count(*) FROM score_log $where", $args);
// don't cache a length of zero when the extension is first installed
if($page_total > 10) {
$database->cache->set("event_log_length", 600);
}
}
$args[] = $limit;
$args[] = $offset;
$events = $database->get_all("SELECT * FROM score_log $where ORDER BY id DESC LIMIT ? OFFSET ?", $args);
$args["limit"] = $limit;
$args["offset"] = $offset;
$events = $database->get_all("SELECT * FROM score_log $where ORDER BY id DESC LIMIT :limit OFFSET :offset", $args);
$this->theme->display_events($events, $page_num, 100);
}
@ -124,8 +120,11 @@ class LogDatabase extends SimpleExtension {
if($event->priority >= $config->get_int("log_db_priority")) {
$database->execute("
INSERT INTO score_log(date_sent, section, priority, username, address, message)
VALUES(now(), ?, ?, ?, ?, ?)
", array($event->section, $event->priority, $user->name, $_SERVER['REMOTE_ADDR'], $event->message));
VALUES(now(), :section, :priority, :username, :address, :message)
", array(
"section"=>$event->section, "priority"=>$event->priority, "username"=>$user->name,
"address"=>$_SERVER['REMOTE_ADDR'], "message"=>$event->message
));
}
}
}

View File

@ -436,7 +436,7 @@ class Notes extends SimpleExtension {
$result = $database->Execute($get_notes, array(1, $pageNumber * $notesPerPage, $notesPerPage));
$totalPages = ceil($database->db->GetOne("SELECT COUNT(DISTINCT image_id) FROM notes") / $notesPerPage);
$totalPages = ceil($database->get_one("SELECT COUNT(DISTINCT image_id) FROM notes") / $notesPerPage);
$images = array();
while(!$result->EOF) {
@ -476,7 +476,7 @@ class Notes extends SimpleExtension {
$result = $database->Execute($get_requests, array($pageNumber * $requestsPerPage, $requestsPerPage));
$totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM note_request") / $requestsPerPage);
$totalPages = ceil($database->get_one("SELECT COUNT(*) FROM note_request") / $requestsPerPage);
$images = array();
while(!$result->EOF) {
@ -498,7 +498,7 @@ class Notes extends SimpleExtension {
$userID = $user->id;
$reviewID = $database->db->GetOne("SELECT COUNT(*) FROM note_histories WHERE note_id = ?", array($noteID));
$reviewID = $database->get_one("SELECT COUNT(*) FROM note_histories WHERE note_id = ?", array($noteID));
$reviewID = $reviewID + 1;
$database->execute("
@ -536,7 +536,7 @@ class Notes extends SimpleExtension {
"ORDER BY date DESC LIMIT ?, ?",
array($pageNumber * $histiriesPerPage, $histiriesPerPage));
$totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM note_histories") / $histiriesPerPage);
$totalPages = ceil($database->get_one("SELECT COUNT(*) FROM note_histories") / $histiriesPerPage);
$this->theme->display_histories($histories, $pageNumber + 1, $totalPages);
}
@ -569,7 +569,7 @@ class Notes extends SimpleExtension {
"ORDER BY date DESC LIMIT ?, ?",
array($noteID, $pageNumber * $histiriesPerPage, $histiriesPerPage));
$totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM note_histories WHERE note_id = ?", array($noteID)) / $histiriesPerPage);
$totalPages = ceil($database->get_one("SELECT COUNT(*) FROM note_histories WHERE note_id = ?", array($noteID)) / $histiriesPerPage);
$this->theme->display_history($histories, $pageNumber + 1, $totalPages);
}

View File

@ -284,7 +284,7 @@ class Pools extends SimpleExtension {
", array($poolsPerPage, $pageNumber * $poolsPerPage)
);
$totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM pools") / $poolsPerPage);
$totalPages = ceil($database->get_one("SELECT COUNT(*) FROM pools") / $poolsPerPage);
$this->theme->list_pools($page, $pools, $pageNumber + 1, $totalPages);
}
@ -372,7 +372,7 @@ class Pools extends SimpleExtension {
}
if(!strlen($images) == 0) {
$count = $database->db->GetOne("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID));
$count = $database->get_one("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID));
$this->add_history($poolID, 1, $images, $count);
}
@ -418,7 +418,7 @@ class Pools extends SimpleExtension {
$images .= " ".$imageID;
}
$count = $database->db->GetOne("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID));
$count = $database->get_one("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID));
$this->add_history($poolID, 0, $images, $count);
return $poolID;
}
@ -430,7 +430,7 @@ class Pools extends SimpleExtension {
*/
private function check_post($poolID, $imageID) {
global $database;
$result = $database->db->GetOne("SELECT COUNT(*) FROM pool_images WHERE pool_id=? AND image_id=?", array($poolID, $imageID));
$result = $database->get_one("SELECT COUNT(*) FROM pool_images WHERE pool_id=? AND image_id=?", array($poolID, $imageID));
return ($result != 0);
}
@ -467,7 +467,7 @@ class Pools extends SimpleExtension {
LIMIT ? OFFSET ?",
array($poolID, $imagesPerPage, $pageNumber * $imagesPerPage));
$totalPages = ceil($database->db->GetOne("
$totalPages = ceil($database->get_one("
SELECT COUNT(*)
FROM pool_images AS p
INNER JOIN images AS i ON i.id = p.image_id
@ -482,7 +482,7 @@ class Pools extends SimpleExtension {
ORDER BY image_order ASC
LIMIT ? OFFSET ?",
array($poolID, $imagesPerPage, $pageNumber * $imagesPerPage));
$totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID)) / $imagesPerPage);
$totalPages = ceil($database->get_one("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID)) / $imagesPerPage);
}
$images = array();
@ -604,7 +604,7 @@ class Pools extends SimpleExtension {
LIMIT ? OFFSET ?
", array($historiesPerPage, $pageNumber * $historiesPerPage));
$totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM pool_history") / $historiesPerPage);
$totalPages = ceil($database->get_one("SELECT COUNT(*) FROM pool_history") / $historiesPerPage);
$this->theme->show_history($history, $pageNumber + 1, $totalPages);
}
@ -645,7 +645,7 @@ class Pools extends SimpleExtension {
}
}
$count = $database->db->GetOne("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID));
$count = $database->get_one("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID));
$this->add_history($poolID, $newAction, $imageArray, $count);
}
}

View File

@ -213,11 +213,11 @@ class Tag_History implements Extension {
// if needed remove oldest one
if($allowed == -1) return;
$entries = $database->db->GetOne("SELECT COUNT(*) FROM tag_histories WHERE image_id = ?", array($image->id));
$entries = $database->get_one("SELECT COUNT(*) FROM tag_histories WHERE image_id = ?", array($image->id));
if($entries > $allowed)
{
// TODO: Make these queries better
$min_id = $database->db->GetOne("SELECT MIN(id) FROM tag_histories WHERE image_id = ?", array($image->id));
$min_id = $database->get_one("SELECT MIN(id) FROM tag_histories WHERE image_id = ?", array($image->id));
$database->execute("DELETE FROM tag_histories WHERE id = ?", array($min_id));
}
}

View File

@ -198,7 +198,7 @@ class Wiki extends SimpleExtension {
private function get_page($title, $revision=-1) {
global $database;
// first try and get the actual page
$row = $database->db->GetRow("
$row = $database->get_row("
SELECT *
FROM wiki_pages
WHERE title LIKE ?
@ -206,7 +206,7 @@ class Wiki extends SimpleExtension {
// fall back to wiki:default
if(empty($row)) {
$row = $database->db->GetRow("
$row = $database->get_row("
SELECT *
FROM wiki_pages
WHERE title LIKE ?

View File

@ -175,7 +175,10 @@ class DatabaseConfig extends BaseConfig {
$this->values = $cached;
}
else {
$this->values = $this->database->db->GetAssoc("SELECT name, value FROM config");
$this->values = array();
foreach($this->database->get_all("SELECT name, value FROM config") as $row) {
$this->values[$row["name"]] = $row["value"];
}
$this->database->cache->set("config", $this->values);
}
}
@ -190,8 +193,8 @@ class DatabaseConfig extends BaseConfig {
}
}
else {
$this->database->Execute("DELETE FROM config WHERE name = ?", array($name));
$this->database->Execute("INSERT INTO config VALUES (?, ?)", array($name, $this->values[$name]));
$this->database->Execute("DELETE FROM config WHERE name = :name", array("name"=>$name));
$this->database->Execute("INSERT INTO config VALUES (:name, :value)", array("name"=>$name, "value"=>$this->values[$name]));
}
$this->database->cache->delete("config");
}

View File

@ -1,8 +1,5 @@
<?php
require_once "compat.inc.php";
$ADODB_CACHE_DIR=sys_get_temp_dir();
require_once "lib/adodb/adodb.inc.php";
require_once "lib/adodb/adodb-exceptions.inc.php";
/** @privatesection */
// Querylet {{{
@ -66,7 +63,7 @@ class MySQL extends DBEngine {
var $name = "mysql";
public function init($db) {
$db->Execute("SET NAMES utf8;");
$db->query("SET NAMES utf8;");
}
public function scoreql_to_sql($data) {
@ -255,7 +252,7 @@ class APCCache implements CacheEngine {
*/
class Database {
/**
* The ADODB database connection object, for anyone who wants direct access
* The PDO database connection object, for anyone who wants direct access
*/
var $db;
@ -276,17 +273,34 @@ class Database {
public function Database() {
global $database_dsn, $cache_dsn;
if(substr($database_dsn, 0, 5) == "mysql") {
# FIXME: detect ADODB URI, automatically translate PDO DSN
/*
* Why does the abstraction layer act differently depending on the
* back-end? Because PHP is deliberately retarded.
*
* http://stackoverflow.com/questions/237367
*/
$matches = array(); $db_user=null; $db_pass=null;
if(preg_match("/user=([^;]*)/", $database_dsn, $matches)) $db_user=$matches[1];
if(preg_match("/password=([^;]*)/", $database_dsn, $matches)) $db_pass=$matches[1];
$this->db = new PDO($database_dsn, $db_user, $db_pass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db_proto = $this->db->getAttribute(PDO::ATTR_DRIVER_NAME);
if($db_proto == "mysql") {
$this->engine = new MySQL();
}
else if(substr($database_dsn, 0, 5) == "pgsql") {
else if($db_proto == "pgsql") {
$this->engine = new PostgreSQL();
}
else if(substr($database_dsn, 0, 6) == "sqlite") {
else if($db_proto == "sqlite") {
$this->engine = new SQLite();
}
$this->db = @NewADOConnection($database_dsn);
else {
die("Unknown PDO driver: $db_proto");
}
if(isset($cache_dsn) && !empty($cache_dsn)) {
$matches = array();
@ -302,73 +316,80 @@ class Database {
$this->cache = new NoCache();
}
if($this->db) {
$this->db->SetFetchMode(ADODB_FETCH_ASSOC);
$this->engine->init($this->db);
}
else {
$version = VERSION;
print "
<html>
<head>
<title>Internal error - Shimmie-$version</title>
</head>
<body>
Internal error: Could not connect to database
</body>
</html>
";
exit;
}
$this->engine->init($this->db);
}
/**
* Execute an SQL query and return an ADODB resultset
* Execute an SQL query and return an PDO resultset
*/
public function execute($query, $args=array()) {
$result = $this->db->Execute($query, $args);
if($result === False) {
print "SQL Error: " . $this->db->ErrorMsg();
print "<br>Query: $query";
print "<br>Args: "; print_r($args);
try {
$stmt = $this->db->prepare($query);
foreach($args as $name=>$value) {
if(is_numeric($value)) {
$stmt->bindValue(":$name", $value, PDO::PARAM_INT);
}
else {
$stmt->bindValue(":$name", $value, PDO::PARAM_STR);
}
}
$stmt->execute();
return $stmt;
}
catch(PDOException $pdoe) {
print "Message: ".$pdoe->getMessage();
print "<p>Error: $query";
exit;
}
return $result;
}
/**
* Execute an SQL query and return a 2D array
*/
public function get_all($query, $args=array()) {
$result = $this->db->GetAll($query, $args);
if($result === False) {
print "SQL Error: " . $this->db->ErrorMsg();
print "<br>Query: $query";
print "<br>Args: "; print_r($args);
exit;
}
return $result;
return $this->execute($query, $args)->fetchAll();
}
/**
* Execute an SQL query and return a single row
*/
public function get_row($query, $args=array()) {
$result = $this->db->GetRow($query, $args);
if($result === False) {
print "SQL Error: " . $this->db->ErrorMsg();
print "<br>Query: $query";
print "<br>Args: "; print_r($args);
exit;
}
if(count($result) == 0) {
return null;
}
else {
return $result;
}
return $this->execute($query, $args)->fetch();
}
/**
* Execute an SQL query and return the first column of each row
*/
public function get_col($query, $args=array()) {
$stmt = $this->execute($query, $args);
$res = array();
foreach($stmt as $row) {
$res[] = $row[0];
}
return $res;
}
/**
* Execute an SQL query and return the the first row => the second rown
*/
public function get_pairs($query, $args=array()) {
$stmt = $this->execute($query, $args);
$res = array();
foreach($stmt as $row) {
$res[$row[0]] = $row[1];
}
return $res;
}
/**
* Execute an SQL query and return a single value
*/
public function get_one($query, $args=array()) {
$row = $this->execute($query, $args)->fetch();
return $row[0];
}
/**
* Create a table from pseudo-SQL
*/

View File

@ -66,7 +66,7 @@ class Image {
assert(is_numeric($id));
global $database;
$image = null;
$row = $database->get_row("SELECT * FROM images WHERE images.id=?", array($id));
$row = $database->get_row("SELECT * FROM images WHERE images.id=:id", array("id"=>$id));
return ($row ? new Image($row) : null);
}
@ -79,7 +79,7 @@ class Image {
assert(is_string($hash));
global $database;
$image = null;
$row = $database->db->GetRow("SELECT images.* FROM images WHERE hash=?", array($hash));
$row = $database->get_row("SELECT images.* FROM images WHERE hash=:hash", array("hash"=>$hash));
return ($row ? new Image($row) : null);
}
@ -112,12 +112,11 @@ class Image {
if($limit < 1) $limit = 1;
$querylet = Image::build_search_querylet($tags);
$querylet->append(new Querylet("ORDER BY images.id DESC LIMIT ? OFFSET ?", array($limit, $start)));
$querylet->append(new Querylet("ORDER BY images.id DESC LIMIT :limit OFFSET :offset", array("limit"=>$limit, "offset"=>$start)));
$result = $database->execute($querylet->sql, $querylet->variables);
while(!$result->EOF) {
$images[] = new Image($result->fields);
$result->MoveNext();
while($row = $result->fetch()) {
$images[] = new Image($row);
}
return $images;
}
@ -133,23 +132,23 @@ class Image {
assert(is_array($tags));
global $database;
if(count($tags) == 0) {
#return $database->db->GetOne("SELECT COUNT(*) FROM images");
#return $database->get_one("SELECT COUNT(*) FROM images");
$total = $database->cache->get("image-count");
if(!$total) {
$total = $database->db->GetOne("SELECT COUNT(*) FROM images");
$total = $database->get_one("SELECT COUNT(*) FROM images");
$database->cache->set("image-count", $total, 600);
}
return $total;
}
else if(count($tags) == 1 && !preg_match("/[:=><]/", $tags[0])) {
return $database->db->GetOne(
$database->engine->scoreql_to_sql("SELECT count FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(?)"),
$tags);
return $database->get_one(
$database->engine->scoreql_to_sql("SELECT count FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag)"),
array("tag"=>$tags[0]));
}
else {
$querylet = Image::build_search_querylet($tags);
$result = $database->execute($querylet->sql, $querylet->variables);
return $result->RecordCount();
return $result->rowCount();
}
}
@ -191,13 +190,13 @@ class Image {
}
if(count($tags) == 0) {
$row = $database->db->GetRow("SELECT images.* FROM images WHERE images.id $gtlt {$this->id} ORDER BY images.id $dir LIMIT 1");
$row = $database->get_row("SELECT images.* FROM images WHERE images.id $gtlt {$this->id} ORDER BY images.id $dir LIMIT 1");
}
else {
$tags[] = "id$gtlt{$this->id}";
$querylet = Image::build_search_querylet($tags);
$querylet->append_sql(" ORDER BY images.id $dir LIMIT 1");
$row = $database->db->GetRow($querylet->sql, $querylet->variables);
$row = $database->get_row($querylet->sql, $querylet->variables);
}
return ($row ? new Image($row) : null);
@ -230,12 +229,7 @@ class Image {
if($cached) return $cached;
if(!isset($this->tag_array)) {
$this->tag_array = Array();
$row = $database->Execute("SELECT tag FROM image_tags JOIN tags ON image_tags.tag_id = tags.id WHERE image_id=? ORDER BY tag", array($this->id));
while(!$row->EOF) {
$this->tag_array[] = $row->fields['tag'];
$row->MoveNext();
}
$this->tag_array = $database->get_col("SELECT tag FROM image_tags JOIN tags ON image_tags.tag_id = tags.id WHERE image_id=:id ORDER BY tag", array("id"=>$this->id));
}
$database->cache->set("image-{$this->id}-tags", $this->tag_array);
@ -371,7 +365,7 @@ class Image {
public function set_source($source) {
global $database;
if(empty($source)) $source = null;
$database->execute("UPDATE images SET source=? WHERE id=?", array($source, $this->id));
$database->execute("UPDATE images SET source=:source WHERE id=:id", array("source"=>$source, "id"=>$this->id));
}
@ -384,7 +378,7 @@ class Image {
$sln = $database->engine->scoreql_to_sql("SCORE_BOOL_$ln");
$sln = str_replace("'", "", $sln);
$sln = str_replace('"', "", $sln);
$database->execute("UPDATE images SET locked=? WHERE id=?", array($sln, $this->id));
$database->execute("UPDATE images SET locked=:yn WHERE id=:id", array("yn"=>$sln, "id"=>$this->id));
}
/**
@ -396,8 +390,8 @@ class Image {
global $database;
$database->execute(
"UPDATE tags SET count = count - 1 WHERE id IN ".
"(SELECT tag_id FROM image_tags WHERE image_id = ?)", array($this->id));
$database->execute("DELETE FROM image_tags WHERE image_id=?", array($this->id));
"(SELECT tag_id FROM image_tags WHERE image_id = :id)", array("id"=>$this->id));
$database->execute("DELETE FROM image_tags WHERE image_id=:id", array("id"=>$this->id));
}
/**
@ -415,32 +409,32 @@ class Image {
// insert each new tags
foreach($tags as $tag) {
$id = $database->db->GetOne(
$id = $database->get_one(
$database->engine->scoreql_to_sql(
"SELECT id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(?)"
"SELECT id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag)"
),
array($tag));
array("tag"=>$tag));
if(empty($id)) {
// a new tag
$database->execute(
"INSERT INTO tags(tag) VALUES (?)",
array($tag));
"INSERT INTO tags(tag) VALUES (:tag)",
array("tag"=>$tag));
$database->execute(
"INSERT INTO image_tags(image_id, tag_id)
VALUES(?, (SELECT id FROM tags WHERE tag = ?))",
array($this->id, $tag));
VALUES(:id, (SELECT id FROM tags WHERE tag = :tag))",
array("id"=>$this->id, "tag"=>$tag));
}
else {
// user of an existing tag
$database->execute(
"INSERT INTO image_tags(image_id, tag_id) VALUES(?, ?)",
array($this->id, $id));
"INSERT INTO image_tags(image_id, tag_id) VALUES(:iid, :tid)",
array("iid"=>$this->id, "tid"=>$id));
}
$database->execute(
$database->engine->scoreql_to_sql(
"UPDATE tags SET count = count + 1 WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(?)"
"UPDATE tags SET count = count + 1 WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag)"
),
array($tag));
array("tag"=>$tag));
}
log_info("core-image", "Tags for Image #{$this->id} set to: ".implode(" ", $tags));
@ -453,7 +447,7 @@ class Image {
public function delete() {
global $database;
$this->delete_tags_from_image();
$database->execute("DELETE FROM images WHERE id=?", array($this->id));
$database->execute("DELETE FROM images WHERE id=:id", array("id"=>$this->id));
log_info("core-image", "Deleted Image #{$this->id} ({$this->hash})");
unlink($this->get_image_filename());
@ -601,8 +595,8 @@ class Image {
$query = new Querylet($database->engine->scoreql_to_sql("
SELECT images.* FROM images
JOIN image_tags ON images.id = image_tags.image_id
WHERE tag_id = (SELECT tags.id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(?))
"), array($tag_querylets[0]->tag));
WHERE tag_id = (SELECT tags.id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag))
"), array("tag"=>$tag_querylets[0]->tag));
if(strlen($img_search->sql) > 0) {
$query->append_sql(" AND ");
@ -619,9 +613,9 @@ class Image {
foreach($tag_querylets as $tq) {
$tag_ids = $database->db->GetCol(
$database->engine->scoreql_to_sql(
"SELECT id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(?)"
"SELECT id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag)"
),
array($tq->tag));
array("tag"=>$tq->tag));
if($tq->positive) {
$positive_tag_id_array = array_merge($positive_tag_id_array, $tag_ids);
$tags_ok = count($tag_ids) > 0;
@ -734,8 +728,8 @@ class Image {
$terms = array();
foreach($tag_querylets as $tq) {
$sign = $tq->positive ? "+" : "-";
$sql .= " $sign (tag LIKE ?)";
$terms[] = $tq->tag;
$sql .= " $sign (tag LIKE :tag)";
$terms["tag"] = $tq->tag;
if($sign == "+") $positive_tag_count++;
else $negative_tag_count++;
@ -774,7 +768,7 @@ class Image {
SELECT images.*, UNIX_TIMESTAMP(posted) AS posted_timestamp
FROM tags, image_tags, images
WHERE
tag LIKE ?
tag LIKE :tag
AND tags.id = image_tags.tag_id
AND image_tags.image_id = images.id
",
@ -794,7 +788,7 @@ class Image {
$tag_id_array = array();
$tags_ok = true;
foreach($tag_search->variables as $tag) {
$tag_ids = $database->db->GetCol("SELECT id FROM tags WHERE tag LIKE ?", array($tag));
$tag_ids = $database->get_col("SELECT id FROM tags WHERE tag LIKE :tag", array("tag"=>$tag));
$tag_id_array = array_merge($tag_id_array, $tag_ids);
$tags_ok = count($tag_ids) > 0;
if(!$tags_ok) break;
@ -809,10 +803,10 @@ class Image {
JOIN tags ON image_tags.tag_id = tags.id
WHERE tags.id IN ({$tag_id_list})
GROUP BY images.id
HAVING score = ?",
HAVING score = :score",
array_merge(
$tag_search->variables,
array($positive_tag_count)
array("score"=>$positive_tag_count)
)
);
$query = new Querylet("
@ -904,7 +898,7 @@ class Tag {
assert(is_string($tag));
global $database;
$newtag = $database->db->GetOne("SELECT newtag FROM aliases WHERE oldtag=?", array($tag));
$newtag = $database->get_one("SELECT newtag FROM aliases WHERE oldtag=:tag", array("tag"=>$tag));
if(!empty($newtag)) {
return $newtag;
} else {

View File

@ -41,26 +41,26 @@ class User {
public static function by_session($name, $session) {
global $config, $database;
if($database->engine->name == "mysql") {
$query = "SELECT * FROM users WHERE name = ? AND md5(concat(pass, ?)) = ?";
$query = "SELECT * FROM users WHERE name = :name AND md5(concat(pass, :ip)) = :sess";
}
else {
$query = "SELECT * FROM users WHERE name = ? AND md5(pass || ?) = ?";
$query = "SELECT * FROM users WHERE name = :name AND md5(pass || :ip) = :sess";
}
$row = $database->get_row($query, array($name, get_session_ip($config), $session));
$row = $database->get_row($query, array("name"=>$name, "ip"=>get_session_ip($config), "sess"=>$session));
return is_null($row) ? null : new User($row);
}
public static function by_id($id) {
assert(is_numeric($id));
global $database;
$row = $database->get_row("SELECT * FROM users WHERE id = ?", array($id));
$row = $database->get_row("SELECT * FROM users WHERE id = :id", array("id"=>$id));
return is_null($row) ? null : new User($row);
}
public static function by_name($name) {
assert(is_string($name));
global $database;
$row = $database->get_row("SELECT * FROM users WHERE name = ?", array($name));
$row = $database->get_row("SELECT * FROM users WHERE name = :name", array("name"=>$name));
return is_null($row) ? null : new User($row);
}
@ -69,7 +69,7 @@ class User {
assert(is_string($hash));
assert(strlen($hash) == 32);
global $database;
$row = $database->get_row("SELECT * FROM users WHERE name = ? AND pass = ?", array($name, $hash));
$row = $database->get_row("SELECT * FROM users WHERE name = :name AND pass = :hash", array("name"=>$name, "hash"=>$hash));
return is_null($row) ? null : new User($row);
}
@ -77,7 +77,7 @@ class User {
assert(is_numeric($offset));
assert(is_numeric($limit));
global $database;
$rows = $database->get_all("SELECT * FROM users WHERE id >= ? AND id < ?", array($offset, $offset+$limit));
$rows = $database->get_all("SELECT * FROM users WHERE id >= :start AND id < :end", array("start"=>$offset, "end"=>$offset+$limit));
return array_map("_new_user", $rows);
}
@ -119,20 +119,20 @@ class User {
assert(is_bool($admin));
global $database;
$yn = $admin ? 'Y' : 'N';
$database->Execute("UPDATE users SET admin=? WHERE id=?", array($yn, $this->id));
$database->Execute("UPDATE users SET admin=:yn WHERE id=:id", array("yn"=>$yn, "id"=>$this->id));
log_info("core-user", "Made {$this->name} admin=$yn");
}
public function set_password($password) {
global $database;
$hash = md5(strtolower($this->name) . $password);
$database->Execute("UPDATE users SET pass=? WHERE id=?", array($hash, $this->id));
$database->Execute("UPDATE users SET pass=:hash WHERE id=:id", array("hash"=>$hash, "id"=>$this->id));
log_info("core-user", "Set password for {$this->name}");
}
public function set_email($address) {
global $database;
$database->Execute("UPDATE users SET email=? WHERE id=?", array($address, $this->id));
$database->Execute("UPDATE users SET email=:email WHERE id=:id", array("email"=>$address, "id"=>$this->id));
log_info("core-user", "Set email for {$this->name}");
}
@ -181,6 +181,5 @@ class User {
public function check_auth_token() {
return ($_POST["auth_token"] == $this->get_auth_token());
}
}
?>

View File

@ -67,12 +67,12 @@ class AliasEditor extends SimpleExtension {
$alias_per_page = $config->get_int('alias_items_per_page', 30);
$query = "SELECT oldtag, newtag FROM aliases ORDER BY newtag ASC LIMIT ? OFFSET ?";
$alias = $database->db->GetAssoc($query,
array($alias_per_page, $page_number * $alias_per_page)
$query = "SELECT oldtag, newtag FROM aliases ORDER BY newtag ASC LIMIT :limit OFFSET :offset";
$alias = $database->get_pairs($query,
array("limit"=>$alias_per_page, "offset"=>$page_number * $alias_per_page)
);
$total_pages = ceil($database->db->GetOne("SELECT COUNT(*) FROM aliases") / $alias_per_page);
$total_pages = ceil($database->get_one("SELECT COUNT(*) FROM aliases") / $alias_per_page);
$this->theme->display_aliases($page, $alias, $user->is_admin(), $page_number + 1, $total_pages);
}
@ -104,7 +104,7 @@ class AliasEditor extends SimpleExtension {
public function onAddAlias(AddAliasEvent $event) {
global $database;
$pair = array($event->oldtag, $event->newtag);
if($database->db->GetRow("SELECT * FROM aliases WHERE oldtag=? AND lower(newtag)=lower(?)", $pair)) {
if($database->get_row("SELECT * FROM aliases WHERE oldtag=? AND lower(newtag)=lower(?)", $pair)) {
throw new AddAliasException("That alias already exists");
}
else {

View File

@ -51,7 +51,7 @@ class Comment {
public static function count_comments_by_user($user) {
global $database;
return $database->db->GetOne("SELECT COUNT(*) AS count FROM comments WHERE owner_id=?", array($user->id));
return $database->get_one("SELECT COUNT(*) AS count FROM comments WHERE owner_id=:owner_id", array("owner_id"=>$user->id));
}
public function get_owner() {
@ -180,7 +180,7 @@ class CommentList extends SimpleExtension {
public function onImageDeletion(ImageDeletionEvent $event) {
global $database;
$image_id = $event->image->id;
$database->Execute("DELETE FROM comments WHERE image_id=?", array($image_id));
$database->Execute("DELETE FROM comments WHERE image_id=:image_id", array("image_id"=>$image_id));
log_info("comment", "Deleting all comments for Image #$image_id");
}
@ -191,7 +191,7 @@ class CommentList extends SimpleExtension {
public function onCommentDeletion(CommentDeletionEvent $event) {
global $database;
$database->Execute("DELETE FROM comments WHERE id=?", array($event->comment_id));
$database->Execute("DELETE FROM comments WHERE id=:comment_id", array("comment_id"=>$event->comment_id));
log_info("comment", "Deleting Comment #{$event->comment_id}");
}
@ -261,16 +261,16 @@ class CommentList extends SimpleExtension {
FROM comments
GROUP BY image_id
ORDER BY latest DESC
LIMIT ? OFFSET ?
LIMIT :limit OFFSET :offset
";
$result = $database->Execute($get_threads, array($threads_per_page, $start));
$result = $database->Execute($get_threads, array("limit"=>$threads_per_page, "offset"=>$start));
$total_pages = (int)($database->db->GetOne("SELECT COUNT(c1) FROM (SELECT COUNT(image_id) AS c1 FROM comments GROUP BY image_id) AS s1") / 10);
$total_pages = (int)($database->get_one("SELECT COUNT(c1) FROM (SELECT COUNT(image_id) AS c1 FROM comments GROUP BY image_id) AS s1") / 10);
$images = array();
while(!$result->EOF) {
$image = Image::by_id($result->fields["image_id"]);
while($row = $result->fetch()) {
$image = Image::by_id($row["image_id"]);
$comments = $this->get_comments($image->id);
if(class_exists("Ratings")) {
if(strpos($user_ratings, $image->rating) === FALSE) {
@ -278,7 +278,6 @@ class CommentList extends SimpleExtension {
}
}
if(!is_null($image)) $images[] = array($image, $comments);
$result->MoveNext();
}
$this->theme->display_comment_list($images, $current_page, $total_pages, $this->can_comment());
@ -297,8 +296,8 @@ class CommentList extends SimpleExtension {
FROM comments
LEFT JOIN users ON comments.owner_id=users.id
ORDER BY comments.id DESC
LIMIT ?
", array($config->get_int('comment_count')));
LIMIT :limit
", array("limit"=>$config->get_int('comment_count')));
$comments = array();
foreach($rows as $row) {
$comments[] = new Comment($row);
@ -318,9 +317,9 @@ class CommentList extends SimpleExtension {
comments.posted as posted
FROM comments
LEFT JOIN users ON comments.owner_id=users.id
WHERE comments.image_id=?
WHERE comments.image_id=:image_id
ORDER BY comments.id ASC
", array($i_image_id));
", array("image_id"=>$i_image_id));
$comments = array();
foreach($rows as $row) {
$comments[] = new Comment($row);
@ -398,7 +397,7 @@ class CommentList extends SimpleExtension {
private function is_dupe($image_id, $comment) {
global $database;
return ($database->db->GetRow("SELECT * FROM comments WHERE image_id=? AND comment=?", array($image_id, $comment)));
return ($database->get_row("SELECT * FROM comments WHERE image_id=? AND comment=?", array($image_id, $comment)));
}
private function add_comment_wrapper($image_id, $user, $comment, $event) {
@ -451,7 +450,7 @@ class CommentList extends SimpleExtension {
"INSERT INTO comments(image_id, owner_id, owner_ip, posted, comment) ".
"VALUES(?, ?, ?, now(), ?)",
array($image_id, $user->id, $_SERVER['REMOTE_ADDR'], $comment));
$cid = $database->db->Insert_ID();
$cid = $database->db->lastInsertId();
log_info("comment", "Comment #$cid added to Image #$image_id");
}
}

View File

@ -234,16 +234,23 @@ class ImageIO extends SimpleExtension {
$database->Execute(
"INSERT INTO images(
owner_id, owner_ip, filename, filesize,
hash, ext, width, height, posted, source)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, now(), ?)",
array($user->id, $_SERVER['REMOTE_ADDR'], $image->filename, $image->filesize,
$image->hash, $image->ext, $image->width, $image->height, $image->source));
hash, ext, width, height, posted, source
)
VALUES (
:owner_id, :owner_ip, :filename, :filesize,
:hash, :ext, :width, :height, now(), :source
)",
array(
"owner_id"=>$user->id, "owner_ip"=>$_SERVER['REMOTE_ADDR'], "filename"=>$image->filename, "filesize"=>$image->filesize,
"hash"=>$image->hash, "ext"=>$image->ext, "width"=>$image->width, "height"=>$image->height, "source"=>$image->source
)
);
if($database->engine->name == "pgsql") {
$database->Execute("UPDATE users SET image_count = image_count+1 WHERE id = ? ", array($user->id));
$image->id = $database->db->GetOne("SELECT id FROM images WHERE hash=?", array($image->hash));
$image->id = $database->get_one("SELECT id FROM images WHERE hash=?", array($image->hash));
}
else {
$image->id = $database->db->Insert_ID();
$image->id = $database->db->lastInsertId();
}
log_info("image", "Uploaded Image #{$image->id} ({$image->hash})");

View File

@ -46,8 +46,8 @@ class TagList implements Extension {
if(($event instanceof PageRequestEvent) && $event->page_matches("api/internal/tag_list/complete")) {
$all = $database->get_all(
"SELECT tag FROM tags WHERE tag LIKE ? AND count > 0 LIMIT 10",
array($_GET["s"]."%"));
"SELECT tag FROM tags WHERE tag LIKE :search AND count > 0 LIMIT 10",
array("search"=>$_GET["s"]."%"));
$res = array();
foreach($all as $row) {$res[] = $row["tag"];}
@ -130,11 +130,11 @@ class TagList implements Extension {
$result = $database->execute("
SELECT
tag,
FLOOR(LOG(2.7, LOG(2.7, count - ? + 1)+1)*1.5*100)/100 AS scaled
FLOOR(LOG(2.7, LOG(2.7, count - :tags_min + 1)+1)*1.5*100)/100 AS scaled
FROM tags
WHERE count >= ?
WHERE count >= :tags_min
ORDER BY tag
", array($tags_min, $tags_min));
", array("tags_min"=>$tags_min));
$tag_data = $result->GetArray();
$html = "";
@ -154,8 +154,8 @@ class TagList implements Extension {
$tags_min = $this->get_tags_min();
$result = $database->execute(
"SELECT tag,count FROM tags WHERE count >= ? ORDER BY tag",
array($tags_min));
"SELECT tag,count FROM tags WHERE count >= :tags_min ORDER BY tag",
array("tags_min"=>$tags_min));
$tag_data = $result->GetArray();
$html = "";
@ -179,8 +179,8 @@ class TagList implements Extension {
$tags_min = $this->get_tags_min();
$result = $database->execute(
"SELECT tag,count,FLOOR(LOG(count)) AS scaled FROM tags WHERE count >= ? ORDER BY count DESC, tag ASC",
array($tags_min));
"SELECT tag,count,FLOOR(LOG(count)) AS scaled FROM tags WHERE count >= :tags_min ORDER BY count DESC, tag ASC",
array("tags_min"=>$tags_min));
$tag_data = $result->GetArray();
$html = "Results grouped by log<sub>e</sub>(n)";
@ -240,7 +240,7 @@ class TagList implements Extension {
tags AS t1,
tags AS t3
WHERE
it1.image_id=?
it1.image_id=:image_id
AND it1.tag_id=it2.tag_id
AND it2.image_id=it3.image_id
AND t1.tag != 'tagme'
@ -249,9 +249,9 @@ class TagList implements Extension {
AND t3.id = it3.tag_id
GROUP BY it3.tag_id
ORDER BY calc_count DESC
LIMIT ?
LIMIT :tag_list_length
";
$args = array($image->id, $config->get_int('tag_list_length'));
$args = array("image_id"=>$image->id, "tag_list_length"=>$config->get_int('tag_list_length'));
$tags = $database->get_all($query, $args);
if(count($tags) > 0) {
@ -267,11 +267,11 @@ class TagList implements Extension {
SELECT tags.tag, tags.count as calc_count
FROM tags, image_tags
WHERE tags.id = image_tags.tag_id
AND image_tags.image_id = ?
AND image_tags.image_id = :image_id
ORDER BY calc_count DESC
LIMIT ?
LIMIT :tag_list_length
";
$args = array($image->id, $config->get_int('tag_list_length'));
$args = array("image_id"=>$image->id, "tag_list_length"=>$config->get_int('tag_list_length'));
$tags = $database->get_all($query, $args);
if(count($tags) > 0) {
@ -288,9 +288,9 @@ class TagList implements Extension {
FROM tags
WHERE count > 0
ORDER BY count DESC
LIMIT ?
LIMIT :tag_list_length
";
$args = array($config->get_int('tag_list_length'));
$args = array("tag_list_length"=>$config->get_int('tag_list_length'));
$tags = $database->get_all($query, $args);
if(count($tags) > 0) {
@ -310,9 +310,9 @@ class TagList implements Extension {
foreach($wild_tags as $tag) {
$tag = str_replace("*", "%", $tag);
$tag = str_replace("?", "_", $tag);
$tag_ids = $database->db->GetCol("SELECT id FROM tags WHERE tag LIKE ?", array($tag));
$tag_ids = $database->get_col("SELECT id FROM tags WHERE tag LIKE :tag", array("tag"=>$tag));
// $search_tags = array_merge($search_tags,
// $database->db->GetCol("SELECT tag FROM tags WHERE tag LIKE ?", array($tag)));
// $database->db->GetCol("SELECT tag FROM tags WHERE tag LIKE :tag", array("tag"=>$tag)));
$tag_id_array = array_merge($tag_id_array, $tag_ids);
$tags_ok = count($tag_ids) > 0;
if(!$tags_ok) break;
@ -334,12 +334,11 @@ class TagList implements Extension {
AND it2.tag_id = t2.id
GROUP BY t2.tag
ORDER BY calc_count
DESC LIMIT ?
DESC LIMIT :limit
";
$args = array($config->get_int('tag_list_length'));
$args = array("limit"=>$config->get_int('tag_list_length'));
$related_tags = $database->get_all($query, $args);
print $database->db->ErrorMsg();
if(count($related_tags) > 0) {
$this->theme->display_refine_block($page, $related_tags, $wild_tags);
}

View File

@ -286,7 +286,7 @@ class UserPage extends SimpleExtension {
"Username contains invalid characters. Allowed characters are ".
"letters, numbers, dash, and underscore");
}
else if($database->db->GetRow("SELECT * FROM users WHERE name = ?", array($name))) {
else if($database->get_row("SELECT * FROM users WHERE name = ?", array($name))) {
throw new UserCreationException("That username is already taken");
}
}
@ -298,13 +298,13 @@ class UserPage extends SimpleExtension {
$email = (!empty($event->email)) ? $event->email : null;
// if there are currently no admins, the new user should be one
$need_admin = ($database->db->GetOne("SELECT COUNT(*) FROM users WHERE admin IN ('Y', 't', '1')") == 0);
$need_admin = ($database->get_one("SELECT COUNT(*) FROM users WHERE admin IN ('Y', 't', '1')") == 0);
$admin = $need_admin ? 'Y' : 'N';
$database->Execute(
"INSERT INTO users (name, pass, joindate, email, admin) VALUES (?, ?, now(), ?, ?)",
array($event->username, $hash, $email, $admin));
$uid = $database->db->Insert_ID();
$uid = $database->db->lastInsertId();
log_info("user", "Created User #$uid ({$event->username})");
}
@ -427,28 +427,28 @@ class UserPage extends SimpleExtension {
// ips {{{
private function count_upload_ips($duser) {
global $database;
$rows = $database->db->GetAssoc("
$rows = $database->get_pairs("
SELECT
owner_ip,
COUNT(images.id) AS count,
MAX(posted) AS most_recent
FROM images
WHERE owner_id=?
WHERE owner_id=:id
GROUP BY owner_ip
ORDER BY most_recent DESC", array($duser->id), false, true);
ORDER BY most_recent DESC", array("id"=>$duser->id));
return $rows;
}
private function count_comment_ips($duser) {
global $database;
$rows = $database->db->GetAssoc("
$rows = $database->get_pairs("
SELECT
owner_ip,
COUNT(comments.id) AS count,
MAX(posted) AS most_recent
FROM comments
WHERE owner_id=?
WHERE owner_id=:id
GROUP BY owner_ip
ORDER BY most_recent DESC", array($duser->id), false, true);
ORDER BY most_recent DESC", array("id"=>$duser->id));
return $rows;
}
// }}}

View File

@ -84,7 +84,8 @@ try {
// connect to the database
$database = new Database();
$database->db->fnExecute = '_count_execs';
//$database->db->fnExecute = '_count_execs'; // FIXME: PDO equivalent
$database->db->beginTransaction();
$config = new DatabaseConfig($database);
@ -129,19 +130,13 @@ try {
send_event(_get_page_request());
$page->display();
// for databases which support transactions
// XXX: removed since we never start a transaction, and postgres
// fills the disk with warnings about that
//if($database->engine->name != "sqlite") {
// $database->db->CommitTrans(true);
//}
$database->db->commit();
_end_cache();
}
catch(Exception $e) {
$version = VERSION;
$message = $e->getMessage();
//$trace = var_dump($e->getTrace());
header("HTTP/1.0 500 Internal Error");
print <<<EOD
<html>
@ -154,5 +149,6 @@ catch(Exception $e) {
</body>
</html>
EOD;
$database->db->rollback();
}
?>

View File

@ -323,7 +323,7 @@ function insert_defaults($dsn) { // {{{
$user_insert = $db->Prepare("INSERT INTO users(name, pass, joindate, admin) VALUES(?, ?, now(), ?)");
$db->Execute($user_insert, Array('Anonymous', null, 'N'));
$db->Execute($config_insert, Array('anon_id', $db->Insert_ID()));
$db->Execute($config_insert, Array('anon_id', $db->lastInsertId()));
if(check_im_version() > 0) {
$db->Execute($config_insert, Array('thumb_engine', 'convert'));

View File

@ -1,318 +0,0 @@
<?php
// security - hide paths
if (!defined('ADODB_DIR')) die();
global $ADODB_INCLUDED_CSV;
$ADODB_INCLUDED_CSV = 1;
/*
V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://adodb.sourceforge.net
Library for CSV serialization. This is used by the csv/proxy driver and is the
CacheExecute() serialization format.
==== NOTE ====
Format documented at http://php.weblogs.com/ADODB_CSV
==============
*/
/**
* convert a recordset into special format
*
* @param rs the recordset
*
* @return the CSV formated data
*/
function _rs2serialize(&$rs,$conn=false,$sql='')
{
$max = ($rs) ? $rs->FieldCount() : 0;
if ($sql) $sql = urlencode($sql);
// metadata setup
if ($max <= 0 || $rs->dataProvider == 'empty') { // is insert/update/delete
if (is_object($conn)) {
$sql .= ','.$conn->Affected_Rows();
$sql .= ','.$conn->Insert_ID();
} else
$sql .= ',,';
$text = "====-1,0,$sql\n";
return $text;
}
$tt = ($rs->timeCreated) ? $rs->timeCreated : time();
## changed format from ====0 to ====1
$line = "====1,$tt,$sql\n";
if ($rs->databaseType == 'array') {
$rows = $rs->_array;
} else {
$rows = array();
while (!$rs->EOF) {
$rows[] = $rs->fields;
$rs->MoveNext();
}
}
for($i=0; $i < $max; $i++) {
$o = $rs->FetchField($i);
$flds[] = $o;
}
$savefetch = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
$class = $rs->connection->arrayClass;
$rs2 = new $class();
$rs2->timeCreated = $rs->timeCreated; # memcache fix
$rs2->sql = $rs->sql;
$rs2->oldProvider = $rs->dataProvider;
$rs2->InitArrayFields($rows,$flds);
$rs2->fetchMode = $savefetch;
return $line.serialize($rs2);
}
/**
* Open CSV file and convert it into Data.
*
* @param url file/ftp/http url
* @param err returns the error message
* @param timeout dispose if recordset has been alive for $timeout secs
*
* @return recordset, or false if error occured. If no
* error occurred in sql INSERT/UPDATE/DELETE,
* empty recordset is returned
*/
function csv2rs($url,&$err,$timeout=0, $rsclass='ADORecordSet_array')
{
$false = false;
$err = false;
$fp = @fopen($url,'rb');
if (!$fp) {
$err = $url.' file/URL not found';
return $false;
}
@flock($fp, LOCK_SH);
$arr = array();
$ttl = 0;
if ($meta = fgetcsv($fp, 32000, ",")) {
// check if error message
if (strncmp($meta[0],'****',4) === 0) {
$err = trim(substr($meta[0],4,1024));
fclose($fp);
return $false;
}
// check for meta data
// $meta[0] is -1 means return an empty recordset
// $meta[1] contains a time
if (strncmp($meta[0], '====',4) === 0) {
if ($meta[0] == "====-1") {
if (sizeof($meta) < 5) {
$err = "Corrupt first line for format -1";
fclose($fp);
return $false;
}
fclose($fp);
if ($timeout > 0) {
$err = " Illegal Timeout $timeout ";
return $false;
}
$rs = new $rsclass($val=true);
$rs->fields = array();
$rs->timeCreated = $meta[1];
$rs->EOF = true;
$rs->_numOfFields = 0;
$rs->sql = urldecode($meta[2]);
$rs->affectedrows = (integer)$meta[3];
$rs->insertid = $meta[4];
return $rs;
}
# Under high volume loads, we want only 1 thread/process to _write_file
# so that we don't have 50 processes queueing to write the same data.
# We use probabilistic timeout, ahead of time.
#
# -4 sec before timeout, give processes 1/32 chance of timing out
# -2 sec before timeout, give processes 1/16 chance of timing out
# -1 sec after timeout give processes 1/4 chance of timing out
# +0 sec after timeout, give processes 100% chance of timing out
if (sizeof($meta) > 1) {
if($timeout >0){
$tdiff = (integer)( $meta[1]+$timeout - time());
if ($tdiff <= 2) {
switch($tdiff) {
case 4:
case 3:
if ((rand() & 31) == 0) {
fclose($fp);
$err = "Timeout 3";
return $false;
}
break;
case 2:
if ((rand() & 15) == 0) {
fclose($fp);
$err = "Timeout 2";
return $false;
}
break;
case 1:
if ((rand() & 3) == 0) {
fclose($fp);
$err = "Timeout 1";
return $false;
}
break;
default:
fclose($fp);
$err = "Timeout 0";
return $false;
} // switch
} // if check flush cache
}// (timeout>0)
$ttl = $meta[1];
}
//================================================
// new cache format - use serialize extensively...
if ($meta[0] === '====1') {
// slurp in the data
$MAXSIZE = 128000;
$text = fread($fp,$MAXSIZE);
if (strlen($text)) {
while ($txt = fread($fp,$MAXSIZE)) {
$text .= $txt;
}
}
fclose($fp);
$rs = unserialize($text);
if (is_object($rs)) $rs->timeCreated = $ttl;
else {
$err = "Unable to unserialize recordset";
//echo htmlspecialchars($text),' !--END--!<p>';
}
return $rs;
}
$meta = false;
$meta = fgetcsv($fp, 32000, ",");
if (!$meta) {
fclose($fp);
$err = "Unexpected EOF 1";
return $false;
}
}
// Get Column definitions
$flds = array();
foreach($meta as $o) {
$o2 = explode(':',$o);
if (sizeof($o2)!=3) {
$arr[] = $meta;
$flds = false;
break;
}
$fld = new ADOFieldObject();
$fld->name = urldecode($o2[0]);
$fld->type = $o2[1];
$fld->max_length = $o2[2];
$flds[] = $fld;
}
} else {
fclose($fp);
$err = "Recordset had unexpected EOF 2";
return $false;
}
// slurp in the data
$MAXSIZE = 128000;
$text = '';
while ($txt = fread($fp,$MAXSIZE)) {
$text .= $txt;
}
fclose($fp);
@$arr = unserialize($text);
//var_dump($arr);
if (!is_array($arr)) {
$err = "Recordset had unexpected EOF (in serialized recordset)";
if (get_magic_quotes_runtime()) $err .= ". Magic Quotes Runtime should be disabled!";
return $false;
}
$rs = new $rsclass();
$rs->timeCreated = $ttl;
$rs->InitArrayFields($arr,$flds);
return $rs;
}
/**
* Save a file $filename and its $contents (normally for caching) with file locking
* Returns true if ok, false if fopen/fwrite error, 0 if rename error (eg. file is locked)
*/
function adodb_write_file($filename, $contents,$debug=false)
{
# http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows
# So to simulate locking, we assume that rename is an atomic operation.
# First we delete $filename, then we create a $tempfile write to it and
# rename to the desired $filename. If the rename works, then we successfully
# modified the file exclusively.
# What a stupid need - having to simulate locking.
# Risks:
# 1. $tempfile name is not unique -- very very low
# 2. unlink($filename) fails -- ok, rename will fail
# 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs
# 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated
if (strncmp(PHP_OS,'WIN',3) === 0) {
// skip the decimal place
$mtime = substr(str_replace(' ','_',microtime()),2);
// getmypid() actually returns 0 on Win98 - never mind!
$tmpname = $filename.uniqid($mtime).getmypid();
if (!($fd = @fopen($tmpname,'w'))) return false;
if (fwrite($fd,$contents)) $ok = true;
else $ok = false;
fclose($fd);
if ($ok) {
@chmod($tmpname,0644);
// the tricky moment
@unlink($filename);
if (!@rename($tmpname,$filename)) {
unlink($tmpname);
$ok = 0;
}
if (!$ok) {
if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));
}
}
return $ok;
}
if (!($fd = @fopen($filename, 'a'))) return false;
if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {
if (fwrite( $fd, $contents )) $ok = true;
else $ok = false;
fclose($fd);
@chmod($filename,0644);
}else {
fclose($fd);
if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");
$ok = false;
}
return $ok;
}
?>

View File

@ -1,258 +0,0 @@
<?php
/**
* @version V5.06 16 Oct 2008 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* The following code is adapted from the PEAR DB error handling code.
* Portions (c)1997-2002 The PHP Group.
*/
if (!defined("DB_ERROR")) define("DB_ERROR",-1);
if (!defined("DB_ERROR_SYNTAX")) {
define("DB_ERROR_SYNTAX", -2);
define("DB_ERROR_CONSTRAINT", -3);
define("DB_ERROR_NOT_FOUND", -4);
define("DB_ERROR_ALREADY_EXISTS", -5);
define("DB_ERROR_UNSUPPORTED", -6);
define("DB_ERROR_MISMATCH", -7);
define("DB_ERROR_INVALID", -8);
define("DB_ERROR_NOT_CAPABLE", -9);
define("DB_ERROR_TRUNCATED", -10);
define("DB_ERROR_INVALID_NUMBER", -11);
define("DB_ERROR_INVALID_DATE", -12);
define("DB_ERROR_DIVZERO", -13);
define("DB_ERROR_NODBSELECTED", -14);
define("DB_ERROR_CANNOT_CREATE", -15);
define("DB_ERROR_CANNOT_DELETE", -16);
define("DB_ERROR_CANNOT_DROP", -17);
define("DB_ERROR_NOSUCHTABLE", -18);
define("DB_ERROR_NOSUCHFIELD", -19);
define("DB_ERROR_NEED_MORE_DATA", -20);
define("DB_ERROR_NOT_LOCKED", -21);
define("DB_ERROR_VALUE_COUNT_ON_ROW", -22);
define("DB_ERROR_INVALID_DSN", -23);
define("DB_ERROR_CONNECT_FAILED", -24);
define("DB_ERROR_EXTENSION_NOT_FOUND",-25);
define("DB_ERROR_NOSUCHDB", -25);
define("DB_ERROR_ACCESS_VIOLATION", -26);
}
function adodb_errormsg($value)
{
global $ADODB_LANG,$ADODB_LANG_ARRAY;
if (empty($ADODB_LANG)) $ADODB_LANG = 'en';
if (isset($ADODB_LANG_ARRAY['LANG']) && $ADODB_LANG_ARRAY['LANG'] == $ADODB_LANG) ;
else {
include_once(ADODB_DIR."/lang/adodb-$ADODB_LANG.inc.php");
}
return isset($ADODB_LANG_ARRAY[$value]) ? $ADODB_LANG_ARRAY[$value] : $ADODB_LANG_ARRAY[DB_ERROR];
}
function adodb_error($provider,$dbType,$errno)
{
//var_dump($errno);
if (is_numeric($errno) && $errno == 0) return 0;
switch($provider) {
case 'mysql': $map = adodb_error_mysql(); break;
case 'oracle':
case 'oci8': $map = adodb_error_oci8(); break;
case 'ibase': $map = adodb_error_ibase(); break;
case 'odbc': $map = adodb_error_odbc(); break;
case 'mssql':
case 'sybase': $map = adodb_error_mssql(); break;
case 'informix': $map = adodb_error_ifx(); break;
case 'postgres': return adodb_error_pg($errno); break;
case 'sqlite': return $map = adodb_error_sqlite(); break;
default:
return DB_ERROR;
}
//print_r($map);
//var_dump($errno);
if (isset($map[$errno])) return $map[$errno];
return DB_ERROR;
}
//**************************************************************************************
function adodb_error_pg($errormsg)
{
if (is_numeric($errormsg)) return (integer) $errormsg;
static $error_regexps = array(
'/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/i' => DB_ERROR_NOSUCHTABLE,
'/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/i' => DB_ERROR_ALREADY_EXISTS,
'/divide by zero$/i' => DB_ERROR_DIVZERO,
'/pg_atoi: error in .*: can\'t parse /i' => DB_ERROR_INVALID_NUMBER,
'/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/i' => DB_ERROR_NOSUCHFIELD,
'/parser: parse error at or near \"/i' => DB_ERROR_SYNTAX,
'/referential integrity violation/i' => DB_ERROR_CONSTRAINT,
'/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*|duplicate key.*violates unique constraint/i'
=> DB_ERROR_ALREADY_EXISTS
);
reset($error_regexps);
while (list($regexp,$code) = each($error_regexps)) {
if (preg_match($regexp, $errormsg)) {
return $code;
}
}
// Fall back to DB_ERROR if there was no mapping.
return DB_ERROR;
}
function adodb_error_odbc()
{
static $MAP = array(
'01004' => DB_ERROR_TRUNCATED,
'07001' => DB_ERROR_MISMATCH,
'21S01' => DB_ERROR_MISMATCH,
'21S02' => DB_ERROR_MISMATCH,
'22003' => DB_ERROR_INVALID_NUMBER,
'22008' => DB_ERROR_INVALID_DATE,
'22012' => DB_ERROR_DIVZERO,
'23000' => DB_ERROR_CONSTRAINT,
'24000' => DB_ERROR_INVALID,
'34000' => DB_ERROR_INVALID,
'37000' => DB_ERROR_SYNTAX,
'42000' => DB_ERROR_SYNTAX,
'IM001' => DB_ERROR_UNSUPPORTED,
'S0000' => DB_ERROR_NOSUCHTABLE,
'S0001' => DB_ERROR_NOT_FOUND,
'S0002' => DB_ERROR_NOSUCHTABLE,
'S0011' => DB_ERROR_ALREADY_EXISTS,
'S0012' => DB_ERROR_NOT_FOUND,
'S0021' => DB_ERROR_ALREADY_EXISTS,
'S0022' => DB_ERROR_NOT_FOUND,
'S1000' => DB_ERROR_NOSUCHTABLE,
'S1009' => DB_ERROR_INVALID,
'S1090' => DB_ERROR_INVALID,
'S1C00' => DB_ERROR_NOT_CAPABLE
);
return $MAP;
}
function adodb_error_ibase()
{
static $MAP = array(
-104 => DB_ERROR_SYNTAX,
-150 => DB_ERROR_ACCESS_VIOLATION,
-151 => DB_ERROR_ACCESS_VIOLATION,
-155 => DB_ERROR_NOSUCHTABLE,
-157 => DB_ERROR_NOSUCHFIELD,
-158 => DB_ERROR_VALUE_COUNT_ON_ROW,
-170 => DB_ERROR_MISMATCH,
-171 => DB_ERROR_MISMATCH,
-172 => DB_ERROR_INVALID,
-204 => DB_ERROR_INVALID,
-205 => DB_ERROR_NOSUCHFIELD,
-206 => DB_ERROR_NOSUCHFIELD,
-208 => DB_ERROR_INVALID,
-219 => DB_ERROR_NOSUCHTABLE,
-297 => DB_ERROR_CONSTRAINT,
-530 => DB_ERROR_CONSTRAINT,
-803 => DB_ERROR_CONSTRAINT,
-551 => DB_ERROR_ACCESS_VIOLATION,
-552 => DB_ERROR_ACCESS_VIOLATION,
-922 => DB_ERROR_NOSUCHDB,
-923 => DB_ERROR_CONNECT_FAILED,
-924 => DB_ERROR_CONNECT_FAILED
);
return $MAP;
}
function adodb_error_ifx()
{
static $MAP = array(
'-201' => DB_ERROR_SYNTAX,
'-206' => DB_ERROR_NOSUCHTABLE,
'-217' => DB_ERROR_NOSUCHFIELD,
'-329' => DB_ERROR_NODBSELECTED,
'-1204' => DB_ERROR_INVALID_DATE,
'-1205' => DB_ERROR_INVALID_DATE,
'-1206' => DB_ERROR_INVALID_DATE,
'-1209' => DB_ERROR_INVALID_DATE,
'-1210' => DB_ERROR_INVALID_DATE,
'-1212' => DB_ERROR_INVALID_DATE
);
return $MAP;
}
function adodb_error_oci8()
{
static $MAP = array(
1 => DB_ERROR_ALREADY_EXISTS,
900 => DB_ERROR_SYNTAX,
904 => DB_ERROR_NOSUCHFIELD,
923 => DB_ERROR_SYNTAX,
942 => DB_ERROR_NOSUCHTABLE,
955 => DB_ERROR_ALREADY_EXISTS,
1476 => DB_ERROR_DIVZERO,
1722 => DB_ERROR_INVALID_NUMBER,
2289 => DB_ERROR_NOSUCHTABLE,
2291 => DB_ERROR_CONSTRAINT,
2449 => DB_ERROR_CONSTRAINT
);
return $MAP;
}
function adodb_error_mssql()
{
static $MAP = array(
208 => DB_ERROR_NOSUCHTABLE,
2601 => DB_ERROR_ALREADY_EXISTS
);
return $MAP;
}
function adodb_error_sqlite()
{
static $MAP = array(
1 => DB_ERROR_SYNTAX
);
return $MAP;
}
function adodb_error_mysql()
{
static $MAP = array(
1004 => DB_ERROR_CANNOT_CREATE,
1005 => DB_ERROR_CANNOT_CREATE,
1006 => DB_ERROR_CANNOT_CREATE,
1007 => DB_ERROR_ALREADY_EXISTS,
1008 => DB_ERROR_CANNOT_DROP,
1045 => DB_ERROR_ACCESS_VIOLATION,
1046 => DB_ERROR_NODBSELECTED,
1049 => DB_ERROR_NOSUCHDB,
1050 => DB_ERROR_ALREADY_EXISTS,
1051 => DB_ERROR_NOSUCHTABLE,
1054 => DB_ERROR_NOSUCHFIELD,
1062 => DB_ERROR_ALREADY_EXISTS,
1064 => DB_ERROR_SYNTAX,
1100 => DB_ERROR_NOT_LOCKED,
1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
1146 => DB_ERROR_NOSUCHTABLE,
1048 => DB_ERROR_CONSTRAINT,
2002 => DB_ERROR_CONNECT_FAILED,
2005 => DB_ERROR_CONNECT_FAILED
);
return $MAP;
}
?>

View File

@ -1,82 +0,0 @@
<?php
/**
* @version V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Exception-handling code using PHP5 exceptions (try-catch-throw).
*/
if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR);
define('ADODB_ERROR_HANDLER','adodb_throw');
class ADODB_Exception extends Exception {
var $dbms;
var $fn;
var $sql = '';
var $params = '';
var $host = '';
var $database = '';
function __construct($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)
{
switch($fn) {
case 'EXECUTE':
$this->sql = $p1;
$this->params = $p2;
$s = "$dbms error: [$errno: $errmsg] in $fn(\"$p1\")\n";
break;
case 'PCONNECT':
case 'CONNECT':
$user = $thisConnection->user;
$s = "$dbms error: [$errno: $errmsg] in $fn($p1, '$user', '****', $p2)\n";
break;
default:
$s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";
break;
}
$this->dbms = $dbms;
if ($thisConnection) {
$this->host = $thisConnection->host;
$this->database = $thisConnection->database;
}
$this->fn = $fn;
$this->msg = $errmsg;
if (!is_numeric($errno)) $errno = -1;
parent::__construct($s,$errno);
}
}
/**
* Default Error Handler. This will be called with the following params
*
* @param $dbms the RDBMS you are connecting to
* @param $fn the name of the calling function (in uppercase)
* @param $errno the native error number from the database
* @param $errmsg the native error msg from the database
* @param $p1 $fn specific parameter - see below
* @param $P2 $fn specific parameter - see below
*/
function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)
{
global $ADODB_EXCEPTION;
if (error_reporting() == 0) return; // obey @ protocol
if (is_string($ADODB_EXCEPTION)) $errfn = $ADODB_EXCEPTION;
else $errfn = 'ADODB_EXCEPTION';
throw new $errfn($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection);
}
?>

View File

@ -1,30 +0,0 @@
<?php
/*
V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
Declares the ADODB Base Class for PHP5 "ADODB_BASE_RS", and supports iteration with
the ADODB_Iterator class.
$rs = $db->Execute("select * from adoxyz");
foreach($rs as $k => $v) {
echo $k; print_r($v); echo "<br>";
}
Iterator code based on http://cvs.php.net/cvs.php/php-src/ext/spl/examples/cachingiterator.inc?login=2
Moved to adodb.inc.php to improve performance.
*/
?>

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +0,0 @@
<?php
/*
V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
*/
class ADODB_BASE_RS {
}
?>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,795 +0,0 @@
<?php
/*
V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 8.
MySQL code that does not support transactions. Use mysqlt if you need transactions.
Requires mysql client. Works on Windows and Unix.
28 Feb 2001: MetaColumns bug fix - suggested by Freek Dijkstra (phpeverywhere@macfreek.com)
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
if (! defined("_ADODB_MYSQL_LAYER")) {
define("_ADODB_MYSQL_LAYER", 1 );
class ADODB_mysql extends ADOConnection {
var $databaseType = 'mysql';
var $dataProvider = 'mysql';
var $hasInsertID = true;
var $hasAffectedRows = true;
var $metaTablesSQL = "SHOW TABLES";
var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasLimit = true;
var $hasMoveFirst = true;
var $hasGenID = true;
var $isoDates = true; // accepts dates in ISO format
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
var $hasTransactions = false;
var $forceNewConnect = false;
var $poorAffectedRows = true;
var $clientFlags = 0;
var $substr = "substring";
var $nameQuote = '`'; /// string to use to quote identifiers and names
var $compat323 = false; // true if compat with mysql 3.23
function ADODB_mysql()
{
if (defined('ADODB_EXTENSION')) $this->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 (is_null($s)) return 'NULL';
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)
{
global $ADODB_GETONE_EOF;
if ($this->compat323 == false && strncasecmp($sql,'sele',4) == 0) {
$rs = $this->SelectLimit($sql,1,-1,$inputarr);
if ($rs) {
$rs->Close();
if ($rs->EOF) return $ADODB_GETONE_EOF;
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 $_genSeqCountSQL = "select count(*) from %s";
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));
$cnt = $this->GetOne(sprintf($this->_genSeqCountSQL,$seqname));
if (!$cnt) $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
$rs = $this->Execute($getnext);
}
if ($rs) {
$this->genID = mysql_insert_id($this->_connectionID);
$rs->Close();
} else
$this->genID = 0;
$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, $normalize=true)
{
$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 || strpos($type,'binary') !== false);
$fld->unsigned = (strpos($type,'unsigned') !== false);
$fld->zerofill = (strpos($type,'zerofill') !== 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=false)
{
//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" <jgonzalez#innox.com.mx>
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 = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];
} 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);
}
// see https://sourceforge.net/tracker/index.php?func=detail&aid=2287278&group_id=42718&atid=433976
if (!isset($foreign_keys[$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);
if ($o) $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
if ($o) $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);
if ($o) $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" <mille562@pilot.msu.edu>
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':
case 'BINARY':
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);
}
}
}
?>

View File

@ -1,14 +0,0 @@
<?php
/*
V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
NOTE: Since 3.31, this file is no longer used, and the "postgres" driver is
remapped to "postgres7". Maintaining multiple postgres drivers is no easy
job, so hopefully this will ensure greater consistency and fewer bugs.
*/
?>

File diff suppressed because it is too large Load Diff

View File

@ -1,313 +0,0 @@
<?php
/*
V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
Postgres7 support.
28 Feb 2001: Currently indicate that we support LIMIT
01 Dec 2001: dannym added support for default values
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
include_once(ADODB_DIR."/drivers/adodb-postgres64.inc.php");
class ADODB_postgres7 extends ADODB_postgres64 {
var $databaseType = 'postgres7';
var $hasLimit = true; // set to true for pgsql 6.5+ only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
var $ansiOuter = true;
var $charSet = true; //set to true for Postgres 7 and above - PG client supports encodings
function ADODB_postgres7()
{
$this->ADODB_postgres64();
if (ADODB_ASSOC_CASE !== 2) {
$this->rsPrefix .= 'assoc_';
}
$this->_bindInputArray = PHP_VERSION >= 5.1;
}
// the following should be compat with postgresql 7.2,
// which makes obsolete the LIMIT limit,offset syntax
function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
{
$offsetStr = ($offset >= 0) ? " OFFSET ".((integer)$offset) : '';
$limitStr = ($nrows >= 0) ? " LIMIT ".((integer)$nrows) : '';
if ($secs2cache)
$rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
else
$rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr);
return $rs;
}
/*
function Prepare($sql)
{
$info = $this->ServerInfo();
if ($info['version']>=7.3) {
return array($sql,false);
}
return $sql;
}
*/
/*
I discovered that the MetaForeignKeys method no longer worked for Postgres 8.3.
I went ahead and modified it to work for both 8.2 and 8.3.
Please feel free to include this change in your next release of adodb.
William Kolodny [William.Kolodny#gt-t.net]
*/
function MetaForeignKeys($table, $owner=false, $upper=false)
{
$sql="
SELECT fum.ftblname AS lookup_table, split_part(fum.rf, ')'::text, 1) AS lookup_field,
fum.ltable AS dep_table, split_part(fum.lf, ')'::text, 1) AS dep_field
FROM (
SELECT fee.ltable, fee.ftblname, fee.consrc, split_part(fee.consrc,'('::text, 2) AS lf,
split_part(fee.consrc, '('::text, 3) AS rf
FROM (
SELECT foo.relname AS ltable, foo.ftblname,
pg_get_constraintdef(foo.oid) AS consrc
FROM (
SELECT c.oid, c.conname AS name, t.relname, ft.relname AS ftblname
FROM pg_constraint c
JOIN pg_class t ON (t.oid = c.conrelid)
JOIN pg_class ft ON (ft.oid = c.confrelid)
JOIN pg_namespace nft ON (nft.oid = ft.relnamespace)
LEFT JOIN pg_description ds ON (ds.objoid = c.oid)
JOIN pg_namespace n ON (n.oid = t.relnamespace)
WHERE c.contype = 'f'::\"char\"
ORDER BY t.relname, n.nspname, c.conname, c.oid
) foo
) fee) fum
WHERE fum.ltable='".strtolower($table)."'
ORDER BY fum.ftblname, fum.ltable, split_part(fum.lf, ')'::text, 1)
";
$rs = $this->Execute($sql);
if (!$rs || $rs->EOF) return false;
$a = array();
while (!$rs->EOF) {
if ($upper) {
$a[strtoupper($rs->Fields('lookup_table'))][] = strtoupper(str_replace('"','',$rs->Fields('dep_field').'='.$rs->Fields('lookup_field')));
} else {
$a[$rs->Fields('lookup_table')][] = str_replace('"','',$rs->Fields('dep_field').'='.$rs->Fields('lookup_field'));
}
$rs->MoveNext();
}
return $a;
}
// from Edward Jaramilla, improved version - works on pg 7.4
function _old_MetaForeignKeys($table, $owner=false, $upper=false)
{
$sql = 'SELECT t.tgargs as args
FROM
pg_trigger t,pg_class c,pg_proc p
WHERE
t.tgenabled AND
t.tgrelid = c.oid AND
t.tgfoid = p.oid AND
p.proname = \'RI_FKey_check_ins\' AND
c.relname = \''.strtolower($table).'\'
ORDER BY
t.tgrelid';
$rs = $this->Execute($sql);
if (!$rs || $rs->EOF) return false;
$arr = $rs->GetArray();
$a = array();
foreach($arr as $v) {
$data = explode(chr(0), $v['args']);
$size = count($data)-1; //-1 because the last node is empty
for($i = 4; $i < $size; $i++) {
if ($upper)
$a[strtoupper($data[2])][] = strtoupper($data[$i].'='.$data[++$i]);
else
$a[$data[2]][] = $data[$i].'='.$data[++$i];
}
}
return $a;
}
function _query($sql,$inputarr=false)
{
if (! $this->_bindInputArray) {
// We don't have native support for parameterized queries, so let's emulate it at the parent
return ADODB_postgres64::_query($sql, $inputarr);
}
$this->_errorMsg = false;
// -- added Cristiano da Cunha Duarte
if ($inputarr) {
$sqlarr = explode('?',trim($sql));
$sql = '';
$i = 1;
$last = sizeof($sqlarr)-1;
foreach($sqlarr as $v) {
if ($last < $i) $sql .= $v;
else $sql .= $v.' $'.$i;
$i++;
}
$rez = pg_query_params($this->_connectionID,$sql, $inputarr);
} else {
$rez = pg_query($this->_connectionID,$sql);
}
// check if no data returned, then no need to create real recordset
if ($rez && pg_numfields($rez) <= 0) {
if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') {
pg_freeresult($this->_resultid);
}
$this->_resultid = $rez;
return true;
}
return $rez;
}
// this is a set of functions for managing client encoding - very important if the encodings
// of your database and your output target (i.e. HTML) don't match
//for instance, you may have UNICODE database and server it on-site as WIN1251 etc.
// GetCharSet - get the name of the character set the client is using now
// the functions should work with Postgres 7.0 and above, the set of charsets supported
// depends on compile flags of postgres distribution - if no charsets were compiled into the server
// it will return 'SQL_ANSI' always
function GetCharSet()
{
//we will use ADO's builtin property charSet
$this->charSet = @pg_client_encoding($this->_connectionID);
if (!$this->charSet) {
return false;
} else {
return $this->charSet;
}
}
// SetCharSet - switch the client encoding
function SetCharSet($charset_name)
{
$this->GetCharSet();
if ($this->charSet !== $charset_name) {
$if = pg_set_client_encoding($this->_connectionID, $charset_name);
if ($if == "0" & $this->GetCharSet() == $charset_name) {
return true;
} else return false;
} else return true;
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordSet_postgres7 extends ADORecordSet_postgres64{
var $databaseType = "postgres7";
function ADORecordSet_postgres7($queryID,$mode=false)
{
$this->ADORecordSet_postgres64($queryID,$mode);
}
// 10% speedup to move MoveNext to child class
function MoveNext()
{
if (!$this->EOF) {
$this->_currentRow++;
if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
$this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
if (is_array($this->fields)) {
if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
return true;
}
}
$this->fields = false;
$this->EOF = true;
}
return false;
}
}
class ADORecordSet_assoc_postgres7 extends ADORecordSet_postgres64{
var $databaseType = "postgres7";
function ADORecordSet_assoc_postgres7($queryID,$mode=false)
{
$this->ADORecordSet_postgres64($queryID,$mode);
}
function _fetch()
{
if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0)
return false;
$this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
if ($this->fields) {
if (isset($this->_blobArr)) $this->_fixblobs();
$this->_updatefields();
}
return (is_array($this->fields));
}
// Create associative array
function _updatefields()
{
if (ADODB_ASSOC_CASE == 2) return; // native
$arr = array();
$lowercase = (ADODB_ASSOC_CASE == 0);
foreach($this->fields as $k => $v) {
if (is_integer($k)) $arr[$k] = $v;
else {
if ($lowercase)
$arr[strtolower($k)] = $v;
else
$arr[strtoupper($k)] = $v;
}
}
$this->fields = $arr;
}
function MoveNext()
{
if (!$this->EOF) {
$this->_currentRow++;
if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
$this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
if (is_array($this->fields)) {
if ($this->fields) {
if (isset($this->_blobArr)) $this->_fixblobs();
$this->_updatefields();
}
return true;
}
}
$this->fields = false;
$this->EOF = true;
}
return false;
}
}
?>

View File

@ -1,12 +0,0 @@
<?php
/*
V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
NOTE: The "postgres8" driver is remapped to "postgres7".
*/
?>

View File

@ -1,398 +0,0 @@
<?php
/*
V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Latest version is available at http://adodb.sourceforge.net
SQLite info: http://www.hwaci.com/sw/sqlite/
Install Instructions:
====================
1. Place this in adodb/drivers
2. Rename the file, remove the .txt prefix.
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
class ADODB_sqlite extends ADOConnection {
var $databaseType = "sqlite";
var $replaceQuote = "''"; // string to use to replace quotes
var $concat_operator='||';
var $_errorNo = 0;
var $hasLimit = true;
var $hasInsertID = true; /// supports autoincrement ID?
var $hasAffectedRows = true; /// supports affected rows for update/delete?
var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name";
var $sysDate = "adodb_date('Y-m-d')";
var $sysTimeStamp = "adodb_date('Y-m-d H:i:s')";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
function ADODB_sqlite()
{
}
/*
function __get($name)
{
switch($name) {
case 'sysDate': return "'".date($this->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($table, $normalize=true)
{
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('$table')");
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, $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()
{
}
}
?>

View File

@ -1,62 +0,0 @@
<?php
/*
V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Portable version of sqlite driver, to make it more similar to other database drivers.
The main differences are
1. When selecting (joining) multiple tables, in assoc mode the table
names are included in the assoc keys in the "sqlite" driver.
In "sqlitepo" driver, the table names are stripped from the returned column names.
When this results in a conflict, the first field get preference.
Contributed by Herman Kuiper herman#ozuzo.net
*/
if (!defined('ADODB_DIR')) die();
include_once(ADODB_DIR.'/drivers/adodb-sqlite.inc.php');
class ADODB_sqlitepo extends ADODB_sqlite {
var $databaseType = 'sqlitepo';
function ADODB_sqlitepo()
{
$this->ADODB_sqlite();
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordset_sqlitepo extends ADORecordset_sqlite {
var $databaseType = 'sqlitepo';
function ADORecordset_sqlitepo($queryID,$mode=false)
{
$this->ADORecordset_sqlite($queryID,$mode);
}
// Modified to strip table names from returned fields
function _fetch($ignore_fields=false)
{
$this->fields = array();
$fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode);
if(is_array($fields))
foreach($fields as $n => $v)
{
if(($p = strpos($n, ".")) !== false)
$n = substr($n, $p+1);
$this->fields[$n] = $v;
}
return !empty($this->fields);
}
}
?>

View File

@ -1,182 +0,0 @@
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