From 64c0d080e12348a6a92d4f4dc1e474d8db08ba6c Mon Sep 17 00:00:00 2001 From: vargenau Date: Sat, 6 Oct 2012 10:28:33 +0000 Subject: [PATCH] Reformat code git-svn-id: svn://svn.code.sf.net/p/phpwiki/code/trunk@8398 96ab9672-09ca-45d6-a79d-3d69d39ca109 --- ImageTile.php | 89 +- RPC2.php | 5 +- SOAP.php | 162 +- admin/wiki2public.php | 6 +- configurator.php | 1495 +++-- index.php | 8 +- lib/AccessLog.php | 623 +- lib/ArchiveCleaner.php | 47 +- lib/AtomParser.php | 22 +- lib/BlockParser.php | 497 +- lib/CachedMarkup.php | 413 +- lib/Captcha.php | 154 +- lib/DbSession.php | 26 +- lib/DbSession/ADODB.php | 90 +- lib/DbSession/PDO.php | 82 +- lib/DbSession/SQL.php | 89 +- lib/DbSession/dba.php | 69 +- lib/DbaDatabase.php | 93 +- lib/DbaListSet.php | 68 +- lib/DbaPartition.php | 46 +- lib/EditToolbar.php | 439 +- lib/ErrorManager.php | 265 +- lib/ExternalReferrer.php | 118 +- lib/FileFinder.php | 165 +- lib/Google.php | 72 +- lib/HtmlElement.php | 398 +- lib/HtmlElement5.php | 398 +- lib/HtmlParser.php | 280 +- lib/HttpClient.php | 228 +- lib/IniConfig.php | 605 +- lib/InlineParser.php | 753 ++- lib/MailNotify.php | 158 +- lib/PageList.php | 1077 ++-- lib/PagePerm.php | 486 +- lib/PageType.php | 313 +- lib/RSSWriter091.php | 52 +- lib/Request.php | 631 +- lib/RssParser.php | 116 +- lib/RssWriter.php | 198 +- lib/RssWriter2.php | 49 +- lib/SemanticWeb.php | 327 +- lib/SpamBlocklist.php | 60 +- lib/Template.php | 88 +- lib/TextSearchQuery.php | 951 +-- lib/Units.php | 43 +- lib/WikiCallback.php | 41 +- lib/WikiDB.php | 736 ++- lib/WikiDB/ADODB.php | 48 +- lib/WikiDB/PDO.php | 39 +- lib/WikiDB/SQL.php | 61 +- lib/WikiDB/adodb/adodb-csvlib.inc.php | 325 +- lib/WikiDB/adodb/adodb-error.inc.php | 332 +- lib/WikiDB/adodb/adodb-errorhandler.inc.php | 58 +- lib/WikiDB/adodb/adodb-errorpear.inc.php | 75 +- lib/WikiDB/adodb/adodb-exceptions.inc.php | 69 +- lib/WikiDB/adodb/adodb-iterator.inc.php | 10 +- lib/WikiDB/adodb/adodb-lib.inc.php | 468 +- lib/WikiDB/adodb/adodb-pear.inc.php | 197 +- lib/WikiDB/adodb/adodb-php4.inc.php | 3 +- lib/WikiDB/adodb/adodb-time.inc.php | 612 +- lib/WikiDB/adodb/adodb.inc.php | 5348 +++++++++-------- lib/WikiDB/adodb/drivers/adodb-access.inc.php | 114 +- lib/WikiDB/adodb/drivers/adodb-ado.inc.php | 541 +- .../adodb/drivers/adodb-ado_access.inc.php | 21 +- .../adodb/drivers/adodb-ado_mssql.inc.php | 12 +- .../adodb/drivers/adodb-borland_ibase.inc.php | 44 +- lib/WikiDB/adodb/drivers/adodb-csv.inc.php | 304 +- lib/WikiDB/adodb/drivers/adodb-db2.inc.php | 375 +- lib/WikiDB/adodb/drivers/adodb-fbsql.inc.php | 429 +- .../adodb/drivers/adodb-firebird.inc.php | 45 +- lib/WikiDB/adodb/drivers/adodb-ibase.inc.php | 523 +- .../adodb/drivers/adodb-informix.inc.php | 37 +- .../adodb/drivers/adodb-informix72.inc.php | 221 +- lib/WikiDB/adodb/drivers/adodb-ldap.inc.php | 218 +- lib/WikiDB/adodb/drivers/adodb-mssql.inc.php | 390 +- .../adodb/drivers/adodb-mssqlnative.inc.php | 375 +- .../adodb/drivers/adodb-mssqlpo.inc.php | 53 +- lib/WikiDB/adodb/drivers/adodb-mysql.inc.php | 1095 ++-- lib/WikiDB/adodb/drivers/adodb-mysqli.inc.php | 1384 +++-- lib/WikiDB/adodb/drivers/adodb-mysqlt.inc.php | 17 +- .../adodb/drivers/adodb-netezza.inc.php | 104 +- lib/WikiDB/adodb/drivers/adodb-oci8.inc.php | 674 ++- lib/WikiDB/adodb/drivers/adodb-oci805.inc.php | 25 +- lib/WikiDB/adodb/drivers/adodb-oci8po.inc.php | 114 +- lib/WikiDB/adodb/drivers/adodb-odbc.inc.php | 275 +- .../adodb/drivers/adodb-odbc_mssql.inc.php | 165 +- .../adodb/drivers/adodb-odbc_oracle.inc.php | 29 +- lib/WikiDB/adodb/drivers/adodb-odbtp.inc.php | 270 +- .../adodb/drivers/adodb-odbtp_unicode.inc.php | 10 +- lib/WikiDB/adodb/drivers/adodb-oracle.inc.php | 259 +- .../adodb/drivers/adodb-postgres64.inc.php | 551 +- .../adodb/drivers/adodb-postgres7.inc.php | 107 +- lib/WikiDB/adodb/drivers/adodb-proxy.inc.php | 23 +- lib/WikiDB/adodb/drivers/adodb-sapdb.inc.php | 66 +- .../adodb/drivers/adodb-sqlanywhere.inc.php | 221 +- lib/WikiDB/adodb/drivers/adodb-sqlite.inc.php | 119 +- lib/WikiDB/adodb/drivers/adodb-sybase.inc.php | 223 +- lib/WikiDB/adodb/drivers/adodb-vfp.inc.php | 146 +- lib/WikiDB/adodb/readme.htm | 99 +- lib/WikiDB/backend.php | 323 +- lib/WikiDB/backend/ADODB.php | 884 +-- lib/WikiDB/backend/ADODB_mssql.php | 36 +- lib/WikiDB/backend/ADODB_mssqlnative.php | 84 +- lib/WikiDB/backend/ADODB_mysql.php | 114 +- lib/WikiDB/backend/ADODB_oci8po.php | 84 +- lib/WikiDB/backend/ADODB_postgres7.php | 111 +- lib/WikiDB/backend/ADODB_sqlite.php | 28 +- lib/WikiDB/backend/PDO.php | 838 +-- lib/WikiDB/backend/PDO_mysql.php | 64 +- lib/WikiDB/backend/PDO_oci8.php | 31 +- lib/WikiDB/backend/PDO_pgsql.php | 8 +- lib/WikiDB/backend/PearDB.php | 556 +- lib/WikiDB/backend/PearDB_ffpgsql.php | 340 +- lib/WikiDB/backend/PearDB_mysql.php | 108 +- lib/WikiDB/backend/PearDB_oci8.php | 71 +- lib/WikiDB/backend/PearDB_pgsql.php | 151 +- lib/WikiDB/backend/PearDB_sqlite.php | 46 +- lib/WikiDB/backend/cvs.php | 594 +- lib/WikiDB/backend/dba.php | 17 +- lib/WikiDB/backend/dbaBase.php | Bin 32149 -> 33258 bytes lib/WikiDB/backend/dumb/AllRevisionsIter.php | 26 +- lib/WikiDB/backend/dumb/BackLinkIter.php | 11 +- lib/WikiDB/backend/dumb/LinkSearchIter.php | 197 +- lib/WikiDB/backend/dumb/MostPopularIter.php | 22 +- lib/WikiDB/backend/dumb/MostRecentIter.php | 28 +- lib/WikiDB/backend/dumb/TextSearchIter.php | 54 +- lib/WikiDB/backend/dumb/WantedPagesIter.php | 17 +- lib/WikiDB/backend/file.php | 325 +- lib/WikiDB/backend/flatfile.php | 123 +- lib/WikiDB/cvs.php | 9 +- lib/WikiDB/dba.php | 12 +- lib/WikiDB/file.php | 9 +- lib/WikiDB/flatfile.php | 9 +- lib/WikiGroup.php | 448 +- lib/WikiPlugin.php | 259 +- lib/WikiPluginCached.php | 434 +- lib/WikiTheme.php | 915 +-- lib/WikiUser.php | 391 +- lib/WikiUser/AdoDb.php | 125 +- lib/WikiUser/BogoLogin.php | 9 +- lib/WikiUser/Db.php | 33 +- lib/WikiUser/EMailConfirm.php | 28 +- lib/WikiUser/Facebook.php | 33 +- lib/WikiUser/File.php | 39 +- lib/WikiUser/Forbidden.php | 5 +- lib/WikiUser/FusionForge.php | 19 +- lib/WikiUser/HttpAuth.php | 43 +- lib/WikiUser/HttpAuthUpper.php | 46 +- lib/WikiUser/IMAP.php | 45 +- lib/WikiUser/LDAP.php | 76 +- lib/WikiUser/LdapUpper.php | 11 +- lib/WikiUser/OpenID.php | 64 +- lib/WikiUser/POP3.php | 39 +- lib/WikiUser/PdoDb.php | 124 +- lib/WikiUser/PearDb.php | 98 +- lib/WikiUser/PersonalPage.php | 45 +- lib/WikiUser/Session.php | 27 +- lib/WikiUserNew.php | 1029 ++-- lib/WysiwygEdit.php | 71 +- lib/WysiwygEdit/FCKeditor.php | 69 +- lib/WysiwygEdit/Wikiwyg.php | 232 +- lib/WysiwygEdit/htmlarea2.php | 19 +- lib/WysiwygEdit/htmlarea3.php | 25 +- lib/WysiwygEdit/spaw.php | 19 +- lib/WysiwygEdit/tinymce.php | 26 +- lib/XMLRPC/utils.php | 261 +- lib/XMLRPC/xmlrpc.inc | 4101 ++++++------- lib/XMLRPC/xmlrpc_emu.inc | 1176 ++-- lib/XMLRPC/xmlrpcs.inc | 882 ++- lib/XMLRPC/xmlrpcs_emu.inc | 378 +- lib/XmlElement.php | 378 +- lib/XmlParser.php | 70 +- lib/XmlRpcClient.php | 43 +- lib/XmlRpcServer.php | 403 +- lib/config.php | 211 +- lib/diff.php | 197 +- lib/diff3.php | 103 +- lib/difflib.php | 618 +- lib/display.php | 171 +- lib/editpage.php | 562 +- lib/fortune.php | 78 +- lib/fpdf.php | 2959 ++++----- lib/fpdf/chinese.php | 730 ++- lib/fpdf/courier.php | 10 +- lib/fpdf/helvetica.php | 26 +- lib/fpdf/helveticab.php | 26 +- lib/fpdf/helveticabi.php | 26 +- lib/fpdf/helveticai.php | 26 +- lib/fpdf/japanese.php | 538 +- lib/fpdf/symbol.php | 26 +- lib/fpdf/times.php | 26 +- lib/fpdf/timesb.php | 26 +- lib/fpdf/timesbi.php | 26 +- lib/fpdf/timesi.php | 26 +- lib/fpdf/zapfdingbats.php | 26 +- lib/gif.php | 590 +- lib/imagecache.php | 30 +- lib/imdb.php | 320 +- lib/install.php | 10 +- lib/loadsave.php | 772 +-- lib/main.php | 811 +-- lib/nusoap/nusoap.php | 3128 +++++----- lib/pdf.php | 28 +- lib/plugin/SystemInfo.php | 2 +- lib/prepend.php | 64 +- lib/purgepage.php | 38 +- lib/removepage.php | 38 +- lib/spam_babycart.php | 15 +- lib/stdlib.php | 1057 ++-- lib/wikilens/Buddy.php | 86 +- lib/wikilens/CustomPrefs.php | 52 +- lib/wikilens/PageListColumns.php | 161 +- lib/wikilens/RatingsDb.php | 187 +- lib/wikilens/RatingsUser.php | 131 +- lib/wikilens/Utils.php | 28 +- lib/ziplib.php | 739 +-- passencrypt.php | 111 +- themes/Crao/themeinfo.php | 102 +- themes/Hawaiian/lib/random.php | 27 +- themes/Hawaiian/themeinfo.php | 133 +- themes/MacOSX/images/index.php | 50 +- themes/MacOSX/lib/RecentChanges.php | 46 +- themes/MacOSX/themeinfo.php | 160 +- themes/MonoBook/themeinfo.php | 189 +- themes/Portland/lib/RecentChanges.php | 78 +- themes/Portland/themeinfo.php | 114 +- themes/Sidebar/clock.php | 12 +- themes/Sidebar/hyperapplet.php | 12 +- themes/Sidebar/hyperwiki.php | 18 +- themes/Sidebar/themeinfo.php | 247 +- themes/SpaceWiki/lib/RecentChanges.php | 79 +- themes/SpaceWiki/themeinfo.php | 102 +- themes/Wordpress/lib/RecentChanges.php | 76 +- themes/Wordpress/themeinfo.php | 112 +- themes/alphatest.php | 99 +- themes/blog/lib/RecentChanges.php | 16 +- themes/blog/themeinfo.php | 131 +- themes/fusionforge/themeinfo.php | 60 +- themes/shamino_com/themeinfo.php | 132 +- themes/smaller/themeinfo.php | 9 +- themes/wikilens/themeinfo.php | 150 +- uploads/index.php | 4 +- view.php | 66 +- wikiadmin.php | 84 +- wikilist.php | 32 +- 245 files changed, 34684 insertions(+), 30813 deletions(-) diff --git a/ImageTile.php b/ImageTile.php index 34f6ca0d0..e194a9825 100644 --- a/ImageTile.php +++ b/ImageTile.php @@ -3,38 +3,38 @@ require_once 'lib/stdlib.php'; $remove = 0; -if (preg_match('/^(http|ftp|https):\/\//i',$_REQUEST['url'])) { +if (preg_match('/^(http|ftp|https):\/\//i', $_REQUEST['url'])) { $data_path = ''; list($usec, $sec) = explode(" ", microtime()); - $fp = fopen('config/config.ini','r'); - while ($config = fgetcsv($fp,1024,';')) { - if (preg_match('/DATA_PATH/',$config[0])) { - list($key,$value) = explode('=', $config[0]); - $data_path = trim($value).'/'; - break; - } + $fp = fopen('config/config.ini', 'r'); + while ($config = fgetcsv($fp, 1024, ';')) { + if (preg_match('/DATA_PATH/', $config[0])) { + list($key, $value) = explode('=', $config[0]); + $data_path = trim($value) . '/'; + break; + } } fclose($fp); - @mkdir($data_path."uploads/thumbs",0775); - $file = $data_path."uploads/thumbs/image_" . ((float)$usec + (float)$sec); + @mkdir($data_path . "uploads/thumbs", 0775); + $file = $data_path . "uploads/thumbs/image_" . ((float)$usec + (float)$sec); $source = url_get_contents($_REQUEST['url']); - @$fp = fopen($file,'w+'); + @$fp = fopen($file, 'w+'); if (!$fp) { - header ("Content-type: text/html"); + header("Content-type: text/html"); echo "ERROR : unable to open $file in write mode"; } - fwrite($fp,$source); + fwrite($fp, $source); $remove = 1; } else { - @$fp = fopen($_REQUEST['url'],"r"); + @$fp = fopen($_REQUEST['url'], "r"); if (!$fp) { - header ("Content-type: text/html"); + header("Content-type: text/html"); echo "Not an image"; exit(); @@ -43,83 +43,83 @@ if (preg_match('/^(http|ftp|https):\/\//i',$_REQUEST['url'])) { fclose($fp); } } -list ($a, $b, $type, $attr) = @getimagesize ($file); +list ($a, $b, $type, $attr) = @getimagesize($file); if (!$type) { - $type = basename ($_REQUEST['url']); - $type = preg_split ('/\./',$type); - $type = array_pop ($type); + $type = basename($_REQUEST['url']); + $type = preg_split('/\./', $type); + $type = array_pop($type); } switch ($type) { case '2': if (function_exists("imagecreatefromjpeg")) - $img = @imagecreatefromjpeg ($file); + $img = @imagecreatefromjpeg($file); else - show_plain ($file); + show_plain($file); break; case '3': if (function_exists("imagecreatefrompng")) - $img = @imagecreatefrompng ($file); + $img = @imagecreatefrompng($file); else - show_plain ($file); + show_plain($file); break; case '1': if (function_exists("imagecreatefromgif")) - $img = @imagecreatefromgif ($file); + $img = @imagecreatefromgif($file); else - show_plain ($file); + show_plain($file); break; case '15': if (function_exists("imagecreatefromwbmp")) - $img = @imagecreatefromwbmp ($file); + $img = @imagecreatefromwbmp($file); else - show_plain ($file); + show_plain($file); break; case '16': if (function_exists("imagecreatefromxbm")) - $img = @imagecreatefromxbm ($file); + $img = @imagecreatefromxbm($file); else - show_plain ($file); + show_plain($file); break; case 'xpm': if (function_exists("imagecreatefromxpm")) - $img = @imagecreatefromxpm ($file); + $img = @imagecreatefromxpm($file); else - show_plain ($file); + show_plain($file); break; case 'gd': if (function_exists("imagecreatefromgd")) - $img = @imagecreatefromgd ($file); + $img = @imagecreatefromgd($file); else - show_plain ($file); + show_plain($file); break; case 'gd2': if (function_exists("imagecreatefromgd2")) - $img = @imagecreatefromgd2 ($file); + $img = @imagecreatefromgd2($file); else - show_plain ($file); + show_plain($file); break; default: //we are not stupid... - header ("Content-type: text/html"); + header("Content-type: text/html"); echo "Not an image"; exit(); break; } -$width = @imagesx($img); +$width = @imagesx($img); $height = @imagesy($img); $newwidth = $_REQUEST['width']; if (empty($newidth)) $newidth = 50; $newheight = $_REQUEST['height']; -if (empty($newheight)) $newheight = round($newwidth * ($height / $width)) ; +if (empty($newheight)) $newheight = round($newwidth * ($height / $width)); // php-4.2.x is stupid enough to define on gd only a stub for imagecopyresampled. // So function_exists('imagecopyresampled') will fail. -if (!extension_loaded('gd2') and (substr(PHP_OS,0,3) != 'WIN')) +if (!extension_loaded('gd2') and (substr(PHP_OS, 0, 3) != 'WIN')) loadPhpExtension('gd2'); if (extension_loaded('gd2')) { $thumb = imagecreatetruecolor($newwidth, $newheight); @@ -129,14 +129,15 @@ if (extension_loaded('gd2')) { $img = imagecopyresized($thumb, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); } -if ($remove == 1) unlink ($file); +if ($remove == 1) unlink($file); -header ("Content-type: image/png"); +header("Content-type: image/png"); imagepng($thumb); -function show_plain () { - $mime = mime_content_type ($_REQUEST['url']); - header ("Content-type: $mime"); +function show_plain() +{ + $mime = mime_content_type($_REQUEST['url']); + header("Content-type: $mime"); readfile($_REQUEST['url']); exit(); } diff --git a/RPC2.php b/RPC2.php index 488056aa2..e6f3fb2c3 100644 --- a/RPC2.php +++ b/RPC2.php @@ -10,9 +10,8 @@ // Intercept GET requests from confused users. Only POST is allowed here! if (empty($GLOBALS['HTTP_SERVER_VARS'])) - $GLOBALS['HTTP_SERVER_VARS'] =& $_SERVER; -if ($HTTP_SERVER_VARS['REQUEST_METHOD'] != "POST") -{ + $GLOBALS['HTTP_SERVER_VARS'] =& $_SERVER; +if ($HTTP_SERVER_VARS['REQUEST_METHOD'] != "POST") { die('This is the address of the XML-RPC interface.' . ' You must use XML-RPC calls to access information here.'); } diff --git a/SOAP.php b/SOAP.php index 264f96a1a..37e2996db 100644 --- a/SOAP.php +++ b/SOAP.php @@ -37,11 +37,12 @@ require_once 'lib/WikiUserNew.php'; require_once 'lib/WikiGroup.php'; */ -function checkCredentials(&$server, &$credentials, $access, $pagename) { +function checkCredentials(&$server, &$credentials, $access, $pagename) +{ // check the "Authorization: Basic '.base64_encode("$this->username:$this->password").'\r\n'" header if (isset($server->header['Authorization'])) { - $line = base64_decode(str_replace("Basic ","",trim($server->header['Authorization']))); - list($credentials['username'],$credentials['password']) = explode(':',$line); + $line = base64_decode(str_replace("Basic ", "", trim($server->header['Authorization']))); + list($credentials['username'], $credentials['password']) = explode(':', $line); } else { if (!isset($_SERVER)) $_SERVER =& $GLOBALS['HTTP_SERVER_VARS']; @@ -50,8 +51,7 @@ function checkCredentials(&$server, &$credentials, $access, $pagename) { if (isset($_SERVER['REMOTE_ADDR'])) $credentials['username'] = $_SERVER['REMOTE_ADDR']; elseif (isset($GLOBALS['REMOTE_ADDR'])) - $credentials['username'] = $GLOBALS['REMOTE_ADDR']; - else + $credentials['username'] = $GLOBALS['REMOTE_ADDR']; else $credentials['username'] = $server->host; } } @@ -64,9 +64,9 @@ function checkCredentials(&$server, &$credentials, $access, $pagename) { $request->_user = new WikiUser($request, $credentials['username']); } $request->_user->AuthCheck(array('userid' => $credentials['username'], - 'passwd' => $credentials['password'])); - if (! mayAccessPage ($access, $pagename)) - $server->fault(401,'',"no permission"); + 'passwd' => $credentials['password'])); + if (!mayAccessPage($access, $pagename)) + $server->fault(401, '', "no permission"); } $GLOBALS['SERVER_NAME'] = SERVER_URL; @@ -76,22 +76,22 @@ $url = SERVER_URL . DATA_PATH . "/SOAP.php"; // Local or external wdsl support is experimental. // It works without also. Just the client has to // know the wdsl definitions. -$server = new soap_server(/* 'PhpWiki.wdsl' */); +$server = new soap_server( /* 'PhpWiki.wdsl' */); // Now change the server url to ours, because in the wdsl is the original PhpWiki address // // $server->ports[$server->currentPort]['location'] = $url; -$server->bindings[ $server->ports[$server->currentPort]['binding'] ]['endpoint'] = $url; +$server->bindings[$server->ports[$server->currentPort]['binding']]['endpoint'] = $url; $server->soapaction = $url; // soap_transport_http -$actions = array('getPageContent','getPageRevision','getCurrentRevision', - 'getPageMeta','doSavePage','getAllPagenames', - 'getBackLinks','doTitleSearch','doFullTextSearch', - 'getRecentChanges','listLinks','listPlugins', - 'getPluginSynopsis','callPlugin','listRelations', - 'linkSearch' - ); +$actions = array('getPageContent', 'getPageRevision', 'getCurrentRevision', + 'getPageMeta', 'doSavePage', 'getAllPagenames', + 'getBackLinks', 'doTitleSearch', 'doFullTextSearch', + 'getRecentChanges', 'listLinks', 'listPlugins', + 'getPluginSynopsis', 'callPlugin', 'listRelations', + 'linkSearch' +); foreach ($actions as $action) { $server->register($actions); $server->operations[$actions]['soapaction'] = $url; @@ -100,9 +100,10 @@ foreach ($actions as $action) { //todo: check and set credentials // requiredAuthorityForPage($action); // require 'edit' access -function doSavePage($pagename,$content,$credentials=false) { +function doSavePage($pagename, $content, $credentials = false) +{ global $server; - checkCredentials($server, $credentials,'edit',$pagename); + checkCredentials($server, $credentials, 'edit', $pagename); $dbi = WikiDB::open($GLOBALS['DBParams']); $page = $dbi->getPage($pagename); $current = $page->getCurrentRevision(); @@ -113,41 +114,48 @@ function doSavePage($pagename,$content,$credentials=false) { } // require 'view' access -function getPageContent($pagename,$credentials=false) { +function getPageContent($pagename, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',$pagename); + checkCredentials($server, $credentials, 'view', $pagename); $dbi = WikiDB::open($GLOBALS['DBParams']); $page = $dbi->getPage($pagename); $rev = $page->getCurrentRevision(); $text = $rev->getPackedContent(); return $text; } + // require 'view' access -function getPageRevision($pagename,$revision,$credentials=false) { +function getPageRevision($pagename, $revision, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',$pagename); + checkCredentials($server, $credentials, 'view', $pagename); $dbi = WikiDB::open($GLOBALS['DBParams']); $page = $dbi->getPage($pagename); $rev = $page->getCurrentRevision(); $text = $rev->getPackedContent(); return $text; } + // require 'view' access -function getCurrentRevision($pagename,$credentials=false) { +function getCurrentRevision($pagename, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',$pagename); - if (!mayAccessPage ('view',$pagename)) - $server->fault(401,'',"no permission"); + checkCredentials($server, $credentials, 'view', $pagename); + if (!mayAccessPage('view', $pagename)) + $server->fault(401, '', "no permission"); $dbi = WikiDB::open($GLOBALS['DBParams']); $page = $dbi->getPage($pagename); $rev = $page->getCurrentRevision(); $version = $current->getVersion(); return (double)$version; } + // require 'change' or 'view' access ? -function getPageMeta($pagename,$credentials=false) { +function getPageMeta($pagename, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',$pagename); + checkCredentials($server, $credentials, 'view', $pagename); $dbi = WikiDB::open($GLOBALS['DBParams']); $page = $dbi->getPage($pagename); $rev = $page->getCurrentRevision(); @@ -155,10 +163,12 @@ function getPageMeta($pagename,$credentials=false) { //todo: reformat the meta hash return $meta; } + // require 'view' access to AllPages -function getAllPagenames($credentials=false) { +function getAllPagenames($credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',_("AllPages")); + checkCredentials($server, $credentials, 'view', _("AllPages")); $dbi = WikiDB::open($GLOBALS['DBParams']); $page_iter = $dbi->getAllPages(); $pages = array(); @@ -167,13 +177,15 @@ function getAllPagenames($credentials=false) { } return $pages; } + // require 'view' access -function getBacklinks($pagename,$credentials=false) { +function getBacklinks($pagename, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',$pagename); + checkCredentials($server, $credentials, 'view', $pagename); $dbi = WikiDB::open($GLOBALS['DBParams']); $backend = &$dbi->_backend; - $result = $backend->get_links($pagename); + $result = $backend->get_links($pagename); $page_iter = new WikiDB_PageIterator($dbi, $result); $pages = array(); while ($page = $page_iter->next()) { @@ -181,10 +193,12 @@ function getBacklinks($pagename,$credentials=false) { } return $pages; } + // require 'view' access to TitleSearch -function doTitleSearch($s, $credentials=false) { +function doTitleSearch($s, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',_("TitleSearch")); + checkCredentials($server, $credentials, 'view', _("TitleSearch")); $dbi = WikiDB::open($GLOBALS['DBParams']); $query = new TextSearchQuery($s); $page_iter = $dbi->titleSearch($query); @@ -194,10 +208,12 @@ function doTitleSearch($s, $credentials=false) { } return $pages; } + // require 'view' access to FullTextSearch -function doFullTextSearch($s, $credentials=false) { +function doFullTextSearch($s, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',_("FullTextSearch")); + checkCredentials($server, $credentials, 'view', _("FullTextSearch")); $dbi = WikiDB::open($GLOBALS['DBParams']); $query = new TextSearchQuery($s); $page_iter = $dbi->fullSearch($query); @@ -209,28 +225,31 @@ function doFullTextSearch($s, $credentials=false) { } // require 'view' access to RecentChanges -function getRecentChanges($limit=false, $since=false, $include_minor=false, $credentials=false) { +function getRecentChanges($limit = false, $since = false, $include_minor = false, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',_("RecentChanges")); + checkCredentials($server, $credentials, 'view', _("RecentChanges")); $dbi = WikiDB::open($GLOBALS['DBParams']); $params = array('limit' => $limit, 'since' => $since, - 'include_minor_revisions' => $include_minor); + 'include_minor_revisions' => $include_minor); $page_iter = $dbi->mostRecent($params); $pages = array(); while ($page = $page_iter->next()) { $pages[] = array('pagename' => $page->getName(), - 'lastModified' => $page->get('mtime'), - 'author' => $page->get('author'), - 'summary' => $page->get('summary'), // added with 1.3.13 - 'version' => $page->getVersion() - ); + 'lastModified' => $page->get('mtime'), + 'author' => $page->get('author'), + 'summary' => $page->get('summary'), // added with 1.3.13 + 'version' => $page->getVersion() + ); } return $pages; } + // require 'view' access -function listLinks($pagename, $credentials=false) { +function listLinks($pagename, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',$pagename); + checkCredentials($server, $credentials, 'view', $pagename); $dbi = WikiDB::open($GLOBALS['DBParams']); $page = $dbi->getPage($pagename); $linkiterator = $page->getPageLinks(); @@ -241,9 +260,11 @@ function listLinks($pagename, $credentials=false) { } return $links; } -function listPlugins($credentials=false) { + +function listPlugins($credentials = false) +{ global $server; - checkCredentials($server,$credentials,'change',_("HomePage")); + checkCredentials($server, $credentials, 'change', _("HomePage")); $plugin_dir = 'lib/plugin'; if (defined('PHPWIKI_DIR')) $plugin_dir = PHPWIKI_DIR . "/$plugin_dir"; @@ -266,9 +287,11 @@ function listPlugins($credentials=false) { } return $RetArray; } -function getPluginSynopsis($pluginname, $credentials=false) { + +function getPluginSynopsis($pluginname, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'change',"Help/".$pluginname."Plugin"); + checkCredentials($server, $credentials, 'change', "Help/" . $pluginname . "Plugin"); require_once 'lib/WikiPlugin.php'; $w = new WikiPluginLoader; $synopsis = ''; @@ -277,21 +300,24 @@ function getPluginSynopsis($pluginname, $credentials=false) { if (strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') { $plugin_args = ''; $desc = $p->getArgumentsDescription(); - $src = array("\n",'"',"'",'|','[',']','\\'); - $replace = array('%0A','%22','%27','%7C','%5B','%5D','%5C'); - $desc = str_replace("
",' ',$desc->asXML()); + $src = array("\n", '"', "'", '|', '[', ']', '\\'); + $replace = array('%0A', '%22', '%27', '%7C', '%5B', '%5D', '%5C'); + $desc = str_replace("
", ' ', $desc->asXML()); if ($desc) - $plugin_args = '\n'.str_replace($src, $replace, $desc); - $synopsis = ""; // args? + $plugin_args = '\n' . str_replace($src, $replace, $desc); + $synopsis = ""; // args? } return $synopsis; } + // only plugins returning pagelists will return something useful. so omit the html output -function callPlugin($pluginname, $pluginargs, $credentials=false) { +function callPlugin($pluginname, $pluginargs, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'change',"Help/".$pluginname."Plugin"); + checkCredentials($server, $credentials, 'change', "Help/" . $pluginname . "Plugin"); - $basepage = '';; + $basepage = ''; + ; require_once 'lib/WikiPlugin.php'; $w = new WikiPluginLoader; $p = $w->getPlugin($pluginName, false); // second arg? @@ -303,6 +329,7 @@ function callPlugin($pluginname, $pluginargs, $credentials=false) { } return $pages; } + /** * array listRelations([ Integer option = 1 ]) * @@ -315,20 +342,23 @@ function callPlugin($pluginname, $pluginargs, $credentials=false) { * * @author: Reini Urban */ -function listRelations($option = 1, $credentials=false) { +function listRelations($option = 1, $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',_("HomePage")); + checkCredentials($server, $credentials, 'view', _("HomePage")); $also_attributes = $option & 2; $only_attributes = $option & 2 and !($option & 1); $sorted = !($option & 4); return $dbh->listRelations($also_attributes, - $only_attributes, - $sorted); + $only_attributes, + $sorted); } + // some basic semantic search -function linkSearch($linktype, $search, $pages="*", $relation="*", $credentials=false) { +function linkSearch($linktype, $search, $pages = "*", $relation = "*", $credentials = false) +{ global $server; - checkCredentials($server,$credentials,'view',_("HomePage")); + checkCredentials($server, $credentials, 'view', _("HomePage")); $dbi = WikiDB::open($GLOBALS['DBParams']); require_once 'lib/TextSearchQuery.php'; $pagequery = new TextSearchQuery($pages); diff --git a/admin/wiki2public.php b/admin/wiki2public.php index cb06d1027..7212ab047 100644 --- a/admin/wiki2public.php +++ b/admin/wiki2public.php @@ -1,4 +1,4 @@ \n"; +echo '<', '?xml version="1.0" encoding="utf-8"?', ">\n"; ?> + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> - -Configuration tool for PhpWiki <?php echo $config_file ?> - - + function do_init() { + // Hide all groups. We do this via JavaScript to avoid + // hiding the groups if JavaScript is not supported... + var rows = document.getElementsByTagName('tr'); + var show = ''; + for (var i = 0; i < rows.length; i++) { + var tr = rows[i]; + if (tr.className == 'header') + if (!show || tr.id != show) + toggle_group(tr.id); + } + + // Select text in textarea upon focus + var area = document.getElementById('config-output'); + if (area) { + listener = { handleEvent:function (e) { + area.select(); + } }; + area.addEventListener('focus', listener, false); + } + } + + -- > + -

Configuration for PhpWiki

+

Configuration for PhpWiki

- Using this configurator.php is experimental!
+ Using this configurator.php is experimental!
On any configuration problems, please edit the resulting config.ini manually.
@@ -330,121 +378,121 @@ $preamble = " // grep \'$x\' configurator.php >/dev/null || echo $x ; done $properties["Part Zero"] = -new part('_part0', $SEPARATOR."\n", " + new part('_part0', $SEPARATOR . "\n", " Part Zero: (optional) Latest Development and Tricky Options"); if (defined('INCLUDE_PATH')) $include_path = INCLUDE_PATH; else { - if (substr(PHP_OS,0,3) == 'WIN') { - $include_path = dirname(__FILE__) . ';' . ini_get('include_path'); - if (strchr(ini_get('include_path'),'/')) - $include_path = strtr($include_path,'\\','/'); - } else { - $include_path = dirname(__FILE__) . ':' . ini_get('include_path'); - } + if (substr(PHP_OS, 0, 3) == 'WIN') { + $include_path = dirname(__FILE__) . ';' . ini_get('include_path'); + if (strchr(ini_get('include_path'), '/')) + $include_path = strtr($include_path, '\\', '/'); + } else { + $include_path = dirname(__FILE__) . ':' . ini_get('include_path'); + } } $properties["PHP include_path"] = -new _define('INCLUDE_PATH', $include_path); + new _define('INCLUDE_PATH', $include_path); // TODO: Convert this to a checkbox row as in tests/unit/test.php $properties["DEBUG"] = -new numeric_define_optional('DEBUG', DEBUG); + new numeric_define_optional('DEBUG', DEBUG); $properties["ENABLE_EDIT_TOOLBAR"] = -new boolean_define_commented_optional('ENABLE_EDIT_TOOLBAR'); + new boolean_define_commented_optional('ENABLE_EDIT_TOOLBAR'); $properties["JS_SEARCHREPLACE"] = -new boolean_define_commented_optional('JS_SEARCHREPLACE'); + new boolean_define_commented_optional('JS_SEARCHREPLACE'); // TESTME: use config-default: = false $properties["ENABLE_DOUBLECLICKEDIT"] = -new boolean_define_commented_optional('ENABLE_DOUBLECLICKEDIT'); + new boolean_define_commented_optional('ENABLE_DOUBLECLICKEDIT'); $properties["ENABLE_WYSIWYG"] = -new boolean_define_commented_optional('ENABLE_WYSIWYG'); + new boolean_define_commented_optional('ENABLE_WYSIWYG'); $properties["WYSIWYG_BACKEND"] = -new _define_selection( -'WYSIWYG_BACKEND', -array('Wikiwyg' => 'Wikiwyg', - 'tinymce' => 'tinymce', - 'FCKeditor' => 'FCKeditor', - 'spaw' => 'spaw', - 'htmlarea3' => 'htmlarea3', - 'htmlarea2' => 'htmlarea2', -)); + new _define_selection( + 'WYSIWYG_BACKEND', + array('Wikiwyg' => 'Wikiwyg', + 'tinymce' => 'tinymce', + 'FCKeditor' => 'FCKeditor', + 'spaw' => 'spaw', + 'htmlarea3' => 'htmlarea3', + 'htmlarea2' => 'htmlarea2', + )); $properties["WYSIWYG_DEFAULT_PAGETYPE_HTML"] = -new boolean_define_commented_optional('WYSIWYG_DEFAULT_PAGETYPE_HTML'); + new boolean_define_commented_optional('WYSIWYG_DEFAULT_PAGETYPE_HTML'); $properties["UPLOAD_USERDIR"] = -new boolean_define_commented_optional('UPLOAD_USERDIR'); + new boolean_define_commented_optional('UPLOAD_USERDIR'); $properties["DISABLE_UNITS"] = -new boolean_define_commented_optional('DISABLE_UNITS'); + new boolean_define_commented_optional('DISABLE_UNITS'); $properties["UNITS_EXE"] = -new _define_commented_optional('UNITS_EXE'); + new _define_commented_optional('UNITS_EXE'); $properties["ENABLE_XHTML_XML"] = -new boolean_define_commented_optional('ENABLE_XHTML_XML'); + new boolean_define_commented_optional('ENABLE_XHTML_XML'); $properties["ENABLE_OPEN_GRAPH"] = -new boolean_define_commented_optional('ENABLE_OPEN_GRAPH'); + new boolean_define_commented_optional('ENABLE_OPEN_GRAPH'); $properties["ENABLE_SPAMASSASSIN"] = -new boolean_define_commented_optional('ENABLE_SPAMASSASSIN'); + new boolean_define_commented_optional('ENABLE_SPAMASSASSIN'); $properties["ENABLE_SPAMBLOCKLIST"] = -new boolean_define_optional('ENABLE_SPAMBLOCKLIST'); + new boolean_define_optional('ENABLE_SPAMBLOCKLIST'); $properties["NUM_SPAM_LINKS"] = -new numeric_define_optional('NUM_SPAM_LINKS'); + new numeric_define_optional('NUM_SPAM_LINKS'); $properties["GOOGLE_LINKS_NOFOLLOW"] = -new boolean_define_commented_optional('GOOGLE_LINKS_NOFOLLOW'); + new boolean_define_commented_optional('GOOGLE_LINKS_NOFOLLOW'); $properties["ENABLE_LIVESEARCH"] = -new boolean_define_commented_optional('ENABLE_LIVESEARCH'); + new boolean_define_commented_optional('ENABLE_LIVESEARCH'); $properties["ENABLE_ACDROPDOWN"] = -new boolean_define_commented_optional('ENABLE_ACDROPDOWN'); + new boolean_define_commented_optional('ENABLE_ACDROPDOWN'); $properties["ENABLE_DISCUSSION_LINK"] = -new boolean_define_commented_optional('ENABLE_DISCUSSION_LINK'); + new boolean_define_commented_optional('ENABLE_DISCUSSION_LINK'); $properties["ENABLE_CAPTCHA"] = -new boolean_define_commented_optional('ENABLE_CAPTCHA'); + new boolean_define_commented_optional('ENABLE_CAPTCHA'); $properties["USE_CAPTCHA_RANDOM_WORD"] = -new boolean_define_commented_optional('USE_CAPTCHA_RANDOM_WORD'); + new boolean_define_commented_optional('USE_CAPTCHA_RANDOM_WORD'); $properties["USE_SAFE_DBSESSION"] = -new boolean_define_commented_optional('USE_SAFE_DBSESSION'); + new boolean_define_commented_optional('USE_SAFE_DBSESSION'); $properties["BLOG_DEFAULT_EMPTY_PREFIX"] = -new boolean_define_commented_optional('BLOG_DEFAULT_EMPTY_PREFIX'); + new boolean_define_commented_optional('BLOG_DEFAULT_EMPTY_PREFIX'); $properties["ENABLE_SEARCHHIGHLIGHT"] = -new boolean_define_commented_optional('ENABLE_SEARCHHIGHLIGHT'); + new boolean_define_commented_optional('ENABLE_SEARCHHIGHLIGHT'); $properties["Part One"] = -new part('_part1', $SEPARATOR."\n", " + new part('_part1', $SEPARATOR . "\n", " Part One: Authentication and security settings. See Part Three for more."); $properties["Wiki Name"] = -new _define_optional('WIKI_NAME', WIKI_NAME); + new _define_optional('WIKI_NAME', WIKI_NAME); $properties["Admin Username"] = -new _define_notempty('ADMIN_USER', ADMIN_USER, " + new _define_notempty('ADMIN_USER', ADMIN_USER, " You must set this! Username and password of the administrator.", -"onchange=\"validate_ereg('Sorry, ADMIN_USER cannot be empty.', '^.+$', 'ADMIN_USER', this);\""); + "onchange=\"validate_ereg('Sorry, ADMIN_USER cannot be empty.', '^.+$', 'ADMIN_USER', this);\""); $properties["Admin Password"] = -new _define_password('ADMIN_PASSWD', ADMIN_PASSWD, " + new _define_password('ADMIN_PASSWD', ADMIN_PASSWD, " You must set this! For heaven's sake pick a good password. @@ -453,74 +501,74 @@ automatically encrypted within the generated config file. Use the \"Create Random Password\" button to create a good (random) password. ADMIN_PASSWD is ignored on HttpAuth", -"onchange=\"validate_ereg('Sorry, ADMIN_PASSWD must be at least 4 chars long.', '^....+$', 'ADMIN_PASSWD', this);\""); + "onchange=\"validate_ereg('Sorry, ADMIN_PASSWD must be at least 4 chars long.', '^....+$', 'ADMIN_PASSWD', this);\""); $properties["Encrypted Passwords"] = -new boolean_define -('ENCRYPTED_PASSWD', - array('true' => "true. use crypt for all passwords", - 'false' => "false. use plaintest passwords (not recommended)")); + new boolean_define + ('ENCRYPTED_PASSWD', + array('true' => "true. use crypt for all passwords", + 'false' => "false. use plaintest passwords (not recommended)")); $properties["Reverse DNS"] = -new boolean_define_optional -('ENABLE_REVERSE_DNS', - array('true' => "true. perform additional reverse dns lookups", - 'false' => "false. just record the address as given by the httpd server")); + new boolean_define_optional + ('ENABLE_REVERSE_DNS', + array('true' => "true. perform additional reverse dns lookups", + 'false' => "false. just record the address as given by the httpd server")); $properties["ZIP Dump Authentication"] = -new boolean_define_optional('ZIPDUMP_AUTH', - array('false' => "false. Everyone may download zip dumps", - 'true' => "true. Only admin may download zip dumps")); + new boolean_define_optional('ZIPDUMP_AUTH', + array('false' => "false. Everyone may download zip dumps", + 'true' => "true. Only admin may download zip dumps")); $properties["Enable RawHtml Plugin"] = -new boolean_define_commented_optional('ENABLE_RAW_HTML'); + new boolean_define_commented_optional('ENABLE_RAW_HTML'); $properties["Allow RawHtml Plugin only on locked pages"] = -new boolean_define_commented_optional('ENABLE_RAW_HTML_LOCKEDONLY'); + new boolean_define_commented_optional('ENABLE_RAW_HTML_LOCKEDONLY'); $properties["Allow RawHtml Plugin if safe HTML code"] = - new boolean_define_commented_optional('ENABLE_RAW_HTML_SAFE','', " + new boolean_define_commented_optional('ENABLE_RAW_HTML_SAFE', '', " If this is set, all unsafe html code is stripped automatically (experimental!) See chxo.com/scripts/safe_html-test.php "); $properties["Maximum Upload Size"] = -new numeric_define_optional('MAX_UPLOAD_SIZE', MAX_UPLOAD_SIZE); + new numeric_define_optional('MAX_UPLOAD_SIZE', MAX_UPLOAD_SIZE); $properties["Minor Edit Timeout"] = -new numeric_define_optional('MINOR_EDIT_TIMEOUT', MINOR_EDIT_TIMEOUT); + new numeric_define_optional('MINOR_EDIT_TIMEOUT', MINOR_EDIT_TIMEOUT); $properties["Disabled Actions"] = -new array_define('DISABLED_ACTIONS', DISABLED_ACTIONS /*array()*/); + new array_define('DISABLED_ACTIONS', DISABLED_ACTIONS /*array()*/); $properties["Moderate all Pagechanges"] = -new boolean_define_commented_optional('ENABLE_MODERATEDPAGE_ALL'); + new boolean_define_commented_optional('ENABLE_MODERATEDPAGE_ALL'); $properties["Access Log File"] = -new _define_commented_optional('ACCESS_LOG', ACCESS_LOG); + new _define_commented_optional('ACCESS_LOG', ACCESS_LOG); $properties["Access Log SQL"] = -new _define_selection( -'ACCESS_LOG_SQL', -array('0' => 'disabled', - '1' => 'read only', - '2' => 'read + write')); + new _define_selection( + 'ACCESS_LOG_SQL', + array('0' => 'disabled', + '1' => 'read only', + '2' => 'read + write')); $properties["Compress Output"] = -new boolean_define_commented_optional -( 'COMPRESS_OUTPUT', - array('' => 'undefined - GZIP compress when appropriate.', - 'false' => 'Never compress output.', - 'true' => 'Always try to compress output.')); + new boolean_define_commented_optional + ('COMPRESS_OUTPUT', + array('' => 'undefined - GZIP compress when appropriate.', + 'false' => 'Never compress output.', + 'true' => 'Always try to compress output.')); $properties["HTTP Cache Control"] = -new _define_selection_optional -('CACHE_CONTROL', - array('LOOSE' => 'LOOSE', - 'STRICT' => 'STRICT', - 'NO_CACHE' => 'NO_CACHE', - 'ALLOW_STALE' => 'ALLOW_STALE'), -" + new _define_selection_optional + ('CACHE_CONTROL', + array('LOOSE' => 'LOOSE', + 'STRICT' => 'STRICT', + 'NO_CACHE' => 'NO_CACHE', + 'ALLOW_STALE' => 'ALLOW_STALE'), + " HTTP CACHE_CONTROL This controls how PhpWiki sets the HTTP cache control @@ -559,46 +607,46 @@ Choose one of: The default is currently LOOSE."); $properties["HTTP Cache Control Max Age"] = -new numeric_define_optional('CACHE_CONTROL_MAX_AGE', CACHE_CONTROL_MAX_AGE); + new numeric_define_optional('CACHE_CONTROL_MAX_AGE', CACHE_CONTROL_MAX_AGE); $properties["Markup Caching"] = -new boolean_define_commented_optional -('WIKIDB_NOCACHE_MARKUP', - array('false' => 'Enable markup cache', - 'true' => 'Disable markup cache')); + new boolean_define_commented_optional + ('WIKIDB_NOCACHE_MARKUP', + array('false' => 'Enable markup cache', + 'true' => 'Disable markup cache')); $properties["COOKIE_EXPIRATION_DAYS"] = -new numeric_define_optional('COOKIE_EXPIRATION_DAYS', COOKIE_EXPIRATION_DAYS); + new numeric_define_optional('COOKIE_EXPIRATION_DAYS', COOKIE_EXPIRATION_DAYS); $properties["COOKIE_DOMAIN"] = -new _define_commented_optional('COOKIE_DOMAIN', COOKIE_DOMAIN); + new _define_commented_optional('COOKIE_DOMAIN', COOKIE_DOMAIN); $properties["Path for PHP Session Support"] = -new _define_optional('SESSION_SAVE_PATH', defined('SESSION_SAVE_PATH') ? SESSION_SAVE_PATH : ini_get('session.save_path')); + new _define_optional('SESSION_SAVE_PATH', defined('SESSION_SAVE_PATH') ? SESSION_SAVE_PATH : ini_get('session.save_path')); $properties["Force PHP Database Sessions"] = -new boolean_define_commented_optional -('USE_DB_SESSION', - array('false' => 'Disable database sessions, use files', - 'true' => 'Enable database sessions')); + new boolean_define_commented_optional + ('USE_DB_SESSION', + array('false' => 'Disable database sessions, use files', + 'true' => 'Enable database sessions')); ///////// database selection $properties["Part Two"] = -new part('_part2', $SEPARATOR."\n", " + new part('_part2', $SEPARATOR . "\n", " Part Two: Database Configuration "); $properties["Database Type"] = -new _define_selection("DATABASE_TYPE", - array('dba' => "dba", - 'SQL' => "SQL PEAR", - 'ADODB' => "SQL ADODB", - 'PDO' => "PDO (php5 only)", - 'file' => "flatfile", - 'cvs' => "CVS File handler")/*, " + new _define_selection("DATABASE_TYPE", + array('dba' => "dba", + 'SQL' => "SQL PEAR", + 'ADODB' => "SQL ADODB", + 'PDO' => "PDO (php5 only)", + 'file' => "flatfile", + 'cvs' => "CVS File handler")/*, " Select the database backend type: Choose dba (default) to use one of the standard UNIX dba libraries. This is the fastest. Choose ADODB or SQL to use an SQL database with ADODB or PEAR. @@ -608,7 +656,7 @@ CVS is highly experimental and slow. Recommended is dba or SQL: PEAR or ADODB."*/); $properties["SQL DSN Setup"] = -new unchangeable_variable('_sqldsnstuff', "", " + new unchangeable_variable('_sqldsnstuff', "", " For SQL based backends, specify the database as a DSN The most general form of a DSN looks like:
@@ -632,30 +680,30 @@ To connect over a unix socket, use something like
 // Choose dba to use one of the standard UNIX dbm libraries.
 
 $properties["SQL Type"] =
-new _variable_selection('_dsn_sqltype',
-              array('mysql'  => "MySQL",
-                    'pgsql'  => "PostgreSQL",
-                    'mssql'  => "Microsoft SQL Server",
-                    'mssqlnative'  => "Microsoft SQL Server (native)",
-                    'oci8'   => "Oracle 8",
-                    'mysqli' => "mysqli (only ADODB)",
-                    'mysqlt' => "mysqlt (only ADODB)",
-                    'ODBC'   => "ODBC (only ADODB or PDO)",
-                    'firebird' => "Firebird (only PDO)",
-                    'oracle'  => "Oracle (only PDO)",
-), "
+    new _variable_selection('_dsn_sqltype',
+        array('mysql' => "MySQL",
+            'pgsql' => "PostgreSQL",
+            'mssql' => "Microsoft SQL Server",
+            'mssqlnative' => "Microsoft SQL Server (native)",
+            'oci8' => "Oracle 8",
+            'mysqli' => "mysqli (only ADODB)",
+            'mysqlt' => "mysqlt (only ADODB)",
+            'ODBC' => "ODBC (only ADODB or PDO)",
+            'firebird' => "Firebird (only PDO)",
+            'oracle' => "Oracle (only PDO)",
+        ), "
 SQL DB types. The DSN hosttype.");
 
 $properties["SQL User"] =
-new _variable('_dsn_sqluser', "wikiuser", "
+    new _variable('_dsn_sqluser', "wikiuser", "
 SQL User Id:");
 
 $properties["SQL Password"] =
-new _variable('_dsn_sqlpass', "", "
+    new _variable('_dsn_sqlpass', "", "
 SQL Password:");
 
 $properties["SQL Database Host"] =
-new _variable('_dsn_sqlhostorsock', "localhost", "
+    new _variable('_dsn_sqlhostorsock', "localhost", "
 SQL Database Hostname:
 
 To connect over a local named socket, use something like
@@ -666,7 +714,7 @@ here.
 mysql on Windows via named pipes might need 127.0.0.1");
 
 $properties["SQL Database Name"] =
-new _variable('_dsn_sqldbname', "phpwiki", "
+    new _variable('_dsn_sqldbname', "phpwiki", "
 SQL Database Name:");
 
 $dsn_sqltype = $properties["SQL Type"]->value();
@@ -674,15 +722,15 @@ $dsn_sqluser = $properties["SQL User"]->value();
 $dsn_sqlpass = $properties["SQL Password"]->value();
 $dsn_sqlhostorsock = $properties["SQL Database Host"]->value();
 $dsn_sqldbname = $properties["SQL Database Name"]->value();
-$dsn_sqlstring = $dsn_sqltype."://{$dsn_sqluser}:{$dsn_sqlpass}@{$dsn_sqlhostorsock}/{$dsn_sqldbname}";
+$dsn_sqlstring = $dsn_sqltype . "://{$dsn_sqluser}:{$dsn_sqlpass}@{$dsn_sqlhostorsock}/{$dsn_sqldbname}";
 
 $properties["SQL dsn"] =
-new unchangeable_define("DATABASE_DSN",
-                        $dsn_sqlstring, "
+    new unchangeable_define("DATABASE_DSN",
+        $dsn_sqlstring, "
 Calculated from the settings above:");
 
 $properties["Filename / Table name Prefix"] =
-new _define_commented('DATABASE_PREFIX', DATABASE_PREFIX, "
+    new _define_commented('DATABASE_PREFIX', DATABASE_PREFIX, "
 Used by all DB types:
 
 Prefix for filenames or table names, e.g. \"phpwiki_\"
@@ -696,13 +744,13 @@ Note: This prefix is NOT prepended to the default DBAUTH_
 ");
 
 $properties["DATABASE_PERSISTENT"] =
-new boolean_define_commented_optional
-('DATABASE_PERSISTENT',
- array('false' => "Disabled",
-       'true'  => "Enabled"));
+    new boolean_define_commented_optional
+    ('DATABASE_PERSISTENT',
+        array('false' => "Disabled",
+            'true' => "Enabled"));
 
 $properties["DB Session table"] =
-new _define_optional("DATABASE_SESSION_TABLE", DATABASE_SESSION_TABLE, "
+    new _define_optional("DATABASE_SESSION_TABLE", DATABASE_SESSION_TABLE, "
 Tablename to store session information. Only supported by SQL backends.
 
 A word of warning - any prefix defined above will be prepended to whatever is given here.
@@ -711,40 +759,40 @@ A word of warning - any prefix defined above will be prepended to whatever is gi
 //TODO: $TEMP
 $temp = !empty($_ENV['TEMP']) ? $_ENV['TEMP'] : "/tmp";
 $properties["dba directory"] =
-new _define("DATABASE_DIRECTORY", $temp);
+    new _define("DATABASE_DIRECTORY", $temp);
 
 // TODO: list the available methods
 $properties["dba handler"] =
-new _define_selection('DATABASE_DBA_HANDLER',
-              array('gdbm' => "gdbm - GNU database manager (not recommended anymore)",
-                    'dbm'  => "DBM - Redhat default. On sf.net there's dbm and not gdbm anymore",
-                    'db2'  => "DB2 - BerkeleyDB (Sleepycat) DB2",
-                    'db3'  => "DB3 - BerkeleyDB (Sleepycat) DB3. Default on Windows but not on every Linux",
-                    'db4'  => "DB4 - BerkeleyDB (Sleepycat) DB4."), "
+    new _define_selection('DATABASE_DBA_HANDLER',
+        array('gdbm' => "gdbm - GNU database manager (not recommended anymore)",
+            'dbm' => "DBM - Redhat default. On sf.net there's dbm and not gdbm anymore",
+            'db2' => "DB2 - BerkeleyDB (Sleepycat) DB2",
+            'db3' => "DB3 - BerkeleyDB (Sleepycat) DB3. Default on Windows but not on every Linux",
+            'db4' => "DB4 - BerkeleyDB (Sleepycat) DB4."), "
 Use 'gdbm', 'dbm', 'db2', 'db3' or 'db4' depending on your DBA handler methods supported: 
" - . join(", ",dba_handlers()) - . "\n\nBetter not use other hacks such as inifile, flatfile or cdb"); + . join(", ", dba_handlers()) + . "\n\nBetter not use other hacks such as inifile, flatfile or cdb"); $properties["dba timeout"] = -new numeric_define("DATABASE_TIMEOUT", DATABASE_TIMEOUT, " + new numeric_define("DATABASE_TIMEOUT", DATABASE_TIMEOUT, " Recommended values are 10-20 seconds. The more load the server has, the higher the timeout."); $properties["DATABASE_OPTIMISE_FREQUENCY"] = -new numeric_define_optional('DATABASE_OPTIMISE_FREQUENCY', DATABASE_OPTIMISE_FREQUENCY); + new numeric_define_optional('DATABASE_OPTIMISE_FREQUENCY', DATABASE_OPTIMISE_FREQUENCY); $properties["DBADMIN_USER"] = -new _define_optional('DBADMIN_USER', DBADMIN_USER); + new _define_optional('DBADMIN_USER', DBADMIN_USER); $properties["DBADMIN_PASSWD"] = -new _define_password_optional('DBADMIN_PASSWD', DBADMIN_PASSWD); + new _define_password_optional('DBADMIN_PASSWD', DBADMIN_PASSWD); $properties["USECACHE"] = -new boolean_define_commented_optional('USECACHE'); + new boolean_define_commented_optional('USECACHE'); /////////////////// $properties["Page Revisions"] = -new unchangeable_variable('_parttworevisions', "", " + new unchangeable_variable('_parttworevisions', "", " Section 2a: Archive Cleanup The next section controls how many old revisions of each page are kept in the database. @@ -840,35 +888,35 @@ but in no case keep more than twenty unique author revisions."); ///////////////////////////////////////////////////////////////////// $properties["Part Three"] = -new part('_part3', $SEPARATOR."\n", " + new part('_part3', $SEPARATOR . "\n", " Part Three: (optional) Basic User Authentication Setup "); $properties["Publicly viewable"] = -new boolean_define_optional('ALLOW_ANON_USER', - array('true' => "true. Permit anonymous view. (Default)", - 'false' => "false. Force login even on view (strictly private)"), " + new boolean_define_optional('ALLOW_ANON_USER', + array('true' => "true. Permit anonymous view. (Default)", + 'false' => "false. Force login even on view (strictly private)"), " If ALLOW_ANON_USER is false, you have to login before viewing any page or doing any other action on a page."); $properties["Allow anonymous edit"] = -new boolean_define_optional('ALLOW_ANON_EDIT', - array('true' => "true. Permit anonymous users to edit. (Default)", - 'false' => "false. Force login on edit (moderately locked)"), " + new boolean_define_optional('ALLOW_ANON_EDIT', + array('true' => "true. Permit anonymous users to edit. (Default)", + 'false' => "false. Force login on edit (moderately locked)"), " If ALLOW_ANON_EDIT is false, you have to login before editing or changing any page. See below."); $properties["Allow Bogo Login"] = -new boolean_define_optional('ALLOW_BOGO_LOGIN', - array('true' => "true. Users may Sign In with any WikiWord, without password. (Default)", - 'false' => "false. Require stricter authentication."), " + new boolean_define_optional('ALLOW_BOGO_LOGIN', + array('true' => "true. Users may Sign In with any WikiWord, without password. (Default)", + 'false' => "false. Require stricter authentication."), " If ALLOW_BOGO_LOGIN is false, you may not login with any wikiword username and empty password. If true, users are allowed to create themselves with any WikiWord username. See below."); $properties["Allow User Passwords"] = -new boolean_define_optional('ALLOW_USER_PASSWORDS', - array('true' => "True user authentication with password checking. (Default)", - 'false' => "false. Ignore authentication settings below."), " + new boolean_define_optional('ALLOW_USER_PASSWORDS', + array('true' => "True user authentication with password checking. (Default)", + 'false' => "false. Ignore authentication settings below."), " If ALLOW_USER_PASSWORDS is true, the authentication settings below define where and how to check against given username/passwords. For completely security disable BOGO_LOGIN and ANON_EDIT above."); @@ -910,17 +958,17 @@ separate the name of each one with colons.
"); $properties["ENABLE_AUTH_OPENID"] = -new boolean_define('ENABLE_AUTH_OPENID'); + new boolean_define('ENABLE_AUTH_OPENID'); $properties["PASSWORD_LENGTH_MINIMUM"] = -new numeric_define('PASSWORD_LENGTH_MINIMUM', PASSWORD_LENGTH_MINIMUM); + new numeric_define('PASSWORD_LENGTH_MINIMUM', PASSWORD_LENGTH_MINIMUM); $properties["USER_AUTH_POLICY"] = -new _define_selection('USER_AUTH_POLICY', - array('first-only' => "first-only - use only the first method in USER_AUTH_ORDER", - 'old' => "old - ignore USER_AUTH_ORDER (legacy)", - 'strict' => "strict - check all methods for userid + password (recommended)", - 'stacked' => "stacked - check all methods for userid, and if found for password"), " + new _define_selection('USER_AUTH_POLICY', + array('first-only' => "first-only - use only the first method in USER_AUTH_ORDER", + 'old' => "old - ignore USER_AUTH_ORDER (legacy)", + 'strict' => "strict - check all methods for userid + password (recommended)", + 'stacked' => "stacked - check all methods for userid, and if found for password"), " The following policies are available for user authentication:
first-only
@@ -937,26 +985,26 @@ The following policies are available for user authentication: methods and return true on the first success.
"); $properties["ENABLE_USER_NEW"] = -new boolean_define_commented_optional('ENABLE_USER_NEW'); + new boolean_define_commented_optional('ENABLE_USER_NEW'); $properties["ENABLE_PAGEPERM"] = -new boolean_define_commented_optional('ENABLE_PAGEPERM'); + new boolean_define_commented_optional('ENABLE_PAGEPERM'); /////////////////// $properties["Part Three A"] = -new part('_part3a', $SEPARATOR."\n", " + new part('_part3a', $SEPARATOR . "\n", " Part Three A: (optional) Group Membership"); $properties["Group membership"] = -new _define_selection("GROUP_METHOD", - array('WIKIPAGE' => "WIKIPAGE - List at \"CategoryGroup\". (Slowest, but easiest to maintain)", - '"NONE"' => "NONE - Disable group membership (Fastest)", - 'DB' => "DB - SQL Database, Optionally external. See USERS/GROUPS queries", - 'FILE' => "Flatfile. See AUTH_GROUP_FILE below.", - 'LDAP' => "LDAP - See \"LDAP authentication options\" above. (Experimental)"), " + new _define_selection("GROUP_METHOD", + array('WIKIPAGE' => "WIKIPAGE - List at \"CategoryGroup\". (Slowest, but easiest to maintain)", + '"NONE"' => "NONE - Disable group membership (Fastest)", + 'DB' => "DB - SQL Database, Optionally external. See USERS/GROUPS queries", + 'FILE' => "Flatfile. See AUTH_GROUP_FILE below.", + 'LDAP' => "LDAP - See \"LDAP authentication options\" above. (Experimental)"), " Group membership. PhpWiki supports defining permissions for a group as well as for individual users. This defines how group membership information is obtained. Supported values are: @@ -974,19 +1022,19 @@ is obtained. Supported values are: lib/WikiGroup.php. (experimental)"); $properties["CATEGORY_GROUP_PAGE"] = - new _define_optional('CATEGORY_GROUP_PAGE', _("CategoryGroup"), " + new _define_optional('CATEGORY_GROUP_PAGE', _("CategoryGroup"), " If GROUP_METHOD = WIKIPAGE: Page where all groups are listed."); $properties["AUTH_GROUP_FILE"] = - new _define_optional('AUTH_GROUP_FILE', _("/etc/groups"), " + new _define_optional('AUTH_GROUP_FILE', _("/etc/groups"), " For GROUP_METHOD = FILE, the file given below is referenced to obtain group membership information. It should be in the same format as the standard unix /etc/groups(5) file."); $properties["Part Three B"] = -new part('_part3b', $SEPARATOR."\n", " + new part('_part3b', $SEPARATOR . "\n", " Part Three B: (optional) External database authentication and authorization. @@ -996,17 +1044,17 @@ below define the SQL queries used to obtain the information out of the database, and (optionally) store the information back to the DB."); $properties["DBAUTH_AUTH_DSN"] = - new _define_optional('DBAUTH_AUTH_DSN', $dsn_sqlstring, " + new _define_optional('DBAUTH_AUTH_DSN', $dsn_sqlstring, " A database DSN to connect to. Defaults to the DSN specified for the Wiki as a whole."); $properties["User Exists Query"] = - new _define('DBAUTH_AUTH_USER_EXISTS', "SELECT userid FROM user WHERE userid='\$userid'", " + new _define('DBAUTH_AUTH_USER_EXISTS', "SELECT userid FROM user WHERE userid='\$userid'", " USER/PASSWORD queries: For USER_AUTH_POLICY=strict and the Db method is required"); $properties["Check Query"] = - new _define_optional('DBAUTH_AUTH_CHECK', "SELECT IF(passwd='\$password',1,0) AS ok FROM user WHERE userid='\$userid'", " + new _define_optional('DBAUTH_AUTH_CHECK', "SELECT IF(passwd='\$password',1,0) AS ok FROM user WHERE userid='\$userid'", " Check to see if the supplied username/password pair is OK @@ -1017,10 +1065,10 @@ database-hashed passwords (more secure):
; DBAUTH_AUTH_CHECK = \"SELECT IF(passwd=PASSWORD('\$password'),1,0) AS ok FROM user WHERE userid='\$userid'\""); $properties["Crypt Method"] = -new _define_selection_optional -('DBAUTH_AUTH_CRYPT_METHOD', - array('plain' => 'plain', - 'crypt' => 'crypt'), " + new _define_selection_optional + ('DBAUTH_AUTH_CRYPT_METHOD', + array('plain' => 'plain', + 'crypt' => 'crypt'), " If you want to use Unix crypt()ed passwords, you can use DBAUTH_AUTH_CHECK to get the password out of the database with a simple SELECT query, and specify DBAUTH_AUTH_USER_EXISTS and DBAUTH_AUTH_CRYPT_METHOD: @@ -1088,52 +1136,52 @@ $properties["DBAUTH_USER_GROUPS"] = if (function_exists('ldap_connect')) { -$properties["LDAP AUTH Host"] = - new _define_optional('LDAP_AUTH_HOST', "ldap://localhost:389", " + $properties["LDAP AUTH Host"] = + new _define_optional('LDAP_AUTH_HOST', "ldap://localhost:389", " If USER_AUTH_ORDER contains Ldap: The LDAP server to connect to. Can either be a hostname, or a complete URL to the server (useful if you want to use ldaps or specify a different port number)."); -$properties["LDAP BASE DN"] = - new _define_optional('LDAP_BASE_DN', "ou=mycompany.com,o=My Company", " + $properties["LDAP BASE DN"] = + new _define_optional('LDAP_BASE_DN', "ou=mycompany.com,o=My Company", " The organizational or domain BASE DN: e.g. \"dc=mydomain,dc=com\". Note: ou=Users and ou=Groups are used for GroupLdap Membership Better use LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP."); -$properties["LDAP SET OPTION"] = - new _define_optional('LDAP_SET_OPTION', "LDAP_OPT_PROTOCOL_VERSION=3:LDAP_OPT_REFERRALS=0", " + $properties["LDAP SET OPTION"] = + new _define_optional('LDAP_SET_OPTION', "LDAP_OPT_PROTOCOL_VERSION=3:LDAP_OPT_REFERRALS=0", " Some LDAP servers need some more options, such as the Windows Active Directory Server. Specify the options (as allowed by the PHP LDAP module) and their values as NAME=value pairs separated by colons."); -$properties["LDAP AUTH USER"] = - new _define_optional('LDAP_AUTH_USER', "CN=ldapuser,ou=Users,o=Development,dc=mycompany.com", " + $properties["LDAP AUTH USER"] = + new _define_optional('LDAP_AUTH_USER', "CN=ldapuser,ou=Users,o=Development,dc=mycompany.com", " DN to initially bind to the LDAP server as. This is needed if the server doesn't allow anonymous queries. (Windows Active Directory Server)"); -$properties["LDAP AUTH PASSWORD"] = - new _define_optional('LDAP_AUTH_PASSWORD', "secret", " + $properties["LDAP AUTH PASSWORD"] = + new _define_optional('LDAP_AUTH_PASSWORD', "secret", " Password to use to initially bind to the LDAP server, as the DN specified in the LDAP_AUTH_USER option (above)."); -$properties["LDAP SEARCH FIELD"] = - new _define_optional('LDAP_SEARCH_FIELD', "uid", " + $properties["LDAP SEARCH FIELD"] = + new _define_optional('LDAP_SEARCH_FIELD', "uid", " If you want to match usernames against an attribute other than uid, specify it here. Default: uid e.g.: LDAP_SEARCH_FIELD = sAMAccountName"); -$properties["LDAP OU USERS"] = - new _define_optional('LDAP_OU_USERS', "ou=Users", " + $properties["LDAP OU USERS"] = + new _define_optional('LDAP_OU_USERS', "ou=Users", " If you have an organizational unit for all users, define it here. This narrows the search, and is needed for LDAP group membership (if GROUP_METHOD=LDAP) Default: ou=Users"); -$properties["LDAP OU GROUP"] = - new _define_optional('LDAP_OU_GROUP', "ou=Groups", " + $properties["LDAP OU GROUP"] = + new _define_optional('LDAP_OU_GROUP', "ou=Groups", " If you have an organizational unit for all groups, define it here. This narrows the search, and is needed for LDAP group membership (if GROUP_METHOD=LDAP) The entries in this ou must have a gidNumber and cn attribute. @@ -1141,8 +1189,8 @@ Default: ou=Groups"); } else { // function_exists('ldap_connect') -$properties["LDAP Authentication"] = -new unchangeable_variable('LDAP Authentication', " + $properties["LDAP Authentication"] = + new unchangeable_variable('LDAP Authentication', " ; If USER_AUTH_ORDER contains Ldap: ; ; The LDAP server to connect to. Can either be a hostname, or a complete @@ -1188,8 +1236,8 @@ new unchangeable_variable('LDAP Authentication', " if (function_exists('imap_open')) { -$properties["IMAP Auth Host"] = - new _define_optional('IMAP_AUTH_HOST', 'localhost:143/imap/notls', " + $properties["IMAP Auth Host"] = + new _define_optional('IMAP_AUTH_HOST', 'localhost:143/imap/notls', " If USER_AUTH_ORDER contains IMAP: The IMAP server to check usernames from. Defaults to localhost. @@ -1200,8 +1248,8 @@ Some IMAP_AUTH_HOST samples: } else { // function_exists('imap_open') -$properties["IMAP Authentication"] = - new unchangeable_variable('IMAP_AUTH_HOST'," + $properties["IMAP Authentication"] = + new unchangeable_variable('IMAP_AUTH_HOST', " ; If USER_AUTH_ORDER contains IMAP: ; The IMAP server to check usernames from. Defaults to localhost. ; @@ -1214,55 +1262,55 @@ Ignored. No IMAP support in this php. configure --with-imap"); } $properties["POP3 Authentication"] = - new _define_optional('POP3_AUTH_HOST', 'localhost:110', " + new _define_optional('POP3_AUTH_HOST', 'localhost:110', " If USER_AUTH_ORDER contains POP3: The POP3 mail server to check usernames and passwords against."); $properties["File Authentication"] = - new _define_optional('AUTH_USER_FILE', '/etc/shadow', " + new _define_optional('AUTH_USER_FILE', '/etc/shadow', " If USER_AUTH_ORDER contains File: File to read for authentication information. Popular choices are /etc/shadow and /etc/httpd/.htpasswd"); $properties["File Storable?"] = -new boolean_define_commented_optional('AUTH_USER_FILE_STORABLE'); + new boolean_define_commented_optional('AUTH_USER_FILE_STORABLE'); $properties["Session Auth USER"] = - new _define_optional('AUTH_SESS_USER', 'userid', " + new _define_optional('AUTH_SESS_USER', 'userid', " If USER_AUTH_ORDER contains Session: Name of the session variable which holds the already authenticated username. Sample: 'userid', 'user[username]', 'user->username'"); $properties["Session Auth LEVEL"] = - new numeric_define('AUTH_SESS_LEVEL', '2', " + new numeric_define('AUTH_SESS_LEVEL', '2', " Which level will the user be? 1 = Bogo or 2 = Pass"); ///////////////////////////////////////////////////////////////////// $properties["Part Four"] = -new part('_part4', $SEPARATOR."\n", " + new part('_part4', $SEPARATOR . "\n", " Part Four: Page appearance and layout"); $properties["Theme"] = -new _define_selection_optional('THEME', - array('default' => "default", - 'MacOSX' => "MacOSX", - 'smaller' => 'smaller', - 'Wordpress'=> 'Wordpress', - 'Portland' => "Portland", - 'Sidebar' => "Sidebar", - 'Crao' => 'Crao', - 'wikilens' => 'wikilens (Ratings)', - 'shamino_com' => 'shamino_com', - 'SpaceWiki' => "SpaceWiki", - 'Hawaiian' => "Hawaiian", - 'MonoBook' => 'MonoBook [experimental]', - 'blog' => 'blog [experimental]', - ), " + new _define_selection_optional('THEME', + array('default' => "default", + 'MacOSX' => "MacOSX", + 'smaller' => 'smaller', + 'Wordpress' => 'Wordpress', + 'Portland' => "Portland", + 'Sidebar' => "Sidebar", + 'Crao' => 'Crao', + 'wikilens' => 'wikilens (Ratings)', + 'shamino_com' => 'shamino_com', + 'SpaceWiki' => "SpaceWiki", + 'Hawaiian' => "Hawaiian", + 'MonoBook' => 'MonoBook [experimental]', + 'blog' => 'blog [experimental]', + ), " THEME Most of the page appearance is controlled by files in the theme @@ -1293,17 +1341,17 @@ $properties["Ignore Charset Not Supported Warning"] = new _define_optional('IGNORE_CHARSET_NOT_SUPPORTED_WARNING'); $properties["Language"] = -new _define_selection_optional('DEFAULT_LANGUAGE', - array('en' => "English", - '' => "<empty> (user-specific)", - 'fr' => "Français", - 'de' => "Deutsch", - 'nl' => "Nederlands", - 'es' => "Español", - 'sv' => "Svenska", - 'it' => "Italiano", - 'ja' => "Japanese", - 'zh' => "Chinese"), " + new _define_selection_optional('DEFAULT_LANGUAGE', + array('en' => "English", + '' => "<empty> (user-specific)", + 'fr' => "Français", + 'de' => "Deutsch", + 'nl' => "Nederlands", + 'es' => "Español", + 'sv' => "Svenska", + 'it' => "Italiano", + 'ja' => "Japanese", + 'zh' => "Chinese"), " Select your language/locale - default language is \"en\" for English. Other languages available:
 English  \"en\" (English    - HomePage)
@@ -1321,7 +1369,7 @@ If you set DEFAULT_LANGUAGE to the empty string, your systems default language
 used.");
 
 $properties["Wiki Page Source"] =
-new _define_optional('WIKI_PGSRC', 'pgsrc', "
+    new _define_optional('WIKI_PGSRC', 'pgsrc', "
 WIKI_PGSRC -- specifies the source for the initial page contents of
 the Wiki. The setting of WIKI_PGSRC only has effect when the wiki is
 accessed for the first time (or after clearing the database.)
@@ -1337,7 +1385,7 @@ define('WIKI_PGSRC',
 
"); $properties["Default Wiki Page Source"] = -new _define('DEFAULT_WIKI_PGSRC', 'pgsrc', " + new _define('DEFAULT_WIKI_PGSRC', 'pgsrc', " DEFAULT_WIKI_PGSRC is only used when the language is *not* the default (English) and when reading from a directory: in that case some English pages are inserted into the wiki as well. @@ -1345,20 +1393,20 @@ DEFAULT_WIKI_PGSRC defines where the English pages reside. "); $properties["Generic Pages"] = -new array_variable('DEFAULT_WIKI_PAGES', array('ReleaseNotes', 'SteveWainstead', 'TestPage'), " + new array_variable('DEFAULT_WIKI_PAGES', array('ReleaseNotes', 'SteveWainstead', 'TestPage'), " These are ':'-seperated pages which will get loaded untranslated from DEFAULT_WIKI_PGSRC. "); /////////////////// $properties["Part Five"] = -new part('_part5', $SEPARATOR."\n", " + new part('_part5', $SEPARATOR . "\n", " Part Five: Mark-up options"); $properties["Allowed Protocols"] = -new list_define('ALLOWED_PROTOCOLS', 'http|https|mailto|ftp|news|nntp|ssh|gopher', " + new list_define('ALLOWED_PROTOCOLS', 'http|https|mailto|ftp|news|nntp|ssh|gopher', " Allowed protocols for links - be careful not to allow \"javascript:\" URL of these types will be automatically linked. within a named link [name|uri] one more protocol is defined: phpwiki"); @@ -1367,18 +1415,18 @@ $properties["Inline Images"] = new list_define('INLINE_IMAGES', 'png|jpg|jpeg|gif'); $properties["WikiName Regexp"] = -new _define('WIKI_NAME_REGEXP', "(? @@ -1429,21 +1477,21 @@ $properties["AUTHORPAGE_URL"] = Default Author URL"); $properties["TOC_FULL_SYNTAX"] = -new boolean_define_optional('TOC_FULL_SYNTAX'); + new boolean_define_optional('TOC_FULL_SYNTAX'); $properties["ENABLE_MARKUP_COLOR"] = -new boolean_define_optional('ENABLE_MARKUP_COLOR'); + new boolean_define_optional('ENABLE_MARKUP_COLOR'); $properties["DISABLE_MARKUP_WIKIWORD"] = -new boolean_define_optional('DISABLE_MARKUP_WIKIWORD'); + new boolean_define_optional('DISABLE_MARKUP_WIKIWORD'); -$properties["ENABLE_MARKUP_DIVSPAN" ] = -new boolean_define_optional('ENABLE_MARKUP_DIVSPAN'); +$properties["ENABLE_MARKUP_DIVSPAN"] = + new boolean_define_optional('ENABLE_MARKUP_DIVSPAN'); /////////////////// $properties["Part Six"] = -new part('_part6', $SEPARATOR."\n", " + new part('_part6', $SEPARATOR . "\n", " Part Six (optional): URL options -- you can probably skip this section. @@ -1457,12 +1505,12 @@ Canonical name of the server on which this PhpWiki resides."); $properties["Server Port"] = new numeric_define_commented('SERVER_PORT', $_SERVER['SERVER_PORT'], " Canonical httpd port of the server on which this PhpWiki resides.", -"onchange=\"validate_ereg('Sorry, \'%s\' is no valid port number.', '^[0-9]+$', 'SERVER_PORT', this);\""); + "onchange=\"validate_ereg('Sorry, \'%s\' is no valid port number.', '^[0-9]+$', 'SERVER_PORT', this);\""); $properties["Server Protocol"] = new _define_selection_optional_commented('SERVER_PROTOCOL', - array('http' => 'http', - 'https' => 'https')); + array('http' => 'http', + 'https' => 'https')); $properties["Script Name"] = new _define_commented_optional('SCRIPT_NAME', $scriptname); @@ -1471,13 +1519,13 @@ $properties["Data Path"] = new _define_commented_optional('DATA_PATH', dirname($scriptname)); $properties["PhpWiki Install Directory"] = -new _define_commented_optional('PHPWIKI_DIR', dirname(__FILE__)); + new _define_commented_optional('PHPWIKI_DIR', dirname(__FILE__)); $properties["Use PATH_INFO"] = -new _define_selection_optional_commented('USE_PATH_INFO', - array('' => 'automatic', - 'true' => 'use PATH_INFO', - 'false' => 'do not use PATH_INFO'), " + new _define_selection_optional_commented('USE_PATH_INFO', + array('' => 'automatic', + 'true' => 'use PATH_INFO', + 'false' => 'do not use PATH_INFO'), " PhpWiki will try to use short urls to pages, eg http://www.example.com/index.php/HomePage If you want to use urls like @@ -1496,7 +1544,7 @@ is supported in by your webserver/PHP configuration, and will use PATH_INFO if it thinks that is possible."); $properties["Virtual Path"] = -new _define_commented_optional('VIRTUAL_PATH', '/SomeWiki', " + new _define_commented_optional('VIRTUAL_PATH', '/SomeWiki', " VIRTUAL_PATH is the canonical URL path under which your your wiki appears. Normally this is the same as dirname(SCRIPT_NAME), however using e.g. seperate starter scripts, apaches mod_actions (or mod_rewrite), @@ -1528,12 +1576,12 @@ new _define_optional('UPLOAD_DATA_PATH', $temp); $temp = !empty($_ENV['TEMP']) ? $_ENV['TEMP'] : "/tmp"; $properties["TEMP_DIR"] = -new _define_optional('TEMP_DIR', $temp); + new _define_optional('TEMP_DIR', $temp); /////////////////// $properties["Part Seven"] = -new part('_part7', $SEPARATOR."\n", " + new part('_part7', $SEPARATOR . "\n", " Part Seven: @@ -1542,8 +1590,8 @@ Miscellaneous settings $properties["Strict Mailable Pagedumps"] = new boolean_define_optional('STRICT_MAILABLE_PAGEDUMPS', - array('false' => "binary", - 'true' => "quoted-printable")); + array('false' => "binary", + 'true' => "quoted-printable")); $properties["Default local Dump Directory"] = new _define_optional('DEFAULT_DUMP_DIR'); @@ -1556,7 +1604,7 @@ $properties["HTML Dump Filename Suffix"] = $properties["Pagename of Recent Changes"] = new _define_optional('RECENT_CHANGES', - "RecentChanges"); + "RecentChanges"); $properties["Disable HTTP Redirects"] = new boolean_define_commented_optional('DISABLE_HTTP_REDIRECT'); @@ -1577,7 +1625,7 @@ $properties["FULLTEXTSEARCH_STOPLIST"] = new _define_commented_optional('FULLTEXTSEARCH_STOPLIST'); $properties["Part Seven A"] = - new part('_part7a', $SEPARATOR."\n", " + new part('_part7a', $SEPARATOR . "\n", " Part Seven A: @@ -1585,7 +1633,7 @@ Optional Plugin Settings and external executables "); $properties["FORTUNE_DIR"] = - new _define_commented_optional('FORTUNE_DIR', "/usr/share/fortune"); + new _define_commented_optional('FORTUNE_DIR', "/usr/share/fortune"); $properties["USE_EXTERNAL_HTML2PDF"] = new _define_commented_optional('USE_EXTERNAL_HTML2PDF', "htmldoc --quiet --format pdf14 --no-toc --no-title %s"); $properties["EXTERNAL_HTML2PDF_PAGELIST"] = @@ -1593,22 +1641,22 @@ $properties["EXTERNAL_HTML2PDF_PAGELIST"] = $properties["BABYCART_PATH"] = new _define_commented_optional('BABYCART_PATH', "/usr/local/bin/babycart"); $properties["GOOGLE_LICENSE_KEY"] = - new _define_commented_optional('GOOGLE_LICENSE_KEY'); + new _define_commented_optional('GOOGLE_LICENSE_KEY'); $properties["RATEIT_IMGPREFIX"] = new _define_commented_optional('RATEIT_IMGPREFIX'); //BStar $properties["GRAPHVIZ_EXE"] = new _define_commented_optional('GRAPHVIZ_EXE'); // /usr/local/bin/dot if (PHP_OS == "Darwin") // Mac OS X - $ttfont = "/System/Library/Frameworks/JavaVM.framework/Versions/1.3.1/Home/lib/fonts/LucidaSansRegular.ttf"; + $ttfont = "/System/Library/Frameworks/JavaVM.framework/Versions/1.3.1/Home/lib/fonts/LucidaSansRegular.ttf"; elseif (isWindows()) { - $ttfont = $_ENV['windir'].'\Fonts\Arial.ttf'; + $ttfont = $_ENV['windir'] . '\Fonts\Arial.ttf'; } else { $ttfont = 'luximr'; // This is the only what sourceforge offered. //$ttfont = 'Helvetica'; } $properties["TTFONT"] = - new _define_commented_optional('TTFONT',$ttfont); + new _define_commented_optional('TTFONT', $ttfont); $properties["VISUALWIKIFONT"] = new _define_commented_optional('VISUALWIKIFONT'); // Arial $properties["VISUALWIKI_ALLOWOPTIONS"] = @@ -1627,7 +1675,7 @@ $properties["HIGHLIGHT_DATA_DIR"] = new _define_commented_optional('HIGHLIGHT_DATA_DIR'); // /usr/share/highlight $properties["Part Eight"] = -new part('_part8', $SEPARATOR."\n", " + new part('_part8', $SEPARATOR . "\n", " Part Eight: @@ -1635,42 +1683,42 @@ Cached Plugin Settings. (pear Cache) "); $properties["pear Cache USECACHE"] = -new boolean_define_optional('PLUGIN_CACHED_USECACHE', - array('true' => 'Enabled', - 'false' => 'Disabled'), " + new boolean_define_optional('PLUGIN_CACHED_USECACHE', + array('true' => 'Enabled', + 'false' => 'Disabled'), " Enable or disable pear caching of plugins."); $properties["pear Cache Database Container"] = -new _define_selection_optional('PLUGIN_CACHED_DATABASE', - array('file' => 'file'), " + new _define_selection_optional('PLUGIN_CACHED_DATABASE', + array('file' => 'file'), " Curently only file is supported. db, trifile and imgfile might be supported, but you must hack that by yourself."); $properties["pear Cache cache directory"] = -new _define_commented_optional('PLUGIN_CACHED_CACHE_DIR', "/tmp/cache", " + new _define_commented_optional('PLUGIN_CACHED_CACHE_DIR', "/tmp/cache", " Should be writable to the webserver."); $properties["pear Cache Filename Prefix"] = -new _define_optional('PLUGIN_CACHED_FILENAME_PREFIX', "phpwiki", ""); + new _define_optional('PLUGIN_CACHED_FILENAME_PREFIX', "phpwiki", ""); $properties["pear Cache HIGHWATER"] = -new numeric_define_optional('PLUGIN_CACHED_HIGHWATER', "4194304", " + new numeric_define_optional('PLUGIN_CACHED_HIGHWATER', "4194304", " Garbage collection parameter."); $properties["pear Cache LOWWATER"] = -new numeric_define_optional('PLUGIN_CACHED_LOWWATER', "3145728", " + new numeric_define_optional('PLUGIN_CACHED_LOWWATER', "3145728", " Garbage collection parameter."); $properties["pear Cache MAXLIFETIME"] = -new numeric_define_optional('PLUGIN_CACHED_MAXLIFETIME', "2592000", " + new numeric_define_optional('PLUGIN_CACHED_MAXLIFETIME', "2592000", " Garbage collection parameter."); $properties["pear Cache MAXARGLEN"] = -new numeric_define_optional('PLUGIN_CACHED_MAXARGLEN', "1000", " + new numeric_define_optional('PLUGIN_CACHED_MAXARGLEN', "1000", " max. generated url length."); $properties["pear Cache FORCE_SYNCMAP"] = -new boolean_define_optional('PLUGIN_CACHED_FORCE_SYNCMAP', - array('true' => 'Enabled', - 'false' => 'Disabled'), ""); + new boolean_define_optional('PLUGIN_CACHED_FORCE_SYNCMAP', + array('true' => 'Enabled', + 'false' => 'Disabled'), ""); $properties["pear Cache IMGTYPES"] = -new list_define('PLUGIN_CACHED_IMGTYPES', "png|gif|gd|gd2|jpeg|wbmp|xbm|xpm", " + new list_define('PLUGIN_CACHED_IMGTYPES', "png|gif|gd|gd2|jpeg|wbmp|xbm|xpm", " Handle those image types via GD handles. Check your GD supported image types."); -$end = "\n".$SEPARATOR."\n"; +$end = "\n" . $SEPARATOR . "\n"; // performance hack text_from_dist("_MAGIC_CLOSE_FILE"); @@ -1687,7 +1735,8 @@ text_from_dist("_MAGIC_CLOSE_FILE"); * e.g.: * $WikiNameRegexp = "value"; */ -class _variable { +class _variable +{ var $config_item_name; var $default_value; @@ -1695,41 +1744,44 @@ class _variable { var $prefix; var $jscheck; - function _variable($config_item_name, $default_value='', $description = '', $jscheck = '') { + function _variable($config_item_name, $default_value = '', $description = '', $jscheck = '') + { $this->config_item_name = $config_item_name; if (!$description) $description = text_from_dist($config_item_name); $this->description = $description; if (defined($config_item_name) and !preg_match("/(selection|boolean)/", get_class($this)) - and !preg_match("/^(SCRIPT_NAME|VIRTUAL_PATH|TEMP_DIR)$/", $config_item_name)) + and !preg_match("/^(SCRIPT_NAME|VIRTUAL_PATH|TEMP_DIR)$/", $config_item_name) + ) $this->default_value = constant($config_item_name); // ignore given default value elseif ($config_item_name == $default_value) - $this->default_value = ''; - else + $this->default_value = ''; else $this->default_value = $default_value; $this->jscheck = $jscheck; if (preg_match("/variable/i", get_class($this))) $this->prefix = "\$"; elseif (preg_match("/ini_set/i", get_class($this))) - $this->prefix = "ini_get: "; - else + $this->prefix = "ini_get: "; else $this->prefix = ""; } - function _define($config_item_name, $default_value='', $description = '', $jscheck = '') { - $this->_variable($config_item_name, $default_value, $description, $jscheck); + function _define($config_item_name, $default_value = '', $description = '', $jscheck = '') + { + $this->_variable($config_item_name, $default_value, $description, $jscheck); } - function value() { - global $HTTP_POST_VARS; - if (isset($HTTP_POST_VARS[$this->config_item_name])) - return $HTTP_POST_VARS[$this->config_item_name]; - else - return $this->default_value; + function value() + { + global $HTTP_POST_VARS; + if (isset($HTTP_POST_VARS[$this->config_item_name])) + return $HTTP_POST_VARS[$this->config_item_name]; + else + return $this->default_value; } - function _config_format($value) { + function _config_format($value) + { return ''; $v = $this->get_config_item_name(); // handle arrays: a|b --> a['b'] @@ -1742,47 +1794,53 @@ class _variable { return sprintf("%s = \"%s\"", $v, $value); } - function get_config_item_name() { + function get_config_item_name() + { return $this->config_item_name; } - function get_config_item_id() { + function get_config_item_id() + { return str_replace('|', '-', $this->config_item_name); } - function get_config_item_header() { - if (strchr($this->config_item_name,'|')) { - list($var,$param) = explode('|',$this->config_item_name); - return "" . $this->prefix . $var . "['" . $param . "']
"; - } - elseif ($this->config_item_name[0] != '_') - return "" . $this->prefix . $this->config_item_name . "
"; - else - return ''; + function get_config_item_header() + { + if (strchr($this->config_item_name, '|')) { + list($var, $param) = explode('|', $this->config_item_name); + return "" . $this->prefix . $var . "['" . $param . "']
"; + } elseif ($this->config_item_name[0] != '_') + return "" . $this->prefix . $this->config_item_name . "
"; else + return ''; } - function _get_description() { + function _get_description() + { return $this->description; } - function _get_config_line($posted_value) { + function _get_config_line($posted_value) + { return "\n" . $this->_config_format($posted_value); } - function get_config($posted_value) { + function get_config($posted_value) + { $d = stripHtml($this->_get_description()); - $d = str_replace("\n", "\n; ", $d) . $this->_get_config_line($posted_value) ."\n"; + $d = str_replace("\n", "\n; ", $d) . $this->_get_config_line($posted_value) . "\n"; return $d; } - function get_instructions($title) { + function get_instructions($title) + { global $tdwidth; $i = "

" . $title . "

\n " . nl2p($this->_get_description()) . "\n"; return "\n\n" . $i . "\n"; } - function get_html() { - $size = strlen($this->default_value) > 45 ? 90 : 50; + function get_html() + { + $size = strlen($this->default_value) > 45 ? 90 : 50; return $this->get_config_item_header() . "get_config_item_name() . "\" value=\"" . htmlspecialchars($this->default_value) . "\" " . $this->jscheck . " />" . "

get_config_item_id() . "\" style=\"color: green\">Input accepted.

"; @@ -1790,53 +1848,69 @@ class _variable { } class unchangeable_variable -extends _variable { - function _config_format($value) { + extends _variable +{ + function _config_format($value) + { return ""; } + // function get_html() { return false; } - function get_html() { + function get_html() + { return $this->get_config_item_header() . - "Not editable." . - "
" . $this->default_value."
"; + "Not editable." . + "
" . $this->default_value . "
"; } - function _get_config_line($posted_value) { + + function _get_config_line($posted_value) + { if ($this->description) $n = "\n"; - return "${n}".$this->default_value; + return "${n}" . $this->default_value; } - function get_instructions($title) { + + function get_instructions($title) + { global $tdwidth; $i = "

" . $title . "

\n " . nl2p($this->_get_description()) . "\n"; // $i .= "Not editable.
\n
" . $this->default_value."
"; - return ''."\n".$i."\n" - . ' '; + return '' . "\n" . $i . "\n" + . ' '; } } class unchangeable_define -extends unchangeable_variable { - function _get_config_line($posted_value) { + extends unchangeable_variable +{ + function _get_config_line($posted_value) + { if ($this->description) $n = "\n"; if (!$posted_value) $posted_value = $this->default_value; - return "${n}".$this->_config_format($posted_value); + return "${n}" . $this->_config_format($posted_value); } - function _config_format($value) { + + function _config_format($value) + { return sprintf("%s = \"%s\"", $this->get_config_item_name(), $value); } } class unchangeable_ini_set -extends unchangeable_variable { - function _config_format($value) { + extends unchangeable_variable +{ + function _config_format($value) + { return ""; } } class _variable_selection -extends _variable { - function value() { + extends _variable +{ + function value() + { global $HTTP_POST_VARS; if (!empty($HTTP_POST_VARS[$this->config_item_name])) return $HTTP_POST_VARS[$this->config_item_name]; @@ -1845,7 +1919,9 @@ extends _variable { return $option; } } - function get_html() { + + function get_html() + { $output = $this->get_config_item_header(); $output .= 'get_config_item_name()) . "\" value=\"" . htmlentities($this->default_value) . "\" {$this->jscheck} />" @@ -1889,15 +1971,16 @@ extends _variable { } class _define_commented -extends _define { - function _get_config_line($posted_value) { + extends _define +{ + function _get_config_line($posted_value) + { if ($this->description) $n = "\n"; if ($posted_value == $this->default_value) return "${n};" . $this->_config_format($posted_value); elseif ($posted_value == '') - return "${n};" . $this->_config_format(""); - else + return "${n};" . $this->_config_format(""); else return "${n}" . $this->_config_format($posted_value); } } @@ -1908,14 +1991,20 @@ extends _define { * But we use _optional for config-default.ini options */ class _define_commented_optional -extends _define_commented { } + extends _define_commented +{ +} class _define_optional -extends _define { } + extends _define +{ +} class _define_notempty -extends _define { - function get_html() { + extends _define +{ + function get_html() + { $s = $this->get_config_item_header() . "get_config_item_name() . "\" value=\"" . $this->default_value . "\" {$this->jscheck} />"; @@ -1927,32 +2016,39 @@ extends _define { } class _variable_commented -extends _variable { - function _get_config_line($posted_value) { + extends _variable +{ + function _get_config_line($posted_value) + { if ($this->description) $n = "\n"; if ($posted_value == $this->default_value) return "${n};" . $this->_config_format($posted_value); elseif ($posted_value == '') - return "${n};" . $this->_config_format(""); - else + return "${n};" . $this->_config_format(""); else return "${n}" . $this->_config_format($posted_value); } } class numeric_define -extends _define { + extends _define +{ - function numeric_define($config_item_name, $default_value='', $description = '', $jscheck = '') { + function numeric_define($config_item_name, $default_value = '', $description = '', $jscheck = '') + { $this->_define($config_item_name, $default_value, $description, $jscheck); if (!$jscheck) $this->jscheck = "onchange=\"validate_ereg('Sorry, \'%s\' is not an integer.', '^[-+]?[0-9]+$', '" . $this->get_config_item_name() . "', this);\""; } - function _config_format($value) { + + function _config_format($value) + { //return sprintf("define('%s', %s);", $this->get_config_item_name(), $value); return sprintf("%s = %s", $this->get_config_item_name(), $value); } - function _get_config_line($posted_value) { + + function _get_config_line($posted_value) + { if ($this->description) $n = "\n"; if ($posted_value == '') @@ -1963,66 +2059,84 @@ extends _define { } class numeric_define_optional -extends numeric_define {} + extends numeric_define +{ +} class numeric_define_commented -extends numeric_define { - function _get_config_line($posted_value) { + extends numeric_define +{ + function _get_config_line($posted_value) + { if ($this->description) $n = "\n"; if ($posted_value == $this->default_value) return "${n};" . $this->_config_format($posted_value); elseif ($posted_value == '') - return "${n};" . $this->_config_format('0'); - else + return "${n};" . $this->_config_format('0'); else return "${n}" . $this->_config_format($posted_value); } } class _define_selection -extends _variable_selection { - function _config_format($value) { + extends _variable_selection +{ + function _config_format($value) + { return sprintf("%s = %s", $this->get_config_item_name(), $value); } - function _get_config_line($posted_value) { + + function _get_config_line($posted_value) + { return _define::_get_config_line($posted_value); } - function get_html() { + + function get_html() + { return _variable_selection::get_html(); } } class _define_selection_optional -extends _define_selection { } + extends _define_selection +{ +} class _variable_selection_optional -extends _variable_selection { } + extends _variable_selection +{ +} class _define_selection_optional_commented -extends _define_selection_optional { - function _get_config_line($posted_value) { + extends _define_selection_optional +{ + function _get_config_line($posted_value) + { if ($this->description) $n = "\n"; if ($posted_value == $this->default_value) return "${n};" . $this->_config_format($posted_value); elseif ($posted_value == '') - return "${n};" . $this->_config_format(""); - else + return "${n};" . $this->_config_format(""); else return "${n}" . $this->_config_format($posted_value); } } class _define_password -extends _define { + extends _define +{ - function _define_password($config_item_name, $default_value='', $description = '', $jscheck = '') { - if ($config_item_name == $default_value) $default_value = ''; + function _define_password($config_item_name, $default_value = '', $description = '', $jscheck = '') + { + if ($config_item_name == $default_value) $default_value = ''; $this->_define($config_item_name, $default_value, $description, $jscheck); if (!$jscheck) $this->jscheck = "onchange=\"validate_ereg('Sorry, \'%s\' cannot be empty.', '^.+$', '" . $this->get_config_item_name() . "', this);\""; } - function _get_config_line($posted_value) { + + function _get_config_line($posted_value) + { if ($this->description) $n = "\n"; if ($posted_value == '') { @@ -2034,10 +2148,10 @@ extends _define { } else { if (function_exists('crypt')) { $salt_length = max(CRYPT_SALT_LENGTH, - 2 * CRYPT_STD_DES, - 9 * CRYPT_EXT_DES, - 12 * CRYPT_MD5, - 16 * CRYPT_BLOWFISH); + 2 * CRYPT_STD_DES, + 9 * CRYPT_EXT_DES, + 12 * CRYPT_MD5, + 16 * CRYPT_BLOWFISH); // generate an encrypted password $crypt_pass = crypt($posted_value, rand_ascii($salt_length)); $p = "${n}" . $this->_config_format($crypt_pass); @@ -2051,21 +2165,26 @@ extends _define { } } } - function get_html() { + + function get_html() + { return _variable_password::get_html(); } } class _define_password_optional -extends _define_password { + extends _define_password +{ - function _define_password_optional($config_item_name, $default_value='', $description = '', $jscheck = '') { - if ($config_item_name == $default_value) $default_value = ''; + function _define_password_optional($config_item_name, $default_value = '', $description = '', $jscheck = '') + { + if ($config_item_name == $default_value) $default_value = ''; if (!$jscheck) $this->jscheck = " "; $this->_define($config_item_name, $default_value, $description, $jscheck); } - function _get_config_line($posted_value) { + function _get_config_line($posted_value) + { if ($this->description) $n = "\n"; if ($posted_value == '') { @@ -2074,32 +2193,40 @@ extends _define_password { return "${n}" . $this->_config_format($posted_value); } } - function get_html() { + + function get_html() + { $s = $this->get_config_item_header(); // dont re-encrypt already encrypted passwords $value = $this->value(); $encrypted = !empty($GLOBALS['properties']["Encrypted Passwords"]) and - $GLOBALS['properties']["Encrypted Passwords"]->value(); + $GLOBALS['properties']["Encrypted Passwords"]->value(); if (empty($value)) $encrypted = false; - $s .= "get_config_item_name() - . "\" value=\"" . $value . "\" {$this->jscheck} />"; + $s .= "get_config_item_name() + . "\" value=\"" . $value . "\" {$this->jscheck} />"; return $s; } } class _define_password_commented_optional -extends _define_password_optional { } + extends _define_password_optional +{ +} class _variable_password -extends _variable { - function _variable_password($config_item_name, $default_value='', $description = '', $jscheck = '') { - if ($config_item_name == $default_value) $default_value = ''; + extends _variable +{ + function _variable_password($config_item_name, $default_value = '', $description = '', $jscheck = '') + { + if ($config_item_name == $default_value) $default_value = ''; $this->_define($config_item_name, $default_value, $description, $jscheck); if (!$jscheck) $this->jscheck = "onchange=\"validate_ereg('Sorry, \'%s\' cannot be empty.', '^.+$', '" . $this->get_config_item_name() . "', this);\""; } - function get_html() { + + function get_html() + { global $HTTP_POST_VARS, $HTTP_GET_VARS; $s = $this->get_config_item_header(); if (isset($HTTP_POST_VARS['create']) or isset($HTTP_GET_VARS['create'])) { @@ -2110,25 +2237,26 @@ extends _variable { // dont re-encrypt already encrypted passwords $value = $this->value(); $encrypted = !empty($GLOBALS['properties']["Encrypted Passwords"]) and - $GLOBALS['properties']["Encrypted Passwords"]->value(); + $GLOBALS['properties']["Encrypted Passwords"]->value(); if (empty($value)) $encrypted = false; - $s .= "get_config_item_name() - . "\" value=\"" . $value . "\" {$this->jscheck} />" - . "  "; + $s .= "get_config_item_name() + . "\" value=\"" . $value . "\" {$this->jscheck} />" + . "  "; if (empty($value)) $s .= "

get_config_item_id() . "\" style=\"color: red\">Cannot be empty.

"; elseif (strlen($this->default_value) < 4) - $s .= "

get_config_item_id() . "\" style=\"color: red\">Must be longer than 4 chars.

"; - else + $s .= "

get_config_item_id() . "\" style=\"color: red\">Must be longer than 4 chars.

"; else $s .= "

get_config_item_id() . "\" style=\"color: green\">Input accepted.

"; return $s; } } class list_variable -extends _variable { - function _get_config_line($posted_value) { + extends _variable +{ + function _get_config_line($posted_value) + { // split the phrase by any number of commas or space characters, // which include " ", \r, \t, \n and \f $list_values = preg_split("/[\s,]+/", $posted_value, -1, PREG_SPLIT_NO_EMPTY); @@ -2136,12 +2264,14 @@ extends _variable { $list_values = join("|", $list_values); return _variable::_get_config_line($list_values); } - function get_html() { + + function get_html() + { $list_values = explode("|", $this->default_value); - $rows = max(3, count($list_values) +1); + $rows = max(3, count($list_values) + 1); $list_values = join("\n", $list_values); $ta = $this->get_config_item_header(); - $ta .= ""; $ta .= "

get_config_item_id() . "\" style=\"color: green\">Input accepted.

"; return $ta; @@ -2149,20 +2279,24 @@ extends _variable { } class list_define -extends _define { - function _get_config_line($posted_value) { + extends _define +{ + function _get_config_line($posted_value) + { $list_values = preg_split("/[\s,]+/", $posted_value, -1, PREG_SPLIT_NO_EMPTY); if ($list_values) $list_values = join("|", $list_values); return _variable::_get_config_line($list_values); } - function get_html() { + + function get_html() + { $list_values = explode("|", $this->default_value); - $rows = max(3, count($list_values) +1); + $rows = max(3, count($list_values) + 1); if ($list_values) $list_values = join("\n", $list_values); $ta = $this->get_config_item_header(); - $ta .= ""; $ta .= "

get_config_item_id() . "\" style=\"color: green\">Input accepted.

"; return $ta; @@ -2170,29 +2304,35 @@ extends _define { } class array_variable -extends _variable { - function _config_format($value) { + extends _variable +{ + function _config_format($value) + { return sprintf("%s = \"%s\"", $this->get_config_item_name(), - is_array($value) ? join(':', $value) : $value); + is_array($value) ? join(':', $value) : $value); } - function _get_config_line($posted_value) { + + function _get_config_line($posted_value) + { // split the phrase by any number of commas or space characters, // which include " ", \r, \t, \n and \f $list_values = preg_split("/[\s,]+/", $posted_value, -1, PREG_SPLIT_NO_EMPTY); if (!empty($list_values)) { - $list_values = "'".join("', '", $list_values)."'"; + $list_values = "'" . join("', '", $list_values) . "'"; return "\n" . $this->_config_format($list_values); } else return "\n;" . $this->_config_format(''); } - function get_html() { - if (is_array($this->default_value)) + + function get_html() + { + if (is_array($this->default_value)) $list_values = join("\n", $this->default_value); else $list_values = $this->default_value; - $rows = max(3, count($this->default_value) +1); + $rows = max(3, count($this->default_value) + 1); $ta = $this->get_config_item_header(); - $ta .= ""; $ta .= "

get_config_item_id() . "\" style=\"color: green\">Input accepted.

"; return $ta; @@ -2200,12 +2340,16 @@ extends _variable { } class array_define -extends _define { - function _config_format($value) { + extends _define +{ + function _config_format($value) + { return sprintf("%s = \"%s\"", $this->get_config_item_name(), - is_array($value) ? join(' : ', $value) : $value); + is_array($value) ? join(' : ', $value) : $value); } - function _get_config_line($posted_value) { + + function _get_config_line($posted_value) + { // split the phrase by any number of commas or space characters, // which include " ", \r, \t, \n and \f $list_values = preg_split("/[\s,:]+/", $posted_value, -1, PREG_SPLIT_NO_EMPTY); @@ -2215,7 +2359,9 @@ extends _define { } else return "\n;" . $this->_config_format(''); } - function get_html () { + + function get_html() + { if (!$this->default_value) $this->default_value = array(); elseif (is_string($this->default_value)) @@ -2223,7 +2369,7 @@ extends _define { $list_values = join(" : \n", $this->default_value); $rows = max(3, count($this->default_value) + 1); $ta = $this->get_config_item_header(); - $ta .= ""; $ta .= "

get_config_item_id() . "\" style=\"color: green\">Input accepted.

"; return $ta; @@ -2254,10 +2400,12 @@ extends _variable { */ class boolean_define -extends _define { + extends _define +{ // adds ->values property, instead of ->default_value - function boolean_define($config_item_name, $values = false, $description = '', $jscheck = '') { + function boolean_define($config_item_name, $values = false, $description = '', $jscheck = '') + { $this->config_item_name = $config_item_name; if (!$description) $description = text_from_dist($config_item_name); @@ -2266,27 +2414,33 @@ extends _define { if (defined($config_item_name)) $this->default_value = constant($config_item_name); // ignore given default value elseif (is_array($values)) - list($this->default_value,$dummy) = $values[0]; + list($this->default_value, $dummy) = $values[0]; if (!$values) $values = array('false' => "Disabled", - 'true' => "Enabled"); - $this->values = $values; + 'true' => "Enabled"); + $this->values = $values; $this->jscheck = $jscheck; $this->prefix = ""; } - function _get_config_line($posted_value) { + + function _get_config_line($posted_value) + { if ($this->description) $n = "\n"; return "${n}" . $this->_config_format($posted_value); } - function _config_format($value) { + + function _config_format($value) + { if (strtolower(trim($value)) == 'false') $value = false; return sprintf("%s = %s", $this->get_config_item_name(), - (bool)$value ? 'true' : 'false'); + (bool)$value ? 'true' : 'false'); } + //TODO: radiobuttons, no list - function get_html() { + function get_html() + { $output = $this->get_config_item_header(); $name = $this->get_config_item_name(); $output .= ' '; @@ -2544,15 +2717,15 @@ if (!empty($HTTP_POST_VARS['action']) while (list($property, $obj) = each($properties)) { echo $obj->get_instructions($property); if ($h = $obj->get_html()) { - if (defined('DEBUG') and DEBUG) $h = get_class($obj) . "
\n" . $h; - echo "\n"; + if (defined('DEBUG') and DEBUG) $h = get_class($obj) . "
\n" . $h; + echo "\n"; } echo ''; } echo '
".$h."" . $h . "
-

+

'; } diff --git a/index.php b/index.php index e425b1b92..e88a2df27 100644 --- a/index.php +++ b/index.php @@ -28,9 +28,9 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -require_once (dirname(__FILE__).'/lib/prepend.php'); -require_once(dirname(__FILE__).'/lib/IniConfig.php'); -IniConfig(dirname(__FILE__)."/config/config.ini"); +require_once (dirname(__FILE__) . '/lib/prepend.php'); +require_once(dirname(__FILE__) . '/lib/IniConfig.php'); +IniConfig(dirname(__FILE__) . "/config/config.ini"); //////////////////////////////////////////////////////////////// // PrettyWiki @@ -50,7 +50,7 @@ IniConfig(dirname(__FILE__)."/config/config.ini"); // to force include "lib/main.php". // Without the dir check it might fail for index.php via DirectoryIndex if (@is_dir(SCRIPT_FILENAME) or realpath(SCRIPT_FILENAME) == realpath(__FILE__)) - include(dirname(__FILE__)."/lib/main.php"); + include(dirname(__FILE__) . "/lib/main.php"); // Local Variables: // mode: php diff --git a/lib/AccessLog.php b/lib/AccessLog.php index 4a431da4e..832e714c0 100644 --- a/lib/AccessLog.php +++ b/lib/AccessLog.php @@ -32,22 +32,24 @@ * Also needed for advanced spam prevention. * global object holding global state (sql or file, entries, to dump) */ -class Request_AccessLog { +class Request_AccessLog +{ /** * @param $logfile string Log file name. */ - function Request_AccessLog ($logfile, $do_sql = false) { + function Request_AccessLog($logfile, $do_sql = false) + { //global $request; // request not yet initialized! $this->logfile = $logfile; if ($logfile and !is_writeable($logfile)) { trigger_error - (sprintf(_("%s is not writable."), _("The PhpWiki access log file")) - . "\n" - . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."), - sprintf(_("the file '%s'"), ACCESS_LOG), - 'ACCESS_LOG') - , E_USER_NOTICE); + (sprintf(_("%s is not writable."), _("The PhpWiki access log file")) + . "\n" + . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."), + sprintf(_("the file '%s'"), ACCESS_LOG), + 'ACCESS_LOG') + , E_USER_NOTICE); } //$request->_accesslog =& $this; //if (empty($request->_accesslog->entries)) @@ -59,62 +61,81 @@ class Request_AccessLog { } else { global $DBParams; //$this->_dbi =& $request->_dbi; - $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '')."accesslog"; + $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog"; } } $this->entries = array(); $this->entries[] = new Request_AccessLogEntry($this); } - function _do($cmd, &$arg) { + function _do($cmd, &$arg) + { if ($this->entries) - for ($i=0; $i < count($this->entries);$i++) + for ($i = 0; $i < count($this->entries); $i++) $this->entries[$i]->$cmd($arg); } - function push(&$request) { $this->_do('push',$request); } - function setSize($arg) { $this->_do('setSize',$arg); } - function setStatus($arg) { $this->_do('setStatus',$arg); } - function setDuration($arg) { $this->_do('setDuration',$arg); } + + function push(&$request) + { + $this->_do('push', $request); + } + + function setSize($arg) + { + $this->_do('setSize', $arg); + } + + function setStatus($arg) + { + $this->_do('setStatus', $arg); + } + + function setDuration($arg) + { + $this->_do('setDuration', $arg); + } /** * Read sequentially all previous entries from the beginning. * while ($logentry = Request_AccessLogEntry::read()) ; * For internal log analyzers: RecentReferrers, WikiAccessRestrictions */ - function read() { + function read() + { return $this->logtable ? $this->read_sql() : $this->read_file(); } /** * Return iterator of referer items reverse sorted (latest first). */ - function get_referer($limit=15, $external_only=false) { + function get_referer($limit = 15, $external_only = false) + { if ($external_only) { // see stdlin.php:isExternalReferrer() $base = SERVER_URL; $blen = strlen($base); } if (!empty($this->_dbi)) { // check same hosts in referer and request and remove them - $ext_where = " AND LEFT(referer,$blen) <> ".$this->_dbi->quote($base) - ." AND LEFT(referer,$blen) <> LEFT(CONCAT(".$this->_dbi->quote(SERVER_URL).",request_uri),$blen)"; + $ext_where = " AND LEFT(referer,$blen) <> " . $this->_dbi->quote($base) + . " AND LEFT(referer,$blen) <> LEFT(CONCAT(" . $this->_dbi->quote(SERVER_URL) . ",request_uri),$blen)"; return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))" - .($external_only ? $ext_where : '') - ." ORDER BY time_stamp DESC" - .($limit ? " LIMIT $limit" : "")); + . ($external_only ? $ext_where : '') + . " ORDER BY time_stamp DESC" + . ($limit ? " LIMIT $limit" : "")); } else { $iter = new WikiDB_Array_generic_iter(0); $logs =& $iter->_array; while ($logentry = $this->read_file()) { if (!empty($logentry->referer) - and (!$external_only or (substr($logentry->referer,0,$blen) != $base))) - { + and (!$external_only or (substr($logentry->referer, 0, $blen) != $base)) + ) { $iter->_array[] = $logentry; if ($limit and count($logs) > $limit) array_shift($logs); } } $logs = array_reverse($logs); - $logs = array_slice($logs,0,min($limit,count($logs))); + $logs = array_slice($logs, 0, min($limit, count($logs))); return $iter; } } @@ -122,12 +143,13 @@ class Request_AccessLog { /** * Return iterator of matching host items reverse sorted (latest first). */ - function get_host($host, $since_minutes=20) { + function get_host($host, $since_minutes = 20) + { if ($this->logtable) { // mysql specific only: - return $this->read_sql("request_host=".$this->_dbi->quote($host) - ." AND time_stamp > ". (time()-$since_minutes*60) - ." ORDER BY time_stamp DESC"); + return $this->read_sql("request_host=" . $this->_dbi->quote($host) + . " AND time_stamp > " . (time() - $since_minutes * 60) + . " ORDER BY time_stamp DESC"); } else { $iter = new WikiDB_Array_generic_iter(); $logs =& $iter->_array; @@ -141,7 +163,7 @@ class Request_AccessLog { } } $logs = array_reverse($logs); - $logs = array_slice($logs,0,min($limit,count($logs))); + $logs = array_slice($logs, 0, min($limit, count($logs))); return $iter; } } @@ -150,19 +172,20 @@ class Request_AccessLog { * Read sequentially backwards all previous entries from log file. * FIXME! */ - function read_file() { + function read_file() + { global $request; if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read - if (empty($this->reader)) // start at the beginning + if (empty($this->reader)) // start at the beginning $this->reader = fopen($this->logfile, "r"); if ($s = fgets($this->reader)) { $entry = new Request_AccessLogEntry($this); $re = '/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/'; if (preg_match($re, $s, $m)) { - list(,$entry->host, $entry->ident, $entry->user, $entry->time, - $entry->request, $entry->status, $entry->size, - $entry->referer, $entry->user_agent) = $m; + list(, $entry->host, $entry->ident, $entry->user, $entry->time, + $entry->request, $entry->status, $entry->size, + $entry->referer, $entry->user_agent) = $m; } return $entry; } else { // until the end @@ -170,23 +193,28 @@ class Request_AccessLog { return false; } } - function read_sql($where='') { + + function read_sql($where = '') + { if (empty($this->sqliter)) $this->sqliter = $this->_read_sql_query($where); return $this->sqliter->next(); } - function _read_sql_query($where='') { + + function _read_sql_query($where = '') + { global $request; $dbh =& $request->_dbi; $log_tbl =& $this->logtable; return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user," - ."remote_host as host,agent as user_agent" - ." FROM $log_tbl" - . ($where ? " WHERE $where" : "")); + . "remote_host as host,agent as user_agent" + . " FROM $log_tbl" + . ($where ? " WHERE $where" : "")); } /* done in request->finish() before the db is closed */ - function write_sql() { + function write_sql() + { global $request; $dbh =& $request->_dbi; if (isset($this->entries) and $dbh and $dbh->isOpen()) @@ -194,16 +222,20 @@ class Request_AccessLog { $entry->write_sql(); } } + /* done in the shutdown callback */ - function write_file() { + function write_file() + { if (isset($this->entries) and $this->logfile) foreach ($this->entries as $entry) { $entry->write_file(); } unset($this->entries); } + /* in an ideal world... */ - function write() { + function write() + { if ($this->logfile) $this->write_file(); if ($this->logtable) $this->write_sql(); unset($this->entries); @@ -231,19 +263,21 @@ class Request_AccessLogEntry * * */ - function Request_AccessLogEntry (&$accesslog) { + function Request_AccessLogEntry(&$accesslog) + { $this->_accesslog = $accesslog; $this->logfile = $accesslog->logfile; $this->time = time(); - $this->status = 200; // see setStatus() - $this->size = 0; // see setSize() + $this->status = 200; // see setStatus() + $this->size = 0; // see setSize() } /** * @param $request object Request object for current request. */ - function push(&$request) { - $this->host = $request->get('REMOTE_HOST'); + function push(&$request) + { + $this->host = $request->get('REMOTE_HOST'); $this->ident = $request->get('REMOTE_IDENT'); if (!$this->ident) $this->ident = '-'; @@ -253,10 +287,10 @@ class Request_AccessLogEntry else $this->user = '-'; $this->request = join(' ', array($request->get('REQUEST_METHOD'), - $request->get('REQUEST_URI'), - $request->get('SERVER_PROTOCOL'))); - $this->referer = (string) $request->get('HTTP_REFERER'); - $this->user_agent = (string) $request->get('HTTP_USER_AGENT'); + $request->get('REQUEST_URI'), + $request->get('SERVER_PROTOCOL'))); + $this->referer = (string)$request->get('HTTP_REFERER'); + $this->user_agent = (string)$request->get('HTTP_USER_AGENT'); } /** @@ -264,7 +298,8 @@ class Request_AccessLogEntry * * @param $status integer HTTP status code. */ - function setStatus ($status) { + function setStatus($status) + { $this->status = $status; } @@ -273,13 +308,16 @@ class Request_AccessLogEntry * * @param $size integer */ - function setSize ($size=0) { + function setSize($size = 0) + { $this->size = (int)$size; } - function setDuration ($seconds) { + + function setDuration($seconds) + { // Pear DB does not correctly quote , in floats using ?. e.g. in european locales. // Workaround: - $this->duration = str_replace(",",".",sprintf("%f",$seconds)); + $this->duration = str_replace(",", ".", sprintf("%f", $seconds)); } /** @@ -290,7 +328,8 @@ class Request_AccessLogEntry * @param $time integer Unix timestamp (defaults to current time). * @return string Zone offset, e.g. "-0800" for PST. */ - function _zone_offset ($time = false) { + function _zone_offset($time = false) + { if (!$time) $time = time(); $offset = date("Z", $time); @@ -300,7 +339,7 @@ class Request_AccessLogEntry $offset = -$offset; } $offhours = floor($offset / 3600); - $offmins = $offset / 60 - $offhours * 60; + $offmins = $offset / 60 - $offhours * 60; return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins); } @@ -312,14 +351,16 @@ class Request_AccessLogEntry * @param $time integer Unix timestamp (defaults to current time). * @return string Formatted date & time. */ - function _ncsa_time($time = false) { + function _ncsa_time($time = false) + { if (!$time) $time = time(); return date("d/M/Y:H:i:s", $time) . " " . $this->_zone_offset(); } - function write() { + function write() + { if ($this->_accesslog->logfile) $this->write_file(); if ($this->_accesslog->logtable) $this->write_sql(); } @@ -327,12 +368,13 @@ class Request_AccessLogEntry /** * Write entry to log file. */ - function write_file() { + function write_file() + { $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"', - $this->host, $this->ident, $this->user, - $this->_ncsa_time($this->time), - $this->request, $this->status, $this->size, - $this->referer, $this->user_agent); + $this->host, $this->ident, $this->user, + $this->_ncsa_time($this->time), + $this->request, $this->status, $this->size, + $this->referer, $this->user_agent); if (!empty($this->_accesslog->reader)) { fclose($this->_accesslog->reader); unset($this->_accesslog->reader); @@ -349,7 +391,8 @@ class Request_AccessLogEntry /* This is better been done by apache mod_log_sql */ /* If ACCESS_LOG_SQL & 2 we do write it by our own */ - function write_sql() { + function write_sql() + { global $request; $dbh =& $request->_dbi; @@ -359,13 +402,13 @@ class Request_AccessLogEntry // strangely HTTP_POST_VARS doesn't contain all posted vars. $args = $_POST; // copy not ref. clone not needed on hashes // garble passwords - if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = ''; + if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = ''; if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = ''; - if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = ''; - if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = ''; - $this->request_args = substr(serialize($args),0,254); // if VARCHAR(255) is used. + if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = ''; + if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = ''; + $this->request_args = substr(serialize($args), 0, 254); // if VARCHAR(255) is used. } else { - $this->request_args = $request->get('QUERY_STRING'); + $this->request_args = $request->get('QUERY_STRING'); } $this->request_method = $request->get('REQUEST_METHOD'); $this->request_uri = $request->get('REQUEST_URI'); @@ -381,7 +424,8 @@ class Request_AccessLogEntry * @access private * @see Request_AccessLogEntry */ -function Request_AccessLogEntry_shutdown_function () { +function Request_AccessLogEntry_shutdown_function() +{ global $request; if (isset($request->_accesslog->entries) and $request->_accesslog->logfile) @@ -422,7 +466,8 @@ class Request_AccessLog_SQL * ."WHERE referer IS NOT NULL " * .$where_conditions */ - function _getQueryString(&$args) { + function _getQueryString(&$args) + { // extract any parametrised conditions from the arguments, // in particular, how much history to select $where_conditions = $this->_getWhereConditions($args); @@ -430,215 +475,226 @@ class Request_AccessLog_SQL // get the correct name for the table //FIXME is there a more correct way to do this? global $DBParams, $request; - $accesslog = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '')."accesslog"; + $accesslog = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog"; $query = ''; $backend_type = $request->_dbi->_backend->backendType(); switch ($backend_type) { - case 'mysql': - $Referring_URL = "left(referer,length(referer)-instr(reverse(referer),'?'))"; break; - case 'pgsql': - case 'postgres7': - $Referring_URL = "substr(referer,0,position('?' in referer))"; break; - default: - $Referring_URL = "referer"; - } - switch ($args['mode']) { - case 'referring_urls': - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - $query = "SELECT " - . "$Referring_URL AS Referring_URL, " - . "count(*) AS Referral_Count " - . "FROM $accesslog " - . $where_conditions - . "GROUP BY Referring_URL"; - break; - case 'external_referers': - $args['local_referrers'] = 'false'; - $where_conditions = $this->_getWhereConditions($args); - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - $query = "SELECT " - . "$Referring_URL AS Referring_URL, " - . "count(*) AS Referral_Count " - . "FROM $accesslog " - . $where_conditions - . "GROUP BY Referring_URL"; - break; - case 'referring_domains': - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - switch ($backend_type) { case 'mysql': - $Referring_Domain = "left(referer, if(locate('/', referer, 8) > 0,locate('/', referer, 8) -1, length(referer)))"; break; - case 'pgsql': - case 'postgres7': - $Referring_Domain = "substr(referer,0,8) || regexp_replace(substr(referer,8), '/.*', '')"; break; - default: - $Referring_Domain = "referer"; break; - } - $query = "SELECT " - . "$Referring_Domain AS Referring_Domain, " - . "count(*) AS Referral_Count " - . "FROM $accesslog " - . $where_conditions - . "GROUP BY Referring_Domain"; - break; - case 'remote_hosts': - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - $query = "SELECT " - ."remote_host AS Remote_Host, " - ."count(*) AS Access_Count " - ."FROM $accesslog " - .$where_conditions - ."GROUP BY Remote_Host"; - break; - case 'users': - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - $query = "SELECT " - ."remote_user AS User, " - ."count(*) AS Access_Count " - ."FROM $accesslog " - .$where_conditions - ."GROUP BY remote_user"; - break; - case 'host_users': - if ($where_conditions<>'') - $where_conditions = 'WHERE '.$where_conditions.' '; - $query = "SELECT " - ."remote_host AS Remote_Host, " - ."remote_user AS User, " - ."count(*) AS Access_Count " - ."FROM $accesslog " - .$where_conditions - ."GROUP BY remote_host, remote_user"; - break; - case "search_bots": - // This queries for all entries in the SQL access log table that - // have a dns name that I know to be a web search engine crawler and - // categorises the results into time buckets as per the list below - // 0 - 1 minute - 60 - // 1 - 1 hour - 3600 = 60 * 60 - // 2 - 1 day - 86400 = 60 * 60 * 24 - // 3 - 1 week - 604800 = 60 * 60 * 24 * 7 - // 4 - 1 month - 2629800 = 60 * 60 * 24 * 365.25 / 12 - // 5 - 1 year - 31557600 = 60 * 60 * 24 * 365.25 - $now = time(); - $query = "SELECT " - ."CASE WHEN $now-time_stamp<60 THEN '"._("0 - last minute")."' ELSE " - ."CASE WHEN $now-time_stamp<3600 THEN '"._("1 - 1 minute to 1 hour")."' ELSE " - ."CASE WHEN $now-time_stamp<86400 THEN '"._("2 - 1 hour to 1 day")."' ELSE " - ."CASE WHEN $now-time_stamp<604800 THEN '"._("3 - 1 day to 1 week")."' ELSE " - ."CASE WHEN $now-time_stamp<2629800 THEN '"._("4 - 1 week to 1 month")."' ELSE " - ."CASE WHEN $now-time_stamp<31557600 THEN '"._("5 - 1 month to 1 year")."' ELSE " - ."'"._("6 - more than 1 year")."' END END END END END END AS Time_Scale, " - ."remote_host AS Remote_Host, " - ."count(*) AS Access_Count " - ."FROM $accesslog " - ."WHERE (remote_host LIKE '%googlebot.com' " - ."OR remote_host LIKE '%alexa.com' " - ."OR remote_host LIKE '%inktomisearch.com' " - ."OR remote_host LIKE '%msnbot.msn.com') " - .($where_conditions ? 'AND '.$where_conditions : '') - ."GROUP BY Time_Scale, remote_host"; - break; - case "search_bots_hits": - // This queries for all entries in the SQL access log table that - // have a dns name that I know to be a web search engine crawler and - // displays the URI that was hit. - // If PHPSESSID appears in the URI, just display the URI to the left of this - $sessname = session_name(); - switch ($backend_type) { - case 'mysql': - $Request_URI = "IF(instr(request_uri, '$sessname')=0, request_uri,left(request_uri, instr(request_uri, '$sessname')-2))"; + $Referring_URL = "left(referer,length(referer)-instr(reverse(referer),'?'))"; break; case 'pgsql': case 'postgres7': - $Request_URI = "regexp_replace(request_uri, '$sessname.*', '')"; break; + $Referring_URL = "substr(referer,0,position('?' in referer))"; + break; default: - $Request_URI = 'request_uri'; break; - } - $now = time(); - $query = "SELECT " - ."CASE WHEN $now-time_stamp<60 THEN '"._("0 - last minute")."' ELSE " - ."CASE WHEN $now-time_stamp<3600 THEN '"._("1 - 1 minute to 1 hour")."' ELSE " - ."CASE WHEN $now-time_stamp<86400 THEN '"._("2 - 1 hour to 1 day")."' ELSE " - ."CASE WHEN $now-time_stamp<604800 THEN '"._("3 - 1 day to 1 week")."' ELSE " - ."CASE WHEN $now-time_stamp<2629800 THEN '"._("4 - 1 week to 1 month")."' ELSE " - ."CASE WHEN $now-time_stamp<31557600 THEN '"._("5 - 1 month to 1 year")."' ELSE " - ."'"._("6 - more than 1 year")."' END END END END END END AS Time_Scale, " - ."remote_host AS Remote_Host, " - ."$Request_URI AS Request_URI " - ."FROM $accesslog " - ."WHERE (remote_host LIKE '%googlebot.com' " - ."OR remote_host LIKE '%alexa.com' " - ."OR remote_host LIKE '%inktomisearch.com' " - ."OR remote_host LIKE '%msnbot.msn.com') " - .($where_conditions ? 'AND '.$where_conditions : '') - ."ORDER BY time_stamp"; + $Referring_URL = "referer"; + } + switch ($args['mode']) { + case 'referring_urls': + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + $query = "SELECT " + . "$Referring_URL AS Referring_URL, " + . "count(*) AS Referral_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY Referring_URL"; + break; + case 'external_referers': + $args['local_referrers'] = 'false'; + $where_conditions = $this->_getWhereConditions($args); + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + $query = "SELECT " + . "$Referring_URL AS Referring_URL, " + . "count(*) AS Referral_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY Referring_URL"; + break; + case 'referring_domains': + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + switch ($backend_type) { + case 'mysql': + $Referring_Domain = "left(referer, if(locate('/', referer, 8) > 0,locate('/', referer, 8) -1, length(referer)))"; + break; + case 'pgsql': + case 'postgres7': + $Referring_Domain = "substr(referer,0,8) || regexp_replace(substr(referer,8), '/.*', '')"; + break; + default: + $Referring_Domain = "referer"; + break; + } + $query = "SELECT " + . "$Referring_Domain AS Referring_Domain, " + . "count(*) AS Referral_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY Referring_Domain"; + break; + case 'remote_hosts': + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + $query = "SELECT " + . "remote_host AS Remote_Host, " + . "count(*) AS Access_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY Remote_Host"; + break; + case 'users': + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + $query = "SELECT " + . "remote_user AS User, " + . "count(*) AS Access_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY remote_user"; + break; + case 'host_users': + if ($where_conditions <> '') + $where_conditions = 'WHERE ' . $where_conditions . ' '; + $query = "SELECT " + . "remote_host AS Remote_Host, " + . "remote_user AS User, " + . "count(*) AS Access_Count " + . "FROM $accesslog " + . $where_conditions + . "GROUP BY remote_host, remote_user"; + break; + case "search_bots": + // This queries for all entries in the SQL access log table that + // have a dns name that I know to be a web search engine crawler and + // categorises the results into time buckets as per the list below + // 0 - 1 minute - 60 + // 1 - 1 hour - 3600 = 60 * 60 + // 2 - 1 day - 86400 = 60 * 60 * 24 + // 3 - 1 week - 604800 = 60 * 60 * 24 * 7 + // 4 - 1 month - 2629800 = 60 * 60 * 24 * 365.25 / 12 + // 5 - 1 year - 31557600 = 60 * 60 * 24 * 365.25 + $now = time(); + $query = "SELECT " + . "CASE WHEN $now-time_stamp<60 THEN '" . _("0 - last minute") . "' ELSE " + . "CASE WHEN $now-time_stamp<3600 THEN '" . _("1 - 1 minute to 1 hour") . "' ELSE " + . "CASE WHEN $now-time_stamp<86400 THEN '" . _("2 - 1 hour to 1 day") . "' ELSE " + . "CASE WHEN $now-time_stamp<604800 THEN '" . _("3 - 1 day to 1 week") . "' ELSE " + . "CASE WHEN $now-time_stamp<2629800 THEN '" . _("4 - 1 week to 1 month") . "' ELSE " + . "CASE WHEN $now-time_stamp<31557600 THEN '" . _("5 - 1 month to 1 year") . "' ELSE " + . "'" . _("6 - more than 1 year") . "' END END END END END END AS Time_Scale, " + . "remote_host AS Remote_Host, " + . "count(*) AS Access_Count " + . "FROM $accesslog " + . "WHERE (remote_host LIKE '%googlebot.com' " + . "OR remote_host LIKE '%alexa.com' " + . "OR remote_host LIKE '%inktomisearch.com' " + . "OR remote_host LIKE '%msnbot.msn.com') " + . ($where_conditions ? 'AND ' . $where_conditions : '') + . "GROUP BY Time_Scale, remote_host"; + break; + case "search_bots_hits": + // This queries for all entries in the SQL access log table that + // have a dns name that I know to be a web search engine crawler and + // displays the URI that was hit. + // If PHPSESSID appears in the URI, just display the URI to the left of this + $sessname = session_name(); + switch ($backend_type) { + case 'mysql': + $Request_URI = "IF(instr(request_uri, '$sessname')=0, request_uri,left(request_uri, instr(request_uri, '$sessname')-2))"; + break; + case 'pgsql': + case 'postgres7': + $Request_URI = "regexp_replace(request_uri, '$sessname.*', '')"; + break; + default: + $Request_URI = 'request_uri'; + break; + } + $now = time(); + $query = "SELECT " + . "CASE WHEN $now-time_stamp<60 THEN '" . _("0 - last minute") . "' ELSE " + . "CASE WHEN $now-time_stamp<3600 THEN '" . _("1 - 1 minute to 1 hour") . "' ELSE " + . "CASE WHEN $now-time_stamp<86400 THEN '" . _("2 - 1 hour to 1 day") . "' ELSE " + . "CASE WHEN $now-time_stamp<604800 THEN '" . _("3 - 1 day to 1 week") . "' ELSE " + . "CASE WHEN $now-time_stamp<2629800 THEN '" . _("4 - 1 week to 1 month") . "' ELSE " + . "CASE WHEN $now-time_stamp<31557600 THEN '" . _("5 - 1 month to 1 year") . "' ELSE " + . "'" . _("6 - more than 1 year") . "' END END END END END END AS Time_Scale, " + . "remote_host AS Remote_Host, " + . "$Request_URI AS Request_URI " + . "FROM $accesslog " + . "WHERE (remote_host LIKE '%googlebot.com' " + . "OR remote_host LIKE '%alexa.com' " + . "OR remote_host LIKE '%inktomisearch.com' " + . "OR remote_host LIKE '%msnbot.msn.com') " + . ($where_conditions ? 'AND ' . $where_conditions : '') + . "ORDER BY time_stamp"; } return $query; } /** Honeypot for xgettext. Those strings are translated dynamically. */ - function _locale_dummy() { + function _locale_dummy() + { $dummy = array( - // mode caption - _("referring_urls"), - _("external_referers"), - _("referring_domains"), - _("remote_hosts"), - _("users"), - _("host_users"), - _("search_bots"), - _("search_bots_hits"), - // period header - _("minutes"), - _("hours"), - _("days"), - _("weeks"), - ); - } - - function getDefaultArguments() { + // mode caption + _("referring_urls"), + _("external_referers"), + _("referring_domains"), + _("remote_hosts"), + _("users"), + _("host_users"), + _("search_bots"), + _("search_bots_hits"), + // period header + _("minutes"), + _("hours"), + _("days"), + _("weeks"), + ); + } + + function getDefaultArguments() + { return array( - 'mode' => 'referring_domains', - // referring_domains, referring_urls, remote_hosts, users, host_users, search_bots, search_bots_hits - 'caption' => '', - // blank means use the mode as the caption/title for the output - 'local_referrers' => 'true', // only show external referring sites - 'period' => '', // the type of period to report: - // may be weeks, days, hours, minutes, or blank for all - 'count' => '0' // the number of periods to report - ); + 'mode' => 'referring_domains', + // referring_domains, referring_urls, remote_hosts, users, host_users, search_bots, search_bots_hits + 'caption' => '', + // blank means use the mode as the caption/title for the output + 'local_referrers' => 'true', // only show external referring sites + 'period' => '', // the type of period to report: + // may be weeks, days, hours, minutes, or blank for all + 'count' => '0' // the number of periods to report + ); } - function table_output () { + function table_output() + { $query = $this->_getQueryString($args); - if ($query=='') - return HTML::p(sprintf( _("Unrecognised parameter 'mode=%s'"), - $args['mode'])); + if ($query == '') + return HTML::p(sprintf(_("Unrecognised parameter 'mode=%s'"), + $args['mode'])); // get the data back. // Note that this must be done before the final generation ofthe table, // otherwise the headers will not be ready $tbody = $this->_getQueryResults($query, $dbi); - return HTML::table(array('border' => 1, - 'cellspacing' => 1, - 'cellpadding' => 1), - HTML::caption(HTML::h1(HTML::br(),$this->_getCaption($args))), - HTML::thead($this->_theadrow), - $tbody); + return HTML::table(array('border' => 1, + 'cellspacing' => 1, + 'cellpadding' => 1), + HTML::caption(HTML::h1(HTML::br(), $this->_getCaption($args))), + HTML::thead($this->_theadrow), + $tbody); } - function _getQueryResults($query, &$dbi) { + function _getQueryResults($query, &$dbi) + { $queryResult = $dbi->genericSqlIter($query); if (!$queryResult) { $tbody = HTML::tbody(HTML::tr(HTML::td(_("")))); @@ -649,7 +705,7 @@ class Request_AccessLog_SQL $tr = HTML::tr(); foreach ($row as $value) { // output a '-' for empty values, otherwise the table looks strange - $tr->pushContent(HTML::td( empty($value) ? '-' : $value )); + $tr->pushContent(HTML::td(empty($value) ? '-' : $value)); } $tbody->pushContent($tr); } @@ -658,7 +714,8 @@ class Request_AccessLog_SQL return $tbody; } - function _setHeaders($row) { + function _setHeaders($row) + { if (!$this->_headerSet) { foreach ($row as $key => $value) { $this->_theadrow->pushContent(HTML::th(_($key))); @@ -667,63 +724,67 @@ class Request_AccessLog_SQL } } - function _getWhereConditions(&$args) { + function _getWhereConditions(&$args) + { $where_conditions = ''; - if ($args['period']<>'') { + if ($args['period'] <> '') { $since = 0; - if ($args['period']=='minutes') { + if ($args['period'] == 'minutes') { $since = 60; - } elseif ($args['period']=='hours') { + } elseif ($args['period'] == 'hours') { $since = 60 * 60; - } elseif ($args['period']=='days') { + } elseif ($args['period'] == 'days') { $since = 60 * 60 * 24; - } elseif ($args['period']=='weeks') { + } elseif ($args['period'] == 'weeks') { $since = 60 * 60 * 24 * 7; } $since = $since * $args['count']; - if ($since>0) { - if ($where_conditions<>'') - $where_conditions = $where_conditions.' AND '; + if ($since > 0) { + if ($where_conditions <> '') + $where_conditions = $where_conditions . ' AND '; $since = time() - $since; - $where_conditions = $where_conditions."time_stamp > $since"; + $where_conditions = $where_conditions . "time_stamp > $since"; } } - if ($args['local_referrers']<>'true') { + if ($args['local_referrers'] <> 'true') { global $request; - if ($where_conditions<>'') - $where_conditions = $where_conditions.' AND '; + if ($where_conditions <> '') + $where_conditions = $where_conditions . ' AND '; $localhost = SERVER_URL; $len = strlen($localhost); $backend_type = $request->_dbi->_backend->backendType(); switch ($backend_type) { - case 'mysql': - $ref_localhost = "left(referer,$len)<>'$localhost'"; break; - case 'pgsql': - case 'postgres7': - $ref_localhost = "substr(referer,0,$len)<>'$localhost'"; break; - default: - $ref_localhost = ""; + case 'mysql': + $ref_localhost = "left(referer,$len)<>'$localhost'"; + break; + case 'pgsql': + case 'postgres7': + $ref_localhost = "substr(referer,0,$len)<>'$localhost'"; + break; + default: + $ref_localhost = ""; } - $where_conditions = $where_conditions.$ref_localhost; + $where_conditions = $where_conditions . $ref_localhost; } // The assumed contract is that there is a space at the end of the // conditions string, so that following SQL clauses (such as GROUP BY) // will not cause a syntax error - if ($where_conditions<>'') - $where_conditions = $where_conditions.' '; + if ($where_conditions <> '') + $where_conditions = $where_conditions . ' '; return $where_conditions; } - function _getCaption(&$args) { + function _getCaption(&$args) + { $caption = $args['caption']; - if ($caption=='') + if ($caption == '') $caption = gettext($args['mode']); - if ($args['period']<>'' && $args['count']) - $caption = $caption." - ".$args['count']." ". gettext($args['period']); + if ($args['period'] <> '' && $args['count']) + $caption = $caption . " - " . $args['count'] . " " . gettext($args['period']); return $caption; } diff --git a/lib/ArchiveCleaner.php b/lib/ArchiveCleaner.php index 312d6d4f2..eda57d8e1 100644 --- a/lib/ArchiveCleaner.php +++ b/lib/ArchiveCleaner.php @@ -21,12 +21,14 @@ class ArchiveCleaner { - function ArchiveCleaner ($expire_params) { + function ArchiveCleaner($expire_params) + { $this->expire_params = $expire_params; } - function isMergeable($revision) { - if ( ! $revision->get('is_minor_edit') ) + function isMergeable($revision) + { + if (!$revision->get('is_minor_edit')) return false; $page = $revision->getPage(); @@ -38,13 +40,15 @@ class ArchiveCleaner && $author_id == $previous->get('author_id'); } - function cleanDatabase($dbi) { + function cleanDatabase($dbi) + { $iter = $dbi->getAllPages(); while ($page = $iter->next()) $this->cleanPageRevisions($page); } - function cleanPageRevisions($page) { + function cleanPageRevisions($page) + { $INFINITY = 0x7fffffff; $expire = &$this->expire_params; @@ -52,16 +56,17 @@ class ArchiveCleaner $counter[$class] = new ArchiveCleaner_Counter($expire[$class]); // shortcut to keep all if (($counter['minor']->min_keep == $INFINITY) - and ($counter['major']->min_keep == $INFINITY)) + and ($counter['major']->min_keep == $INFINITY) + ) return; $authors_seen = array(); $current = $page->getCurrentRevision(false); - for ( $revision = $page->getRevisionBefore($current,false); - $revision->getVersion() > 0; - $revision = $page->getRevisionBefore($revision,false) ) { + for ($revision = $page->getRevisionBefore($current, false); + $revision->getVersion() > 0; + $revision = $page->getRevisionBefore($revision, false)) { if ($revision->get('is_minor_edit')) $keep = $counter['minor']->keep($revision); @@ -72,8 +77,7 @@ class ArchiveCleaner if (!$keep) { $page->mergeRevision($revision); } - } - else { + } else { $author_id = $revision->get('author_id'); if (empty($authors_seen[$author_id])) { if ($counter['author']->keep($revision)) @@ -93,7 +97,8 @@ class ArchiveCleaner */ class ArchiveCleaner_Counter { - function ArchiveCleaner_Counter($params) { + function ArchiveCleaner_Counter($params) + { if (!empty($params)) extract($params); @@ -101,11 +106,11 @@ class ArchiveCleaner_Counter $this->max_keep = isset($max_keep) ? $max_keep : $INFINITY; - $this->min_age = isset($min_age) ? $min_age : 0; + $this->min_age = isset($min_age) ? $min_age : 0; $this->min_keep = isset($min_keep) ? $min_keep : 0; - $this->max_age = isset($max_age) ? $max_age : $INFINITY; - $this->keep = isset($keep) ? $keep : $INFINITY; + $this->max_age = isset($max_age) ? $max_age : $INFINITY; + $this->keep = isset($keep) ? $keep : $INFINITY; if ($this->keep > $this->max_keep) $this->keep = $this->max_keep; @@ -124,16 +129,17 @@ class ArchiveCleaner_Counter } - function computeAge($revision) { + function computeAge($revision) + { $supplanted = $revision->get('_supplanted'); if (!$supplanted) { // Every revision but the most recent should have a supplanted time. // However, if it doesn't... trigger_error(sprintf("Warning: Page '%s', version '%d' has no '_supplanted' timestamp", - $revision->getPageName(), - $revision->getVersion()), - E_USER_NOTICE); + $revision->getPageName(), + $revision->getVersion()), + E_USER_NOTICE); // Assuming revisions are chronologically ordered, the previous // supplanted time is a good value to use... if ($this->previous_supplanted > 0) @@ -149,7 +155,8 @@ class ArchiveCleaner_Counter return ($this->now - $supplanted) / (24 * 3600); } - function keep($revision) { + function keep($revision) + { $INFINITY = 0x7fffffff; if ($this->min_keep == $INFINITY) return true; diff --git a/lib/AtomParser.php b/lib/AtomParser.php index 9034387cb..ac50a7d96 100644 --- a/lib/AtomParser.php +++ b/lib/AtomParser.php @@ -28,7 +28,7 @@ require_once 'lib/XmlParser.php'; class AtomParser -extends XmlParser + extends XmlParser { // Feed var $feed = array(); @@ -67,7 +67,8 @@ extends XmlParser var $inside_content = false; var $content = ''; - function tag_open($parser, $name, $attrs='') { + function tag_open($parser, $name, $attrs = '') + { global $current_tag, $current_attrs; $current_tag = $name; @@ -82,7 +83,8 @@ extends XmlParser } } - function tag_close($parser, $name, $attrs='') { + function tag_close($parser, $name, $attrs = '') + { if ($name == "AUTHOR") { $an_author = $this->trim_data(array( "name" => $this->name, @@ -162,7 +164,8 @@ extends XmlParser } } - function cdata($parser, $data) { + function cdata($parser, $data) + { global $current_tag, $current_attrs; if ($this->inside_content) { @@ -232,11 +235,13 @@ extends XmlParser } } - function trim_data($array) { + function trim_data($array) + { return array_map(array("self", "trim_element"), $array); } - function trim_element($element) { + function trim_element($element) + { if (is_array($element)) { return $this->trim_data($element); } elseif (is_string($element)) { @@ -244,10 +249,11 @@ extends XmlParser } } - function serialize_tag($tag_name, $attributes) { + function serialize_tag($tag_name, $attributes) + { $tag = "<" . $tag_name; foreach ($attributes as $k => $v) { - $tag .= " " . strtolower($k). "=\"$v\""; + $tag .= " " . strtolower($k) . "=\"$v\""; } $tag .= ">"; return $tag; diff --git a/lib/BlockParser.php b/lib/BlockParser.php index 83d6d8687..b893ec6ea 100644 --- a/lib/BlockParser.php +++ b/lib/BlockParser.php @@ -49,7 +49,8 @@ require_once 'lib/InlineParser.php'; * * @see RegexpSet */ -class AnchoredRegexpSet_match { +class AnchoredRegexpSet_match +{ /** * The matched text. */ @@ -80,7 +81,8 @@ class AnchoredRegexpSet * "(...)". (Anonymous groups, like "(?:...)", as well as * look-ahead and look-behind assertions are fine.) */ - function AnchoredRegexpSet ($regexps) { + function AnchoredRegexpSet($regexps) + { $this->_regexps = $regexps; $this->_re = "/((" . join(")|(", $regexps) . "))/Ax"; } @@ -92,9 +94,10 @@ class AnchoredRegexpSet * * @return object A RegexpSet_match object, or false if no match. */ - function match ($text) { + function match($text) + { if (!is_string($text)) return false; - if (! preg_match($this->_re, $text, $m)) { + if (!preg_match($this->_re, $text, $m)) { return false; } @@ -124,30 +127,34 @@ class AnchoredRegexpSet * * @return object A RegexpSet_match object, or false if no match. */ - function nextMatch ($text, $prevMatch) { + function nextMatch($text, $prevMatch) + { // Try to find match at same position. $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1); if (!$regexps) { return false; } - $pat= "/ ( (" . join(')|(', $regexps) . ") ) /Axs"; + $pat = "/ ( (" . join(')|(', $regexps) . ") ) /Axs"; - if (! preg_match($pat, $text, $m)) { + if (!preg_match($pat, $text, $m)) { return false; } $match = new AnchoredRegexpSet_match; $match->postmatch = substr($text, strlen($m[0])); $match->match = $m[1]; - $match->regexp_ind = count($m) - 3 + $prevMatch->regexp_ind + 1;; + $match->regexp_ind = count($m) - 3 + $prevMatch->regexp_ind + 1; + ; return $match; } } -class BlockParser_Input { +class BlockParser_Input +{ - function BlockParser_Input ($text) { + function BlockParser_Input($text) + { // Expand leading tabs. // FIXME: do this better. @@ -161,12 +168,13 @@ class BlockParser_Input { $this->_pos = 0; // Strip leading blank lines. - while ($this->_lines and ! $this->_lines[0]) + while ($this->_lines and !$this->_lines[0]) array_shift($this->_lines); $this->_atSpace = false; } - function skipSpace () { + function skipSpace() + { $nlines = count($this->_lines); while (1) { if ($this->_pos >= $nlines) { @@ -181,14 +189,16 @@ class BlockParser_Input { return $this->_atSpace; } - function currentLine () { + function currentLine() + { if ($this->_pos >= count($this->_lines)) { return false; } return $this->_lines[$this->_pos]; } - function nextLine () { + function nextLine() + { $this->_atSpace = $this->_lines[$this->_pos++] === ''; if ($this->_pos >= count($this->_lines)) { return false; @@ -196,48 +206,56 @@ class BlockParser_Input { return $this->_lines[$this->_pos]; } - function advance () { + function advance() + { $this->_atSpace = ($this->_lines[$this->_pos] === ''); $this->_pos++; } - function getPos () { + function getPos() + { return array($this->_pos, $this->_atSpace); } - function setPos ($pos) { + function setPos($pos) + { list($this->_pos, $this->_atSpace) = $pos; } - function getPrefix () { + function getPrefix() + { return ''; } - function getDepth () { + function getDepth() + { return 0; } - function where () { + function where() + { if ($this->_pos < count($this->_lines)) return $this->_lines[$this->_pos]; else return ""; } - function _debug ($tab, $msg) { + function _debug($tab, $msg) + { //return ; $where = $this->where(); - $tab = str_repeat('____', $this->getDepth() ) . $tab; + $tab = str_repeat('____', $this->getDepth()) . $tab; printXML(HTML::div("$tab $msg: at: '", - HTML::tt($where), - "'")); + HTML::tt($where), + "'")); flush(); } } class BlockParser_InputSubBlock extends BlockParser_Input { - function BlockParser_InputSubBlock (&$input, $prefix_re, $initial_prefix = false) { + function BlockParser_InputSubBlock(&$input, $prefix_re, $initial_prefix = false) + { $this->_input = &$input; $this->_prefix_pat = "/$prefix_re|\\s*\$/Ax"; $this->_atSpace = false; @@ -246,18 +264,17 @@ class BlockParser_InputSubBlock extends BlockParser_Input $this->_line = false; elseif ($initial_prefix) { assert(substr($line, 0, strlen($initial_prefix)) == $initial_prefix); - $this->_line = (string) substr($line, strlen($initial_prefix)); - $this->_atBlank = ! ltrim($line); - } - elseif (preg_match($this->_prefix_pat, $line, $m)) { - $this->_line = (string) substr($line, strlen($m[0])); - $this->_atBlank = ! ltrim($line); - } - else + $this->_line = (string)substr($line, strlen($initial_prefix)); + $this->_atBlank = !ltrim($line); + } elseif (preg_match($this->_prefix_pat, $line, $m)) { + $this->_line = (string)substr($line, strlen($m[0])); + $this->_atBlank = !ltrim($line); + } else $this->_line = false; } - function skipSpace () { + function skipSpace() + { // In contrast to the case for top-level blocks, // for sub-blocks, there never appears to be any trailing space. // (The last block in the sub-block should always be of class tight-bottom.) @@ -270,11 +287,13 @@ class BlockParser_InputSubBlock extends BlockParser_Input return $this->_atSpace; } - function currentLine () { + function currentLine() + { return $this->_line; } - function nextLine () { + function nextLine() + { if ($this->_line === '') $this->_atSpace = $this->_atBlank ? 'weak_space' : 'strong_space'; else @@ -282,74 +301,83 @@ class BlockParser_InputSubBlock extends BlockParser_Input $line = $this->_input->nextLine(); if ($line !== false && preg_match($this->_prefix_pat, $line, $m)) { - $this->_line = (string) substr($line, strlen($m[0])); - $this->_atBlank = ! ltrim($line); - } - else + $this->_line = (string)substr($line, strlen($m[0])); + $this->_atBlank = !ltrim($line); + } else $this->_line = false; return $this->_line; } - function advance () { + function advance() + { $this->nextLine(); } - function getPos () { + function getPos() + { return array($this->_line, $this->_atSpace, $this->_input->getPos()); } - function setPos ($pos) { + function setPos($pos) + { $this->_line = $pos[0]; $this->_atSpace = $pos[1]; $this->_input->setPos($pos[2]); } - function getPrefix () { - assert ($this->_line !== false); + function getPrefix() + { + assert($this->_line !== false); $line = $this->_input->currentLine(); - assert ($line !== false && strlen($line) >= strlen($this->_line)); + assert($line !== false && strlen($line) >= strlen($this->_line)); return substr($line, 0, strlen($line) - strlen($this->_line)); } - function getDepth () { + function getDepth() + { return $this->_input->getDepth() + 1; } - function where () { + function where() + { return $this->_input->where(); } } class Block_HtmlElement extends HtmlElement { - function Block_HtmlElement($tag /*, ... */) { + function Block_HtmlElement($tag /*, ... */) + { $this->_init(func_get_args()); } - function setTightness($top, $bottom) { + function setTightness($top, $bottom) + { } } -class ParsedBlock extends Block_HtmlElement { +class ParsedBlock extends Block_HtmlElement +{ - function ParsedBlock (&$input, $tag = 'div', $attr = false) { + function ParsedBlock(&$input, $tag = 'div', $attr = false) + { $this->Block_HtmlElement($tag, $attr); $this->_initBlockTypes(); $this->_parse($input); } - function _parse (&$input) { + function _parse(&$input) + { // php5 failed to advance the block. php5 copies objects by ref. // nextBlock == block, both are the same objects. So we have to clone it. for ($block = $this->_getBlock($input); $block; - $block = (is_object($nextBlock) ? clone($nextBlock) : $nextBlock)) - { + $block = (is_object($nextBlock) ? clone($nextBlock) : $nextBlock)) { while ($nextBlock = $this->_getBlock($input)) { // Attempt to merge current with following block. - if (! ($merged = $block->merge($nextBlock)) ) { - break; // can't merge + if (!($merged = $block->merge($nextBlock))) { + break; // can't merge } $block = $merged; } @@ -358,23 +386,24 @@ class ParsedBlock extends Block_HtmlElement { } // FIXME: hackish. This should only be called once. - function _initBlockTypes () { + function _initBlockTypes() + { // better static or global? static $_regexpset, $_block_types; if (!is_object($_regexpset)) { // nowiki_wikicreole must be before template_plugin - $Block_types = array + $Block_types = array ('nowiki_wikicreole', 'template_plugin', 'placeholder', 'oldlists', 'list', 'dl', - 'table_dl', 'table_wikicreole', 'table_mediawiki', - 'blockquote', 'heading', 'heading_wikicreole', 'hr', 'pre', - 'email_blockquote', 'wikicreole_indented', - 'plugin', 'plugin_wikicreole', 'p'); + 'table_dl', 'table_wikicreole', 'table_mediawiki', + 'blockquote', 'heading', 'heading_wikicreole', 'hr', 'pre', + 'email_blockquote', 'wikicreole_indented', + 'plugin', 'plugin_wikicreole', 'p'); // insert it before p! if (ENABLE_MARKUP_DIVSPAN) { array_pop($Block_types); - $Block_types[] = 'divspan'; - $Block_types[] = 'p'; + $Block_types[] = 'divspan'; + $Block_types[] = 'p'; } foreach ($Block_types as $type) { $class = "Block_$type"; @@ -387,12 +416,13 @@ class ParsedBlock extends Block_HtmlElement { $_block_types = $this->_block_types; unset($Block_types); } else { - $this->_regexpset = $_regexpset; - $this->_block_types = $_block_types; + $this->_regexpset = $_regexpset; + $this->_block_types = $_block_types; } } - function _getBlock (&$input) { + function _getBlock(&$input) + { $this->_atSpace = $input->skipSpace(); $line = $input->currentLine(); @@ -411,7 +441,7 @@ class ParsedBlock extends Block_HtmlElement { //$block->_text = $line; if (DEBUG & _DEBUG_PARSER) $input->_debug('<', get_class($block)); - $tight_bottom = ! $input->skipSpace(); + $tight_bottom = !$input->skipSpace(); $block->_setTightness($tight_top, $tight_bottom); return $block; } @@ -426,16 +456,20 @@ class ParsedBlock extends Block_HtmlElement { } } -class WikiText extends ParsedBlock { - function WikiText ($text) { +class WikiText extends ParsedBlock +{ + function WikiText($text) + { $input = new BlockParser_Input($text); $this->ParsedBlock($input); } } -class SubBlock extends ParsedBlock { - function SubBlock (&$input, $indent_re, $initial_indent = false, - $tag = 'div', $attr = false) { +class SubBlock extends ParsedBlock +{ + function SubBlock(&$input, $indent_re, $initial_indent = false, + $tag = 'div', $attr = false) + { $subinput = new BlockParser_InputSubBlock($input, $indent_re, $initial_indent); $this->ParsedBlock($subinput, $tag, $attr); } @@ -451,9 +485,11 @@ class SubBlock extends ParsedBlock { * in older (non-CSS) browsers. (If you don't do this, then, without * CSS, you only get "loose" lists. */ -class TightSubBlock extends SubBlock { - function TightSubBlock (&$input, $indent_re, $initial_indent = false, - $tag = 'div', $attr = false) { +class TightSubBlock extends SubBlock +{ + function TightSubBlock(&$input, $indent_re, $initial_indent = false, + $tag = 'div', $attr = false) + { $this->SubBlock($input, $indent_re, $initial_indent, $tag, $attr); // If content is a single paragraph, eliminate the paragraph... @@ -466,21 +502,26 @@ class TightSubBlock extends SubBlock { } } -class BlockMarkup { +class BlockMarkup +{ var $_re; - function _match (&$input, $match) { + function _match(&$input, $match) + { trigger_error('pure virtual', E_USER_ERROR); } - function _setTightness ($top, $bot) { + function _setTightness($top, $bot) + { } - function merge ($followingBlock) { + function merge($followingBlock) + { return false; } - function finish () { + function finish() + { return $this->_element; } } @@ -490,20 +531,22 @@ class Block_blockquote extends BlockMarkup var $_depth; var $_re = '\ +(?=\S)'; - function _match (&$input, $m) { + function _match(&$input, $m) + { $this->_depth = strlen($m->match); $indent = sprintf("\\ {%d}", $this->_depth); $this->_element = new SubBlock($input, $indent, $m->match, - 'blockquote'); + 'blockquote'); return true; } - function merge ($nextBlock) { + function merge($nextBlock) + { if (get_class($nextBlock) == get_class($this)) { - assert ($nextBlock->_depth < $this->_depth); + assert($nextBlock->_depth < $this->_depth); $nextBlock->_element->unshiftContent($this->_element); - if (!empty($this->_tight_top)) - $nextBlock->_tight_top = $this->_tight_top; + if (!empty($this->_tight_top)) + $nextBlock->_tight_top = $this->_tight_top; return $nextBlock; } return false; @@ -522,7 +565,8 @@ class Block_list extends BlockMarkup )\ *(?=\S)'; var $_content = array(); - function _match (&$input, $m) { + function _match(&$input, $m) + { // A list as the first content in a list is not allowed. // E.g.: // * * Item @@ -542,21 +586,24 @@ class Block_list extends BlockMarkup return true; } - function _setTightness($top, $bot) { + function _setTightness($top, $bot) + { $li = &$this->_content[0]; $li->setTightness($top, $bot); } - function merge ($nextBlock) { + function merge($nextBlock) + { if (isa($nextBlock, 'Block_list') and $this->_tag == $nextBlock->_tag) { array_splice($this->_content, count($this->_content), 0, - $nextBlock->_content); + $nextBlock->_content); return $this; } return false; } - function finish () { + function finish() + { return new Block_HtmlElement($this->_tag, false, $this->_content); } } @@ -565,11 +612,13 @@ class Block_dl extends Block_list { var $_tag = 'dl'; - function Block_dl () { - $this->_re = '\ {0,4}\S.*(?_re = '\ {0,4}\S.*(?_do_match($input, $m))) return false; list ($term, $defn, $loose) = $p; @@ -580,7 +629,8 @@ class Block_dl extends Block_list return true; } - function _setTightness($top, $bot) { + function _setTightness($top, $bot) + { $dt = &$this->_content[0]; $dd = &$this->_content[1]; @@ -588,7 +638,8 @@ class Block_dl extends Block_list $dd->setTightness($this->_tight_defn, $bot); } - function _do_match (&$input, $m) { + function _do_match(&$input, $m) + { $pos = $input->getPos(); $firstIndent = strspn($m->match, ' '); @@ -600,11 +651,11 @@ class Block_dl extends Block_list if (!$line || !preg_match($pat, $line, $mm)) { $input->setPos($pos); - return false; // No body found. + return false; // No body found. } $indent = strlen($mm[0]); - $term = TransformInline(rtrim(substr(trim($m->match),0,-1))); + $term = TransformInline(rtrim(substr(trim($m->match), 0, -1))); $defn = new TightSubBlock($input, sprintf("\\ {%d}", $indent), false, 'dd'); return array($term, $defn, $loose); } @@ -615,12 +666,13 @@ class Block_table_dl_defn extends XmlContent var $nrows; var $ncols; - function Block_table_dl_defn ($term, $defn) { + function Block_table_dl_defn($term, $defn) + { $this->XmlContent(); if (!is_array($defn)) $defn = $defn->getContent(); - $this->_next_tight_top = false; // value irrelevant - gets fixed later + $this->_next_tight_top = false; // value irrelevant - gets fixed later $this->_ncols = $this->_ComputeNcols($defn); $this->_nrows = 0; @@ -638,12 +690,14 @@ class Block_table_dl_defn extends XmlContent $this->_setTerm($th); } - function setTightness($tight_top, $tight_bot) { + function setTightness($tight_top, $tight_bot) + { $this->_tight_top = $tight_top; - $this->_tight_bot = $tight_bot; + $this->_tight_bot = $tight_bot; } - function _addToRow ($item) { + function _addToRow($item) + { if (empty($this->_accum)) { $this->_accum = HTML::td(); if ($this->_ncols > 2) @@ -652,7 +706,8 @@ class Block_table_dl_defn extends XmlContent $this->_accum->pushContent($item); } - function _flushRow ($tight_bottom=false) { + function _flushRow($tight_bottom = false) + { if (!empty($this->_accum)) { $row = new Block_HtmlElement('tr', false, $this->_accum); @@ -665,7 +720,8 @@ class Block_table_dl_defn extends XmlContent } } - function _addSubtable ($table) { + function _addSubtable($table) + { if (!($table_rows = $table->getContent())) return; @@ -678,7 +734,8 @@ class Block_table_dl_defn extends XmlContent } } - function _setTerm ($th) { + function _setTerm($th) + { $first_row = &$this->_content[0]; if (isa($first_row, 'Block_table_dl_defn')) $first_row->_setTerm($th); @@ -686,7 +743,8 @@ class Block_table_dl_defn extends XmlContent $first_row->unshiftContent($th); } - function _ComputeNcols ($defn) { + function _ComputeNcols($defn) + { $ncols = 2; foreach ($defn as $item) { if ($this->_IsASubtable($item)) { @@ -697,40 +755,47 @@ class Block_table_dl_defn extends XmlContent return $ncols; } - function _IsASubtable ($item) { + function _IsASubtable($item) + { return isa($item, 'HtmlElement') && $item->getTag() == 'table' && $item->getAttr('class') == 'wiki-dl-table'; } - function _FirstDefn ($subtable) { + function _FirstDefn($subtable) + { $defs = $subtable->getContent(); return $defs[0]; } - function ncols () { + function ncols() + { return $this->_ncols; } - function nrows () { + function nrows() + { return $this->_nrows; } - function & firstTR() { - $first = &$this->_content[0]; - if (isa($first, 'Block_table_dl_defn')) - return $first->firstTR(); - return $first; + function & firstTR() + { + $first = &$this->_content[0]; + if (isa($first, 'Block_table_dl_defn')) + return $first->firstTR(); + return $first; } - function & lastTR() { - $last = &$this->_content[$this->_nrows - 1]; - if (isa($last, 'Block_table_dl_defn')) - return $last->lastTR(); - return $last; + function & lastTR() + { + $last = &$this->_content[$this->_nrows - 1]; + if (isa($last, 'Block_table_dl_defn')) + return $last->lastTR(); + return $last; } - function setWidth ($ncols) { + function setWidth($ncols) + { assert($ncols >= $this->_ncols); if ($ncols <= $this->_ncols) return; @@ -743,7 +808,7 @@ class Block_table_dl_defn extends XmlContent $n = count($row->_content); $lastcol = &$row->_content[$n - 1]; if (!empty($lastcol)) - $lastcol->setAttr('colspan', $ncols - 1); + $lastcol->setAttr('colspan', $ncols - 1); } } } @@ -751,13 +816,15 @@ class Block_table_dl_defn extends XmlContent class Block_table_dl extends Block_dl { - var $_tag = 'dl-table'; // phony. + var $_tag = 'dl-table'; // phony. - function Block_table_dl() { - $this->_re = '\ {0,4} (?:\S.*)? (?_re = '\ {0,4} (?:\S.*)? (?_do_match($input, $m))) return false; list ($term, $defn, $loose) = $p; @@ -766,11 +833,13 @@ class Block_table_dl extends Block_dl return true; } - function _setTightness($top, $bot) { + function _setTightness($top, $bot) + { $this->_content[0]->setTightness($top, $bot); } - function finish () { + function finish() + { $defs = &$this->_content; @@ -782,10 +851,10 @@ class Block_table_dl extends Block_dl $defs[$key]->setWidth($ncols); return HTML::table(array('class' => 'wiki-dl-table', - 'border' => 1, - 'cellspacing' => 0, - 'cellpadding' => 6), - $defs); + 'border' => 1, + 'cellspacing' => 0, + 'cellpadding' => 6), + $defs); } } @@ -797,7 +866,8 @@ class Block_oldlists extends Block_list | ; .*? : ) .*? (?=\S)'; - function _match (&$input, $m) { + function _match(&$input, $m) + { // FIXME: if (!preg_match('/[*#;]*$/A', $input->getPrefix())) { return false; @@ -812,18 +882,16 @@ class Block_oldlists extends Block_list if ($bullet == '*') { $this->_tag = 'ul'; $itemtag = 'li'; - } - elseif ($bullet == '#') { + } elseif ($bullet == '#') { $this->_tag = 'ol'; $itemtag = 'li'; - } - else { + } else { $this->_tag = 'dl'; list ($term,) = explode(':', substr($prefix, 1), 2); $term = trim($term); if ($term) $this->_content[] = new Block_HtmlElement('dt', false, - TransformInline($term)); + TransformInline($term)); $itemtag = 'dd'; } @@ -831,12 +899,12 @@ class Block_oldlists extends Block_list return true; } - function _setTightness($top, $bot) { + function _setTightness($top, $bot) + { if (count($this->_content) == 1) { $li = &$this->_content[0]; $li->setTightness($top, $bot); - } - else { + } else { // This is where php5 usually brakes. // wrong duplicated
  • contents if (DEBUG and DEBUG & _DEBUG_PARSER and check_php_version(5)) { @@ -865,20 +933,24 @@ class Block_oldlists extends Block_list // Print class properties printf("---> Properties: %s\n", var_export($class->getProperties(), 1)); */ - echo 'count($this->_content): ', count($this->_content),"\n"; - echo "\$this->_content[0]: "; var_dump ($this->_content[0]); + echo 'count($this->_content): ', count($this->_content), "\n"; + echo "\$this->_content[0]: "; + var_dump($this->_content[0]); - for ($i=1; $i < min(5, count($this->_content)); $i++) { + for ($i = 1; $i < min(5, count($this->_content)); $i++) { $c =& $this->_content[$i]; - echo '$this->_content[',$i,"]: \n"; - echo "_tag: "; var_dump ($c->_tag); - echo "_content: "; var_dump ($c->_content); - echo "_properties: "; var_dump ($c->_properties); + echo '$this->_content[', $i, "]: \n"; + echo "_tag: "; + var_dump($c->_tag); + echo "_content: "; + var_dump($c->_content); + echo "_properties: "; + var_dump($c->_properties); } debug_print_backtrace(); if (DEBUG & _DEBUG_APD) { if (function_exists("xdebug_get_function_stack")) { - var_dump (xdebug_get_function_stack()); + var_dump(xdebug_get_function_stack()); } } echo ""; @@ -898,7 +970,8 @@ class Block_pre extends BlockMarkup { var $_re = '<(?:pre|verbatim|nowiki|noinclude)>'; - function _match (&$input, $m) { + function _match(&$input, $m) + { $endtag = 'match, 1); $text = array(); $pos = $input->getPos(); @@ -913,9 +986,9 @@ class Block_pre extends BlockMarkup } $input->advance(); - if ($m->match == '') - $text = join("
    \n", $text); - else + if ($m->match == '') + $text = join("
    \n", $text); + else $text = join("\n", $text); // FIXME: no , , , , or 's allowed @@ -923,15 +996,15 @@ class Block_pre extends BlockMarkup if ($m->match == '
    ') {
                 $text = TransformInline($text);
             }
    -    if ($m->match == '') {
    -        $text = TransformText($text);
    -        $this->_element = new Block_HtmlElement('div', false, $text);
    -    } elseif ($m->match == '') {
    +        if ($m->match == '') {
    +            $text = TransformText($text);
    +            $this->_element = new Block_HtmlElement('div', false, $text);
    +        } elseif ($m->match == '') {
                 $text = TransformInlineNowiki($text);
    -        $this->_element = new Block_HtmlElement('p', false, $text);
    -    } else {
    +            $this->_element = new Block_HtmlElement('p', false, $text);
    +        } else {
                 $this->_element = new Block_HtmlElement('pre', false, $text);
    -    }
    +        }
             return true;
         }
     }
    @@ -942,7 +1015,8 @@ class Block_placeholder extends BlockMarkup
     {
         var $_re = '<<<';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             $endtag = '>>>';
             $text = array();
             $pos = $input->getPos();
    @@ -968,7 +1042,8 @@ class Block_nowiki_wikicreole extends BlockMarkup
     {
         var $_re = '{{{';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             $endtag = '}}}';
             $text = array();
             $pos = $input->getPos();
    @@ -1001,10 +1076,11 @@ class Block_plugin extends Block_pre
          *
          * should all work.
          */
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             $pos = $input->getPos();
             $pi = $m->match . $m->postmatch;
    -        while (!preg_match('/(?\s*$/', $pi)) {
    +        while (!preg_match('/(?\s*$/', $pi)) {
                 if (($line = $input->nextLine()) === false) {
                     $input->setPos($pos);
                     return false;
    @@ -1013,7 +1089,7 @@ class Block_plugin extends Block_pre
             }
             $input->advance();
     
    -    $this->_element = new Cached_PluginInvocation($pi);
    +        $this->_element = new Cached_PluginInvocation($pi);
             return true;
         }
     }
    @@ -1023,14 +1099,15 @@ class Block_plugin_wikicreole extends Block_pre
         // var $_re = '<<(?!\S)';
         var $_re = '<<';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             $pos = $input->getPos();
             $pi = $m->postmatch;
             if ($pi[0] == '<') {
                 return false;
             }
             $pi = ">\s*$/', $pi)) {
    +        while (!preg_match('/(?>\s*$/', $pi)) {
                 if (($line = $input->nextLine()) === false) {
                     $input->setPos($pos);
                     return false;
    @@ -1050,7 +1127,8 @@ class Block_table_wikicreole extends Block_pre
     {
         var $_re = '\s*\|';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             $pos = $input->getPos();
             $pi = "|" . $m->postmatch;
     
    @@ -1072,7 +1150,7 @@ class Block_table_wikicreole extends Block_pre
                 $pi .= "\n$trimline";
             }
     
    -        $pi = '<'.'?plugin WikicreoleTable ' . $pi . '?'.'>';
    +        $pi = '<' . '?plugin WikicreoleTable ' . $pi . '?' . '>';
     
             $this->_element = new Cached_PluginInvocation($pi);
             return true;
    @@ -1090,10 +1168,11 @@ class Block_table_mediawiki extends Block_pre
     {
         var $_re = '{\|';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             $pos = $input->getPos();
             $pi = $m->postmatch;
    -        while (!preg_match('/(?nextLine()) === false) {
                     $input->setPos($pos);
                     return false;
    @@ -1103,7 +1182,7 @@ class Block_table_mediawiki extends Block_pre
             $input->advance();
     
             $pi = str_replace("\|}", "", $pi);
    -        $pi = '<'.'?plugin MediawikiTable ' . $pi . '?'.'>';
    +        $pi = '<' . '?plugin MediawikiTable ' . $pi . '?' . '>';
             $this->_element = new Cached_PluginInvocation($pi);
             return true;
         }
    @@ -1124,7 +1203,8 @@ class Block_template_plugin extends Block_pre
     {
         var $_re = '{{';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             // If we find "}}", this is an inline template.
             if (strpos($m->postmatch, "}}") !== false) {
                 return false;
    @@ -1134,7 +1214,7 @@ class Block_template_plugin extends Block_pre
             if ($pi[0] == '{') {
                 return false;
             }
    -        while (!preg_match('/(?nextLine()) === false) {
                     $input->setPos($pos);
                     return false;
    @@ -1162,7 +1242,7 @@ class Block_template_plugin extends Block_pre
     
             // It's a video
             if (is_video($imagename)) {
    -            $pi = '<'.'?plugin Video file="' . $pi . '" ?>';
    +            $pi = '<' . '?plugin Video file="' . $pi . '" ?>';
                 $this->_element = new Cached_PluginInvocation($pi);
                 return true;
             }
    @@ -1189,9 +1269,9 @@ class Block_template_plugin extends Block_pre
             }
     
             if ($vars)
    -            $pi = '<'.'?plugin Template page="'.$pi.'" '.$vars . ' ?>';
    +            $pi = '<' . '?plugin Template page="' . $pi . '" ' . $vars . ' ?>';
             else
    -            $pi = '<'.'?plugin Template page="' . $pi . '" ?>';
    +            $pi = '<' . '?plugin Template page="' . $pi . '" ?>';
             $this->_element = new Cached_PluginInvocation($pi);
             return true;
         }
    @@ -1202,11 +1282,12 @@ class Block_email_blockquote extends BlockMarkup
         var $_attr = array('class' => 'mail-style-quote');
         var $_re = '>\ ?';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             //$indent = str_replace(' ', '\\ ', $m->match) . '|>$';
             $indent = $this->_re;
             $this->_element = new SubBlock($input, $indent, $m->match,
    -                                       'blockquote', $this->_attr);
    +            'blockquote', $this->_attr);
             return true;
         }
     }
    @@ -1216,10 +1297,11 @@ class Block_wikicreole_indented extends BlockMarkup
         var $_attr = array('style' => 'margin-left:2em');
         var $_re = ':\ ?';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             $indent = $this->_re;
             $this->_element = new SubBlock($input, $indent, $m->match,
    -                                       'div', $this->_attr);
    +            'div', $this->_attr);
             return true;
         }
     }
    @@ -1228,7 +1310,8 @@ class Block_hr extends BlockMarkup
     {
         var $_re = '-{4,}\s*$';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             $input->advance();
             $this->_element = new Block_HtmlElement('hr');
             return true;
    @@ -1239,7 +1322,8 @@ class Block_heading extends BlockMarkup
     {
         var $_re = '!{1,3}';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             $tag = "h" . (5 - strlen($m->match));
             $text = TransformInline(trim($m->postmatch));
             $input->advance();
    @@ -1254,7 +1338,8 @@ class Block_heading_wikicreole extends BlockMarkup
     {
         var $_re = '={2,6}';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             $tag = "h" . strlen($m->match);
             // Remove spaces
             $header = trim($m->postmatch);
    @@ -1275,18 +1360,21 @@ class Block_p extends BlockMarkup
         var $_re = '\S.*';
         var $_text = '';
     
    -    function _match (&$input, $m) {
    +    function _match(&$input, $m)
    +    {
             $this->_text = $m->match;
             $input->advance();
             return true;
         }
     
    -    function _setTightness ($top, $bot) {
    +    function _setTightness($top, $bot)
    +    {
             $this->_tight_top = $top;
             $this->_tight_bot = $bot;
         }
     
    -    function merge ($nextBlock) {
    +    function merge($nextBlock)
    +    {
             $class = get_class($nextBlock);
             if (strtolower($class) == 'block_p' and $this->_tight_bot) {
                 $this->_text .= "\n" . $nextBlock->_text;
    @@ -1296,7 +1384,8 @@ class Block_p extends BlockMarkup
             return false;
         }
     
    -    function finish () {
    +    function finish()
    +    {
             $content = TransformInline(trim($this->_text));
             $p = new Block_HtmlElement('p', false, $content);
             $p->setTightness($this->_tight_top, $this->_tight_bot);
    @@ -1308,17 +1397,18 @@ class Block_divspan extends BlockMarkup
     {
         var $_re = '<(?im)(?: div|span)(?:[^>]*)?>';
     
    -    function _match (&$input, $m) {
    -        if (substr($m->match,1,4) == 'span') {
    +    function _match(&$input, $m)
    +    {
    +        if (substr($m->match, 1, 4) == 'span') {
                 $tag = 'span';
    -    } else {
    +        } else {
                 $tag = 'div';
    -    }
    -    // without last >
    -        $argstr = substr(trim(substr($m->match,strlen($tag)+1)),0,-1);
    +        }
    +        // without last >
    +        $argstr = substr(trim(substr($m->match, strlen($tag) + 1)), 0, -1);
             $pos = $input->getPos();
    -        $pi  = $content = $m->postmatch;
    -        while (!preg_match('/^(.*)\<\/'.$tag.'\>(.*)$/i', $pi, $me)) {
    +        $pi = $content = $m->postmatch;
    +        while (!preg_match('/^(.*)\<\/' . $tag . '\>(.*)$/i', $pi, $me)) {
                 if ($pi != $content)
                     $content .= "\n$pi";
                 if (($pi = $input->nextLine()) === false) {
    @@ -1340,7 +1430,8 @@ class Block_divspan extends BlockMarkup
             else {
                 $args = array();
                 while (preg_match("/(\w+)=(.+)/", $argstr, $m)) {
    -                $k = $m[1]; $v = $m[2];
    +                $k = $m[1];
    +                $v = $m[2];
                     if (preg_match("/^\"(.+?)\"(.*)$/", $v, $m)) {
                         $v = $m[1];
                         $argstr = $m[2];
    @@ -1364,7 +1455,8 @@ class Block_divspan extends BlockMarkup
     /**
      * Transform the text of a page, and return a parse tree.
      */
    -function TransformTextPre ($text, $markup = 2.0, $basepage=false) {
    +function TransformTextPre($text, $markup = 2.0, $basepage = false)
    +{
         if (isa($text, 'WikiDB_PageRevision')) {
             $rev = $text;
             $text = $rev->getPackedContent();
    @@ -1385,7 +1477,8 @@ function TransformTextPre ($text, $markup = 2.0, $basepage=false) {
      * Transform the text of a page, and return an XmlContent,
      * suitable for printXml()-ing.
      */
    -function TransformText ($text, $markup = 2.0, $basepage = false) {
    +function TransformText($text, $markup = 2.0, $basepage = false)
    +{
         $output = TransformTextPre($text, $markup, $basepage);
         if ($basepage) {
             // This is for immediate consumption.
    diff --git a/lib/CachedMarkup.php b/lib/CachedMarkup.php
    index fb876eda0..31dda729f 100644
    --- a/lib/CachedMarkup.php
    +++ b/lib/CachedMarkup.php
    @@ -23,9 +23,11 @@
     
     require_once 'lib/Units.php';
     
    -class CacheableMarkup extends XmlContent {
    +class CacheableMarkup extends XmlContent
    +{
     
    -    function CacheableMarkup($content, $basepage) {
    +    function CacheableMarkup($content, $basepage)
    +    {
             $this->_basepage = $basepage;
             $this->_buf = '';
             $this->_content = array();
    @@ -35,7 +37,8 @@ class CacheableMarkup extends XmlContent {
             unset($this->_buf);
         }
     
    -    function pack() {
    +    function pack()
    +    {
             // FusionForge hack
             // This causes a strange bug when a comment containing
             // a single quote is entered in the Summary box:
    @@ -54,15 +57,17 @@ class CacheableMarkup extends XmlContent {
             //   when no gzcompress is available.
         }
     
    -    function unpack($packed) {
    +    function unpack($packed)
    +    {
             if (!$packed)
                 return false;
     
             // ZLIB format has a five bit checksum in it's header.
             // Lets check for sanity.
             if (((ord($packed[0]) * 256 + ord($packed[1])) % 31 == 0)
    -             and (substr($packed,0,2) == "\037\213")
    -                  or (substr($packed,0,2) == "x\332"))   // 120, 218
    +            and (substr($packed, 0, 2) == "\037\213")
    +            or (substr($packed, 0, 2) == "x\332")
    +        ) // 120, 218
             {
                 if (function_exists('gzuncompress')) {
                     // Looks like ZLIB.
    @@ -72,11 +77,11 @@ class CacheableMarkup extends XmlContent {
                     // user our php lib. TESTME
                     include_once 'ziplib.php';
                     $zip = new ZipReader($packed);
    -                list(,$data,$attrib) = $zip->readFile();
    +                list(, $data, $attrib) = $zip->readFile();
                     return unserialize($data);
                 }
             }
    -        if (substr($packed,0,2) == "O:") {
    +        if (substr($packed, 0, 2) == "O:") {
                 // Looks like a serialized object
                 return unserialize($packed);
             }
    @@ -84,7 +89,7 @@ class CacheableMarkup extends XmlContent {
                 return $packed;
             // happened with _BackendInfo problem also.
             trigger_error("Can't unpack bad cached markup. Probably php_zlib extension not loaded.",
    -                      E_USER_WARNING);
    +            E_USER_WARNING);
             return false;
         }
     
    @@ -92,7 +97,8 @@ class CacheableMarkup extends XmlContent {
          *
          * @return array of hashes { linkto=>pagename, relation=>pagename }
          */
    -    function getWikiPageLinks() {
    +    function getWikiPageLinks()
    +    {
             $links = array();
             foreach ($this->_content as $item) {
                 if (!isa($item, 'Cached_DynamicContent'))
    @@ -114,10 +120,11 @@ class CacheableMarkup extends XmlContent {
          * @return array
          * Returns an array of hashes.
          */
    -    function getLinkInfo() {
    +    function getLinkInfo()
    +    {
             $link = array();
             foreach ($this->_content as $link) {
    -            if (! isa($link, 'Cached_Link'))
    +            if (!isa($link, 'Cached_Link'))
                     continue;
                 $info = $link->getLinkInfo($this->_basepage);
                 $links[$info->href] = $info;
    @@ -125,26 +132,23 @@ class CacheableMarkup extends XmlContent {
             return array_values($links);
         }
     
    -    function _append($item) {
    +    function _append($item)
    +    {
             if (is_array($item)) {
                 foreach ($item as $subitem)
                     $this->_append($subitem);
    -        }
    -        elseif (!is_object($item)) {
    -            $this->_buf .= $this->_quote((string) $item);
    -        }
    -        elseif (isa($item, 'Cached_DynamicContent')) {
    +        } elseif (!is_object($item)) {
    +            $this->_buf .= $this->_quote((string)$item);
    +        } elseif (isa($item, 'Cached_DynamicContent')) {
                 if ($this->_buf) {
                     $this->_content[] = $this->_buf;
                     $this->_buf = '';
                 }
                 $this->_content[] = $item;
    -        }
    -        elseif (isa($item, 'XmlElement')) {
    +        } elseif (isa($item, 'XmlElement')) {
                 if ($item->isEmpty()) {
                     $this->_buf .= $item->emptyTag();
    -            }
    -            else {
    +            } else {
                     $this->_buf .= $item->startTag();
                     foreach ($item->getContent() as $subitem)
                         $this->_append($subitem);
    @@ -156,29 +160,26 @@ class CacheableMarkup extends XmlContent {
                     }
                 }
                 if (!$item->isInlineElement())
    -            $this->_buf .= "\n";
    -        }
    -        elseif (isa($item, 'XmlContent')) {
    +                $this->_buf .= "\n";
    +        } elseif (isa($item, 'XmlContent')) {
                 foreach ($item->getContent() as $item)
                     $this->_append($item);
    -        }
    -        elseif (method_exists($item, 'asXML')) {
    +        } elseif (method_exists($item, 'asXML')) {
                 $this->_buf .= $item->asXML();
    -        }
    -        elseif (method_exists($item, 'asString')) {
    +        } elseif (method_exists($item, 'asString')) {
                 $this->_buf .= $this->_quote($item->asString());
    -        }
    -        else {
    +        } else {
                 $this->_buf .= sprintf("==Object(%s)==", get_class($item));
             }
         }
     
    -    function _glean_description($text) {
    +    function _glean_description($text)
    +    {
             static $two_sentences;
             if (!$two_sentences) {
                 $two_sentences = "[.?!][\")]*\s+[\"(]*[[:upper:])]"
    -                           . ".*"
    -                           . "[.?!][\")]*\s*[\"(]*([[:upper:])]|$)";
    +                . ".*"
    +                . "[.?!][\")]*\s*[\"(]*([[:upper:])]|$)";
             }
     
             if (!isset($this->_description) and preg_match("/$two_sentences/sx", $text))
    @@ -200,52 +201,51 @@ class CacheableMarkup extends XmlContent {
          *
          * @return string
          */
    -    function getDescription () {
    +    function getDescription()
    +    {
             return isset($this->_description) ? $this->_description : '';
         }
     
    -    function asXML () {
    +    function asXML()
    +    {
             $xml = '';
             $basepage = $this->_basepage;
     
             foreach ($this->_content as $item) {
                 if (is_string($item)) {
                     $xml .= $item;
    -            }
    -            elseif (is_subclass_of($item,
    -                                   check_php_version(5)
    -                                     ? 'Cached_DynamicContent'
    -                                     : 'cached_dynamiccontent'))
    -            {
    +            } elseif (is_subclass_of($item,
    +                check_php_version(5)
    +                    ? 'Cached_DynamicContent'
    +                    : 'cached_dynamiccontent')
    +            ) {
                     $val = $item->expand($basepage, $this);
                     $xml .= $val->asXML();
    -            }
    -            else {
    +            } else {
                     $xml .= $item->asXML();
                 }
             }
             return $xml;
         }
     
    -    function printXML () {
    +    function printXML()
    +    {
             $basepage = $this->_basepage;
             // _content might be changed from a plugin (CreateToc)
    -        for ($i=0; $i < count($this->_content); $i++) {
    +        for ($i = 0; $i < count($this->_content); $i++) {
                 $item = $this->_content[$i];
                 if (is_string($item)) {
                     print $item;
    -            }
    -            elseif (is_subclass_of($item,
    -                                   check_php_version(5)
    -                                     ? 'Cached_DynamicContent'
    -                                     : 'cached_dynamiccontent'))
    -            {      // give the content the chance to know about itself or even
    +            } elseif (is_subclass_of($item,
    +                check_php_version(5)
    +                    ? 'Cached_DynamicContent'
    +                    : 'cached_dynamiccontent')
    +            ) { // give the content the chance to know about itself or even
                     // to change itself
                     $val = $item->expand($basepage, $this);
                     if ($val) $val->printXML();
                     else trigger_error('empty item ' . print_r($item, true));
    -            }
    -            else {
    +            } else {
                     $item->printXML();
                 }
             }
    @@ -258,23 +258,29 @@ class CacheableMarkup extends XmlContent {
      * Dynamic content is anything that can change even when the original
      * wiki-text from which it was parsed is unchanged.
      */
    -class Cached_DynamicContent {
    +class Cached_DynamicContent
    +{
     
    -    function cache(&$cache) {
    +    function cache(&$cache)
    +    {
             $cache[] = $this;
         }
     
    -    function expand($basepage, &$obj) {
    +    function expand($basepage, &$obj)
    +    {
             trigger_error("Pure virtual", E_USER_ERROR);
         }
     
    -    function getWikiPageLinks($basepage) {
    +    function getWikiPageLinks($basepage)
    +    {
             return false;
         }
     }
     
    -class XmlRpc_LinkInfo {
    -    function XmlRpc_LinkInfo($page, $type, $href, $relation = '') {
    +class XmlRpc_LinkInfo
    +{
    +    function XmlRpc_LinkInfo($page, $type, $href, $relation = '')
    +    {
             $this->page = $page;
             $this->type = $type;
             $this->href = $href;
    @@ -283,9 +289,11 @@ class XmlRpc_LinkInfo {
         }
     }
     
    -class Cached_Link extends Cached_DynamicContent {
    +class Cached_Link extends Cached_DynamicContent
    +{
     
    -    function isInlineElement() {
    +    function isInlineElement()
    +    {
             return true;
         }
     
    @@ -294,33 +302,44 @@ class Cached_Link extends Cached_DynamicContent {
          * This is here to support the XML-RPC listLinks method.
          * (See http://www.ecyrd.com/JSPWiki/Wiki.jsp?page=WikiRPCInterface)
          */
    -    function getLinkInfo($basepage) {
    +    function getLinkInfo($basepage)
    +    {
             return new XmlRpc_LinkInfo($this->_getName($basepage),
    -                                   $this->_getType(),
    -                                   $this->_getURL($basepage),
    -                                   $this->_getRelation($basepage));
    +            $this->_getType(),
    +            $this->_getURL($basepage),
    +            $this->_getRelation($basepage));
         }
     
    -    function _getURL($basepage) {
    +    function _getURL($basepage)
    +    {
             return $this->_url;
         }
    -    function __getRelation($basepage) {
    +
    +    function __getRelation($basepage)
    +    {
             return $this->_relation;
         }
     }
    +
     /*
      * Defer interwiki inline links. img src=upload:xx.png
      * LinkImage($url, $alt = false)
      */
    -class Cached_InlinedImage extends Cached_DynamicContent {
    -    function isInlineElement() {
    +class Cached_InlinedImage extends Cached_DynamicContent
    +{
    +    function isInlineElement()
    +    {
             return true;
         }
    -    function _getURL($basepage) {
    +
    +    function _getURL($basepage)
    +    {
             return $this->_url;
         }
    +
         // TODO: fix interwiki inline links in case of static dumps
    -    function expand($basepage, &$markup) {
    +    function expand($basepage, &$markup)
    +    {
             global $WikiTheme;
             $this->_basepage = $basepage;
             $label = isset($this->_label) ? $this->_label : false;
    @@ -334,13 +353,15 @@ class Cached_InlinedImage extends Cached_DynamicContent {
         }
     }
     
    -class Cached_WikiLink extends Cached_Link {
    +class Cached_WikiLink extends Cached_Link
    +{
     
    -    function Cached_WikiLink ($page, $label = false, $anchor = false) {
    +    function Cached_WikiLink($page, $label = false, $anchor = false)
    +    {
             $this->_page = $page;
             /* ":DontStoreLink" */
    -        if (substr($this->_page,0,1) == ':') {
    -            $this->_page = substr($this->_page,1);
    +        if (substr($this->_page, 0, 1) == ':') {
    +            $this->_page = substr($this->_page, 1);
                 $this->_nolink = true;
             }
             if ($anchor)
    @@ -350,17 +371,20 @@ class Cached_WikiLink extends Cached_Link {
             $this->_basepage = false;
         }
     
    -    function _getType() {
    +    function _getType()
    +    {
             return 'internal';
         }
     
    -    function getPagename($basepage) {
    +    function getPagename($basepage)
    +    {
             $page = new WikiPageName($this->_page, $basepage);
             if ($page->isValid()) return $page->name;
             else return false;
         }
     
    -    function getWikiPageLinks($basepage) {
    +    function getWikiPageLinks($basepage)
    +    {
             if ($basepage == '') return false;
             if (isset($this->_nolink)) return false;
             if ($link = $this->getPagename($basepage))
    @@ -369,16 +393,19 @@ class Cached_WikiLink extends Cached_Link {
                 return false;
         }
     
    -    function _getName($basepage) {
    +    function _getName($basepage)
    +    {
             return $this->getPagename($basepage);
         }
     
    -    function _getURL($basepage) {
    +    function _getURL($basepage)
    +    {
             return WikiURL($this->getPagename($basepage));
             //return WikiURL($this->getPagename($basepage), false, 'abs_url');
         }
     
    -    function expand($basepage, &$markup) {
    +    function expand($basepage, &$markup)
    +    {
             global $WikiTheme;
             $this->_basepage = $basepage;
             $label = isset($this->_label) ? $this->_label : false;
    @@ -389,10 +416,11 @@ class Cached_WikiLink extends Cached_Link {
                     return HTML($label ? $label : $page->getName());
             }
             if ($page->isValid()) return WikiLink($page, 'auto', $label);
    -            else return HTML($label);
    +        else return HTML($label);
         }
     
    -    function asXML() {
    +    function asXML()
    +    {
             global $WikiTheme;
             $label = isset($this->_label) ? $this->_label : false;
             $anchor = isset($this->_anchor) ? (string)$this->_anchor : '';
    @@ -406,7 +434,8 @@ class Cached_WikiLink extends Cached_Link {
             return $link->asXML();
         }
     
    -    function asString() {
    +    function asString()
    +    {
             if (isset($this->_label))
                 return $this->_label;
             return $this->_page;
    @@ -415,11 +444,13 @@ class Cached_WikiLink extends Cached_Link {
     
     class Cached_WikiLinkIfKnown extends Cached_WikiLink
     {
    -    function Cached_WikiLinkIfKnown ($moniker) {
    +    function Cached_WikiLinkIfKnown($moniker)
    +    {
             $this->_page = $moniker;
         }
     
    -    function expand($basepage, &$markup) {
    +    function expand($basepage, &$markup)
    +    {
             global $WikiTheme;
             if ($WikiTheme->DUMP_MODE and $WikiTheme->VALID_LINKS) {
                 if (!in_array($this->_page, $WikiTheme->VALID_LINKS))
    @@ -431,15 +462,17 @@ class Cached_WikiLinkIfKnown extends Cached_WikiLink
     
     class Cached_SpellCheck extends Cached_WikiLink
     {
    -    function Cached_SpellCheck ($word, $suggs) {
    +    function Cached_SpellCheck($word, $suggs)
    +    {
             $this->_page = $word;
             $this->suggestions = $suggs;
         }
     
    -    function expand($basepage, &$markup) {
    +    function expand($basepage, &$markup)
    +    {
             $link = HTML::a(array('class' => 'spell-wrong',
    -                  'title' => 'SpellCheck: '.join(', ', $this->suggestions),
    -                  'name' => $this->_page),
    +                'title' => 'SpellCheck: ' . join(', ', $this->suggestions),
    +                'name' => $this->_page),
                 $this->_page);
             return $link;
         }
    @@ -447,18 +480,21 @@ class Cached_SpellCheck extends Cached_WikiLink
     
     class Cached_PhpwikiURL extends Cached_DynamicContent
     {
    -    function Cached_PhpwikiURL ($url, $label) {
    -    $this->_url = $url;
    +    function Cached_PhpwikiURL($url, $label)
    +    {
    +        $this->_url = $url;
             if ($label)
                 $this->_label = $label;
         }
     
    -    function isInlineElement() {
    +    function isInlineElement()
    +    {
             return true;
         }
     
    -    function expand($basepage, &$markup) {
    -    global $WikiTheme;
    +    function expand($basepage, &$markup)
    +    {
    +        global $WikiTheme;
             $label = isset($this->_label) ? $this->_label : false;
             if ($WikiTheme->DUMP_MODE and $WikiTheme->VALID_LINKS) {
                 if (!in_array($this->_page, $WikiTheme->VALID_LINKS))
    @@ -467,13 +503,15 @@ class Cached_PhpwikiURL extends Cached_DynamicContent
             return LinkPhpwikiURL($this->_url, $label, $basepage);
         }
     
    -    function asXML() {
    +    function asXML()
    +    {
             $label = isset($this->_label) ? $this->_label : false;
             $link = LinkPhpwikiURL($this->_url, $label);
             return $link->asXML();
         }
     
    -    function asString() {
    +    function asString()
    +    {
             if (isset($this->_label))
                 return $this->_label;
             return $this->_url;
    @@ -490,20 +528,24 @@ class Cached_PhpwikiURL extends Cached_DynamicContent
      * to denote that this is an attribute,
      * and to enable a fast listRelations mode=attributes
      */
    -class Cached_SemanticLink extends Cached_WikiLink {
    +class Cached_SemanticLink extends Cached_WikiLink
    +{
     
    -    function Cached_SemanticLink ($url, $label=false) {
    -    $this->_url = $url;
    +    function Cached_SemanticLink($url, $label = false)
    +    {
    +        $this->_url = $url;
             if ($label && $label != $url)
                 $this->_label = $label;
             $this->_expandurl($this->_url);
         }
     
    -    function isInlineElement() {
    +    function isInlineElement()
    +    {
             return true;
         }
     
    -    function getPagename($basepage) {
    +    function getPagename($basepage)
    +    {
             if (!isset($this->_page)) return false;
             $page = new WikiPageName($this->_page, $basepage);
             if ($page->isValid()) return $page->name;
    @@ -513,7 +555,8 @@ class Cached_SemanticLink extends Cached_WikiLink {
         /* Add relation to the link table.
          * attributes have the _relation, but not the _page set.
          */
    -    function getWikiPageLinks($basepage) {
    +    function getWikiPageLinks($basepage)
    +    {
             if ($basepage == '') return false;
             if (!isset($this->_page) and isset($this->_attribute)) {
                 // An attribute: we store it in the basepage now, to fill the cache for page->save
    @@ -529,7 +572,8 @@ class Cached_SemanticLink extends Cached_WikiLink {
                 return false;
         }
     
    -    function _expandurl($url) {
    +    function _expandurl($url)
    +    {
             $m = array();
             if (!preg_match('/^ ([^:]+) (:[:=]) (.+) $/x', $url, $m)) {
                 return HTML::span(array('class' => 'error'), _("BAD semantic relation link"));
    @@ -551,7 +595,8 @@ class Cached_SemanticLink extends Cached_WikiLink {
             return $m;
         }
     
    -    function _expand($url, $label = false) {
    +    function _expand($url, $label = false)
    +    {
             global $WikiTheme;
             $m = $this->_expandurl($url);
             $class = 'wiki';
    @@ -563,51 +608,54 @@ class Cached_SemanticLink extends Cached_WikiLink {
             }
             if ($is_attribute)
                 $title = isset($this->_attribute_base)
    -            ? sprintf(_("Attribute %s, base value: %s"), $this->_relation, $this->_attribute_base)
    -            : sprintf(_("Attribute %s, value: %s"), $this->_relation, $this->_attribute);
    -            if ($label) {
    -                return HTML::span(
    -                    HTML::a(array('href'  => WikiURL($is_attribute ? $this->_relation : $this->_page),
    -                   'class' => "wiki ".($is_attribute ? "attribute" : "relation"),
    -                   'title' => $is_attribute
    -                   ? $title
    -                   : sprintf(_("Relation %s to page %s"), $this->_relation, $this->_page)),
    -             $label)
    -         );
    -            } elseif ($is_attribute) {
    -                return HTML::span
    -        (
    -         HTML::a(array('href'  => WikiURL($this->_relation),
    -                   'class' => "wiki attribute",
    -                   'title' => $title),
    -             $url)
    -         );
    +                ? sprintf(_("Attribute %s, base value: %s"), $this->_relation, $this->_attribute_base)
    +                : sprintf(_("Attribute %s, value: %s"), $this->_relation, $this->_attribute);
    +        if ($label) {
    +            return HTML::span(
    +                HTML::a(array('href' => WikiURL($is_attribute ? $this->_relation : $this->_page),
    +                        'class' => "wiki " . ($is_attribute ? "attribute" : "relation"),
    +                        'title' => $is_attribute
    +                            ? $title
    +                            : sprintf(_("Relation %s to page %s"), $this->_relation, $this->_page)),
    +                    $label)
    +            );
    +        } elseif ($is_attribute) {
    +            return HTML::span
    +            (
    +                HTML::a(array('href' => WikiURL($this->_relation),
    +                        'class' => "wiki attribute",
    +                        'title' => $title),
    +                    $url)
    +            );
             } else {
                 return HTML::span
    -        (
    -         HTML::a(array('href'  => WikiURL($this->_relation),
    -                   'class' => "wiki relation"),
    -             $this->_relation),
    -         HTML::span(array('class'=>'relation-symbol'), $m[2]),
    -         HTML::a(array('href'  => WikiURL($this->_page),
    -                   'class' => "wiki"),
    -             $this->_page)
    -         );
    +            (
    +                HTML::a(array('href' => WikiURL($this->_relation),
    +                        'class' => "wiki relation"),
    +                    $this->_relation),
    +                HTML::span(array('class' => 'relation-symbol'), $m[2]),
    +                HTML::a(array('href' => WikiURL($this->_page),
    +                        'class' => "wiki"),
    +                    $this->_page)
    +            );
             }
         }
     
    -    function expand($basepage, &$markup) {
    +    function expand($basepage, &$markup)
    +    {
             $label = isset($this->_label) ? $this->_label : false;
             return $this->_expand($this->_url, $label);
         }
     
    -    function asXML() {
    +    function asXML()
    +    {
             $label = isset($this->_label) ? $this->_label : false;
             $link = $this->_expand($this->_url, $label);
             return $link->asXML();
         }
     
    -    function asString() {
    +    function asString()
    +    {
             if (isset($this->_label))
                 return $this->_label;
             return $this->_url;
    @@ -619,36 +667,43 @@ class Cached_SemanticLink extends Cached_WikiLink {
      */
     class Cached_SearchHighlight extends Cached_DynamicContent
     {
    -    function Cached_SearchHighlight ($word, $engine) {
    +    function Cached_SearchHighlight($word, $engine)
    +    {
             $this->_word = $word;
             $this->engine = $engine;
         }
     
    -    function expand($basepage, &$markup) {
    +    function expand($basepage, &$markup)
    +    {
             return HTML::span(array('class' => 'search-term',
    -                                'title' => _("Found by ") . $this->engine),
    -                          $this->_word);
    +                'title' => _("Found by ") . $this->engine),
    +            $this->_word);
         }
     }
     
    -class Cached_ExternalLink extends Cached_Link {
    +class Cached_ExternalLink extends Cached_Link
    +{
     
    -    function Cached_ExternalLink($url, $label=false) {
    +    function Cached_ExternalLink($url, $label = false)
    +    {
             $this->_url = $url;
             if ($label && $label != $url)
                 $this->_label = $label;
         }
     
    -    function _getType() {
    +    function _getType()
    +    {
             return 'external';
         }
     
    -    function _getName($basepage) {
    +    function _getName($basepage)
    +    {
             $label = isset($this->_label) ? $this->_label : false;
             return ($label and is_string($label)) ? $label : $this->_url;
         }
     
    -    function expand($basepage, &$markup) {
    +    function expand($basepage, &$markup)
    +    {
             global $request;
     
             $label = isset($this->_label) ? $this->_label : false;
    @@ -664,32 +719,37 @@ class Cached_ExternalLink extends Cached_Link {
             return $link;
         }
     
    -    function asString() {
    +    function asString()
    +    {
             if (isset($this->_label) and is_string($this->_label))
                 return $this->_label;
             return $this->_url;
         }
     }
     
    -class Cached_InterwikiLink extends Cached_ExternalLink {
    +class Cached_InterwikiLink extends Cached_ExternalLink
    +{
     
    -    function Cached_InterwikiLink($link, $label=false) {
    +    function Cached_InterwikiLink($link, $label = false)
    +    {
             $this->_link = $link;
             if ($label)
                 $this->_label = $label;
         }
     
    -    function getPagename($basepage) {
    -        list ($moniker, $page) = explode (":", $this->_link, 2);
    +    function getPagename($basepage)
    +    {
    +        list ($moniker, $page) = explode(":", $this->_link, 2);
             $page = new WikiPageName($page, $basepage);
             if ($page->isValid()) return $page->name;
             else return false;
         }
     
    -    function getWikiPageLinks($basepage) {
    +    function getWikiPageLinks($basepage)
    +    {
             if ($basepage == '') return false;
             /* ":DontStoreLink" */
    -        if (substr($this->_link,0,1) == ':') return false;
    +        if (substr($this->_link, 0, 1) == ':') return false;
             /* store only links to valid pagenames */
             $dbi = $GLOBALS['request']->getDbh();
             if ($link = $this->getPagename($basepage) and $dbi->isWikiPage($link)) {
    @@ -699,34 +759,39 @@ class Cached_InterwikiLink extends Cached_ExternalLink {
             }
         }
     
    -    function _getName($basepage) {
    +    function _getName($basepage)
    +    {
             $label = isset($this->_label) ? $this->_label : false;
             return ($label and is_string($label)) ? $label : $this->_link;
         }
     
         /* there may be internal interwiki links also */
    -    function _getType() {
    +    function _getType()
    +    {
             return $this->getPagename(false) ? 'internal' : 'external';
         }
     
    -    function _getURL($basepage) {
    +    function _getURL($basepage)
    +    {
             $link = $this->expand($basepage, $this);
             return $link->getAttr('href');
         }
     
    -    function expand($basepage, &$markup) {
    +    function expand($basepage, &$markup)
    +    {
             global $WikiTheme;
             $intermap = getInterwikiMap();
             $label = isset($this->_label) ? $this->_label : false;
             //FIXME: check Upload: inlined images
             if ($WikiTheme->DUMP_MODE and !empty($WikiTheme->VALID_LINKS)) {
                 if (!in_array($this->_link, $WikiTheme->VALID_LINKS))
    -            return HTML($label ? $label : $this->_link);
    +                return HTML($label ? $label : $this->_link);
             }
             return $intermap->link($this->_link, $label);
         }
     
    -    function asString() {
    +    function asString()
    +    {
             if (isset($this->_label))
                 return $this->_label;
             return $this->_link;
    @@ -736,8 +801,10 @@ class Cached_InterwikiLink extends Cached_ExternalLink {
     // Needed to put UserPages to backlinks. Special method to markup userpages with icons
     // Thanks to PhpWiki:DanFr for finding this bug.
     // Fixed since 1.3.8, prev. versions had no userpages in backlinks
    -class Cached_UserLink extends Cached_WikiLink {
    -    function expand($basepage, &$markup) {
    +class Cached_UserLink extends Cached_WikiLink
    +{
    +    function expand($basepage, &$markup)
    +    {
             $label = isset($this->_label) ? $this->_label : false;
             $anchor = isset($this->_anchor) ? (string)$this->_anchor : '';
             $page = new WikiPageName($this->_page, $basepage, $anchor);
    @@ -754,9 +821,11 @@ class Cached_UserLink extends Cached_WikiLink {
      * A fresh generated cache has now ->name and ->args also.
      * main::isActionPage only checks the raw content.
      */
    -class Cached_PluginInvocation extends Cached_DynamicContent {
    +class Cached_PluginInvocation extends Cached_DynamicContent
    +{
     
    -    function Cached_PluginInvocation ($pi) {
    +    function Cached_PluginInvocation($pi)
    +    {
             $this->_pi = $pi;
             $loader = $this->_getLoader();
             if (is_array($plugin_cmdline = $loader->parsePI($pi)) and $plugin_cmdline[1]) {
    @@ -766,30 +835,36 @@ class Cached_PluginInvocation extends Cached_DynamicContent {
             }
         }
     
    -    function setTightness($top, $bottom) {
    +    function setTightness($top, $bottom)
    +    {
         }
     
    -    function isInlineElement() {
    +    function isInlineElement()
    +    {
             return false;
         }
     
    -    function expand($basepage, &$markup) {
    +    function expand($basepage, &$markup)
    +    {
             $loader = $this->_getLoader();
             $xml = $loader->expandPI($this->_pi, $GLOBALS['request'], $markup, $basepage);
             return $xml;
         }
     
    -    function asString() {
    +    function asString()
    +    {
             return $this->_pi;
         }
     
    -    function getWikiPageLinks($basepage) {
    +    function getWikiPageLinks($basepage)
    +    {
             $loader = $this->_getLoader();
     
             return $loader->getWikiPageLinks($this->_pi, $basepage);
         }
     
    -    function & _getLoader() {
    +    function & _getLoader()
    +    {
             static $loader = false;
     
             if (!$loader) {
    diff --git a/lib/Captcha.php b/lib/Captcha.php
    index 119770265..62f233eb6 100644
    --- a/lib/Captcha.php
    +++ b/lib/Captcha.php
    @@ -22,73 +22,81 @@
      * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
      */
     
    -class Captcha {
    +class Captcha
    +{
     
    -    function Captcha($meta = array(), $width = 250, $height = 80) {
    -        $this->meta   =& $meta;
    -        $this->width  = $width;
    +    function Captcha($meta = array(), $width = 250, $height = 80)
    +    {
    +        $this->meta =& $meta;
    +        $this->width = $width;
             $this->height = $height;
             $this->length = 8;
             $this->failed_msg = _("Typed in verification word mismatch ... are you a bot?");
             $this->request =& $GLOBALS['request'];
         }
     
    -    function captchaword() {
    -        if ( ! $this->request->getSessionVar('captchaword')) {
    +    function captchaword()
    +    {
    +        if (!$this->request->getSessionVar('captchaword')) {
                 $this->request->setSessionVar('captchaword', $this->get_word());
             }
             return $this->request->getSessionVar('captchaword');
         }
     
    -    function Failed () {
    +    function Failed()
    +    {
             if ($this->request->getSessionVar('captcha_ok') == true)
                 return false;
     
    -        if ( ! array_key_exists ( 'captcha_input', $this->meta )
    -             or ($this->request->getSessionVar('captchaword')
    -                 and ($this->request->getSessionVar('captchaword') != $this->meta['captcha_input'])))
    +        if (!array_key_exists('captcha_input', $this->meta)
    +            or ($this->request->getSessionVar('captchaword')
    +                and ($this->request->getSessionVar('captchaword') != $this->meta['captcha_input']))
    +        )
                 return true;
     
             $this->request->setSessionVar('captcha_ok', true);
             return false;
         }
     
    -    function getFormElements() {
    +    function getFormElements()
    +    {
             $el = array();
    -        if (! $this->request->getSessionVar('captcha_ok')) {
    +        if (!$this->request->getSessionVar('captcha_ok')) {
                 $el['CAPTCHA_INPUT']
    -                = HTML::input(array('type'  => 'text',
    -                                    'class' => 'wikitext',
    -                                    'id'    => 'edit-captcha_input',
    -                                    'name'  => 'edit[captcha_input]',
    -                                    'size'  => $this->length + 2,
    -                                    'maxlength' => 256));
    -            $url = WikiURL("", array("action"=>"captcha","id"=>time()), false);
    +                = HTML::input(array('type' => 'text',
    +                'class' => 'wikitext',
    +                'id' => 'edit-captcha_input',
    +                'name' => 'edit[captcha_input]',
    +                'size' => $this->length + 2,
    +                'maxlength' => 256));
    +            $url = WikiURL("", array("action" => "captcha", "id" => time()), false);
                 $el['CAPTCHA_IMAGE'] = HTML::img(array('src' => $url, 'alt' => 'captcha'));
                 $el['CAPTCHA_LABEL'] = HTML::label(array('for' => 'edit-captcha_input'),
    -                                               _("Type word above:"));
    +                _("Type word above:"));
             }
             return $el;
         }
     
    -    function get_word () {
    +    function get_word()
    +    {
             if (USE_CAPTCHA_RANDOM_WORD)
                 return get_dictionary_word();
             else
                 return rand_ascii_readable($this->length); // lib/stdlib.php
         }
     
    -    function get_dictionary_word () {
    +    function get_dictionary_word()
    +    {
             // Load In the Word List
             $fp = fopen(findfile("lib/captcha/dictionary"), "r");
    -        while ( !feof($fp) )
    +        while (!feof($fp))
                 $text[] = trim(fgets($fp, 1024));
             fclose($fp);
     
             // Pick a Word
             $word = "";
             better_srand();
    -        while ( strlen(trim($word)) == 0 ) {
    +        while (strlen(trim($word)) == 0) {
                 if (function_exists('mt_rand'))
                     $x = mt_rand(0, count($text));
                 else
    @@ -98,80 +106,82 @@ class Captcha {
         }
     
         // Draw the Spiral
    -    function spiral( &$im, $origin_x = 100, $origin_y = 100, $r = 0, $g = 0, $b = 0 ) {
    +    function spiral(&$im, $origin_x = 100, $origin_y = 100, $r = 0, $g = 0, $b = 0)
    +    {
             $theta = 1;
             $thetac = 6;
             $radius = 15;
             $circles = 10;
             $points = 35;
    -        $lcolor = imagecolorallocate( $im, $r, $g, $b );
    -        for( $i = 0; $i < ( $circles * $points ) - 1; $i++ ) {
    +        $lcolor = imagecolorallocate($im, $r, $g, $b);
    +        for ($i = 0; $i < ($circles * $points) - 1; $i++) {
                 $theta = $theta + $thetac;
    -            $rad = $radius * ( $i / $points );
    -            $x = ( $rad * cos( $theta ) ) + $origin_x;
    -            $y = ( $rad * sin( $theta ) ) + $origin_y;
    +            $rad = $radius * ($i / $points);
    +            $x = ($rad * cos($theta)) + $origin_x;
    +            $y = ($rad * sin($theta)) + $origin_y;
                 $theta = $theta + $thetac;
    -            $rad1 = $radius * ( ( $i + 1 ) / $points );
    -            $x1 = ( $rad1 * cos( $theta ) ) + $origin_x;
    -            $y1 = ( $rad1 * sin( $theta ) ) + $origin_y;
    -            imageline( $im, $x, $y, $x1, $y1, $lcolor );
    +            $rad1 = $radius * (($i + 1) / $points);
    +            $x1 = ($rad1 * cos($theta)) + $origin_x;
    +            $y1 = ($rad1 * sin($theta)) + $origin_y;
    +            imageline($im, $x, $y, $x1, $y1, $lcolor);
                 $theta = $theta - $thetac;
             }
         }
     
    -    function image ( $word ) {
    -        $width  =& $this->width;
    +    function image($word)
    +    {
    +        $width =& $this->width;
             $height =& $this->height;
     
             // Create the Image
    -        $jpg = ImageCreate($width,$height);
    -        $bg  = ImageColorAllocate($jpg,255,255,255);
    -        $tx  = ImageColorAllocate($jpg,185,140,140);
    -        ImageFilledRectangle($jpg,0,0,$width,$height,$bg);
    +        $jpg = ImageCreate($width, $height);
    +        $bg = ImageColorAllocate($jpg, 255, 255, 255);
    +        $tx = ImageColorAllocate($jpg, 185, 140, 140);
    +        ImageFilledRectangle($jpg, 0, 0, $width, $height, $bg);
     
             $x = rand(0, $width);
             $y = rand(0, $height);
    -        $this->spiral($jpg, $x, $y, $width-25, 190, 190);
    +        $this->spiral($jpg, $x, $y, $width - 25, 190, 190);
     
             $x = rand(10, 30);
    -        $y = rand(50, $height-20); //50-60
    +        $y = rand(50, $height - 20); //50-60
     
             // randomize the chars
    -        for ($i=0; $i < strlen($word); $i++) {
    +        for ($i = 0; $i < strlen($word); $i++) {
                 $angle += rand(-5, 5);
    -            if ( $angle > 25 )  $angle = 15;
    -            elseif ( $angle < -25 ) $angle = -15;
    -            $size  = rand(14, 20);
    +            if ($angle > 25) $angle = 15;
    +            elseif ($angle < -25) $angle = -15;
    +            $size = rand(14, 20);
                 $y += rand(-10, 10);
    -            if ( $y < 10 )  $y = 11;
    -            elseif ( $y > $height-10 ) $y = $height-11;
    -            $x += rand($size, $size*2);
    +            if ($y < 10) $y = 11;
    +            elseif ($y > $height - 10) $y = $height - 11;
    +            $x += rand($size, $size * 2);
                 imagettftext($jpg, $size, $angle, $x, $y, $tx,
    -                         realpath(findfile("lib/captcha/Vera.ttf")),
    -                         $word[$i]);
    +                realpath(findfile("lib/captcha/Vera.ttf")),
    +                $word[$i]);
             }
     
    -        $x = rand(0, $width+30);
    -        $y = rand(0, $height+35); // 115
    -        $this->spiral($jpg, $x, $y, 255,190,190);
    -
    -        imageline($jpg, 0,0,$width-1,0,$tx);
    -        imageline($jpg, 0,0,0,$height-1,$tx);
    -        imageline($jpg, 0,$height-1,$width-1,$height-1,$tx);
    -        imageline($jpg, $width-1,0,$width-1,$height-1,$tx);
    -
    -    if (function_exists("ImageJpeg")) {
    -        header("Content-type: image/jpeg");
    -        ImageJpeg($jpg);
    -    } elseif (function_exists("ImagePNG")) {
    -        header("Content-type: image/png");
    -        ImagePNG($jpg);
    -    } elseif (function_exists("ImageGIF")) {
    -        header("Content-type: image/gif");
    -        ImageGIF($jpg);
    -    } else {
    -        trigger_error("missing GD bitmap support", E_USER_WARNING);
    -    }
    +        $x = rand(0, $width + 30);
    +        $y = rand(0, $height + 35); // 115
    +        $this->spiral($jpg, $x, $y, 255, 190, 190);
    +
    +        imageline($jpg, 0, 0, $width - 1, 0, $tx);
    +        imageline($jpg, 0, 0, 0, $height - 1, $tx);
    +        imageline($jpg, 0, $height - 1, $width - 1, $height - 1, $tx);
    +        imageline($jpg, $width - 1, 0, $width - 1, $height - 1, $tx);
    +
    +        if (function_exists("ImageJpeg")) {
    +            header("Content-type: image/jpeg");
    +            ImageJpeg($jpg);
    +        } elseif (function_exists("ImagePNG")) {
    +            header("Content-type: image/png");
    +            ImagePNG($jpg);
    +        } elseif (function_exists("ImageGIF")) {
    +            header("Content-type: image/gif");
    +            ImageGIF($jpg);
    +        } else {
    +            trigger_error("missing GD bitmap support", E_USER_WARNING);
    +        }
         }
     
     }
    diff --git a/lib/DbSession.php b/lib/DbSession.php
    index fdd01bc6c..e82d41499 100644
    --- a/lib/DbSession.php
    +++ b/lib/DbSession.php
    @@ -24,13 +24,14 @@ class DbSession
          * @param string $table
          * Name of SQL table containing session data.
          */
    -    function DbSession(&$dbh, $table = 'session') {
    +    function DbSession(&$dbh, $table = 'session')
    +    {
             // Check for existing DbSession handler
             $db_type = $dbh->getParam('dbtype');
             if (isa($dbh, 'WikiDB')) {
    -            @include_once("lib/DbSession/".$db_type.".php");
    +            @include_once("lib/DbSession/" . $db_type . ".php");
     
    -            $class = "DbSession_".$db_type;
    +            $class = "DbSession_" . $db_type;
                 if (class_exists($class)) {
                     // dba has no ->_dbh, so this is used for the session link
                     $this->_backend = new $class($dbh->_backend->_dbh, $table);
    @@ -38,19 +39,26 @@ class DbSession
                 }
             }
             //Fixme: E_USER_WARNING ignored!
    -        trigger_error(sprintf(_("Your WikiDB DB backend '%s' cannot be used for DbSession.")." ".
    -                              _("Set USE_DB_SESSION to false."),
    -                             $db_type), E_USER_WARNING);
    +        trigger_error(sprintf(_("Your WikiDB DB backend '%s' cannot be used for DbSession.") . " " .
    +                _("Set USE_DB_SESSION to false."),
    +            $db_type), E_USER_WARNING);
             return false;
         }
     
    -    function currentSessions() {
    +    function currentSessions()
    +    {
             return $this->_backend->currentSessions();
         }
    -    function query($sql) {
    +
    +    function query($sql)
    +    {
             return $this->_backend->query($sql);
         }
    -    function quote($string) { return $string; }
    +
    +    function quote($string)
    +    {
    +        return $string;
    +    }
     }
     
     // Local Variables:
    diff --git a/lib/DbSession/ADODB.php b/lib/DbSession/ADODB.php
    index 46aaf7aac..708ecd1fd 100644
    --- a/lib/DbSession/ADODB.php
    +++ b/lib/DbSession/ADODB.php
    @@ -25,49 +25,54 @@
      * @author: Reini Urban
      */
     class DbSession_ADODB
    -extends DbSession
    +    extends DbSession
     {
         var $_backend_type = "ADODB";
     
    -    function DbSession_ADODB ($dbh, $table) {
    +    function DbSession_ADODB($dbh, $table)
    +    {
     
             $this->_dbh = $dbh;
             $this->_table = $table;
     
    -        ini_set('session.save_handler','user');
    +        ini_set('session.save_handler', 'user');
             session_module_name('user'); // new style
             session_set_save_handler(array(&$this, 'open'),
    -                                 array(&$this, 'close'),
    -                                 array(&$this, 'read'),
    -                                 array(&$this, 'write'),
    -                                 array(&$this, 'destroy'),
    -                                 array(&$this, 'gc'));
    +            array(&$this, 'close'),
    +            array(&$this, 'read'),
    +            array(&$this, 'write'),
    +            array(&$this, 'destroy'),
    +            array(&$this, 'gc'));
             return $this;
         }
     
    -    function & _connect() {
    +    function & _connect()
    +    {
             global $request;
             static $parsed = false;
             $dbh = &$this->_dbh;
             if (!$dbh or !is_resource($dbh->_connectionID)) {
                 if (!$parsed) $parsed = parseDSN($request->_dbi->getParam('dsn'));
                 $this->_dbh =& ADONewConnection($parsed['phptype']); // Probably only MySql works just now
    -            $this->_dbh->Connect($parsed['hostspec'],$parsed['username'],
    -                                 $parsed['password'], $parsed['database']);
    +            $this->_dbh->Connect($parsed['hostspec'], $parsed['username'],
    +                $parsed['password'], $parsed['database']);
                 $dbh = &$this->_dbh;
             }
             return $dbh;
         }
     
    -    function query($sql) {
    +    function query($sql)
    +    {
             return $this->_dbh->Execute($sql);
         }
     
    -    function quote($string) {
    +    function quote($string)
    +    {
             return $this->_dbh->qstr($string);
         }
     
    -    function _disconnect() {
    +    function _disconnect()
    +    {
             if (0 and $this->_dbh)
                 $this->_dbh->close();
         }
    @@ -82,7 +87,8 @@ extends DbSession
          * is good.
          * @access private
          */
    -    function open ($save_path, $session_name) {
    +    function open($save_path, $session_name)
    +    {
             //$this->log("_open($save_path, $session_name)");
             return true;
         }
    @@ -96,7 +102,8 @@ extends DbSession
          * is good.
          * @access private
          */
    -    function close() {
    +    function close()
    +    {
             //$this->log("_close()");
             return true;
         }
    @@ -108,7 +115,8 @@ extends DbSession
          * @return string
          * @access private
          */
    -    function read ($id) {
    +    function read($id)
    +    {
             //$this->log("_read($id)");
             $dbh = $this->_connect();
             $table = $this->_table;
    @@ -121,10 +129,10 @@ extends DbSession
             if (!empty($res) and preg_match('|^[a-zA-Z0-9/+=]+$|', $res))
                 $res = base64_decode($res);
             if (strlen($res) > 4000) {
    -            trigger_error("Overlarge session data! ".strlen($res).
    -                        " gt. 4000", E_USER_WARNING);
    -            $res = preg_replace('/s:6:"_cache";O:12:"WikiDB_cache".+}$/',"",$res);
    -            $res = preg_replace('/s:12:"_cached_html";s:.+",s:4:"hits"/','s:4:"hits"',$res);
    +            trigger_error("Overlarge session data! " . strlen($res) .
    +                " gt. 4000", E_USER_WARNING);
    +            $res = preg_replace('/s:6:"_cache";O:12:"WikiDB_cache".+}$/', "", $res);
    +            $res = preg_replace('/s:12:"_cached_html";s:.+",s:4:"hits"/', 's:4:"hits"', $res);
                 if (strlen($res) > 4000) $res = '';
             }
             return $res;
    @@ -146,7 +154,8 @@ extends DbSession
          * otherwise.
          * @access private
          */
    -    function write ($id, $sess_data) {
    +    function write($id, $sess_data)
    +    {
             if (defined("WIKI_XMLRPC") or defined("WIKI_SOAP")) return;
     
             $dbh = $this->_connect();
    @@ -165,22 +174,22 @@ extends DbSession
              */
             if (USE_SAFE_DBSESSION) {
                 $dbh->Execute("DELETE FROM $table"
    -                          . " WHERE sess_id=$qid");
    +                . " WHERE sess_id=$qid");
                 $rs = $dbh->Execute("INSERT INTO $table"
    -                                . " (sess_id, sess_data, sess_date, sess_ip)"
    -                                . " VALUES ($qid, $qdata, $time, $qip)");
    +                . " (sess_id, sess_data, sess_date, sess_ip)"
    +                . " VALUES ($qid, $qdata, $time, $qip)");
             } else {
                 $rs = $dbh->Execute("UPDATE $table"
    -                                . " SET sess_data=$qdata, sess_date=$time, sess_ip=$qip"
    -                                . " WHERE sess_id=$qid");
    +                . " SET sess_data=$qdata, sess_date=$time, sess_ip=$qip"
    +                . " WHERE sess_id=$qid");
                 $result = $dbh->Affected_Rows();
    -            if ( $result === false or $result < 1 ) { // false or int > 0
    +            if ($result === false or $result < 1) { // false or int > 0
                     $rs = $dbh->Execute("INSERT INTO $table"
    -                                    . " (sess_id, sess_data, sess_date, sess_ip)"
    -                                    . " VALUES ($qid, $qdata, $time, $qip)");
    +                    . " (sess_id, sess_data, sess_date, sess_ip)"
    +                    . " VALUES ($qid, $qdata, $time, $qip)");
                 }
             }
    -        $result = ! $rs->EOF;
    +        $result = !$rs->EOF;
             if ($result) $rs->free();
             $this->_disconnect();
             return $result;
    @@ -195,7 +204,8 @@ extends DbSession
          * @return boolean true
          * @access private
          */
    -    function destroy ($id) {
    +    function destroy($id)
    +    {
             $dbh = $this->_connect();
             $table = $this->_table;
             $qid = $dbh->qstr($id);
    @@ -213,7 +223,8 @@ extends DbSession
          * @return boolean true
          * @access private
          */
    -    function gc ($maxlifetime) {
    +    function gc($maxlifetime)
    +    {
             $dbh = $this->_connect();
             $table = $this->_table;
             $threshold = time() - $maxlifetime;
    @@ -226,7 +237,8 @@ extends DbSession
     
         // WhoIsOnline support.
         // TODO: ip-accesstime dynamic blocking API
    -    function currentSessions() {
    +    function currentSessions()
    +    {
             $sessions = array();
             $dbh = $this->_connect();
             $table = $this->_table;
    @@ -239,17 +251,17 @@ extends DbSession
                 $row = $rs->fetchRow();
                 $data = $row[0];
                 $date = $row[1];
    -            $ip   = $row[2];
    +            $ip = $row[2];
                 if (preg_match('|^[a-zA-Z0-9/+=]+$|', $data))
                     $data = base64_decode($data);
                 if ($date < 908437560 or $date > 1588437560)
                     $date = 0;
                 // session_data contains the  + "|" + 
                 // we need just the wiki_user object (might be array as well)
    -            $user = strstr($data,"wiki_user|");
    -            $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
    -                                'date' => $date,
    -                                'ip' => $ip);
    +            $user = strstr($data, "wiki_user|");
    +            $sessions[] = array('wiki_user' => substr($user, 10), // from "O:" onwards
    +                'date' => $date,
    +                'ip' => $ip);
                 $rs->MoveNext();
             }
             $rs->free();
    diff --git a/lib/DbSession/PDO.php b/lib/DbSession/PDO.php
    index e4dc01873..2c167990e 100644
    --- a/lib/DbSession/PDO.php
    +++ b/lib/DbSession/PDO.php
    @@ -6,27 +6,29 @@
      * @author: Reini Urban
      */
     class DbSession_PDO
    -extends DbSession
    +    extends DbSession
     {
         var $_backend_type = "PDO";
     
    -    function DbSession_PDO ($dbh, $table) {
    +    function DbSession_PDO($dbh, $table)
    +    {
     
             $this->_dbh = $dbh;
             $this->_table = $table;
     
    -        ini_set('session.save_handler','user');
    +        ini_set('session.save_handler', 'user');
             session_module_name('user'); // new style
             session_set_save_handler(array(&$this, 'open'),
    -                                 array(&$this, 'close'),
    -                                 array(&$this, 'read'),
    -                                 array(&$this, 'write'),
    -                                 array(&$this, 'destroy'),
    -                                 array(&$this, 'gc'));
    +            array(&$this, 'close'),
    +            array(&$this, 'read'),
    +            array(&$this, 'write'),
    +            array(&$this, 'destroy'),
    +            array(&$this, 'gc'));
             return $this;
         }
     
    -    function & _connect() {
    +    function & _connect()
    +    {
             $dbh =& $this->_dbh;
             if (!$dbh or !is_object($dbh)) {
                 global $DBParams;
    @@ -37,15 +39,18 @@ extends DbSession
             return $dbh->_dbh;
         }
     
    -    function query($sql) {
    +    function query($sql)
    +    {
             return $this->_backend->query($sql);
         }
     
    -    function quote($string) {
    +    function quote($string)
    +    {
             return $this->_backend->quote($sql);
         }
     
    -    function _disconnect() {
    +    function _disconnect()
    +    {
             if (0 and $this->_dbh)
                 unset($this->_dbh);
         }
    @@ -60,7 +65,8 @@ extends DbSession
          * is good.
          * @access private
          */
    -    function open ($save_path, $session_name) {
    +    function open($save_path, $session_name)
    +    {
             //$this->log("_open($save_path, $session_name)");
             return true;
         }
    @@ -74,7 +80,8 @@ extends DbSession
          * is good.
          * @access private
          */
    -    function close() {
    +    function close()
    +    {
             //$this->log("_close()");
             return true;
         }
    @@ -86,7 +93,8 @@ extends DbSession
          * @return string
          * @access private
          */
    -    function read ($id) {
    +    function read($id)
    +    {
             //$this->log("_read($id)");
             $dbh = $this->_connect();
             $table = $this->_table;
    @@ -98,10 +106,10 @@ extends DbSession
             if (!empty($res) and isa($dbh, 'ADODB_postgres64'))
                 $res = base64_decode($res);
             if (strlen($res) > 4000) {
    -            trigger_error("Overlarge session data! ".strlen($res).
    -                        " gt. 4000", E_USER_WARNING);
    -            $res = preg_replace('/s:6:"_cache";O:12:"WikiDB_cache".+}$/',"",$res);
    -            $res = preg_replace('/s:12:"_cached_html";s:.+",s:4:"hits"/','s:4:"hits"',$res);
    +            trigger_error("Overlarge session data! " . strlen($res) .
    +                " gt. 4000", E_USER_WARNING);
    +            $res = preg_replace('/s:6:"_cache";O:12:"WikiDB_cache".+}$/', "", $res);
    +            $res = preg_replace('/s:12:"_cached_html";s:.+",s:4:"hits"/', 's:4:"hits"', $res);
                 if (strlen($res) > 4000) $res = '';
             }
             return $res;
    @@ -123,7 +131,8 @@ extends DbSession
          * otherwise.
          * @access private
          */
    -    function write ($id, $sess_data) {
    +    function write($id, $sess_data)
    +    {
             if (defined("WIKI_XMLRPC") or defined("WIKI_SOAP")) return;
     
             $dbh = $this->_connect();
    @@ -140,10 +149,10 @@ extends DbSession
             if (USE_SAFE_DBSESSION) {
                 $this->_backend->beginTransaction();
                 $rs = $this->query("DELETE FROM $table"
    -                               . " WHERE sess_id=$qid");
    +                . " WHERE sess_id=$qid");
                 $sth = $dbh->prepare("INSERT INTO $table"
    -                                . " (sess_id, sess_data, sess_date, sess_ip)"
    -                                 . " VALUES (?, ?, ?, ?)");
    +                . " (sess_id, sess_data, sess_date, sess_ip)"
    +                . " VALUES (?, ?, ?, ?)");
                 $sth->bindParam(1, $id, PDO_PARAM_STR, 32);
                 $sth->bindParam(2, $sess_data, PDO_PARAM_LOB);
                 $sth->bindParam(3, $time, PDO_PARAM_INT);
    @@ -155,17 +164,17 @@ extends DbSession
                 }
             } else {
                 $sth = $dbh->prepare("UPDATE $table"
    -                                . " SET sess_data=?, sess_date=?, sess_ip=?"
    -                                . " WHERE sess_id=?");
    +                . " SET sess_data=?, sess_date=?, sess_ip=?"
    +                . " WHERE sess_id=?");
                 $sth->bindParam(1, $sess_data, PDO_PARAM_LOB);
                 $sth->bindParam(2, $time, PDO_PARAM_INT);
                 $sth->bindParam(3, $GLOBALS['request']->get('REMOTE_ADDR'), PDO_PARAM_STR, 15);
                 $sth->bindParam(4, $id, PDO_PARAM_STR, 32);
                 $result = $sth->execute(); // implicit affected rows
    -            if ( $result === false or $result < 1 ) { // false or int > 0
    +            if ($result === false or $result < 1) { // false or int > 0
                     $sth = $dbh->prepare("INSERT INTO $table"
    -                                     . " (sess_id, sess_data, sess_date, sess_ip)"
    -                                     . " VALUES (?, ?, ?, ?)");
    +                    . " (sess_id, sess_data, sess_date, sess_ip)"
    +                    . " VALUES (?, ?, ?, ?)");
                     $sth->bindParam(1, $id, PDO_PARAM_STR, 32);
                     $sth->bindParam(2, $sess_data, PDO_PARAM_LOB);
                     $sth->bindParam(3, $time, PDO_PARAM_INT);
    @@ -186,7 +195,8 @@ extends DbSession
          * @return boolean true
          * @access private
          */
    -    function destroy ($id) {
    +    function destroy($id)
    +    {
             $table = $this->_table;
             $dbh = $this->_connect();
             $sth = $dbh->prepare("DELETE FROM $table WHERE sess_id=?");
    @@ -203,7 +213,8 @@ extends DbSession
          * @return boolean true
          * @access private
          */
    -    function gc ($maxlifetime) {
    +    function gc($maxlifetime)
    +    {
             $table = $this->_table;
             $threshold = time() - $maxlifetime;
             $dbh = $this->_connect();
    @@ -216,7 +227,8 @@ extends DbSession
     
         // WhoIsOnline support.
         // TODO: ip-accesstime dynamic blocking API
    -    function currentSessions() {
    +    function currentSessions()
    +    {
             $sessions = array();
             $table = $this->_table;
             $dbh = $this->_connect();
    @@ -227,7 +239,7 @@ extends DbSession
             while ($row = $sth->fetch(PDO_FETCH_NUM)) {
                 $data = $row[0];
                 $date = $row[1];
    -            $ip   = $row[2];
    +            $ip = $row[2];
                 if (preg_match('|^[a-zA-Z0-9/+=]+$|', $data))
                     $data = base64_decode($data);
                 if ($date < 908437560 or $date > 1588437560)
    @@ -235,9 +247,9 @@ extends DbSession
                 // session_data contains the  + "|" + 
                 // we need just the wiki_user object (might be array as well)
                 $user = strstr($data, "wiki_user|");
    -            $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
    -                                'date' => $date,
    -                                'ip' => $ip);
    +            $sessions[] = array('wiki_user' => substr($user, 10), // from "O:" onwards
    +                'date' => $date,
    +                'ip' => $ip);
             }
             $this->_disconnect();
             return $sessions;
    diff --git a/lib/DbSession/SQL.php b/lib/DbSession/SQL.php
    index 9e39879f0..ab460b95d 100644
    --- a/lib/DbSession/SQL.php
    +++ b/lib/DbSession/SQL.php
    @@ -11,27 +11,29 @@
      */
     
     class DbSession_SQL
    -extends DbSession
    +    extends DbSession
     {
         var $_backend_type = "SQL";
     
    -    function DbSession_SQL (&$dbh, $table) {
    +    function DbSession_SQL(&$dbh, $table)
    +    {
     
             $this->_dbh = $dbh;
             $this->_table = $table;
     
    -        ini_set('session.save_handler','user');
    +        ini_set('session.save_handler', 'user');
             session_module_name('user'); // new style
             session_set_save_handler(array(&$this, 'open'),
    -                                 array(&$this, 'close'),
    -                                 array(&$this, 'read'),
    -                                 array(&$this, 'write'),
    -                                 array(&$this, 'destroy'),
    -                                 array(&$this, 'gc'));
    +            array(&$this, 'close'),
    +            array(&$this, 'read'),
    +            array(&$this, 'write'),
    +            array(&$this, 'destroy'),
    +            array(&$this, 'gc'));
             return $this;
         }
     
    -    function & _connect() {
    +    function & _connect()
    +    {
             $dbh = &$this->_dbh;
             $this->_connected = is_resource($dbh->connection);
             if (!$this->_connected) {
    @@ -43,15 +45,19 @@ extends DbSession
             return $dbh;
         }
     
    -    function query($sql) {
    +    function query($sql)
    +    {
             return $this->_dbh->query($sql);
         }
    +
         // adds surrounding quotes
    -    function quote($string) {
    +    function quote($string)
    +    {
             return $this->_dbh->quote($string);
         }
     
    -    function _disconnect() {
    +    function _disconnect()
    +    {
             if (0 and $this->_connected)
                 $this->_dbh->disconnect();
         }
    @@ -66,7 +72,8 @@ extends DbSession
          * is good.
          * @access private
          */
    -    function open ($save_path, $session_name) {
    +    function open($save_path, $session_name)
    +    {
             //$this->log("_open($save_path, $session_name)");
             return true;
         }
    @@ -80,7 +87,8 @@ extends DbSession
          * is good.
          * @access private
          */
    -    function close() {
    +    function close()
    +    {
             //$this->log("_close()");
             return true;
         }
    @@ -92,7 +100,8 @@ extends DbSession
          * @return string
          * @access private
          */
    -    function read ($id) {
    +    function read($id)
    +    {
             //$this->log("_read($id)");
             $dbh = $this->_connect();
             $table = $this->_table;
    @@ -108,8 +117,8 @@ extends DbSession
                 $res = base64_decode($res);
             if (strlen($res) > 4000) {
                 // trigger_error("Overlarge session data! ".strlen($res). " gt. 4000", E_USER_WARNING);
    -            $res = preg_replace('/s:6:"_cache";O:12:"WikiDB_cache".+}$/',"",$res);
    -            $res = preg_replace('/s:12:"_cached_html";s:.+",s:4:"hits"/','s:4:"hits"',$res);
    +            $res = preg_replace('/s:6:"_cache";O:12:"WikiDB_cache".+}$/', "", $res);
    +            $res = preg_replace('/s:12:"_cached_html";s:.+",s:4:"hits"/', 's:4:"hits"', $res);
                 if (strlen($res) > 4000) $res = '';
             }
             return $res;
    @@ -131,7 +140,8 @@ extends DbSession
          * otherwise.
          * @access private
          */
    -    function write ($id, $sess_data) {
    +    function write($id, $sess_data)
    +    {
             if (defined("WIKI_XMLRPC") or defined("WIKI_SOAP")) return;
     
             $dbh = $this->_connect();
    @@ -140,9 +150,9 @@ extends DbSession
             $qid = $dbh->quote($id);
             $qip = $dbh->quote($GLOBALS['request']->get('REMOTE_ADDR'));
             $time = $dbh->quote(time());
    -    if (DEBUG and $sess_data == 'wiki_user|N;') {
    -        trigger_error("delete empty session $qid", E_USER_WARNING);
    -    }
    +        if (DEBUG and $sess_data == 'wiki_user|N;') {
    +            trigger_error("delete empty session $qid", E_USER_WARNING);
    +        }
             // postgres can't handle binary data in a TEXT field.
             if (isa($dbh, 'DB_pgsql'))
                 $sess_data = base64_encode($sess_data);
    @@ -153,23 +163,23 @@ extends DbSession
              */
             if (USE_SAFE_DBSESSION) {
                 $dbh->query("DELETE FROM $table"
    -                        . " WHERE sess_id=$qid");
    +                . " WHERE sess_id=$qid");
                 $res = $dbh->query("INSERT INTO $table"
    -                               . " (sess_id, sess_data, sess_date, sess_ip)"
    -                               . " VALUES ($qid, $qdata, $time, $qip)");
    +                . " (sess_id, sess_data, sess_date, sess_ip)"
    +                . " VALUES ($qid, $qdata, $time, $qip)");
             } else {
                 $res = $dbh->query("UPDATE $table"
    -                               . " SET sess_data=$qdata, sess_date=$time, sess_ip=$qip"
    -                               . " WHERE sess_id=$qid");
    +                . " SET sess_data=$qdata, sess_date=$time, sess_ip=$qip"
    +                . " WHERE sess_id=$qid");
                 $result = $dbh->AffectedRows();
    -            if ( $result === false or $result < 1 ) { // 0 cannot happen: time, -1 (failure) on mysql
    +            if ($result === false or $result < 1) { // 0 cannot happen: time, -1 (failure) on mysql
                     $res = $dbh->query("INSERT INTO $table"
    -                                   . " (sess_id, sess_data, sess_date, sess_ip)"
    -                                   . " VALUES ($qid, $qdata, $time, $qip)");
    +                    . " (sess_id, sess_data, sess_date, sess_ip)"
    +                    . " VALUES ($qid, $qdata, $time, $qip)");
                 }
             }
             $this->_disconnect();
    -        return ! DB::isError($res);
    +        return !DB::isError($res);
         }
     
         /**
    @@ -181,7 +191,8 @@ extends DbSession
          * @return boolean true
          * @access private
          */
    -    function destroy ($id) {
    +    function destroy($id)
    +    {
             $dbh = $this->_connect();
             $table = $this->_table;
             $qid = $dbh->quote($id);
    @@ -199,7 +210,8 @@ extends DbSession
          * @return boolean true
          * @access private
          */
    -    function gc ($maxlifetime) {
    +    function gc($maxlifetime)
    +    {
             $dbh = $this->_connect();
             $table = $this->_table;
             $threshold = time() - $maxlifetime;
    @@ -212,7 +224,8 @@ extends DbSession
     
         // WhoIsOnline support
         // TODO: ip-accesstime dynamic blocking API
    -    function currentSessions() {
    +    function currentSessions()
    +    {
             $sessions = array();
             $dbh = $this->_connect();
             $table = $this->_table;
    @@ -222,17 +235,17 @@ extends DbSession
             while ($row = $res->fetchRow()) {
                 $data = $row['sess_data'];
                 $date = $row['sess_date'];
    -            $ip   = $row['sess_ip'];
    +            $ip = $row['sess_ip'];
                 if (preg_match('|^[a-zA-Z0-9/+=]+$|', $data))
                     $data = base64_decode($data);
                 if ($date < 908437560 or $date > 1588437560)
                     $date = 0;
                 // session_data contains the  + "|" + 
                 // we need just the wiki_user object (might be array as well)
    -            $user = strstr($data,"wiki_user|");
    -            $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
    -                                'date' => $date,
    -                                'ip'   => $ip);
    +            $user = strstr($data, "wiki_user|");
    +            $sessions[] = array('wiki_user' => substr($user, 10), // from "O:" onwards
    +                'date' => $date,
    +                'ip' => $ip);
             }
             $this->_disconnect();
             return $sessions;
    diff --git a/lib/DbSession/dba.php b/lib/DbSession/dba.php
    index 8479f3147..bb10f58b0 100644
    --- a/lib/DbSession/dba.php
    +++ b/lib/DbSession/dba.php
    @@ -11,27 +11,36 @@
      * @author: Reini Urban.
      */
     class DbSession_dba
    -extends DbSession
    +    extends DbSession
     {
         var $_backend_type = "dba";
     
    -    function DbSession_dba (&$dbh, $table) {
    +    function DbSession_dba(&$dbh, $table)
    +    {
             $this->_dbh = $dbh;
    -        ini_set('session.save_handler','user');
    +        ini_set('session.save_handler', 'user');
             session_module_name('user'); // new style
             session_set_save_handler(array(&$this, 'open'),
    -                                 array(&$this, 'close'),
    -                                 array(&$this, 'read'),
    -                                 array(&$this, 'write'),
    -                                 array(&$this, 'destroy'),
    -                                 array(&$this, 'gc'));
    +            array(&$this, 'close'),
    +            array(&$this, 'read'),
    +            array(&$this, 'write'),
    +            array(&$this, 'destroy'),
    +            array(&$this, 'gc'));
             return $this;
         }
     
    -    function quote($str) { return $str; }
    -    function query($sql) { return false; }
    +    function quote($str)
    +    {
    +        return $str;
    +    }
    +
    +    function query($sql)
    +    {
    +        return false;
    +    }
     
    -    function & _connect() {
    +    function & _connect()
    +    {
             global $DBParams;
             $dbh = &$this->_dbh;
             if (!$dbh) {
    @@ -47,29 +56,33 @@ extends DbSession
             return $dbh;
         }
     
    -    function _disconnect() {
    +    function _disconnect()
    +    {
             if (isset($this->_dbh)) {
                 $this->_dbh->close();
                 unset($this->_dbh);
             }
         }
     
    -    function open ($save_path, $session_name) {
    +    function open($save_path, $session_name)
    +    {
             $dbh = $this->_connect();
             $dbh->open();
         }
     
    -    function close() {
    +    function close()
    +    {
             $this->_disconnect();
         }
     
    -    function read ($id) {
    +    function read($id)
    +    {
             $dbh = $this->_connect();
             $result = $dbh->get($id);
             if (!$result) {
                 return false;
             }
    -        list(,,$packed) = explode(':', $result, 3);
    +        list(, , $packed) = explode(':', $result, 3);
             $this->_disconnect();
             if (strlen($packed) > 4000) {
                 trigger_error("Overlarge session data!", E_USER_WARNING);
    @@ -79,7 +92,8 @@ extends DbSession
             return $packed;
         }
     
    -    function write ($id, $sess_data) {
    +    function write($id, $sess_data)
    +    {
             if (defined("WIKI_XMLRPC") or defined("WIKI_SOAP")) return;
     
             $dbh = $this->_connect();
    @@ -89,24 +103,26 @@ extends DbSession
                 trigger_error("Overlarge session data!", E_USER_WARNING);
                 $sess_data = '';
             }
    -        $dbh->set($id, $time.':'.$ip.':'.$sess_data);
    +        $dbh->set($id, $time . ':' . $ip . ':' . $sess_data);
             $this->_disconnect();
             return true;
         }
     
    -    function destroy ($id) {
    +    function destroy($id)
    +    {
             $dbh = $this->_connect();
             $dbh->delete($id);
             $this->_disconnect();
             return true;
         }
     
    -    function gc ($maxlifetime) {
    +    function gc($maxlifetime)
    +    {
             $dbh = $this->_connect();
             $threshold = time() - $maxlifetime;
             for ($id = $dbh->firstkey(); $id !== false; $id = $dbh->nextkey()) {
                 $result = $dbh->get($id);
    -            list($date,,) = explode(':', $result, 3);
    +            list($date, ,) = explode(':', $result, 3);
                 if ($date < $threshold)
                     $dbh->delete($id);
             }
    @@ -116,21 +132,22 @@ extends DbSession
     
         // WhoIsOnline support.
         // TODO: ip-accesstime dynamic blocking API
    -    function currentSessions() {
    +    function currentSessions()
    +    {
             $sessions = array();
             $dbh = $this->_connect();
             for ($id = $dbh->firstkey(); $id !== false; $id = $dbh->nextkey()) {
                 $result = $dbh->get($id);
    -            list($date,$ip,$packed) = explode(':', $result, 3);
    +            list($date, $ip, $packed) = explode(':', $result, 3);
                 if (!$packed) continue;
                 // session_data contains the  + "|" + 
                 // we need just the wiki_user object (might be array as well)
                 if ($date < 908437560 or $date > 1588437560)
                     $date = 0;
                 $user = strstr($packed, "wiki_user|");
    -            $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
    -                                'date' => $date,
    -                                'ip' => $ip);
    +            $sessions[] = array('wiki_user' => substr($user, 10), // from "O:" onwards
    +                'date' => $date,
    +                'ip' => $ip);
             }
             $this->_disconnect();
             return $sessions;
    diff --git a/lib/DbaDatabase.php b/lib/DbaDatabase.php
    index dc8e6660a..fa2beede8 100644
    --- a/lib/DbaDatabase.php
    +++ b/lib/DbaDatabase.php
    @@ -9,7 +9,8 @@ else
     
     class DbaDatabase
     {
    -    function DbaDatabase($filename, $mode = false, $handler = 'gdbm') {
    +    function DbaDatabase($filename, $mode = false, $handler = 'gdbm')
    +    {
             $this->_file = $filename;
             $this->_handler = $handler;
             $this->_timeout = DBA_DATABASE_DEFAULT_TIMEOUT;
    @@ -17,21 +18,23 @@ class DbaDatabase
             if (!in_array($handler, dba_handlers()))
                 $this->_error(
                     sprintf(
    -                    _("The DBA handler %s is unsupported!")."\n".
    +                    _("The DBA handler %s is unsupported!") . "\n" .
                             _("Supported handlers are: %s"),
    -                         $handler, join(",",dba_handlers())));
    +                    $handler, join(",", dba_handlers())));
             $this->readonly = false;
             if ($mode)
                 $this->open($mode);
         }
     
    -    function set_timeout($timeout) {
    +    function set_timeout($timeout)
    +    {
             $this->_timeout = $timeout;
         }
     
    -    function open($mode = 'w') {
    +    function open($mode = 'w')
    +    {
             if ($this->_dbh)
    -            return;             // already open.
    +            return; // already open.
     
             $watchdog = $this->_timeout;
     
    @@ -51,9 +54,9 @@ class DbaDatabase
             if ((strlen($mode) == 1)) {
                 // PHP 4.3.x Windows lock bug workaround: http://bugs.php.net/bug.php?id=23975
                 if (isWindows()) {
    -                $mode .= "-";             // suppress locking, or
    -            } elseif ($this->_handler != 'gdbm') {     // gdbm does it internally
    -                $mode .= "d";             // else use internal locking
    +                $mode .= "-"; // suppress locking, or
    +            } elseif ($this->_handler != 'gdbm') { // gdbm does it internally
    +                $mode .= "d"; // else use internal locking
                 }
             }
             while (($dbh = dba_open($this->_file, $mode, $this->_handler)) < 1) {
    @@ -62,8 +65,8 @@ class DbaDatabase
                 // "c" failed, try "w" instead.
                 if ($mode == "w"
                     and file_exists($this->_file)
    -                and (isWindows() or !is_writable($this->_file)))
    -            {
    +                    and (isWindows() or !is_writable($this->_file))
    +            ) {
                     // try to continue with read-only
                     if (!defined("READONLY"))
                         define("READONLY", true);
    @@ -71,22 +74,22 @@ class DbaDatabase
                     $this->readonly = true;
                     $mode = "r";
                 }
    -            if (substr($mode,0,1) == "c" and file_exists($this->_file) and !READONLY)
    +            if (substr($mode, 0, 1) == "c" and file_exists($this->_file) and !READONLY)
                     $mode = "w";
                 // conflict: wait some random time to unlock (as with ethernet)
    -            $secs = 0.5 + ((double)rand(1,32767)/32767);
    +            $secs = 0.5 + ((double)rand(1, 32767) / 32767);
                 sleep($secs);
                 $watchdog -= $secs;
    -            if (strlen($mode) == 2) $mode = substr($mode,0,-1);
    +            if (strlen($mode) == 2) $mode = substr($mode, 0, -1);
             }
             $ErrorManager->popErrorHandler();
     
             if (!$dbh) {
    -            if ( ($error = $this->_dba_open_error) ) {
    +            if (($error = $this->_dba_open_error)) {
                     $error->errno = E_USER_ERROR;
                     $error->errstr .= "\nfile: " . $this->_file
    -                               .  "\nmode: " . $mode
    -                               .  "\nhandler: " . $this->_handler;
    +                    . "\nmode: " . $mode
    +                    . "\nhandler: " . $this->_handler;
                     // try to continue with read-only
                     if (!defined("READONLY"))
                         define("READONLY", true);
    @@ -94,10 +97,9 @@ class DbaDatabase
                     $this->readonly = true;
                     if (!file_exists($this->_file)) {
                         $ErrorManager->handleError($error);
    -                flush();
    +                    flush();
                     }
    -            }
    -            else {
    +            } else {
                     trigger_error("dba_open failed", E_USER_ERROR);
                 }
             }
    @@ -105,95 +107,108 @@ class DbaDatabase
             return !empty($dbh);
         }
     
    -    function close() {
    +    function close()
    +    {
             if ($this->_dbh)
                 dba_close($this->_dbh);
             $this->_dbh = false;
         }
     
    -    function exists($key) {
    +    function exists($key)
    +    {
             return dba_exists($key, $this->_dbh);
         }
     
    -    function fetch($key) {
    +    function fetch($key)
    +    {
             $val = dba_fetch($key, $this->_dbh);
             if ($val === false)
                 return $this->_error("fetch($key)");
             return $val;
         }
     
    -    function insert($key, $val) {
    +    function insert($key, $val)
    +    {
             if (!dba_insert($key, $val, $this->_dbh))
                 return $this->_error("insert($key)");
         }
     
    -    function replace($key, $val) {
    +    function replace($key, $val)
    +    {
             if (!dba_replace($key, $val, $this->_dbh))
                 return $this->_error("replace($key)");
         }
     
     
    -    function firstkey() {
    +    function firstkey()
    +    {
             return dba_firstkey($this->_dbh);
         }
     
    -    function nextkey() {
    +    function nextkey()
    +    {
             return dba_nextkey($this->_dbh);
         }
     
    -    function delete($key) {
    +    function delete($key)
    +    {
             if ($this->readonly) return;
             if (!dba_delete($key, $this->_dbh))
                 return $this->_error("delete($key)");
         }
     
    -    function get($key) {
    +    function get($key)
    +    {
             return dba_fetch($key, $this->_dbh);
         }
     
    -    function set($key, $val) {
    +    function set($key, $val)
    +    {
             $dbh = &$this->_dbh;
             if ($this->readonly) return;
             if (dba_exists($key, $dbh)) {
                 if ($val !== false) {
                     if (!dba_replace($key, $val, $dbh))
                         return $this->_error("store[replace]($key)");
    -            }
    -            else {
    +            } else {
                     if (!dba_delete($key, $dbh))
                         return $this->_error("store[delete]($key)");
                 }
    -        }
    -        else {
    +        } else {
                 if (!dba_insert($key, $val, $dbh))
                     return $this->_error("store[insert]($key)");
             }
         }
     
    -    function sync() {
    +    function sync()
    +    {
             if (!dba_sync($this->_dbh))
                 return $this->_error("sync()");
         }
     
    -    function optimize() {
    +    function optimize()
    +    {
             if (!dba_optimize($this->_dbh))
                 return $this->_error("optimize()");
             return 1;
         }
     
    -    function _error($mes) {
    +    function _error($mes)
    +    {
             //trigger_error("DbaDatabase: $mes", E_USER_WARNING);
             //return false;
             trigger_error("$this->_file: dba error: $mes", E_USER_ERROR);
         }
     
    -    function _dump() {
    +    function _dump()
    +    {
             $dbh = &$this->_dbh;
             for ($key = $this->firstkey($dbh); $key; $key = $this->nextkey($dbh))
                 printf("%10s: %s\n", $key, $this->fetch($key));
         }
     
    -    function _dba_open_error_handler($error) {
    +    function _dba_open_error_handler($error)
    +    {
             $this->_dba_open_error = $error;
             return true;
         }
    diff --git a/lib/DbaListSet.php b/lib/DbaListSet.php
    index d08687065..6086d4266 100644
    --- a/lib/DbaListSet.php
    +++ b/lib/DbaListSet.php
    @@ -2,11 +2,13 @@
     
     class DbaListSet
     {
    -    function DbaListSet(&$dbh) {
    +    function DbaListSet(&$dbh)
    +    {
             $this->_dbh = &$dbh;
         }
     
    -    function create_sequence($seq) {
    +    function create_sequence($seq)
    +    {
             $dbh = &$this->_dbh;
     
             if (!$dbh->exists('max_key')) {
    @@ -21,7 +23,8 @@ class DbaListSet
                 $dbh->insert($key, "$key:$key:");
         }
     
    -    function delete_sequence($seq) {
    +    function delete_sequence($seq)
    +    {
             $key = "s" . urlencode($seq);
             for ($i = $this->firstkey($seq); $i; $i = $next) {
                 $next = $this->next($i);
    @@ -30,66 +33,78 @@ class DbaListSet
             $this->_dbh->delete($key);
         }
     
    -    function firstkey($seq) {
    +    function firstkey($seq)
    +    {
             $key = "s" . urlencode($seq);
    -        list(, $next) =  explode(':', $this->_dbh->fetch($key), 3);
    +        list(, $next) = explode(':', $this->_dbh->fetch($key), 3);
             return intval($next);
         }
     
    -    function lastkey($seq) {
    +    function lastkey($seq)
    +    {
             $key = "s" . urlencode($seq);
    -        list($prev) =  explode(':', $this->_dbh->fetch($key), 3);
    +        list($prev) = explode(':', $this->_dbh->fetch($key), 3);
             return intval($prev);
         }
     
     
    -    function next($i) {
    -        list( , $next, ) = explode(':', $this->_dbh->fetch(intval($i)), 3);
    +    function next($i)
    +    {
    +        list(, $next,) = explode(':', $this->_dbh->fetch(intval($i)), 3);
             return intval($next);
         }
     
    -    function prev(&$i) {
    -        list( $prev , , ) = explode(':', $this->_dbh->fetch(intval($i)), 3);
    +    function prev(&$i)
    +    {
    +        list($prev, ,) = explode(':', $this->_dbh->fetch(intval($i)), 3);
             return intval($prev);
         }
     
    -    function exists($i) {
    +    function exists($i)
    +    {
             $i = intval($i);
             return $i && $this->_dbh->exists($i);
         }
     
    -    function fetch($i) {
    +    function fetch($i)
    +    {
             list(, , $data) = explode(':', $this->_dbh->fetch(intval($i)), 3);
             return $data;
         }
     
    -    function replace($i, $data) {
    +    function replace($i, $data)
    +    {
             $dbh = &$this->_dbh;
             list($prev, $next,) = explode(':', $dbh->fetch(intval($i)), 3);
             $dbh->replace($i, "$prev:$next:$data");
         }
     
    -    function insert_before($i, $data) {
    +    function insert_before($i, $data)
    +    {
             assert(intval($i));
             return $this->_insert_before_nc($i, $data);
         }
     
    -    function insert_after($i, $data) {
    +    function insert_after($i, $data)
    +    {
             assert(intval($i));
             return $this->_insert_after_nc($i, $data);
         }
     
    -    function append($seq, $data) {
    +    function append($seq, $data)
    +    {
             $key = "s" . urlencode($seq);
             $this->_insert_before_nc($key, $data);
         }
     
    -    function prepend($seq, $data) {
    +    function prepend($seq, $data)
    +    {
             $key = "s" . urlencode($seq);
             $this->_insert_after_nc($key, $data);
         }
     
    -    function _insert_before_nc($i, &$data) {
    +    function _insert_before_nc($i, &$data)
    +    {
             $newkey = $this->_new_key();
             $old_prev = $this->_setprev($i, $newkey);
             $this->_setnext($old_prev, $newkey);
    @@ -97,7 +112,8 @@ class DbaListSet
             return $newkey;
         }
     
    -    function _insert_after_nc($i, &$data) {
    +    function _insert_after_nc($i, &$data)
    +    {
             $newkey = $this->_new_key();
             $old_next = $this->_setnext($i, $newkey);
             $this->_setprev($old_next, $newkey);
    @@ -105,7 +121,8 @@ class DbaListSet
             return $newkey;
         }
     
    -    function delete($i) {
    +    function delete($i)
    +    {
             $dbh = &$this->_dbh;
             list($prev, $next) = explode(':', $dbh->fetch(intval($i)), 3);
             $this->_setnext($prev, $next);
    @@ -113,21 +130,24 @@ class DbaListSet
             $dbh->delete(intval($i));
         }
     
    -    function _new_key() {
    +    function _new_key()
    +    {
             $dbh = &$this->_dbh;
             $new_key = $dbh->fetch('max_key') + 1;
             $dbh->replace('max_key', $new_key);
             return $new_key;
         }
     
    -    function _setprev($i, $new_prev) {
    +    function _setprev($i, $new_prev)
    +    {
             $dbh = &$this->_dbh;
             list($old_prev, $next, $data) = explode(':', $dbh->fetch($i), 3);
             $dbh->replace($i, "$new_prev:$next:$data");
             return $old_prev;
         }
     
    -    function _setnext($i, $new_next) {
    +    function _setnext($i, $new_next)
    +    {
             $dbh = &$this->_dbh;
             list($prev, $old_next, $data) = explode(':', $dbh->fetch($i), 3);
             $dbh->replace($i, "$prev:$new_next:$data");
    diff --git a/lib/DbaPartition.php b/lib/DbaPartition.php
    index 4fe6e9c50..3bef0dd61 100644
    --- a/lib/DbaPartition.php
    +++ b/lib/DbaPartition.php
    @@ -2,74 +2,88 @@
     
     class DbaPartition
     {
    -    function DbaPartition(&$dbm, $prefix) {
    +    function DbaPartition(&$dbm, $prefix)
    +    {
             $this->_h = &$dbm;
             $this->_p = $prefix;
         }
     
    -    function open($mode = 'w') {
    +    function open($mode = 'w')
    +    {
             $this->_h->open();
         }
     
    -    function close() {
    +    function close()
    +    {
             $this->_h->close();
         }
     
    -    function firstkey() {
    +    function firstkey()
    +    {
             $dbh = &$this->_h;
             $prefix = &$this->_p;
             $n = strlen($prefix);
             for ($key = $dbh->firstkey(); $key !== false; $key = $dbh->nextkey()) {
                 if (substr($key, 0, $n) == $prefix)
    -                return (string) substr($key, $n);
    +                return (string)substr($key, $n);
             }
             return false;
         }
     
    -    function nextkey() {
    +    function nextkey()
    +    {
             $dbh = &$this->_h;
             $prefix = &$this->_p;
             $n = strlen($prefix);
             for ($key = $dbh->nextkey(); $key !== false; $key = $dbh->nextkey()) {
                 if (substr($key, 0, $n) == $prefix)
    -                return (string) substr($key, $n);
    +                return (string)substr($key, $n);
             }
             return false;
         }
     
    -    function exists($key) {
    +    function exists($key)
    +    {
             return $this->_h->exists($this->_p . $key);
         }
     
    -    function fetch($key) {
    +    function fetch($key)
    +    {
             return $this->_h->fetch($this->_p . $key);
         }
     
    -    function insert($key, $val) {
    +    function insert($key, $val)
    +    {
             return $this->_h->insert($this->_p . $key, $val);
         }
     
    -    function replace($key, $val) {
    +    function replace($key, $val)
    +    {
             return $this->_h->replace($this->_p . $key, $val);
         }
     
    -    function delete($key) {
    +    function delete($key)
    +    {
             return $this->_h->delete($this->_p . $key);
         }
     
    -    function get($key) {
    +    function get($key)
    +    {
             return $this->_h->get($this->_p . $key);
         }
     
    -    function set($key, $val) {
    +    function set($key, $val)
    +    {
             return $this->_h->set($this->_p . $key, $val);
         }
     
    -    function sync() {
    +    function sync()
    +    {
             return $this->_h->sync();
         }
     
    -    function optimize() {
    +    function optimize()
    +    {
             return $this->_h->optimize();
         }
     }
    diff --git a/lib/EditToolbar.php b/lib/EditToolbar.php
    index 25fde0089..8f873f22d 100644
    --- a/lib/EditToolbar.php
    +++ b/lib/EditToolbar.php
    @@ -30,9 +30,11 @@
      * - pageinsert popup by Reini Urban (TODO: should be a pulldown, use acdropdown)
      */
     
    -class EditToolbar {
    +class EditToolbar
    +{
     
    -    function EditToolbar() {
    +    function EditToolbar()
    +    {
             global $WikiTheme;
     
             $this->tokens = array();
    @@ -43,32 +45,32 @@ class EditToolbar {
                 $undo_btn = $WikiTheme->getImageURL("ed_undo.png");
                 $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png");
                 // JS_SEARCHREPLACE from walterzorn.de
    -        $js = Javascript("
    -uri_undo_btn   = '".$undo_btn."'
    -msg_undo_alt   = '"._("Undo")."'
    -uri_undo_d_btn = '".$undo_d_btn."'
    -msg_undo_d_alt = '"._("Undo disabled")."'
    -msg_do_undo    = '"._("Operation undone")."'
    -msg_replfound  = '"._("Substring \"\\1\" found \\2 times. Replace with \"\\3\"?")."'
    -msg_replnot    = '"._("String \"%s\" not found.")."'
    -msg_repl_title     = '"._("Search & Replace")."'
    -msg_repl_search    = '"._("Search for")."'
    -msg_repl_replace_with = '"._("Replace with")."'
    -msg_repl_ok        = '"._("OK")."'
    -msg_repl_close     = '"._("Close")."'
    +            $js = Javascript("
    +uri_undo_btn   = '" . $undo_btn . "'
    +msg_undo_alt   = '" . _("Undo") . "'
    +uri_undo_d_btn = '" . $undo_d_btn . "'
    +msg_undo_d_alt = '" . _("Undo disabled") . "'
    +msg_do_undo    = '" . _("Operation undone") . "'
    +msg_replfound  = '" . _("Substring \"\\1\" found \\2 times. Replace with \"\\3\"?") . "'
    +msg_replnot    = '" . _("String \"%s\" not found.") . "'
    +msg_repl_title     = '" . _("Search & Replace") . "'
    +msg_repl_search    = '" . _("Search for") . "'
    +msg_repl_replace_with = '" . _("Replace with") . "'
    +msg_repl_ok        = '" . _("OK") . "'
    +msg_repl_close     = '" . _("Close") . "'
     ");
                 if (empty($WikiTheme->_headers_printed)) {
    -        $WikiTheme->addMoreHeaders($js);
    -        $WikiTheme->addMoreAttr('body', "SearchReplace"," onload='define_f()'");
    -        } else { // from an actionpage: WikiBlog, AddComment, WikiForum
    -        printXML($js);
    -        }
    +                $WikiTheme->addMoreHeaders($js);
    +                $WikiTheme->addMoreAttr('body', "SearchReplace", " onload='define_f()'");
    +            } else { // from an actionpage: WikiBlog, AddComment, WikiForum
    +                printXML($js);
    +            }
             } else {
                 $WikiTheme->addMoreAttr('body', "editfocus", "document.getElementById('edit-content]').editarea.focus()");
             }
     
             if (ENABLE_EDIT_TOOLBAR) {
    -            $js = JavaScript('',array('src' => $WikiTheme->_findData("toolbar.js")));
    +            $js = JavaScript('', array('src' => $WikiTheme->_findData("toolbar.js")));
                 if (empty($WikiTheme->_headers_printed)) {
                     $WikiTheme->addMoreHeaders($js);
                 } else { // from an actionpage: WikiBlog, AddComment, WikiForum
    @@ -102,11 +104,13 @@ msg_repl_close     = '"._("Close")."'
             }
         }
     
    -    function getTokens () {
    +    function getTokens()
    +    {
             return $this->tokens;
         }
     
    -    function _generate () {
    +    function _generate()
    +    {
             global $WikiTheme, $request;
     
             $toolbar = "document.writeln(\"
    \");\n"; @@ -114,153 +118,153 @@ msg_repl_close = '"._("Close")."' if (ENABLE_EDIT_TOOLBAR) { $username = $request->_user->UserName(); if (FUSIONFORGE or DISABLE_MARKUP_WIKIWORD or (!isWikiWord($username))) { - $username = '[['.$username.']]'; + $username = '[[' . $username . ']]'; } - $signature = " ––".$username." ".CTime(); + $signature = " ––" . $username . " " . CTime(); $toolarray = array( - array( - "image"=>"ed_format_bold.png", - "open"=>"**", - "close"=>"**", - "sample"=>_("Bold text"), - "title"=>_("Bold text [alt-b]")), - array("image"=>"ed_format_italic.png", - "open"=>"//", - "close"=>"//", - "sample"=>_("Italic text"), - "title"=>_("Italic text [alt-i]")), - array("image"=>"ed_format_strike.png", - "open"=>"", - "close"=>"", - "sample"=>_("Strike-through text"), - "title"=>_("Strike")), - array("image"=>"ed_format_color.png", - "open"=>"%color=green% ", - "close"=>" %%", - "sample"=>_("Color text"), - "title"=>_("Color")), - array("image"=>"ed_pagelink.png", - "open"=>"[[", - "close"=>"]]", - "sample"=>_("PageName|optional label"), - "title"=>_("Link to page")), - array("image"=>"ed_link.png", - "open"=>"[[", - "close"=>"]]", - "sample"=>_("http://www.example.com|optional label"), - "title"=>_("External link (remember http:// prefix)")), - array("image"=>"ed_headline.png", - "open"=>"\\n== ", - "close"=>" ==\\n", - "sample"=>_("Headline text"), - "title"=>_("Level 1 headline")), - array("image"=>"ed_nowiki.png", - "open"=>"\\\\n", - "close"=>"\\n\\", - "sample"=>_("Insert non-formatted text here"), - "title"=>_("Ignore wiki formatting")), - array("image"=>"ed_sig.png", - "open" => $signature, - "close" => "", - "sample"=>"", - "title"=>_("Your signature")), - array("image"=>"ed_hr.png", - "open"=>"\\n----\\n", - "close"=>"", - "sample"=>"", - "title"=>_("Horizontal line")), - array("image"=>"ed_table.png", - "open"=>"\\n{| class=\"bordered\"\\n|+ This is the table caption\\n|= This is the table summary\\n|-\\n! Header A !! Header B !! Header C\\n|-\\n| Cell A1 || Cell B1 || Cell C1\\n|-\\n| Cell A2 || Cell B2 || Cell C2\\n|-\\n| Cell A3 || Cell B3 || Cell C3\\n|}\\n", - "close"=>"", - "sample"=>"", - "title"=>_("Sample table")), - array("image"=>"ed_enumlist.png", - "open"=>"\\n# Item 1\\n# Item 2\\n# Item 3\\n", - "close"=>"", - "sample"=>"", - "title"=>_("Enumeration")), - array("image"=>"ed_list.png", - "open"=>"\\n* Item 1\\n* Item 2\\n* Item 3\\n", - "close"=>"", - "sample"=>"", - "title"=>_("List")), - array("image"=>"ed_toc.png", - "open"=>"<>\\n", - "close"=>"", - "sample"=>"", - "title"=>_("Table of Contents")), - array("image"=>"ed_redirect.png", - "open"=>"<"\">>", - "sample"=>_("Page Name"), - "title"=>_("Redirect")), - array("image"=>"ed_templateplugin.png", - "open"=>"{{", - "close"=>"}}", - "sample"=>_("Template Name"), - "title"=>_("Template")) - ); + array( + "image" => "ed_format_bold.png", + "open" => "**", + "close" => "**", + "sample" => _("Bold text"), + "title" => _("Bold text [alt-b]")), + array("image" => "ed_format_italic.png", + "open" => "//", + "close" => "//", + "sample" => _("Italic text"), + "title" => _("Italic text [alt-i]")), + array("image" => "ed_format_strike.png", + "open" => "", + "close" => "", + "sample" => _("Strike-through text"), + "title" => _("Strike")), + array("image" => "ed_format_color.png", + "open" => "%color=green% ", + "close" => " %%", + "sample" => _("Color text"), + "title" => _("Color")), + array("image" => "ed_pagelink.png", + "open" => "[[", + "close" => "]]", + "sample" => _("PageName|optional label"), + "title" => _("Link to page")), + array("image" => "ed_link.png", + "open" => "[[", + "close" => "]]", + "sample" => _("http://www.example.com|optional label"), + "title" => _("External link (remember http:// prefix)")), + array("image" => "ed_headline.png", + "open" => "\\n== ", + "close" => " ==\\n", + "sample" => _("Headline text"), + "title" => _("Level 1 headline")), + array("image" => "ed_nowiki.png", + "open" => "\\\\n", + "close" => "\\n\\", + "sample" => _("Insert non-formatted text here"), + "title" => _("Ignore wiki formatting")), + array("image" => "ed_sig.png", + "open" => $signature, + "close" => "", + "sample" => "", + "title" => _("Your signature")), + array("image" => "ed_hr.png", + "open" => "\\n----\\n", + "close" => "", + "sample" => "", + "title" => _("Horizontal line")), + array("image" => "ed_table.png", + "open" => "\\n{| class=\"bordered\"\\n|+ This is the table caption\\n|= This is the table summary\\n|-\\n! Header A !! Header B !! Header C\\n|-\\n| Cell A1 || Cell B1 || Cell C1\\n|-\\n| Cell A2 || Cell B2 || Cell C2\\n|-\\n| Cell A3 || Cell B3 || Cell C3\\n|}\\n", + "close" => "", + "sample" => "", + "title" => _("Sample table")), + array("image" => "ed_enumlist.png", + "open" => "\\n# Item 1\\n# Item 2\\n# Item 3\\n", + "close" => "", + "sample" => "", + "title" => _("Enumeration")), + array("image" => "ed_list.png", + "open" => "\\n* Item 1\\n* Item 2\\n* Item 3\\n", + "close" => "", + "sample" => "", + "title" => _("List")), + array("image" => "ed_toc.png", + "open" => "<>\\n", + "close" => "", + "sample" => "", + "title" => _("Table of Contents")), + array("image" => "ed_redirect.png", + "open" => "< "\">>", + "sample" => _("Page Name"), + "title" => _("Redirect")), + array("image" => "ed_templateplugin.png", + "open" => "{{", + "close" => "}}", + "sample" => _("Template Name"), + "title" => _("Template")) + ); $btn = new SubmitImageButton(_("Save"), "edit[save]", 'toolbar', - $WikiTheme->getImageURL("ed_save.png")); + $WikiTheme->getImageURL("ed_save.png")); $btn->addTooltip(_("Save")); - $btn->setAccesskey("s"); - $toolbar .= ('document.writeln("'.addslashes($btn->asXml()).'");'."\n"); - // preview not supported yet on Wikiblog + $btn->setAccesskey("s"); + $toolbar .= ('document.writeln("' . addslashes($btn->asXml()) . '");' . "\n"); + // preview not supported yet on Wikiblog if (empty($WikiTheme->_headers_printed)) { - $btn = new SubmitImageButton(_("Preview"), "edit[preview]", 'toolbar', - $WikiTheme->getImageURL("ed_preview.png")); - $btn->addTooltip(_("Preview")); - $btn->setAccesskey("p"); - $toolbar .= ('document.writeln("'.addslashes($btn->asXml()).'");'."\n"); - } + $btn = new SubmitImageButton(_("Preview"), "edit[preview]", 'toolbar', + $WikiTheme->getImageURL("ed_preview.png")); + $btn->addTooltip(_("Preview")); + $btn->setAccesskey("p"); + $toolbar .= ('document.writeln("' . addslashes($btn->asXml()) . '");' . "\n"); + } foreach ($toolarray as $tool) { $image = $WikiTheme->getImageURL($tool["image"]); - $open = $tool["open"]; + $open = $tool["open"]; $close = $tool["close"]; - $sample = addslashes( $tool["sample"] ); + $sample = addslashes($tool["sample"]); // Note that we use the title both for the ALT tag and the TITLE tag of the image. // Older browsers show a "speedtip" type message only for ALT. // Ideally these should be different, realistically they // probably don't need to be. $tool = $WikiTheme->fixAccesskey($tool); - $title = addslashes( $tool["title"] ); + $title = addslashes($tool["title"]); $toolbar .= ("addTagButton('$image','$title','$open','$close','$sample');\n"); } /* Fails with Chrome */ if (!isBrowserSafari()) { $toolbar .= ("addInfobox('" - . addslashes( _("Click a button to get an example text") ) - . "');\n"); + . addslashes(_("Click a button to get an example text")) + . "');\n"); } } if (JS_SEARCHREPLACE) { $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png"); //$redo_btn = $WikiTheme->getImageURL("ed_redo.png"); - $sr_btn = $WikiTheme->getImageURL("ed_replace.png"); + $sr_btn = $WikiTheme->getImageURL("ed_replace.png"); //TODO: generalize the UNDO button and fix it for Search & Replace $sr_html = HTML(HTML::img - (array('class'=>"toolbar", - 'id' =>"sr_undo", - 'src' =>$undo_d_btn, - 'title'=>_("Undo Search & Replace"), - 'alt' =>_("Undo Search & Replace"), - //'disabled'=>"disabled", //non-XHTML conform - //'onfocus' =>"if(this.blur && undo_buffer_index==0) this.blur()", - 'onclick' =>"do_undo()")), - HTML::img - (array('class'=>"toolbar", - 'src' => $sr_btn, - 'alt' =>_("Search & Replace"), - 'title'=>_("Search & Replace"), - 'onclick'=>"replace()"))); + (array('class' => "toolbar", + 'id' => "sr_undo", + 'src' => $undo_d_btn, + 'title' => _("Undo Search & Replace"), + 'alt' => _("Undo Search & Replace"), + //'disabled'=>"disabled", //non-XHTML conform + //'onfocus' =>"if(this.blur && undo_buffer_index==0) this.blur()", + 'onclick' => "do_undo()")), + HTML::img + (array('class' => "toolbar", + 'src' => $sr_btn, + 'alt' => _("Search & Replace"), + 'title' => _("Search & Replace"), + 'onclick' => "replace()"))); } else { $sr_html = ''; } //TODO: Delegate this to run-time with showing an hidden input at the right, and do - // a seperate moacdropdown and xmlrpc:titleSearch. + // a seperate moacdropdown and xmlrpc:titleSearch. // Button to generate categories, display in extra window as popup and insert $sr_html = HTML($sr_html, $this->categoriesPulldown()); @@ -282,14 +286,15 @@ msg_repl_close = '"._("Close")."' $toolbar_end = "document.writeln(\"
    \");"; if ($sr_html) return HTML(Javascript($toolbar), - "\n", $sr_html, "\n", - Javascript($toolbar_end)); + "\n", $sr_html, "\n", + Javascript($toolbar_end)); else return HTML(Javascript($toolbar . $toolbar_end)); } //result is cached - function categoriesPulldown() { + function categoriesPulldown() + { global $WikiTheme; require_once 'lib/TextSearchQuery.php'; @@ -299,34 +304,35 @@ msg_repl_close = '"._("Close")."' if ($pages) { $categories = array(); while ($p = $pages->next()) { - $page = $p->getName(); + $page = $p->getName(); if (FUSIONFORGE) { - $categories[] = "['$page', '%0A----%0A%5B%5B".$page."%5D%5D']"; - } elseif (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page))) { - $categories[] = "['$page', '%0A%5B".$page."%5D']"; - } else { - $categories[] = "['$page', '%0A".$page."']"; + $categories[] = "['$page', '%0A----%0A%5B%5B" . $page . "%5D%5D']"; + } elseif (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page))) { + $categories[] = "['$page', '%0A%5B" . $page . "%5D']"; + } else { + $categories[] = "['$page', '%0A" . $page . "']"; } } if (!$categories) return ''; - // Ensure this to be inserted at the very end. Hence we added the id to the function. - $more_buttons = HTML::img(array('class'=> "toolbar", - 'id' => 'tb-categories', - 'src' => $WikiTheme->getImageURL("ed_category.png"), - 'title'=>_("Insert Categories"), - 'alt'=>"Insert Categories", // to detect this at js - 'onclick'=>"showPulldown('". - _("Insert Categories") - ."',[".join(",",$categories)."],'" - ._("Insert")."','" - ._("Close")."','tb-categories')")); + // Ensure this to be inserted at the very end. Hence we added the id to the function. + $more_buttons = HTML::img(array('class' => "toolbar", + 'id' => 'tb-categories', + 'src' => $WikiTheme->getImageURL("ed_category.png"), + 'title' => _("Insert Categories"), + 'alt' => "Insert Categories", // to detect this at js + 'onclick' => "showPulldown('" . + _("Insert Categories") + . "',[" . join(",", $categories) . "],'" + . _("Insert") . "','" + . _("Close") . "','tb-categories')")); return HTML("\n", $more_buttons); } return ''; } // result is cached. Esp. the args are expensive - function pluginPulldown() { + function pluginPulldown() + { global $WikiTheme; global $AllAllowedPlugins; @@ -349,34 +355,35 @@ msg_repl_close = '"._("Close")."' if (strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') { $plugin_args = ''; $desc = $p->getArgumentsDescription(); - $src = array("\n",'"',"'",'|','[',']','\\'); - $replace = array('%0A','%22','%27','%7C','%5B','%5D','%5C'); - $desc = str_replace("
    ",' ',$desc->asXML()); + $src = array("\n", '"', "'", '|', '[', ']', '\\'); + $replace = array('%0A', '%22', '%27', '%7C', '%5B', '%5D', '%5C'); + $desc = str_replace("
    ", ' ', $desc->asXML()); if ($desc) - $plugin_args = ' '.str_replace($src, $replace, $desc); - $toinsert = "%0A<<".$pluginName.$plugin_args.">>"; // args? + $plugin_args = ' ' . str_replace($src, $replace, $desc); + $toinsert = "%0A<<" . $pluginName . $plugin_args . ">>"; // args? $plugin_js .= ",['$pluginName','$toinsert']"; } } } $plugin_js = substr($plugin_js, 1); - $more_buttons = HTML::img(array('class'=>"toolbar", - 'id' => 'tb-plugins', - 'src' => $WikiTheme->getImageURL("ed_plugins.png"), - 'title'=>_("Insert Plugin"), - 'alt'=>_("Insert Plugin"), - 'onclick'=>"showPulldown('". - _("Insert Plugin") - ."',[".$plugin_js."],'" - ._("Insert")."','" - ._("Close")."','tb-plugins')")); + $more_buttons = HTML::img(array('class' => "toolbar", + 'id' => 'tb-plugins', + 'src' => $WikiTheme->getImageURL("ed_plugins.png"), + 'title' => _("Insert Plugin"), + 'alt' => _("Insert Plugin"), + 'onclick' => "showPulldown('" . + _("Insert Plugin") + . "',[" . $plugin_js . "],'" + . _("Insert") . "','" + . _("Close") . "','tb-plugins')")); return HTML("\n", $more_buttons); } return ''; } // result is cached. Esp. the args are expensive - function pagesPulldown($query, $case_exact=false, $regex='auto') { + function pagesPulldown($query, $case_exact = false, $regex = 'auto') + { require_once 'lib/TextSearchQuery.php'; $dbi =& $GLOBALS['request']->_dbi; $page_iter = $dbi->titleSearch(new TextSearchQuery($query, $case_exact, $regex)); @@ -384,28 +391,29 @@ msg_repl_close = '"._("Close")."' global $WikiTheme; $pages = array(); while ($p = $page_iter->next()) { - $page = $p->getName(); - if (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page))) - $pages[] = "['$page', '%5B".$page."%5D']"; - else - $pages[] = "['$page', '$page']"; + $page = $p->getName(); + if (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page))) + $pages[] = "['$page', '%5B" . $page . "%5D']"; + else + $pages[] = "['$page', '$page']"; } - return HTML("\n", HTML::img(array('class'=>"toolbar", - 'id' => 'tb-pages', - 'src' => $WikiTheme->getImageURL("ed_pages.png"), - 'title'=>_("Insert PageLink"), - 'alt'=>_("Insert PageLink"), - 'onclick'=>"showPulldown('". - _("Insert PageLink") - ."',[".join(",",$pages)."],'" - ._("Insert")."','" - ._("Close")."','tb-pages')"))); + return HTML("\n", HTML::img(array('class' => "toolbar", + 'id' => 'tb-pages', + 'src' => $WikiTheme->getImageURL("ed_pages.png"), + 'title' => _("Insert PageLink"), + 'alt' => _("Insert PageLink"), + 'onclick' => "showPulldown('" . + _("Insert PageLink") + . "',[" . join(",", $pages) . "],'" + . _("Insert") . "','" + . _("Close") . "','tb-pages')"))); } return ''; } // result is cached. Esp. the args are expensive - function imagePulldown($query, $case_exact=false, $regex='auto') { + function imagePulldown($query, $case_exact = false, $regex = 'auto') + { global $WikiTheme; $image_dir = getUploadFilePath(); @@ -424,20 +432,20 @@ msg_repl_close = '"._("Close")."' foreach ($images as $image) { // Select only image and video files if (is_image($image) or is_video($image)) { - $image_js .= ",['$image','{{".$image."}}']"; + $image_js .= ",['$image','{{" . $image . "}}']"; } } $image_js = substr($image_js, 1); - $more_buttons = HTML::img(array('class'=>"toolbar", - 'id' => 'tb-images', - 'src' => $WikiTheme->getImageURL("ed_image.png"), - 'title'=>_("Insert Image or Video"), - 'alt'=>_("Insert Image or Video"), - 'onclick'=>"showPulldown('". - _("Insert Image or Video") - ."',[".$image_js."],'" - ._("Insert")."','" - ._("Close")."','tb-images')")); + $more_buttons = HTML::img(array('class' => "toolbar", + 'id' => 'tb-images', + 'src' => $WikiTheme->getImageURL("ed_image.png"), + 'title' => _("Insert Image or Video"), + 'alt' => _("Insert Image or Video"), + 'onclick' => "showPulldown('" . + _("Insert Image or Video") + . "',[" . $image_js . "],'" + . _("Insert") . "','" + . _("Close") . "','tb-images')")); return HTML("\n", $more_buttons); } return ''; @@ -445,7 +453,8 @@ msg_repl_close = '"._("Close")."' // result is cached. Esp. the args are expensive // FIXME! - function templatePulldown($query, $case_exact=false, $regex='auto') { + function templatePulldown($query, $case_exact = false, $regex = 'auto') + { global $request; require_once 'lib/TextSearchQuery.php'; $dbi =& $request->_dbi; @@ -456,23 +465,23 @@ msg_repl_close = '"._("Close")."' $pages_js = ''; while ($p = $page_iter->next()) { $rev = $p->getCurrentRevision(); - $toinsert = str_replace(array("\n",'"'), array('_nl','_quot'), $rev->_get_content()); + $toinsert = str_replace(array("\n", '"'), array('_nl', '_quot'), $rev->_get_content()); //$toinsert = str_replace("\n",'\n',addslashes($rev->_get_content())); - $pages_js .= ",['".$p->getName()."','_nl$toinsert']"; + $pages_js .= ",['" . $p->getName() . "','_nl$toinsert']"; } $pages_js = substr($pages_js, 1); if (!empty($pages_js)) return HTML("\n", HTML::img - (array('class'=>"toolbar", - 'id' => 'tb-templates', - 'src' => $WikiTheme->getImageURL("ed_template.png"), - 'title'=>_("Insert Template"), - 'alt'=>_("Insert Template"), - 'onclick'=>"showPulldown('". - _("Insert Template") - ."',[".$pages_js."],'" - ._("Insert")."','" - ._("Close")."','tb-templates')"))); + (array('class' => "toolbar", + 'id' => 'tb-templates', + 'src' => $WikiTheme->getImageURL("ed_template.png"), + 'title' => _("Insert Template"), + 'alt' => _("Insert Template"), + 'onclick' => "showPulldown('" . + _("Insert Template") + . "',[" . $pages_js . "],'" + . _("Insert") . "','" + . _("Close") . "','tb-templates')"))); } return ''; } diff --git a/lib/ErrorManager.php b/lib/ErrorManager.php index 88ddcf26f..7105f5256 100644 --- a/lib/ErrorManager.php +++ b/lib/ErrorManager.php @@ -12,9 +12,9 @@ if (defined('E_STRICT') error_reporting(E_ALL & ~E_STRICT); } */ -define ('EM_FATAL_ERRORS', E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | ~2048 & ((check_php_version(5,3)) ? ~E_DEPRECATED : ~0)); +define ('EM_FATAL_ERRORS', E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | ~2048 & ((check_php_version(5, 3)) ? ~E_DEPRECATED : ~0)); define ('EM_WARNING_ERRORS', - E_WARNING | E_CORE_WARNING | E_COMPILE_WARNING | E_USER_WARNING | ((check_php_version(5,3)) ? E_DEPRECATED : 0)); + E_WARNING | E_CORE_WARNING | E_COMPILE_WARNING | E_USER_WARNING | ((check_php_version(5, 3)) ? E_DEPRECATED : 0)); define ('EM_NOTICE_ERRORS', E_NOTICE | E_USER_NOTICE); /* It is recommended to leave assertions on. @@ -24,13 +24,14 @@ define ('EM_NOTICE_ERRORS', E_NOTICE | E_USER_NOTICE); */ //also turn it on if phpwiki_version notes no release if (defined('DEBUG') and DEBUG) - assert_options (ASSERT_ACTIVE, 1); + assert_options(ASSERT_ACTIVE, 1); else - assert_options (ASSERT_ACTIVE, 0); -assert_options (ASSERT_CALLBACK, 'wiki_assert_handler'); + assert_options(ASSERT_ACTIVE, 0); +assert_options(ASSERT_CALLBACK, 'wiki_assert_handler'); -function wiki_assert_handler ($file, $line, $code) { - ErrorManager_errorHandler( $code, sprintf("
    %s:%s: %s: Assertion failed
    ", $file, $line, $code), $file, $line); +function wiki_assert_handler($file, $line, $code) +{ + ErrorManager_errorHandler($code, sprintf("
    %s:%s: %s: Assertion failed
    ", $file, $line, $code), $file, $line); } /** @@ -49,7 +50,8 @@ class ErrorManager * As this is a singleton class, you should never call this. * @access private */ - function ErrorManager() { + function ErrorManager() + { $this->_handlers = array(); $this->_fatal_handler = false; $this->_postpone_mask = 0; @@ -63,7 +65,8 @@ class ErrorManager * @access public * @return int The current postponed error mask. */ - function getPostponedErrorMask() { + function getPostponedErrorMask() + { return $this->_postpone_mask; } @@ -78,7 +81,8 @@ class ErrorManager * @access public * @param $newmask int The new value for the mask. */ - function setPostponedErrorMask($newmask) { + function setPostponedErrorMask($newmask) + { $this->_postpone_mask = $newmask; if (function_exists('PrintXML')) PrintXML($this->_flush_errors($newmask)); @@ -91,7 +95,8 @@ class ErrorManager * Report any queued error messages. * @access public */ - function flushPostponedErrors() { + function flushPostponedErrors() + { if (function_exists('PrintXML')) PrintXML($this->_flush_errors()); else @@ -103,7 +108,8 @@ class ErrorManager * - pdf or image - output. * @access public */ - function destroyPostponedErrors () { + function destroyPostponedErrors() + { $this->_postponed_errors = array(); } @@ -114,7 +120,8 @@ class ErrorManager * * @return object HTML describing any queued errors (or false, if none). */ - function getPostponedErrorsAsHTML() { + function getPostponedErrorsAsHTML() + { $flushed = $this->_flush_errors(); if (!$flushed) return false; @@ -131,8 +138,8 @@ class ErrorManager return $flushed; $class = $worst_err->getHtmlClass(); $html = HTML::div(array('class' => $class), - HTML::div(array('class' => 'errors'), - "PHP " . $worst_err->getDescription())); + HTML::div(array('class' => 'errors'), + "PHP " . $worst_err->getDescription())); $html->pushContent($flushed); return $html; } @@ -177,7 +184,8 @@ class ErrorManager * @access public * @param $handler WikiCallback Handler to call. */ - function pushErrorHandler($handler) { + function pushErrorHandler($handler) + { array_unshift($this->_handlers, $handler); } @@ -185,7 +193,8 @@ class ErrorManager * Pop an error handler off the handler stack. * @access public */ - function popErrorHandler() { + function popErrorHandler() + { return array_shift($this->_handlers); } @@ -199,7 +208,8 @@ class ErrorManager * @access public * @param $handler WikiCallback Callback to call on fatal errors. */ - function setFatalHandler($handler) { + function setFatalHandler($handler) + { $this->_fatal_handler = $handler; } @@ -212,13 +222,14 @@ class ErrorManager * @access public * @param $error object A PhpError object. */ - function handleError($error) { + function handleError($error) + { static $in_handler; if (!empty($in_handler)) { $msg = $error->_getDetail(); $msg->unshiftContent(HTML::h2(fmt("%s: error while handling error:", - "ErrorManager"))); + "ErrorManager"))); $msg->printXML(); return; } @@ -227,7 +238,7 @@ class ErrorManager // so display now all errors directly. if (!empty($GLOBALS['request']->_finishing)) { $this->_postpone_mask = 0; - } + } $in_handler = true; @@ -235,9 +246,8 @@ class ErrorManager if (!$handler) continue; $result = $handler->call($error); if (!$result) { - continue; // Handler did not handle error. - } - elseif (is_object($result)) { + continue; // Handler did not handle error. + } elseif (is_object($result)) { // handler filtered the result. Still should pass to // the rest of the chain. if ($error->isFatal()) { @@ -245,8 +255,7 @@ class ErrorManager $result->errno = $error->errno; } $error = $result; - } - else { + } else { // Handler handled error. if (!$error->isFatal()) { $in_handler = false; @@ -262,7 +271,7 @@ class ErrorManager $this->_noCacheHeaders(); echo "\n"; echo "\n"; + echo "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"; echo "\n"; echo "\n"; echo "\n"; @@ -273,31 +282,30 @@ class ErrorManager echo "
    Fatal Error:
    \n"; if (defined('DEBUG') and (DEBUG & _DEBUG_TRACE)) { - echo "error_reporting=",error_reporting(),"\n
    "; + echo "error_reporting=", error_reporting(), "\n
    "; $error->printSimpleTrace(debug_backtrace()); } - $this->_die($error); - } - else if (($error->errno & error_reporting()) != 0) { - if (($error->errno & $this->_postpone_mask) != 0) { + $this->_die($error); + } else if (($error->errno & error_reporting()) != 0) { + if (($error->errno & $this->_postpone_mask) != 0) { if ((function_exists('isa') and isa($error, 'PhpErrorOnce')) or (!function_exists('isa') and - ( - // stdlib independent isa() - (strtolower(get_class($error)) == 'phperroronce') - or (is_subclass_of($error, 'PhpErrorOnce'))))) { + ( + // stdlib independent isa() + (strtolower(get_class($error)) == 'phperroronce') + or (is_subclass_of($error, 'PhpErrorOnce')))) + ) { $error->removeDoublettes($this->_postponed_errors); - if ( $error->_count < 2 ) + if ($error->_count < 2) $this->_postponed_errors[] = $error; } else { $this->_postponed_errors[] = $error; } - } - else { + } else { //echo "postponed errors: "; $this->_noCacheHeaders(); if (defined('DEBUG') and (DEBUG & _DEBUG_TRACE)) { - echo "error_reporting=",error_reporting(),"\n"; + echo "error_reporting=", error_reporting(), "\n"; $error->printSimpleTrace(debug_backtrace()); } $error->printXML(); @@ -306,32 +314,35 @@ class ErrorManager $in_handler = false; } - function warning($msg, $errno = E_USER_NOTICE) { + function warning($msg, $errno = E_USER_NOTICE) + { $this->handleError(new PhpWikiError($errno, $msg, '?', '?')); } /** * @access private */ - function _die($error) { + function _die($error) + { global $WikiTheme; //echo "\n\n"; $error->printXML(); PrintXML($this->_flush_errors()); if ($this->_fatal_handler) $this->_fatal_handler->call($error); - if (!$WikiTheme->DUMP_MODE) - exit -1; + if (!$WikiTheme->DUMP_MODE) + exit - 1; } /** * @access private */ - function _flush_errors($keep_mask = 0) { + function _flush_errors($keep_mask = 0) + { $errors = &$this->_postponed_errors; if (empty($errors)) return ''; $flushed = HTML(); - for ($i=0; $icacheControl()? if (!headers_sent()) { - header( "Cache-control: no-cache" ); - header( "Pragma: nocache" ); + header("Cache-control: no-cache"); + header("Pragma: nocache"); } $already = true; } @@ -374,7 +386,7 @@ class ErrorManager function ErrorManager_errorHandler($errno, $errstr, $errfile, $errline) { if (!isset($GLOBALS['ErrorManager'])) { - $GLOBALS['ErrorManager'] = new ErrorManager; + $GLOBALS['ErrorManager'] = new ErrorManager; } if (defined('DEBUG') and DEBUG) { @@ -391,7 +403,8 @@ function ErrorManager_errorHandler($errno, $errstr, $errfile, $errline) * @see The PHP documentation for set_error_handler at * http://php.net/manual/en/function.set-error-handler.php . */ -class PhpError { +class PhpError +{ /** * The PHP errno */ @@ -419,9 +432,10 @@ class PhpError { * @param $errfile string * @param $errline int */ - function PhpError($errno, $errstr, $errfile, $errline) { - $this->errno = $errno; - $this->errstr = $errstr; + function PhpError($errno, $errstr, $errfile, $errline) + { + $this->errno = $errno; + $this->errstr = $errstr; $this->errfile = $errfile; $this->errline = $errline; } @@ -430,15 +444,17 @@ class PhpError { * Determine whether this is a fatal error. * @return boolean True if this is a fatal error. */ - function isFatal() { - return ($this->errno & (2048|EM_WARNING_ERRORS|EM_NOTICE_ERRORS)) == 0; + function isFatal() + { + return ($this->errno & (2048 | EM_WARNING_ERRORS | EM_NOTICE_ERRORS)) == 0; } /** * Determine whether this is a warning level error. * @return boolean */ - function isWarning() { + function isWarning() + { return ($this->errno & EM_WARNING_ERRORS) != 0; } @@ -446,10 +462,13 @@ class PhpError { * Determine whether this is a notice level error. * @return boolean */ - function isNotice() { + function isNotice() + { return ($this->errno & EM_NOTICE_ERRORS) != 0; } - function getHtmlClass() { + + function getHtmlClass() + { if ($this->isNotice()) { return 'hint'; } elseif ($this->isWarning()) { @@ -459,7 +478,8 @@ class PhpError { } } - function getDescription() { + function getDescription() + { if ($this->isNotice()) { return 'Notice'; } elseif ($this->isWarning()) { @@ -473,31 +493,32 @@ class PhpError { * Get a printable, HTML, message detailing this error. * @return object The detailed error message. */ - function _getDetail() { - $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : substr(dirname(__FILE__),0,-4); - if (substr(PHP_OS,0,3) == 'WIN') { - $dir = str_replace('/','\\',$dir); - $this->errfile = str_replace('/','\\',$this->errfile); - $dir .= "\\"; + function _getDetail() + { + $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : substr(dirname(__FILE__), 0, -4); + if (substr(PHP_OS, 0, 3) == 'WIN') { + $dir = str_replace('/', '\\', $dir); + $this->errfile = str_replace('/', '\\', $this->errfile); + $dir .= "\\"; } else - $dir .= '/'; + $dir .= '/'; $errfile = preg_replace('|^' . preg_quote($dir) . '|', '', $this->errfile); $lines = explode("\n", $this->errstr); if (DEBUG & _DEBUG_VERBOSE) { - $msg = sprintf("%s:%d %s[%d]: %s", - $errfile, $this->errline, - $this->getDescription(), $this->errno, - array_shift($lines)); - }/* elseif (! $this->isFatal()) { + $msg = sprintf("%s:%d %s[%d]: %s", + $errfile, $this->errline, + $this->getDescription(), $this->errno, + array_shift($lines)); + } /* elseif (! $this->isFatal()) { $msg = sprintf("%s:%d %s: \"%s\"", $errfile, $this->errline, $this->getDescription(), array_shift($lines)); }*/ else { - $msg = sprintf("%s:%d %s: \"%s\"", - $errfile, $this->errline, - $this->getDescription(), - array_shift($lines)); + $msg = sprintf("%s:%d %s: \"%s\"", + $errfile, $this->errline, + $this->getDescription(), + array_shift($lines)); } $html = HTML::div(array('class' => $this->getHtmlClass()), HTML::p($msg)); @@ -517,28 +538,32 @@ class PhpError { * Print an HTMLified version of this error. * @see asXML() */ - function printXML() { + function printXML() + { PrintXML($this->_getDetail()); } /** * Return an HTMLified version of this error. */ - function asXML() { + function asXML() + { return AsXML($this->_getDetail()); } /** * Return a plain-text version of this error. */ - function asString() { + function asString() + { return AsString($this->_getDetail()); } - function printSimpleTrace($bt) { + function printSimpleTrace($bt) + { global $HTTP_SERVER_VARS; $nl = isset($HTTP_SERVER_VARS['REQUEST_METHOD']) ? "
    " : "\n"; - echo $nl."Traceback:".$nl; + echo $nl . "Traceback:" . $nl; foreach ($bt as $i => $elem) { if (!array_key_exists('file', $elem)) { continue; @@ -555,19 +580,22 @@ class PhpError { * This is essentially the same as a PhpError, except that the * error message is quieter: no source line, etc... */ -class PhpWikiError extends PhpError { +class PhpWikiError extends PhpError +{ /** * Construct a new PhpError. * @param $errno int * @param $errstr string */ - function PhpWikiError($errno, $errstr, $errfile, $errline) { + function PhpWikiError($errno, $errstr, $errfile, $errline) + { $this->PhpError($errno, $errstr, $errfile, $errline); } - function _getDetail() { + function _getDetail() + { return HTML::div(array('class' => $this->getHtmlClass()), - HTML::p($this->getDescription() . ": $this->errstr")); + HTML::p($this->getDescription() . ": $this->errstr")); } } @@ -577,23 +605,27 @@ class PhpWikiError extends PhpError { * Similar to PhpError, except only the first same error message is printed, * with number of occurences. */ -class PhpErrorOnce extends PhpError { +class PhpErrorOnce extends PhpError +{ - function PhpErrorOnce($errno, $errstr, $errfile, $errline) { + function PhpErrorOnce($errno, $errstr, $errfile, $errline) + { $this->_count = 1; $this->PhpError($errno, $errstr, $errfile, $errline); } - function _sameError($error) { + function _sameError($error) + { if (!$error) return false; return ($this->errno == $error->errno and - $this->errfile == $error->errfile and + $this->errfile == $error->errfile and $this->errline == $error->errline); } // count similar handlers, increase _count and remove the rest - function removeDoublettes(&$errors) { - for ($i=0; $i < count($errors); $i++) { + function removeDoublettes(&$errors) + { + for ($i = 0; $i < count($errors); $i++) { if (!isset($errors[$i])) continue; if ($this->_sameError($errors[$i])) { $errors[$i]->_count++; @@ -604,37 +636,38 @@ class PhpErrorOnce extends PhpError { return $this->_count; } - function _getDetail($count=0) { + function _getDetail($count = 0) + { if (!$count) $count = $this->_count; - $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : substr(dirname(__FILE__),0,-4); - if (substr(PHP_OS,0,3) == 'WIN') { - $dir = str_replace('/','\\',$dir); - $this->errfile = str_replace('/','\\',$this->errfile); - $dir .= "\\"; + $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : substr(dirname(__FILE__), 0, -4); + if (substr(PHP_OS, 0, 3) == 'WIN') { + $dir = str_replace('/', '\\', $dir); + $this->errfile = str_replace('/', '\\', $this->errfile); + $dir .= "\\"; } else - $dir .= '/'; + $dir .= '/'; $errfile = preg_replace('|^' . preg_quote($dir) . '|', '', $this->errfile); if (is_string($this->errstr)) $lines = explode("\n", $this->errstr); - elseif (is_object($this->errstr)) + elseif (is_object($this->errstr)) $lines = array($this->errstr->asXML()); $errtype = (DEBUG & _DEBUG_VERBOSE) ? sprintf("%s[%d]", $this->getDescription(), $this->errno) - : sprintf("%s", $this->getDescription()); + : sprintf("%s", $this->getDescription()); if ((DEBUG & _DEBUG_VERBOSE) or $this->isFatal()) { - $msg = sprintf("%s:%d %s: %s %s", - $errfile, $this->errline, - $errtype, - array_shift($lines), - $count > 1 ? sprintf(" (...repeated %d times)",$count) : "" - ); - } else { - $msg = sprintf("%s: \"%s\" %s", - $errtype, - array_shift($lines), - $count > 1 ? sprintf(" (...repeated %d times)",$count) : ""); - } + $msg = sprintf("%s:%d %s: %s %s", + $errfile, $this->errline, + $errtype, + array_shift($lines), + $count > 1 ? sprintf(" (...repeated %d times)", $count) : "" + ); + } else { + $msg = sprintf("%s: \"%s\" %s", + $errtype, + array_shift($lines), + $count > 1 ? sprintf(" (...repeated %d times)", $count) : ""); + } $html = HTML::div(array('class' => $this->getHtmlClass()), - HTML::p($msg)); + HTML::p($msg)); if ($lines) { $list = HTML::ul(); foreach ($lines as $line) @@ -646,10 +679,10 @@ class PhpErrorOnce extends PhpError { } } -if (check_php_version(5,2)) { - require_once(dirname(__FILE__).'/HtmlElement5.php'); +if (check_php_version(5, 2)) { + require_once(dirname(__FILE__) . '/HtmlElement5.php'); } else { - require_once(dirname(__FILE__).'/HtmlElement.php'); + require_once(dirname(__FILE__) . '/HtmlElement.php'); } if (!isset($GLOBALS['ErrorManager'])) { diff --git a/lib/ExternalReferrer.php b/lib/ExternalReferrer.php index 5713d1552..d2ecac463 100644 --- a/lib/ExternalReferrer.php +++ b/lib/ExternalReferrer.php @@ -8,63 +8,65 @@ * store all external referrers in (rotatable) log/db for a RecentReferrers plugin. */ if (!function_exists('isExternalReferrer')) { // also defined in stdlib.php - function isExternalReferrer(&$request) { - if ($referrer = $request->get('HTTP_REFERER')) { - $home = SCRIPT_NAME; // was SERVER_URL, check sister wiki's: same host but other other script url - if (substr(strtolower($referrer),0,strlen($home)) == strtolower($home)) return false; - require_once 'lib/ExternalReferrer.php'; - $se = new SearchEngines(); - return $se->parseSearchQuery($referrer); + function isExternalReferrer(&$request) + { + if ($referrer = $request->get('HTTP_REFERER')) { + $home = SCRIPT_NAME; // was SERVER_URL, check sister wiki's: same host but other other script url + if (substr(strtolower($referrer), 0, strlen($home)) == strtolower($home)) return false; + require_once 'lib/ExternalReferrer.php'; + $se = new SearchEngines(); + return $se->parseSearchQuery($referrer); + } + return false; } - return false; - } } -class SearchEngines { +class SearchEngines +{ var $searchEngines = - array( - "search.sli.sympatico.ca/" => array("engine" => "Sympatico", "query1" => "query=", "query2" => "", "url" => "http://www1.sympatico.ca/"), - "www.search123.com/cgi-bin/" => array("engine" => "Search123", "query1" => "query=", "query2" => "", "url" => "http://www.search123.com/"), - "search.dogpile.com" => array("engine" => "Dogpile", "query1" => "q=", "query2" => "", "url" => "http://www.dogpile.com"), - "vivisimo." => array("engine" => "Vivisimo", "query1" => "query=", "query2" => "", "url" => "http://www.vivisimo.com"), - "webindex.sanook.com" => array("engine" => "Sanook", "query1" => "d1=", "query2" => "", "url" => "http://www.sanook.com/"), - "tiscali.cz/search" => array("engine" => "JANAS", "query1" => "query=", "query2" => "", "url" => "http://www.tiscali.cz/"), - "teoma.com/gs?" => array("engine" => "Teoma", "query1" => "terms=", "query2" => "", "url" => "http://www.teoma.com/"), - "redbox." => array("engine" => "RedBox", "query1" => "srch=", "query2" => "", "url" => "http://www.redbox.cz/"), - "globetrotter.net" => array("engine" => "Telus Network - Globetrotter.net", "query1" => "string=", "query2" => "", "url" => "http://www.globetrotter.net/"), - "myto.com" => array("engine" => "Telus Network - myTO.com", "query1" => "string=", "query2" => "", "url" => "http://www.myto.com/"), - "alberta.com" => array("engine" => "Telus Network - Alberta.com", "query1" => "string=", "query2" => "", "url" => "http://www.alberta.com/"), - "mybc.com" => array("engine" => "Telus Network - myBC.com", "query1" => "string=", "query2" => "", "url" => "http://www.mybc.com/"), - "monstercrawler." => array("engine" => "MonsterCrawler", "query1" => "qry=", "query2" => "", "url" => "http://www.monstercrawler.com/"), - "allthesites." => array("engine" => "All the Sites", "query1" => "query=", "query2" => "", "url" => "http://www.althesites.com/"), - "suche.web" => array("engine" => "Web.de", "query1" => "su=", "query2" => "", "url" => "http://www.web.de/"), - "rediff." => array("engine" => "reDiff", "query1" => "MT=", "query2" => "", "url" => "http://www.rediff.com/"), - "evreka." => array("engine" => "Evreka", "query1" => "q=", "query2" => "", "url" => "http://evreka.suomi24.fi/"), - "findia." => array("engine" => "Findia", "query1" => "query=", "query2" => "", "url" => "http://www.findia.net/"), - "av.yahoo" => array("engine" => "Yahoo", "query1" => "p=", "query2" => "", "url" => "http://www.yahoo.com/"), - "google.yahoo" => array("engine" => "Yahoo", "query1" => "p=", "query2" => "", "url" => "http://www.yahoo.com/"), - "yahoo." => array("engine" => "Yahoo", "query1" => "q=", "query2" => "", "url" => "http://www.yahoo.com/"), - "aol." => array("engine" => "AOL Search", "query1" => "query=", "query2" => "", "url" => "http://search.aol.com/"), - "about." => array("engine" => "About", "query1" => "terms=", "query2" => "", "url" => "http://www.about.com/"), - "altavista." => array("engine" => "Altavista", "query1" => "q=", "query2" => "", "url" => "http://www.altavista.com/"), - "directhit." => array("engine" => "DirectHit", "query1" => "qry=", "query2" => "", "url" => "http://www.directhit.com/"), - "lk=webcrawler" => array("engine" => "Webcrawler", "query1" => "s=", "query2" => "", "url" => "http://www.webcrawler.com/"), - "excite." => array("engine" => "Excite", "query1" => "search=", "query2" => "", "url" => "http://www.excite.com/"), - "alltheweb." => array("engine" => "All the Web", "query1" => "query=", "query2" => "q=", "url" => "http://www.alltheweb.com/"), - "netscape." => array("engine" => "Netscape", "query1" => "search=", "query2" => "", "url" => "http://search.netscape.com/"), - "google." => array("engine" => "Google", "query1" => "q=", "query2" => "query=", "url" => "http://www.google.com/"), - "?partner=go_home" => array("engine" => "Infoseek/Go", "query1" => "Keywords=", "query2" => "", "url" => "http://www.go.com/"), - "nbci." => array("engine" => "NBCi", "query1" => "Keywords=", "query2" => "", "url" => "http://www.nbci.com/"), - "goto." => array("engine" => "GoTo", "query1" => "Keywords=", "query2" => "", "url" => "http://www.goto.com/"), - "hotbot." => array("engine" => "HotBot", "query1" => "MT=", "query2" => "", "url" => "http://hotbot.lycos.com/"), - "iwon." => array("engine" => "IWon", "query1" => "searchfor=", "query2" => "", "url" => "http://home.iwon.com/index_gen.html"), - "looksmart." => array("engine" => "Looksmart", "query1" => "key=", "query2" => "", "url" => "http://www.looksmart.com/"), - "lycos." => array("engine" => "Lycos", "query1" => "query=", "query2" => "", "url" => "http://www.lycos.com/"), - "msn." => array("engine" => "MSN", "query1" => "q=", "query2" => "", "url" => "http://search.msn.com/"), - "dmoz." => array("engine" => "Dmoz", "query1" => "search=", "query2" => "", "url" => "http://www.dmoz.org/"), + array( + "search.sli.sympatico.ca/" => array("engine" => "Sympatico", "query1" => "query=", "query2" => "", "url" => "http://www1.sympatico.ca/"), + "www.search123.com/cgi-bin/" => array("engine" => "Search123", "query1" => "query=", "query2" => "", "url" => "http://www.search123.com/"), + "search.dogpile.com" => array("engine" => "Dogpile", "query1" => "q=", "query2" => "", "url" => "http://www.dogpile.com"), + "vivisimo." => array("engine" => "Vivisimo", "query1" => "query=", "query2" => "", "url" => "http://www.vivisimo.com"), + "webindex.sanook.com" => array("engine" => "Sanook", "query1" => "d1=", "query2" => "", "url" => "http://www.sanook.com/"), + "tiscali.cz/search" => array("engine" => "JANAS", "query1" => "query=", "query2" => "", "url" => "http://www.tiscali.cz/"), + "teoma.com/gs?" => array("engine" => "Teoma", "query1" => "terms=", "query2" => "", "url" => "http://www.teoma.com/"), + "redbox." => array("engine" => "RedBox", "query1" => "srch=", "query2" => "", "url" => "http://www.redbox.cz/"), + "globetrotter.net" => array("engine" => "Telus Network - Globetrotter.net", "query1" => "string=", "query2" => "", "url" => "http://www.globetrotter.net/"), + "myto.com" => array("engine" => "Telus Network - myTO.com", "query1" => "string=", "query2" => "", "url" => "http://www.myto.com/"), + "alberta.com" => array("engine" => "Telus Network - Alberta.com", "query1" => "string=", "query2" => "", "url" => "http://www.alberta.com/"), + "mybc.com" => array("engine" => "Telus Network - myBC.com", "query1" => "string=", "query2" => "", "url" => "http://www.mybc.com/"), + "monstercrawler." => array("engine" => "MonsterCrawler", "query1" => "qry=", "query2" => "", "url" => "http://www.monstercrawler.com/"), + "allthesites." => array("engine" => "All the Sites", "query1" => "query=", "query2" => "", "url" => "http://www.althesites.com/"), + "suche.web" => array("engine" => "Web.de", "query1" => "su=", "query2" => "", "url" => "http://www.web.de/"), + "rediff." => array("engine" => "reDiff", "query1" => "MT=", "query2" => "", "url" => "http://www.rediff.com/"), + "evreka." => array("engine" => "Evreka", "query1" => "q=", "query2" => "", "url" => "http://evreka.suomi24.fi/"), + "findia." => array("engine" => "Findia", "query1" => "query=", "query2" => "", "url" => "http://www.findia.net/"), + "av.yahoo" => array("engine" => "Yahoo", "query1" => "p=", "query2" => "", "url" => "http://www.yahoo.com/"), + "google.yahoo" => array("engine" => "Yahoo", "query1" => "p=", "query2" => "", "url" => "http://www.yahoo.com/"), + "yahoo." => array("engine" => "Yahoo", "query1" => "q=", "query2" => "", "url" => "http://www.yahoo.com/"), + "aol." => array("engine" => "AOL Search", "query1" => "query=", "query2" => "", "url" => "http://search.aol.com/"), + "about." => array("engine" => "About", "query1" => "terms=", "query2" => "", "url" => "http://www.about.com/"), + "altavista." => array("engine" => "Altavista", "query1" => "q=", "query2" => "", "url" => "http://www.altavista.com/"), + "directhit." => array("engine" => "DirectHit", "query1" => "qry=", "query2" => "", "url" => "http://www.directhit.com/"), + "lk=webcrawler" => array("engine" => "Webcrawler", "query1" => "s=", "query2" => "", "url" => "http://www.webcrawler.com/"), + "excite." => array("engine" => "Excite", "query1" => "search=", "query2" => "", "url" => "http://www.excite.com/"), + "alltheweb." => array("engine" => "All the Web", "query1" => "query=", "query2" => "q=", "url" => "http://www.alltheweb.com/"), + "netscape." => array("engine" => "Netscape", "query1" => "search=", "query2" => "", "url" => "http://search.netscape.com/"), + "google." => array("engine" => "Google", "query1" => "q=", "query2" => "query=", "url" => "http://www.google.com/"), + "?partner=go_home" => array("engine" => "Infoseek/Go", "query1" => "Keywords=", "query2" => "", "url" => "http://www.go.com/"), + "nbci." => array("engine" => "NBCi", "query1" => "Keywords=", "query2" => "", "url" => "http://www.nbci.com/"), + "goto." => array("engine" => "GoTo", "query1" => "Keywords=", "query2" => "", "url" => "http://www.goto.com/"), + "hotbot." => array("engine" => "HotBot", "query1" => "MT=", "query2" => "", "url" => "http://hotbot.lycos.com/"), + "iwon." => array("engine" => "IWon", "query1" => "searchfor=", "query2" => "", "url" => "http://home.iwon.com/index_gen.html"), + "looksmart." => array("engine" => "Looksmart", "query1" => "key=", "query2" => "", "url" => "http://www.looksmart.com/"), + "lycos." => array("engine" => "Lycos", "query1" => "query=", "query2" => "", "url" => "http://www.lycos.com/"), + "msn." => array("engine" => "MSN", "query1" => "q=", "query2" => "", "url" => "http://search.msn.com/"), + "dmoz." => array("engine" => "Dmoz", "query1" => "search=", "query2" => "", "url" => "http://www.dmoz.org/"), - ); + ); /** * parseSearchQuery(url) @@ -75,7 +77,8 @@ class SearchEngines { * @returns array engine, engine_url, query * @public */ - function parseSearchQuery($url) { + function parseSearchQuery($url) + { // test local referrers if (DEBUG & _DEBUG_REMOTE) { $this->searchEngines[strtolower(SERVER_URL)] = array("engine" => "DEBUG", "query1" => "s=", "query2" => "", "url" => SCRIPT_NAME); @@ -83,12 +86,12 @@ class SearchEngines { } $url = strtolower($url); $ref = $url; - while (list($key,$var) = @each($this->searchEngines)) { + while (list($key, $var) = @each($this->searchEngines)) { if (strstr($ref, $key)) { unset($ref); $ref["engine"] = $var["engine"]; - $query1 = $var["query1"]; - $query2 = $var["query2"]; + $query1 = $var["query1"]; + $query2 = $var["query2"]; $ref["engine_url"] = $var["url"]; break; } @@ -101,9 +104,8 @@ class SearchEngines { if (!empty($url["query"])) $url = $url["query"]; if ($query1 and @stristr($url, $query1)) { - $query = @explode($query1, $url); - } - else if ($query2 and @stristr($url, $query2)) { + $query = @explode($query1, $url); + } else if ($query2 and @stristr($url, $query2)) { $query = explode($query2, $url); } if (!empty($query)) { diff --git a/lib/FileFinder.php b/lib/FileFinder.php index 8aa879e49..b6924aae1 100644 --- a/lib/FileFinder.php +++ b/lib/FileFinder.php @@ -1,6 +1,6 @@ _pathsep = $this->_get_syspath_separator(); if (!isset($this->_path) and $path === false) $path = $this->_get_include_path(); @@ -33,12 +34,12 @@ class FileFinder * @param $file string File to search for. * @return string The filename (including path), if found, otherwise false. */ - function findFile ($file, $missing_okay = false) { + function findFile($file, $missing_okay = false) + { if ($this->_is_abs($file)) { if (file_exists($file)) return $file; - } - elseif ( ($dir = $this->_search_path($file)) ) { + } elseif (($dir = $this->_search_path($file))) { return $dir . $this->_use_path_separator($dir) . $file; } return $missing_okay ? false : $this->_not_found($file); @@ -49,17 +50,21 @@ class FileFinder * Accepts array of paths also. * This might not work on Windows95 or FAT volumes. (not tested) */ - function slashifyPath ($path) { + function slashifyPath($path) + { return $this->forcePathSlashes($path, $this->_pathsep); } /** * Force using '/' as path seperator. */ - function forcePathSlashes ($path, $sep='/') { + function forcePathSlashes($path, $sep = '/') + { if (is_array($path)) { $result = array(); - foreach ($path as $dir) { $result[] = $this->forcePathSlashes($dir,$sep); } + foreach ($path as $dir) { + $result[] = $this->forcePathSlashes($dir, $sep); + } return $result; } else { if (isWindows() or $this->_isOtherPathsep()) { @@ -67,10 +72,10 @@ class FileFinder else $from = "\\"; // PHP is stupid enough to use \\ instead of \ if (isWindows()) { - if (substr($path,0,2) != '\\\\') - $path = str_replace('\\\\','\\',$path); + if (substr($path, 0, 2) != '\\\\') + $path = str_replace('\\\\', '\\', $path); else // UNC paths - $path = '\\\\' . str_replace('\\\\','\\',substr($path,2)); + $path = '\\\\' . str_replace('\\\\', '\\', substr($path, 2)); } return strtr($path, $from, $sep); } else @@ -88,12 +93,13 @@ class FileFinder * @param $file string File to include. * @return bool True if file was successfully included. */ - function includeOnce ($file) { - if ( ($ret = @include_once($file)) ) + function includeOnce($file) + { + if (($ret = @include_once($file))) return $ret; if (!$this->_is_abs($file)) { - if ( ($dir = $this->_search_path($file)) && is_file($dir . $this->_pathsep . $file)) { + if (($dir = $this->_search_path($file)) && is_file($dir . $this->_pathsep . $file)) { $this->_append_to_include_path($dir); return include_once($file); } @@ -101,7 +107,8 @@ class FileFinder return $this->_not_found($file); } - function _isOtherPathsep() { + function _isOtherPathsep() + { return $this->_pathsep != '/'; } @@ -114,10 +121,11 @@ class FileFinder * @access private * @return string path_separator. */ - function _get_syspath_separator () { + function _get_syspath_separator() + { if (!empty($this->_pathsep)) return $this->_pathsep; elseif (isWindowsNT()) return "/"; // we can safely use '/' - elseif (isWindows()) return "\\"; // FAT might use '\' + elseif (isWindows()) return "\\"; // FAT might use '\' // VMS or LispM is really weird, we ignore it. else return '/'; } @@ -134,10 +142,11 @@ class FileFinder * @access private * @return string path_separator. */ - function _use_path_separator ($path) { + function _use_path_separator($path) + { if (isWindows95()) { if (empty($path)) return "\\"; - else return (strchr($path,"\\")) ? "\\" : '/'; + else return (strchr($path, "\\")) ? "\\" : '/'; } else { return $this->_get_syspath_separator(); } @@ -150,12 +159,13 @@ class FileFinder * @param $path string Path. * @return bool True if path is absolute. */ - function _is_abs($path) { - if (substr($path,0,1) == '/') { + function _is_abs($path) + { + if (substr($path, 0, 1) == '/') { return true; } elseif (isWindows() and preg_match("/^[a-z]:/i", $path) - and (substr($path,2,1) == "/" or substr($path,2,1) == "\\")) - { + and (substr($path, 2, 1) == "/" or substr($path, 2, 1) == "\\") + ) { return true; } else { return false; @@ -169,9 +179,10 @@ class FileFinder * @param $path string Path. * @return bool New path (destructive) */ - function _strip_last_pathchar(&$path) { - if (substr($path,-1) == '/' or substr($path,-1) == "\\") - $path = substr($path,0,-1); + function _strip_last_pathchar(&$path) + { + if (substr($path, -1) == '/' or substr($path, -1) == "\\") + $path = substr($path, 0, -1); return $path; } @@ -182,7 +193,8 @@ class FileFinder * @param $file string Name of missing file. * @return bool false. */ - function _not_found($file) { + function _not_found($file) + { if (function_exists("_")) trigger_error(sprintf(_("%s: file not found"), $file), E_USER_ERROR); else @@ -199,7 +211,8 @@ class FileFinder * @return string Directory which contains $file, or false. * [5x,44ms] */ - function _search_path ($file) { + function _search_path($file) + { foreach ($this->_path as $dir) { // ensure we use the same pathsep if ($this->_isOtherPathsep()) { @@ -208,7 +221,7 @@ class FileFinder if (file_exists($dir . $this->_pathsep . $file)) return $dir; } elseif (@file_exists($dir . $this->_pathsep . $file)) - return $dir; + return $dir; } return false; } @@ -222,7 +235,8 @@ class FileFinder * @access private * @return string path_separator. */ - function _get_ini_separator () { + function _get_ini_separator() + { return isWindows() ? ';' : ':'; // return preg_match('/^Windows/', php_uname()) } @@ -233,7 +247,8 @@ class FileFinder * @access private * @return array Include path. */ - function _get_include_path() { + function _get_include_path() + { if (defined("INCLUDE_PATH")) $path = INCLUDE_PATH; else { @@ -254,7 +269,8 @@ class FileFinder * @access private * @param $dir string Directory to add. */ - function _append_to_include_path ($dir) { + function _append_to_include_path($dir) + { $dir = $this->slashifyPath($dir); if (!in_array($dir, $this->_path)) { $this->_path[] = $dir; @@ -282,7 +298,8 @@ class FileFinder * @access private * @param $dir string Directory to add. */ - function _prepend_to_include_path ($dir) { + function _prepend_to_include_path($dir) + { $dir = $this->slashifyPath($dir); // remove duplicates if ($i = array_search($dir, $this->_path) !== false) { @@ -297,11 +314,12 @@ class FileFinder // Most specific first. // de_DE.iso8859-1@euro => de_DE.iso8859-1, de_DE, de // This code might needed somewhere else also. - function locale_versions ($lang) { + function locale_versions($lang) + { // Try less specific versions of the locale $langs[] = $lang; foreach (array('@', '.', '_') as $sep) { - if ( ($tail = strchr($lang, $sep)) ) + if (($tail = strchr($lang, $sep))) $langs[] = substr($lang, 0, -strlen($tail)); } return $langs; @@ -310,10 +328,11 @@ class FileFinder /** * Try to figure out the appropriate value for $LANG. * - *@access private - *@return string The value of $LANG. + * @access private + * @return string The value of $LANG. */ - function _get_lang() { + function _get_lang() + { if (!empty($GLOBALS['LANG'])) return $GLOBALS['LANG']; @@ -361,20 +380,21 @@ class PearFileFinder * A good set of defaults is provided, so you can probably leave * this parameter blank. */ - function PearFileFinder ($path = array()) { + function PearFileFinder($path = array()) + { $this->FileFinder(array_merge( - $path, - array('/usr/share/php4', - '/usr/share/php', - '/usr/lib/php4', - '/usr/lib/php', - '/usr/local/share/php4', - '/usr/local/share/php', - '/usr/local/lib/php4', - '/usr/local/lib/php', - '/System/Library/PHP', - '/Apache/pear' // Windows - ))); + $path, + array('/usr/share/php4', + '/usr/share/php', + '/usr/lib/php4', + '/usr/lib/php', + '/usr/local/share/php4', + '/usr/local/share/php', + '/usr/local/lib/php4', + '/usr/local/lib/php', + '/System/Library/PHP', + '/Apache/pear' // Windows + ))); } } @@ -390,12 +410,13 @@ class PearFileFinder * "de_DE.iso8859-1", "de_DE" and "de". */ class LocalizedFileFinder -extends FileFinder + extends FileFinder { /** * Constructor. */ - function LocalizedFileFinder () { + function LocalizedFileFinder() + { $this->_pathsep = $this->_get_syspath_separator(); $include_path = $this->_get_include_path(); $path = array(); @@ -427,12 +448,13 @@ extends FileFinder * "de_DE.iso8859-1", "de_DE" and "de". */ class LocalizedButtonFinder -extends FileFinder + extends FileFinder { /** * Constructor. */ - function LocalizedButtonFinder () { + function LocalizedButtonFinder() + { global $WikiTheme; $this->_pathsep = $this->_get_syspath_separator(); $include_path = $this->_get_include_path(); @@ -457,19 +479,19 @@ extends FileFinder } // Search PHP's include_path to find file or directory. -function FindFile ($file, $missing_okay = false, $slashify = false) +function FindFile($file, $missing_okay = false, $slashify = false) { static $finder; if (!isset($finder)) { $finder = new FileFinder; // remove "/lib" from dirname(__FILE__) - $wikidir = preg_replace('/.lib$/','',dirname(__FILE__)); + $wikidir = preg_replace('/.lib$/', '', dirname(__FILE__)); // let the system favor its local pear? - $finder->_append_to_include_path(dirname(__FILE__)."/pear"); + $finder->_append_to_include_path(dirname(__FILE__) . "/pear"); $finder->_prepend_to_include_path($wikidir); // Don't override existing INCLUDE_PATH config. if (!defined("INCLUDE_PATH")) - define("INCLUDE_PATH", implode($finder->_get_ini_separator(), $finder->_path)); + define("INCLUDE_PATH", implode($finder->_get_ini_separator(), $finder->_path)); } $s = $finder->findFile($file, $missing_okay); if ($slashify) @@ -479,7 +501,7 @@ function FindFile ($file, $missing_okay = false, $slashify = false) // Search PHP's include_path to find file or directory. // Searches for "locale/$LANG/$file", then for "$file". -function FindLocalizedFile ($file, $missing_okay = false, $re_init = false) +function FindLocalizedFile($file, $missing_okay = false, $re_init = false) { static $finder; if ($re_init or !isset($finder)) @@ -487,7 +509,7 @@ function FindLocalizedFile ($file, $missing_okay = false, $re_init = false) return $finder->findFile($file, $missing_okay); } -function FindLocalizedButtonFile ($file, $missing_okay = false, $re_init = false) +function FindLocalizedButtonFile($file, $missing_okay = false, $re_init = false) { static $buttonfinder; if ($re_init or !isset($buttonfinder)) @@ -504,7 +526,8 @@ function FindLocalizedButtonFile ($file, $missing_okay = false, $re_init = false * * NormalizeLocalFileName("lib/config.php") => /home/user/phpwiki/lib/config.php */ -function NormalizeLocalFileName($file) { +function NormalizeLocalFileName($file) +{ static $finder; if (!isset($finder)) { $finder = new FileFinder; @@ -514,7 +537,7 @@ function NormalizeLocalFileName($file) { return $finder->slashifyPath($file); else { if (defined("PHPWIKI_DIR")) $wikidir = PHPWIKI_DIR; - else $wikidir = preg_replace('/.lib$/','',dirname(__FILE__)); + else $wikidir = preg_replace('/.lib$/', '', dirname(__FILE__)); $wikidir = $finder->_strip_last_pathchar($wikidir); $pathsep = $finder->_use_path_separator($wikidir); return $finder->slashifyPath($wikidir . $pathsep . $file); @@ -525,7 +548,8 @@ function NormalizeLocalFileName($file) { /** * Prefixes with DATA_PATH and slashify */ -function NormalizeWebFileName($file) { +function NormalizeWebFileName($file) +{ static $finder; if (!isset($finder)) { $finder = new FileFinder; @@ -542,22 +566,25 @@ function NormalizeWebFileName($file) { } } -function isWindows() { +function isWindows() +{ static $win; if (isset($win)) return $win; //return preg_match('/^Windows/', php_uname()); - $win = (substr(PHP_OS,0,3) == 'WIN'); + $win = (substr(PHP_OS, 0, 3) == 'WIN'); return $win; } -function isWindows95() { +function isWindows95() +{ static $win95; if (isset($win95)) return $win95; $win95 = isWindows() and !isWindowsNT(); return $win95; } -function isWindowsNT() { +function isWindowsNT() +{ static $winnt; if (isset($winnt)) return $winnt; // FIXME: Do this using PHP_OS instead of php_uname(). @@ -565,7 +592,7 @@ function isWindowsNT() { if (function_usable('php_uname')) $winnt = preg_match('/^Windows NT/', php_uname()); else - $winnt = false; // FIXME: punt. + $winnt = false; // FIXME: punt. return $winnt; } diff --git a/lib/Google.php b/lib/Google.php index 701485eb6..80aa5aa16 100644 --- a/lib/Google.php +++ b/lib/Google.php @@ -84,16 +84,19 @@ * server time to return the search results, measured in seconds. */ -class GoogleSearchResults { +class GoogleSearchResults +{ var $_fields = "documentFiltering,searchComments,estimatedTotalResultsCount,estimateIsExact,searchQuery,startIndex,endIndex,searchTips,directoryCategories,searchTime,resultElements"; var $resultElements, $results; - function GoogleSearchResults ($result) { - $this->fields = explode(',',$this->_fields); + function GoogleSearchResults($result) + { + $this->fields = explode(',', $this->_fields); foreach ($this->fields as $f) { $this->{$f} = $result[$f]; } - $i = 0; $this->results = array(); + $i = 0; + $this->results = array(); //$this->resultElements = $result['resultElements']; foreach ($this->resultElements as $r) { $this->results[] = new GoogleSearchResult($r); @@ -140,10 +143,13 @@ class GoogleSearchResults { * appears here as a text string. Note that the directoryTitle may * be different from the URL's . */ -class GoogleSearchResult { +class GoogleSearchResult +{ var $_fields = "summary,URL,snippet,title,cachedSize,relatedInformationPresent,hostName,directoryCategory,directoryTitle"; - function GoogleSearchResult ($result) { - $this->fields = explode(',',$this->_fields); + + function GoogleSearchResult($result) + { + $this->fields = explode(',', $this->_fields); foreach ($this->fields as $f) { $this->{$f} = $result[$f]; } @@ -151,18 +157,19 @@ class GoogleSearchResult { } } -class Google { +class Google +{ - function Google($maxResults=10,$license_key=false,$proxy=false) { + function Google($maxResults = 10, $license_key = false, $proxy = false) + { if ($license_key) $this->license_key = $license_key; elseif (!defined('GOOGLE_LICENSE_KEY')) { trigger_error("\nYou must first obtain a license key at http://www.google.com/apis/" - ."\nto be able to use the Google API.". - "\nIt's free however.", E_USER_WARNING); + . "\nto be able to use the Google API." . + "\nIt's free however.", E_USER_WARNING); return false; - } - else + } else $this->license_key = GOOGLE_LICENSE_KEY; require_once 'lib/nusoap/nusoap.php'; @@ -217,22 +224,23 @@ class Google { * ignored. All requests to the APIs should be made with UTF-8 * encoding. */ - function doGoogleSearch($query, $startIndex=1, $maxResults=10, $filter = "false", - $restrict='', $safeSearch='false', $lr='', - $inputencoding='UTF-8', $outputencoding='UTF-8') { + function doGoogleSearch($query, $startIndex = 1, $maxResults = 10, $filter = "false", + $restrict = '', $safeSearch = 'false', $lr = '', + $inputencoding = 'UTF-8', $outputencoding = 'UTF-8') + { if (!$this->license_key) return false; // doGoogleSearch() gets created automatically!! (some eval'ed code from the soap request) $result = $this->proxy->doGoogleSearch($this->license_key, // "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", - $query, - $startIndex, - $maxResults, - $filter, - $restrict, - $safeSearch, - $lr, - $inputencoding, // ignored by server, everything is UTF-8 now - $outputencoding); + $query, + $startIndex, + $maxResults, + $filter, + $restrict, + $safeSearch, + $lr, + $inputencoding, // ignored by server, everything is UTF-8 now + $outputencoding); return new GoogleSearchResults($result); } @@ -248,15 +256,16 @@ class Google { * * The return type for cached pages is base64 encoded text. * - * @params string url - full URL to the page to retrieve - * @return string full text of the cached page + * @params string url - full URL to the page to retrieve + * @return string full text of the cached page */ - function doGetCachedPage($url) { + function doGetCachedPage($url) + { if (!$this->license_key) return false; // This method gets created automatically!! (some eval'ed code from the soap request) $result = $this->proxy->doGetCachedPage($this->license_key, - $url); + $url); if (!empty($result)) return base64_decode($result); } @@ -266,12 +275,13 @@ class Google { * @param string phrase word or phrase to spell-check * @return string text of any suggested replacement, or None */ - function doSpellingSuggestion($phrase) { + function doSpellingSuggestion($phrase) + { if (!$this->license_key) return false; // This method gets created automatically!! (some eval'ed code from the soap request) return $this->proxy->doSpellingSuggestion($this->license_key, - $phrase); + $phrase); } } diff --git a/lib/HtmlElement.php b/lib/HtmlElement.php index 94e0e3bb7..0eee84395 100644 --- a/lib/HtmlElement.php +++ b/lib/HtmlElement.php @@ -10,7 +10,7 @@ * HTML::div(array('onClick' => 'HTML::div(...)')) */ if (!class_exists("XmlElement")) - require_once(dirname(__FILE__)."/XmlElement.php"); + require_once(dirname(__FILE__) . "/XmlElement.php"); if (class_exists("HtmlElement")) return; @@ -21,12 +21,14 @@ if (class_exists("HtmlElement")) class HtmlElement extends XmlElement { - function __construct ($tagname /* , $attr_or_content , ...*/) { + function __construct($tagname /* , $attr_or_content , ...*/) + { $this->_init(func_get_args()); $this->_properties = HTML::getTagProperties($tagname); } - function _init ($args) { + function _init($args) + { if (!is_array($args)) $args = func_get_args(); @@ -49,7 +51,8 @@ class HtmlElement extends XmlElement * @access protected * This is used by the static factory methods is class HTML. */ - function _init2 ($args) { + function _init2($args) + { if ($args) { if (is_array($args[0])) $this->_attr = array_shift($args); @@ -67,72 +70,83 @@ class HtmlElement extends XmlElement * * @param $tooltip_text string The tooltip text. */ - function addTooltip ($tooltip_text, $accesskey = null) { + function addTooltip($tooltip_text, $accesskey = null) + { $this->setAttr('title', $tooltip_text); - if ($accesskey) $this->setAccesskey($accesskey); + if ($accesskey) $this->setAccesskey($accesskey); // FIXME: this should be initialized from title by an onLoad() function. // (though, that may not be possible.) $qtooltip = str_replace("'", "\\'", $tooltip_text); $this->setAttr('onmouseover', - sprintf('window.status="%s"; return true;', - addslashes($tooltip_text))); + sprintf('window.status="%s"; return true;', + addslashes($tooltip_text))); $this->setAttr('onmouseout', "window.status='';return true;"); } - function setAccesskey ($key) { - global $WikiTheme; - if (strlen($key) != 1) return; - $this->setAttr("accesskey", $key); + function setAccesskey($key) + { + global $WikiTheme; + if (strlen($key) != 1) return; + $this->setAttr("accesskey", $key); if (!empty($this->_attr['title'])) { - if (preg_match("/\[(alt-)?(.)\]$/", $this->_attr['title'], $m)) - { - $this->_attr['title'] = preg_replace - ("/\[(alt-)?(.)\]$/", - "[".$WikiTheme->tooltipAccessKeyPrefix()."-\\2]", - $this->_attr['title']); - } else { - $this->_attr['title'] .= - " [".$WikiTheme->tooltipAccessKeyPrefix()."-$key]"; + if (preg_match("/\[(alt-)?(.)\]$/", $this->_attr['title'], $m)) { + $this->_attr['title'] = preg_replace + ("/\[(alt-)?(.)\]$/", + "[" . $WikiTheme->tooltipAccessKeyPrefix() . "-\\2]", + $this->_attr['title']); + } else { + $this->_attr['title'] .= + " [" . $WikiTheme->tooltipAccessKeyPrefix() . "-$key]"; + } + } else { + $this->_attr['title'] = + "[" . $WikiTheme->tooltipAccessKeyPrefix() . "-$key]"; } - } else { - $this->_attr['title'] = - "[".$WikiTheme->tooltipAccessKeyPrefix()."-$key]"; - } } - function emptyTag () { + function emptyTag() + { if (($this->_properties & HTMLTAG_EMPTY) == 0) return $this->startTag() . "</$this->_tag>"; return substr($this->startTag(), 0, -1) . " />"; } - function hasInlineContent () { + function hasInlineContent() + { return ($this->_properties & HTMLTAG_ACCEPTS_INLINE) != 0; } - function isInlineElement () { + function isInlineElement() + { return ($this->_properties & HTMLTAG_INLINE) != 0; } -}; +} -function HTML (/* $content, ... */) { +; + +function HTML( /* $content, ... */) +{ return new XmlContent(func_get_args()); } -class HTML extends HtmlElement { - function raw ($html_text) { +class HTML extends HtmlElement +{ + function raw($html_text) + { return new RawXml($html_text); } - function getTagProperties($tag) { + function getTagProperties($tag) + { $props = &$GLOBALS['HTML_TagProperties']; return isset($props[$tag]) ? $props[$tag] : 0; } - function _setTagProperty($prop_flag, $tags) { + function _setTagProperty($prop_flag, $tags) + { $props = &$GLOBALS['HTML_TagProperties']; if (is_string($tags)) $tags = preg_split('/\s+/', $tags); @@ -148,271 +162,384 @@ class HTML extends HtmlElement { // See admin/mkfuncs shell script to generate the following static methods - function link (/*...*/) { + function link( /*...*/) + { $el = new HtmlElement('link'); return $el->_init2(func_get_args()); } - function meta (/*...*/) { + + function meta( /*...*/) + { $el = new HtmlElement('meta'); return $el->_init2(func_get_args()); } - function style (/*...*/) { + + function style( /*...*/) + { $el = new HtmlElement('style'); return $el->_init2(func_get_args()); } - function script (/*...*/) { + + function script( /*...*/) + { $el = new HtmlElement('script'); return $el->_init2(func_get_args()); } - function noscript (/*...*/) { + + function noscript( /*...*/) + { $el = new HtmlElement('noscript'); return $el->_init2(func_get_args()); } /****************************************/ - function a (/*...*/) { + function a( /*...*/) + { $el = new HtmlElement('a'); return $el->_init2(func_get_args()); } - function img (/*...*/) { + + function img( /*...*/) + { $el = new HtmlElement('img'); return $el->_init2(func_get_args()); } - function br (/*...*/) { + + function br( /*...*/) + { $el = new HtmlElement('br'); return $el->_init2(func_get_args()); } - function span (/*...*/) { + + function span( /*...*/) + { $el = new HtmlElement('span'); return $el->_init2(func_get_args()); } /****************************************/ - function h1 (/*...*/) { + function h1( /*...*/) + { $el = new HtmlElement('h1'); return $el->_init2(func_get_args()); } - function h2 (/*...*/) { + + function h2( /*...*/) + { $el = new HtmlElement('h2'); return $el->_init2(func_get_args()); } - function h3 (/*...*/) { + + function h3( /*...*/) + { $el = new HtmlElement('h3'); return $el->_init2(func_get_args()); } - function h4 (/*...*/) { + + function h4( /*...*/) + { $el = new HtmlElement('h4'); return $el->_init2(func_get_args()); } - function h5 (/*...*/) { + + function h5( /*...*/) + { $el = new HtmlElement('h5'); return $el->_init2(func_get_args()); } - function h6 (/*...*/) { + + function h6( /*...*/) + { $el = new HtmlElement('h6'); return $el->_init2(func_get_args()); } /****************************************/ - function hr (/*...*/) { + function hr( /*...*/) + { $el = new HtmlElement('hr'); return $el->_init2(func_get_args()); } - function div (/*...*/) { + + function div( /*...*/) + { $el = new HtmlElement('div'); return $el->_init2(func_get_args()); } - function p (/*...*/) { + + function p( /*...*/) + { $el = new HtmlElement('p'); return $el->_init2(func_get_args()); } - function pre (/*...*/) { + + function pre( /*...*/) + { $el = new HtmlElement('pre'); return $el->_init2(func_get_args()); } - function blockquote (/*...*/) { + + function blockquote( /*...*/) + { $el = new HtmlElement('blockquote'); return $el->_init2(func_get_args()); } /****************************************/ - function em (/*...*/) { + function em( /*...*/) + { $el = new HtmlElement('em'); return $el->_init2(func_get_args()); } - function strong (/*...*/) { + + function strong( /*...*/) + { $el = new HtmlElement('strong'); return $el->_init2(func_get_args()); } - function small (/*...*/) { + + function small( /*...*/) + { $el = new HtmlElement('small'); return $el->_init2(func_get_args()); } /****************************************/ - function tt (/*...*/) { + function tt( /*...*/) + { $el = new HtmlElement('tt'); return $el->_init2(func_get_args()); } - function u (/*...*/) { + + function u( /*...*/) + { $el = new HtmlElement('u'); return $el->_init2(func_get_args()); } - function sup (/*...*/) { + + function sup( /*...*/) + { $el = new HtmlElement('sup'); return $el->_init2(func_get_args()); } - function sub (/*...*/) { + + function sub( /*...*/) + { $el = new HtmlElement('sub'); return $el->_init2(func_get_args()); } /****************************************/ - function ul (/*...*/) { + function ul( /*...*/) + { $el = new HtmlElement('ul'); return $el->_init2(func_get_args()); } - function ol (/*...*/) { + + function ol( /*...*/) + { $el = new HtmlElement('ol'); return $el->_init2(func_get_args()); } - function dl (/*...*/) { + + function dl( /*...*/) + { $el = new HtmlElement('dl'); return $el->_init2(func_get_args()); } - function li (/*...*/) { + + function li( /*...*/) + { $el = new HtmlElement('li'); return $el->_init2(func_get_args()); } - function dt (/*...*/) { + + function dt( /*...*/) + { $el = new HtmlElement('dt'); return $el->_init2(func_get_args()); } - function dd (/*...*/) { + + function dd( /*...*/) + { $el = new HtmlElement('dd'); return $el->_init2(func_get_args()); } /****************************************/ - function table (/*...*/) { + function table( /*...*/) + { $el = new HtmlElement('table'); return $el->_init2(func_get_args()); } - function caption (/*...*/) { + + function caption( /*...*/) + { $el = new HtmlElement('caption'); return $el->_init2(func_get_args()); } - function thead (/*...*/) { + + function thead( /*...*/) + { $el = new HtmlElement('thead'); return $el->_init2(func_get_args()); } - function tbody (/*...*/) { + + function tbody( /*...*/) + { $el = new HtmlElement('tbody'); return $el->_init2(func_get_args()); } - function tfoot (/*...*/) { + + function tfoot( /*...*/) + { $el = new HtmlElement('tfoot'); return $el->_init2(func_get_args()); } - function tr (/*...*/) { + + function tr( /*...*/) + { $el = new HtmlElement('tr'); return $el->_init2(func_get_args()); } - function td (/*...*/) { + + function td( /*...*/) + { $el = new HtmlElement('td'); return $el->_init2(func_get_args()); } - function th (/*...*/) { + + function th( /*...*/) + { $el = new HtmlElement('th'); return $el->_init2(func_get_args()); } - function colgroup (/*...*/) { + + function colgroup( /*...*/) + { $el = new HtmlElement('colgroup'); return $el->_init2(func_get_args()); } - function col (/*...*/) { + + function col( /*...*/) + { $el = new HtmlElement('col'); return $el->_init2(func_get_args()); } /****************************************/ - function form (/*...*/) { + function form( /*...*/) + { $el = new HtmlElement('form'); return $el->_init2(func_get_args()); } - function input (/*...*/) { + + function input( /*...*/) + { $el = new HtmlElement('input'); return $el->_init2(func_get_args()); } - function button (/*...*/) { + + function button( /*...*/) + { $el = new HtmlElement('button'); return $el->_init2(func_get_args()); } - function option (/*...*/) { + + function option( /*...*/) + { $el = new HtmlElement('option'); return $el->_init2(func_get_args()); } - function select (/*...*/) { + + function select( /*...*/) + { $el = new HtmlElement('select'); return $el->_init2(func_get_args()); } - function textarea (/*...*/) { + + function textarea( /*...*/) + { $el = new HtmlElement('textarea'); return $el->_init2(func_get_args()); } - function label (/*...*/) { + + function label( /*...*/) + { $el = new HtmlElement('label'); return $el->_init2(func_get_args()); } /****************************************/ - function area (/*...*/) { + function area( /*...*/) + { $el = new HtmlElement('area'); return $el->_init2(func_get_args()); } - function map (/*...*/) { + + function map( /*...*/) + { $el = new HtmlElement('map'); return $el->_init2(func_get_args()); } - function frame (/*...*/) { + + function frame( /*...*/) + { $el = new HtmlElement('frame'); return $el->_init2(func_get_args()); } - function frameset (/*...*/) { + + function frameset( /*...*/) + { $el = new HtmlElement('frameset'); return $el->_init2(func_get_args()); } - function iframe (/*...*/) { + + function iframe( /*...*/) + { $el = new HtmlElement('iframe'); return $el->_init2(func_get_args()); } - function nobody (/*...*/) { + + function nobody( /*...*/) + { $el = new HtmlElement('nobody'); return $el->_init2(func_get_args()); } - function object (/*...*/) { + + function object( /*...*/) + { $el = new HtmlElement('object'); return $el->_init2(func_get_args()); } - function embed (/*...*/) { + + function embed( /*...*/) + { $el = new HtmlElement('embed'); return $el->_init2(func_get_args()); } - function param (/*...*/) { + + function param( /*...*/) + { $el = new HtmlElement('param'); return $el->_init2(func_get_args()); } - function fieldset (/*...*/) { + + function fieldset( /*...*/) + { $el = new HtmlElement('fieldset'); return $el->_init2(func_get_args()); } - function legend (/*...*/) { + + function legend( /*...*/) + { $el = new HtmlElement('legend'); return $el->_init2(func_get_args()); } /****************************************/ - function video (/*...*/) { + function video( /*...*/) + { $el = new HtmlElement('video'); return $el->_init2(func_get_args()); } @@ -423,34 +550,34 @@ define('HTMLTAG_INLINE', 2); define('HTMLTAG_ACCEPTS_INLINE', 4); HTML::_setTagProperty(HTMLTAG_EMPTY, - 'area base basefont br col frame hr img input isindex link meta param'); + 'area base basefont br col frame hr img input isindex link meta param'); HTML::_setTagProperty(HTMLTAG_ACCEPTS_INLINE, - // %inline elements: - 'b big i small tt ' // %fontstyle - . 's strike u ' // (deprecated) - . 'abbr acronym cite code dfn em kbd samp strong var ' //%phrase - . 'a img object embed br script map q sub sup span bdo '//%special - . 'button input label option select textarea label ' //%formctl - - // %block elements which contain inline content - . 'address h1 h2 h3 h4 h5 h6 p pre ' - // %block elements which contain either block or inline content - . 'div fieldset frameset' - - // other with inline content - . 'caption dt label legend video ' - // other with either inline or block - . 'dd del ins li td th colgroup'); + // %inline elements: + 'b big i small tt ' // %fontstyle + . 's strike u ' // (deprecated) + . 'abbr acronym cite code dfn em kbd samp strong var ' //%phrase + . 'a img object embed br script map q sub sup span bdo ' //%special + . 'button input label option select textarea label ' //%formctl + + // %block elements which contain inline content + . 'address h1 h2 h3 h4 h5 h6 p pre ' + // %block elements which contain either block or inline content + . 'div fieldset frameset' + + // other with inline content + . 'caption dt label legend video ' + // other with either inline or block + . 'dd del ins li td th colgroup'); HTML::_setTagProperty(HTMLTAG_INLINE, - // %inline elements: - 'b big i small tt ' // %fontstyle - . 's strike u ' // (deprecated) - . 'abbr acronym cite code dfn em kbd samp strong var ' //%phrase - . 'a img object br script map q sub sup span bdo '//%special - . 'button input label option select textarea ' //%formctl - . 'nobody iframe' - ); + // %inline elements: + 'b big i small tt ' // %fontstyle + . 's strike u ' // (deprecated) + . 'abbr acronym cite code dfn em kbd samp strong var ' //%phrase + . 'a img object br script map q sub sup span bdo ' //%special + . 'button input label option select textarea ' //%formctl + . 'nobody iframe' +); /** * Generate hidden form input fields. @@ -474,7 +601,8 @@ HTML::_setTagProperty(HTMLTAG_INLINE, * * @return object An XmlContent object containing the inputs. */ -function HiddenInputs ($query_args, $pfx = false, $exclude = array()) { +function HiddenInputs($query_args, $pfx = false, $exclude = array()) +{ $inputs = HTML(); foreach ($query_args as $key => $val) { @@ -484,8 +612,8 @@ function HiddenInputs ($query_args, $pfx = false, $exclude = array()) { $inputs->pushContent(HiddenInputs($val, $name)); else $inputs->pushContent(HTML::input(array('type' => 'hidden', - 'name' => $name, - 'value' => $val))); + 'name' => $name, + 'value' => $val))); } return $inputs; } @@ -497,19 +625,20 @@ function HiddenInputs ($query_args, $pfx = false, $exclude = array()) { * e.g. to provide another version or the defer attr * @return HtmlElement A <script> element. */ -function JavaScript ($js, $script_args = false) { - $default_script_args = array(//'version' => 'JavaScript', // not xhtml conformant - 'type' => 'text/javascript'); +function JavaScript($js, $script_args = false) +{ + $default_script_args = array( //'version' => 'JavaScript', // not xhtml conformant + 'type' => 'text/javascript'); $script_args = $script_args ? array_merge($default_script_args, $script_args) - : $default_script_args; + : $default_script_args; if (empty($js)) - return HTML(HTML::script($script_args),"\n"); + return HTML(HTML::script($script_args), "\n"); else // see http://devedge.netscape.com/viewsource/2003/xhtml-style-script/ return HTML(HTML::script($script_args, - new RawXml((ENABLE_XHTML_XML ? "\n//<![CDATA[" : "\n<!--//") - . "\n".trim($js)."\n" - . (ENABLE_XHTML_XML ? "//]]>\n" : "// -->"))),"\n"); + new RawXml((ENABLE_XHTML_XML ? "\n//<![CDATA[" : "\n<!--//") + . "\n" . trim($js) . "\n" + . (ENABLE_XHTML_XML ? "//]]>\n" : "// -->"))), "\n"); } /** Conditionally display content based of whether javascript is supported. @@ -529,12 +658,13 @@ function JavaScript ($js, $script_args = false) { * * @return XmlContent */ -function IfJavaScript($if_content = false, $else_content = false) { +function IfJavaScript($if_content = false, $else_content = false) +{ $html = array(); if ($if_content) { $xml = AsXML($if_content); $js = sprintf('document.write("%s");', - addcslashes($xml, "\0..\37!@\\\177..\377")); + addcslashes($xml, "\0..\37!@\\\177..\377")); $html[] = JavaScript($js); } if ($else_content) { diff --git a/lib/HtmlElement5.php b/lib/HtmlElement5.php index ff320fa64..a4b108184 100644 --- a/lib/HtmlElement5.php +++ b/lib/HtmlElement5.php @@ -10,7 +10,7 @@ * HTML::div(array('onclick' => 'HTML::div(...)')) */ if (!class_exists("XmlElement")) - require_once(dirname(__FILE__)."/XmlElement.php"); + require_once(dirname(__FILE__) . "/XmlElement.php"); if (class_exists("HtmlElement")) return; @@ -21,12 +21,14 @@ if (class_exists("HtmlElement")) class HtmlElement extends XmlElement { - function __construct ($tagname /* , $attr_or_content , ...*/) { + function __construct($tagname /* , $attr_or_content , ...*/) + { $this->_init(func_get_args()); $this->_properties = HTML::getTagProperties($tagname); } - function _init ($args) { + function _init($args) + { if (!is_array($args)) $args = func_get_args(); @@ -49,7 +51,8 @@ class HtmlElement extends XmlElement * @access protected * This is used by the static factory methods is class HTML. */ - function _init2 ($args) { + function _init2($args) + { if ($args) { if (is_array($args[0])) $this->_attr = array_shift($args); @@ -67,72 +70,83 @@ class HtmlElement extends XmlElement * * @param $tooltip_text string The tooltip text. */ - function addTooltip ($tooltip_text, $accesskey = null) { + function addTooltip($tooltip_text, $accesskey = null) + { $this->setAttr('title', $tooltip_text); - if ($accesskey) $this->setAccesskey($accesskey); + if ($accesskey) $this->setAccesskey($accesskey); // FIXME: this should be initialized from title by an onLoad() function. // (though, that may not be possible.) $qtooltip = str_replace("'", "\\'", $tooltip_text); $this->setAttr('onmouseover', - sprintf('window.status="%s"; return true;', - addslashes($tooltip_text))); + sprintf('window.status="%s"; return true;', + addslashes($tooltip_text))); $this->setAttr('onmouseout', "window.status='';return true;"); } - function setAccesskey ($key) { - global $WikiTheme; - if (strlen($key) != 1) return; - $this->setAttr("accesskey", $key); + function setAccesskey($key) + { + global $WikiTheme; + if (strlen($key) != 1) return; + $this->setAttr("accesskey", $key); if (!empty($this->_attr['title'])) { - if (preg_match("/\[(alt-)?(.)\]$/", $this->_attr['title'], $m)) - { - $this->_attr['title'] = preg_replace - ("/\[(alt-)?(.)\]$/", - "[".$WikiTheme->tooltipAccessKeyPrefix()."-\\2]", - $this->_attr['title']); - } else { - $this->_attr['title'] .= - " [".$WikiTheme->tooltipAccessKeyPrefix()."-$key]"; + if (preg_match("/\[(alt-)?(.)\]$/", $this->_attr['title'], $m)) { + $this->_attr['title'] = preg_replace + ("/\[(alt-)?(.)\]$/", + "[" . $WikiTheme->tooltipAccessKeyPrefix() . "-\\2]", + $this->_attr['title']); + } else { + $this->_attr['title'] .= + " [" . $WikiTheme->tooltipAccessKeyPrefix() . "-$key]"; + } + } else { + $this->_attr['title'] = + "[" . $WikiTheme->tooltipAccessKeyPrefix() . "-$key]"; } - } else { - $this->_attr['title'] = - "[".$WikiTheme->tooltipAccessKeyPrefix()."-$key]"; - } } - function emptyTag () { + function emptyTag() + { if (($this->_properties & HTMLTAG_EMPTY) == 0) return $this->startTag() . "</$this->_tag>"; return substr($this->startTag(), 0, -1) . " />"; } - function hasInlineContent () { + function hasInlineContent() + { return ($this->_properties & HTMLTAG_ACCEPTS_INLINE) != 0; } - function isInlineElement () { + function isInlineElement() + { return ($this->_properties & HTMLTAG_INLINE) != 0; } -}; +} -function HTML (/* $content, ... */) { +; + +function HTML( /* $content, ... */) +{ return new XmlContent(func_get_args()); } -class HTML extends HtmlElement { - public static function raw ($html_text) { +class HTML extends HtmlElement +{ + public static function raw($html_text) + { return new RawXml($html_text); } - public static function getTagProperties($tag) { + public static function getTagProperties($tag) + { $props = &$GLOBALS['HTML_TagProperties']; return isset($props[$tag]) ? $props[$tag] : 0; } - public static function _setTagProperty($prop_flag, $tags) { + public static function _setTagProperty($prop_flag, $tags) + { $props = &$GLOBALS['HTML_TagProperties']; if (is_string($tags)) $tags = preg_split('/\s+/', $tags); @@ -148,271 +162,384 @@ class HTML extends HtmlElement { // See admin/mkfuncs shell script to generate the following static methods - public static function link (/*...*/) { + public static function link( /*...*/) + { $el = new HtmlElement('link'); return $el->_init2(func_get_args()); } - public static function meta (/*...*/) { + + public static function meta( /*...*/) + { $el = new HtmlElement('meta'); return $el->_init2(func_get_args()); } - public static function style (/*...*/) { + + public static function style( /*...*/) + { $el = new HtmlElement('style'); return $el->_init2(func_get_args()); } - public static function script (/*...*/) { + + public static function script( /*...*/) + { $el = new HtmlElement('script'); return $el->_init2(func_get_args()); } - public static function noscript (/*...*/) { + + public static function noscript( /*...*/) + { $el = new HtmlElement('noscript'); return $el->_init2(func_get_args()); } /****************************************/ - public static function a (/*...*/) { + public static function a( /*...*/) + { $el = new HtmlElement('a'); return $el->_init2(func_get_args()); } - public static function img (/*...*/) { + + public static function img( /*...*/) + { $el = new HtmlElement('img'); return $el->_init2(func_get_args()); } - public static function br (/*...*/) { + + public static function br( /*...*/) + { $el = new HtmlElement('br'); return $el->_init2(func_get_args()); } - public static function span (/*...*/) { + + public static function span( /*...*/) + { $el = new HtmlElement('span'); return $el->_init2(func_get_args()); } /****************************************/ - public static function h1 (/*...*/) { + public static function h1( /*...*/) + { $el = new HtmlElement('h1'); return $el->_init2(func_get_args()); } - public static function h2 (/*...*/) { + + public static function h2( /*...*/) + { $el = new HtmlElement('h2'); return $el->_init2(func_get_args()); } - public static function h3 (/*...*/) { + + public static function h3( /*...*/) + { $el = new HtmlElement('h3'); return $el->_init2(func_get_args()); } - public static function h4 (/*...*/) { + + public static function h4( /*...*/) + { $el = new HtmlElement('h4'); return $el->_init2(func_get_args()); } - public static function h5 (/*...*/) { + + public static function h5( /*...*/) + { $el = new HtmlElement('h5'); return $el->_init2(func_get_args()); } - public static function h6 (/*...*/) { + + public static function h6( /*...*/) + { $el = new HtmlElement('h6'); return $el->_init2(func_get_args()); } /****************************************/ - public static function hr (/*...*/) { + public static function hr( /*...*/) + { $el = new HtmlElement('hr'); return $el->_init2(func_get_args()); } - public static function div (/*...*/) { + + public static function div( /*...*/) + { $el = new HtmlElement('div'); return $el->_init2(func_get_args()); } - public static function p (/*...*/) { + + public static function p( /*...*/) + { $el = new HtmlElement('p'); return $el->_init2(func_get_args()); } - public static function pre (/*...*/) { + + public static function pre( /*...*/) + { $el = new HtmlElement('pre'); return $el->_init2(func_get_args()); } - public static function blockquote (/*...*/) { + + public static function blockquote( /*...*/) + { $el = new HtmlElement('blockquote'); return $el->_init2(func_get_args()); } /****************************************/ - public static function em (/*...*/) { + public static function em( /*...*/) + { $el = new HtmlElement('em'); return $el->_init2(func_get_args()); } - public static function strong (/*...*/) { + + public static function strong( /*...*/) + { $el = new HtmlElement('strong'); return $el->_init2(func_get_args()); } - public static function small (/*...*/) { + + public static function small( /*...*/) + { $el = new HtmlElement('small'); return $el->_init2(func_get_args()); } /****************************************/ - public static function tt (/*...*/) { + public static function tt( /*...*/) + { $el = new HtmlElement('tt'); return $el->_init2(func_get_args()); } - public static function u (/*...*/) { + + public static function u( /*...*/) + { $el = new HtmlElement('u'); return $el->_init2(func_get_args()); } - public static function sup (/*...*/) { + + public static function sup( /*...*/) + { $el = new HtmlElement('sup'); return $el->_init2(func_get_args()); } - public static function sub (/*...*/) { + + public static function sub( /*...*/) + { $el = new HtmlElement('sub'); return $el->_init2(func_get_args()); } /****************************************/ - public static function ul (/*...*/) { + public static function ul( /*...*/) + { $el = new HtmlElement('ul'); return $el->_init2(func_get_args()); } - public static function ol (/*...*/) { + + public static function ol( /*...*/) + { $el = new HtmlElement('ol'); return $el->_init2(func_get_args()); } - public static function dl (/*...*/) { + + public static function dl( /*...*/) + { $el = new HtmlElement('dl'); return $el->_init2(func_get_args()); } - public static function li (/*...*/) { + + public static function li( /*...*/) + { $el = new HtmlElement('li'); return $el->_init2(func_get_args()); } - public static function dt (/*...*/) { + + public static function dt( /*...*/) + { $el = new HtmlElement('dt'); return $el->_init2(func_get_args()); } - public static function dd (/*...*/) { + + public static function dd( /*...*/) + { $el = new HtmlElement('dd'); return $el->_init2(func_get_args()); } /****************************************/ - public static function table (/*...*/) { + public static function table( /*...*/) + { $el = new HtmlElement('table'); return $el->_init2(func_get_args()); } - public static function caption (/*...*/) { + + public static function caption( /*...*/) + { $el = new HtmlElement('caption'); return $el->_init2(func_get_args()); } - public static function thead (/*...*/) { + + public static function thead( /*...*/) + { $el = new HtmlElement('thead'); return $el->_init2(func_get_args()); } - public static function tbody (/*...*/) { + + public static function tbody( /*...*/) + { $el = new HtmlElement('tbody'); return $el->_init2(func_get_args()); } - public static function tfoot (/*...*/) { + + public static function tfoot( /*...*/) + { $el = new HtmlElement('tfoot'); return $el->_init2(func_get_args()); } - public static function tr (/*...*/) { + + public static function tr( /*...*/) + { $el = new HtmlElement('tr'); return $el->_init2(func_get_args()); } - public static function td (/*...*/) { + + public static function td( /*...*/) + { $el = new HtmlElement('td'); return $el->_init2(func_get_args()); } - public static function th (/*...*/) { + + public static function th( /*...*/) + { $el = new HtmlElement('th'); return $el->_init2(func_get_args()); } - public static function colgroup (/*...*/) { + + public static function colgroup( /*...*/) + { $el = new HtmlElement('colgroup'); return $el->_init2(func_get_args()); } - public static function col (/*...*/) { + + public static function col( /*...*/) + { $el = new HtmlElement('col'); return $el->_init2(func_get_args()); } /****************************************/ - public static function form (/*...*/) { + public static function form( /*...*/) + { $el = new HtmlElement('form'); return $el->_init2(func_get_args()); } - public static function input (/*...*/) { + + public static function input( /*...*/) + { $el = new HtmlElement('input'); return $el->_init2(func_get_args()); } - public static function button (/*...*/) { + + public static function button( /*...*/) + { $el = new HtmlElement('button'); return $el->_init2(func_get_args()); } - public static function option (/*...*/) { + + public static function option( /*...*/) + { $el = new HtmlElement('option'); return $el->_init2(func_get_args()); } - public static function select (/*...*/) { + + public static function select( /*...*/) + { $el = new HtmlElement('select'); return $el->_init2(func_get_args()); } - public static function textarea (/*...*/) { + + public static function textarea( /*...*/) + { $el = new HtmlElement('textarea'); return $el->_init2(func_get_args()); } - public static function label (/*...*/) { + + public static function label( /*...*/) + { $el = new HtmlElement('label'); return $el->_init2(func_get_args()); } /****************************************/ - public static function area (/*...*/) { + public static function area( /*...*/) + { $el = new HtmlElement('area'); return $el->_init2(func_get_args()); } - public static function map (/*...*/) { + + public static function map( /*...*/) + { $el = new HtmlElement('map'); return $el->_init2(func_get_args()); } - public static function frame (/*...*/) { + + public static function frame( /*...*/) + { $el = new HtmlElement('frame'); return $el->_init2(func_get_args()); } - public static function frameset (/*...*/) { + + public static function frameset( /*...*/) + { $el = new HtmlElement('frameset'); return $el->_init2(func_get_args()); } - public static function iframe (/*...*/) { + + public static function iframe( /*...*/) + { $el = new HtmlElement('iframe'); return $el->_init2(func_get_args()); } - public static function nobody (/*...*/) { + + public static function nobody( /*...*/) + { $el = new HtmlElement('nobody'); return $el->_init2(func_get_args()); } - public static function object (/*...*/) { + + public static function object( /*...*/) + { $el = new HtmlElement('object'); return $el->_init2(func_get_args()); } - public static function embed (/*...*/) { + + public static function embed( /*...*/) + { $el = new HtmlElement('embed'); return $el->_init2(func_get_args()); } - public static function param (/*...*/) { + + public static function param( /*...*/) + { $el = new HtmlElement('param'); return $el->_init2(func_get_args()); } - public static function fieldset (/*...*/) { + + public static function fieldset( /*...*/) + { $el = new HtmlElement('fieldset'); return $el->_init2(func_get_args()); } - public static function legend (/*...*/) { + + public static function legend( /*...*/) + { $el = new HtmlElement('legend'); return $el->_init2(func_get_args()); } /****************************************/ - public static function video (/*...*/) { + public static function video( /*...*/) + { $el = new HtmlElement('video'); return $el->_init2(func_get_args()); } @@ -423,34 +550,34 @@ define('HTMLTAG_INLINE', 2); define('HTMLTAG_ACCEPTS_INLINE', 4); HTML::_setTagProperty(HTMLTAG_EMPTY, - 'area base basefont br col embed frame hr img input isindex link meta param'); + 'area base basefont br col embed frame hr img input isindex link meta param'); HTML::_setTagProperty(HTMLTAG_ACCEPTS_INLINE, - // %inline elements: - 'b big i small tt ' // %fontstyle - . 's strike u ' // (deprecated) - . 'abbr acronym cite code dfn em kbd samp strong var ' //%phrase - . 'a img object embed br script map q sub sup span bdo '//%special - . 'button input label option select textarea label ' //%formctl - - // %block elements which contain inline content - . 'address h1 h2 h3 h4 h5 h6 p pre ' - // %block elements which contain either block or inline content - . 'div fieldset frameset' - - // other with inline content - . 'caption dt label legend video ' - // other with either inline or block - . 'dd del ins li td th colgroup'); + // %inline elements: + 'b big i small tt ' // %fontstyle + . 's strike u ' // (deprecated) + . 'abbr acronym cite code dfn em kbd samp strong var ' //%phrase + . 'a img object embed br script map q sub sup span bdo ' //%special + . 'button input label option select textarea label ' //%formctl + + // %block elements which contain inline content + . 'address h1 h2 h3 h4 h5 h6 p pre ' + // %block elements which contain either block or inline content + . 'div fieldset frameset' + + // other with inline content + . 'caption dt label legend video ' + // other with either inline or block + . 'dd del ins li td th colgroup'); HTML::_setTagProperty(HTMLTAG_INLINE, - // %inline elements: - 'b big i small tt ' // %fontstyle - . 's strike u ' // (deprecated) - . 'abbr acronym cite code dfn em kbd samp strong var ' //%phrase - . 'a img object br script map q sub sup span bdo '//%special - . 'button input label option select textarea ' //%formctl - . 'nobody iframe' - ); + // %inline elements: + 'b big i small tt ' // %fontstyle + . 's strike u ' // (deprecated) + . 'abbr acronym cite code dfn em kbd samp strong var ' //%phrase + . 'a img object br script map q sub sup span bdo ' //%special + . 'button input label option select textarea ' //%formctl + . 'nobody iframe' +); /** * Generate hidden form input fields. @@ -474,7 +601,8 @@ HTML::_setTagProperty(HTMLTAG_INLINE, * * @return object An XmlContent object containing the inputs. */ -function HiddenInputs ($query_args, $pfx = false, $exclude = array()) { +function HiddenInputs($query_args, $pfx = false, $exclude = array()) +{ $inputs = HTML(); foreach ($query_args as $key => $val) { @@ -484,8 +612,8 @@ function HiddenInputs ($query_args, $pfx = false, $exclude = array()) { $inputs->pushContent(HiddenInputs($val, $name)); else $inputs->pushContent(HTML::input(array('type' => 'hidden', - 'name' => $name, - 'value' => $val))); + 'name' => $name, + 'value' => $val))); } return $inputs; } @@ -497,19 +625,20 @@ function HiddenInputs ($query_args, $pfx = false, $exclude = array()) { * e.g. to provide another version or the defer attr * @return HtmlElement A <script> element. */ -function JavaScript ($js, $script_args = false) { - $default_script_args = array(//'version' => 'JavaScript', // not xhtml conformant - 'type' => 'text/javascript'); +function JavaScript($js, $script_args = false) +{ + $default_script_args = array( //'version' => 'JavaScript', // not xhtml conformant + 'type' => 'text/javascript'); $script_args = $script_args ? array_merge($default_script_args, $script_args) - : $default_script_args; + : $default_script_args; if (empty($js)) - return HTML(HTML::script($script_args),"\n"); + return HTML(HTML::script($script_args), "\n"); else // see http://devedge.netscape.com/viewsource/2003/xhtml-style-script/ return HTML(HTML::script($script_args, - new RawXml((ENABLE_XHTML_XML ? "\n//<![CDATA[" : "\n<!--//") - . "\n".trim($js)."\n" - . (ENABLE_XHTML_XML ? "//]]>\n" : "// -->"))),"\n"); + new RawXml((ENABLE_XHTML_XML ? "\n//<![CDATA[" : "\n<!--//") + . "\n" . trim($js) . "\n" + . (ENABLE_XHTML_XML ? "//]]>\n" : "// -->"))), "\n"); } /** Conditionally display content based of whether javascript is supported. @@ -529,12 +658,13 @@ function JavaScript ($js, $script_args = false) { * * @return XmlContent */ -function IfJavaScript($if_content = false, $else_content = false) { +function IfJavaScript($if_content = false, $else_content = false) +{ $html = array(); if ($if_content) { $xml = AsXML($if_content); $js = sprintf('document.write("%s");', - addcslashes($xml, "\0..\37!@\\\177..\377")); + addcslashes($xml, "\0..\37!@\\\177..\377")); $html[] = JavaScript($js); } if ($else_content) { diff --git a/lib/HtmlParser.php b/lib/HtmlParser.php index c5be2c5a8..ab82b4714 100644 --- a/lib/HtmlParser.php +++ b/lib/HtmlParser.php @@ -41,7 +41,7 @@ require_once 'lib/XmlParser.php'; class HtmlParser -extends XmlParser + extends XmlParser { var $dialect, $_handlers, $root; @@ -49,17 +49,18 @@ extends XmlParser * dialect: "PhpWiki2", "PhpWiki" * possible more dialects: MediaWiki, kwiki, c2 */ - function HtmlParser($dialect = "PhpWiki2", $encoding = '') { - $classname = "HtmlParser_".$dialect; + function HtmlParser($dialect = "PhpWiki2", $encoding = '') + { + $classname = "HtmlParser_" . $dialect; if (class_exists($classname)) $this->dialect = new $classname; else { - trigger_error(sprintf("unknown HtmlParser dialect %s",$dialect),E_USER_ERROR); + trigger_error(sprintf("unknown HtmlParser dialect %s", $dialect), E_USER_ERROR); } $this->_handlers =& $this->dialect->_handlers; $this->XmlParser($encoding); - xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, 0); - xml_parser_set_option($this->_parser, XML_OPTION_SKIP_WHITE, 1); + xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, 0); + xml_parser_set_option($this->_parser, XML_OPTION_SKIP_WHITE, 1); } // The three callbacks, called on walking through the HTML tree. @@ -74,26 +75,28 @@ extends XmlParser function parse_url($file, $debug=false) */ - function output () { + function output() + { if (is_null($this->root)) $this->root = $GLOBALS['xml_parser_root']; - $output = $this->wikify( $this->root ); + $output = $this->wikify($this->root); return $output; } - function wikify ($node, $parent = null) { + function wikify($node, $parent = null) + { $output = ''; - if( isa($node, 'XmlElement')) { + if (isa($node, 'XmlElement')) { $dialect =& $this->dialect; $conv = $dialect->_handlers[$node->_tag]; - if( is_string($conv) and method_exists($dialect, $conv)) { + if (is_string($conv) and method_exists($dialect, $conv)) { $output = $dialect->$conv($node); - } elseif( is_array($conv) ) { + } elseif (is_array($conv)) { foreach ($node->getContent() as $n) { $output .= $this->wikify($n, $node); } - $output = $conv[0] . $output . $conv[count($conv)-1]; - } elseif( !empty($conv) ) { + $output = $conv[0] . $output . $conv[count($conv) - 1]; + } elseif (!empty($conv)) { $output = $conv; foreach ($node->getContent() as $n) { $output .= $this->wikify($n, $node); @@ -106,7 +109,7 @@ extends XmlParser } else { $output = $node; if ($parent and $parent->_tag != 'pre') - preg_replace("/ {2,}/"," ",$output); + preg_replace("/ {2,}/", " ", $output); if (trim($output) == '') $output = ''; } @@ -115,15 +118,15 @@ extends XmlParser /** elem_contents() * $output = $parser->elem_contents( $elem ); - * Returns a wikified version of the contents of the specified * HTML element. This is done by passing each element of this * element's content list through the C<wikify()> method, and * returning the concatenated result. */ - function elem_contents($node) { + function elem_contents($node) + { $output = ''; - if (isa($node,'XmlElement')) { + if (isa($node, 'XmlElement')) { foreach ($node->getContent() as $child) { $output .= $this->wikify($child, isset($node->parent) ? $node->parent : null); } @@ -144,11 +147,12 @@ extends XmlParser // attribute name/value pairs are specified in attr="value" // format. // - function _elem_attr_str($node, $attrs) { + function _elem_attr_str($node, $attrs) + { $s = ''; foreach ($node->_attr as $attr => $val) { $attr = strtolower($attr); - if (in_array($attr,$attrs)) + if (in_array($attr, $attrs)) $s .= " $attr=\"$val\""; } return $s; @@ -161,7 +165,8 @@ extends XmlParser // whose element tag equals $tag. This is useful for determining if // an element belongs to the specified tag. // - function _elem_has_ancestor($node, $tag) { + function _elem_has_ancestor($node, $tag) + { if (isset($node->parent)) { if ($node->parent->_tag == $tag) return true; return $this->_elem_has_ancestor($node->parent, $tag); @@ -180,9 +185,10 @@ extends XmlParser // contained within a sole A tag (not counting child elements with // whitespace text only). // - function _elem_is_image_div( $node ) { + function _elem_is_image_div($node) + { // Return false if node is undefined or isn't a DIV at all - if (!$node or !in_array($node->_tag,array("div","p"))) + if (!$node or !in_array($node->_tag, array("div", "p"))) return false; $contents = $node->getContent(); // Returns true if sole child is an IMG tag @@ -199,108 +205,120 @@ extends XmlParser /** preserves tags and content */ - function wikify_default($node) { + function wikify_default($node) + { return $this->wikify_preserve($node); } /** preserves tags and content - */ - function wikify_preserve($node) { + */ + function wikify_preserve($node) + { return $node->asXML(); } - function log($dummy) {} + function log($dummy) + { + } } class HtmlParser_PhpWiki2 -extends HtmlParser + extends HtmlParser { - function HtmlParser_PhpWiki2() { + function HtmlParser_PhpWiki2() + { $this->_handlers = - array('html' => '', - 'head' => '', - 'title' => '', - 'meta' => '', - 'link' => '', - 'script' => '', - 'body' => '', - - 'br' => "<br>", - 'b' => array( "*" ), - 'strong' => array( "*" ), - 'i' => array( "_" ), - 'em' => array( "_" ), - 'hr' => "----\n\n", - - // PRE blocks are handled specially (see tidy_whitespace and - // wikify methods) - 'pre' => array( "<pre>", "</pre>" ), - - 'dl' => array( '', "\n\n" ), - 'dt' => array( ';', '' ), - 'dd' => array( ':', '' ), - - 'p' => array( "\n\n", "\n\n" ), - 'ul' => array( '', "\n" ), - 'ol' => array( '', "\n" ), - - 'li' => "wikify_list_item", - 'table' => "wikify_table", - 'tr' => "wikify_tr", - 'td' => "wikify_td", - 'th' => "wikify_td", - 'div' => array( '', "\n\n" ), - 'img' => "wikify_img", - 'a' => "wikify_link", - 'span' => array( '', '' ), - - 'h1' => "wikify_h", - 'h2' => "wikify_h", - 'h3' => "wikify_h", - 'h4' => "wikify_h", - 'h5' => "wikify_h", - 'h6' => "wikify_h", - - 'font' => array( '', '' ), - 'sup' => "wikify_default", - 'sub' => "wikify_default", - 'nowiki' => "wikify_verbatim", - 'verbatim' => "wikify_default", - 'noinclude' => "wikify_noinclude", - ); + array('html' => '', + 'head' => '', + 'title' => '', + 'meta' => '', + 'link' => '', + 'script' => '', + 'body' => '', + + 'br' => "<br>", + 'b' => array("*"), + 'strong' => array("*"), + 'i' => array("_"), + 'em' => array("_"), + 'hr' => "----\n\n", + + // PRE blocks are handled specially (see tidy_whitespace and + // wikify methods) + 'pre' => array("<pre>", "</pre>"), + + 'dl' => array('', "\n\n"), + 'dt' => array(';', ''), + 'dd' => array(':', ''), + + 'p' => array("\n\n", "\n\n"), + 'ul' => array('', "\n"), + 'ol' => array('', "\n"), + + 'li' => "wikify_list_item", + 'table' => "wikify_table", + 'tr' => "wikify_tr", + 'td' => "wikify_td", + 'th' => "wikify_td", + 'div' => array('', "\n\n"), + 'img' => "wikify_img", + 'a' => "wikify_link", + 'span' => array('', ''), + + 'h1' => "wikify_h", + 'h2' => "wikify_h", + 'h3' => "wikify_h", + 'h4' => "wikify_h", + 'h5' => "wikify_h", + 'h6' => "wikify_h", + + 'font' => array('', ''), + 'sup' => "wikify_default", + 'sub' => "wikify_default", + 'nowiki' => "wikify_verbatim", + 'verbatim' => "wikify_default", + 'noinclude' => "wikify_noinclude", + ); } - function wikify_table( $node ) { + function wikify_table($node) + { $this->ident = ''; return "| \n" . $this->elem_contents($node) . "|\n\n"; } - function wikify_tr( $node ) { + + function wikify_tr($node) + { return "\n| " . $this->elem_contents($node); } - function wikify_th( $node ) { + + function wikify_th($node) + { $ident = empty($this->ident) ? '' : $this->ident; $output = "$ident| "; $content = $this->elem_contents($node); - preg_replace("s/^\s+/","",$content); + preg_replace("s/^\s+/", "", $content); $output .= $content; $this->ident .= ' '; return "$output |\n"; } - function wikify_list_item( $node ) { - return ($this->_elem_has_ancestor($node, 'ol') ? '*' : '#') . " " . trim($this->elem_contents($node)). "\n"; + function wikify_list_item($node) + { + return ($this->_elem_has_ancestor($node, 'ol') ? '*' : '#') . " " . trim($this->elem_contents($node)) . "\n"; } - function wikify_link( $node ) { - $url = $this->absolute_url( $node->getAttr('href') ); + function wikify_link($node) + { + $url = $this->absolute_url($node->getAttr('href')); $title = $this->elem_contents($node); if (empty($url)) $title = trim($title); // Just return the link title if this tag is contained // within an header tag - if (isset($node->parent) and preg_match('/^h\d$/',$node->parent->_tag)) + if (isset($node->parent) and preg_match('/^h\d$/', $node->parent->_tag)) return $title; // Return if this is a link to an image contained within @@ -314,58 +332,62 @@ extends HtmlParser return "[ $url | $title ]"; } - function wikify_h( $node ) { - $level = substr($node->_tag,1); + function wikify_h($node) + { + $level = substr($node->_tag, 1); if ($level < 4) { - $markup = str_repeat('!',4 - $level); + $markup = str_repeat('!', 4 - $level); } else { $markup = '!'; } - return $markup.' '.trim($this->elem_contents($node))."\n\n"; + return $markup . ' ' . trim($this->elem_contents($node)) . "\n\n"; } - function wikify_verbatim( $node ) { - $contents = $this->elem_contents( $node ); + function wikify_verbatim($node) + { + $contents = $this->elem_contents($node); return "\n<verbatim>\n$contents\n</verbatim>"; } - function wikify_noinclude( $node ) { - return $this->elem_contents( $node ); + function wikify_noinclude($node) + { + return $this->elem_contents($node); } - function wikify_img( $node ) { - $image_url = $this->absolute_url( $node->getAttr('src') ); - $file = basename( $image_url ); + function wikify_img($node) + { + $image_url = $this->absolute_url($node->getAttr('src')); + $file = basename($image_url); $alignment = $node->getAttr('align'); - $this->log( "Processing IMG tag for SRC: ".$image_url."..." ); + $this->log("Processing IMG tag for SRC: " . $image_url . "..."); // // Grab attributes to be added to the [ Image ] markup (since 1.3.10) // if (!$alignment) { - if ($this->_elem_is_image_div( $node->parent )) + if ($this->_elem_is_image_div($node->parent)) $image_div = $node->parent; - elseif (isset($node->parent) and $this->_elem_is_image_div( $node->parent->parent )) + elseif (isset($node->parent) and $this->_elem_is_image_div($node->parent->parent)) $image_div = $node->parent->parent; } - if ( !$alignment and $image_div ) { + if (!$alignment and $image_div) { $css_style = $image_div->getAttr('style'); $css_class = $image_div->getAttr('class'); // float => align: Check for float attribute; if it's there, // then we'll add it to the [Image] syntax - if (!$alignment and preg_match("/float\:\s*(right|left)/i",$css_style,$m)) - $alignment = $m[1]; - if (!$alignment and preg_match("/float(right|left)/i",$css_class,$m)); + if (!$alignment and preg_match("/float\:\s*(right|left)/i", $css_style, $m)) $alignment = $m[1]; - if( $alignment ) { + if (!$alignment and preg_match("/float(right|left)/i", $css_class, $m)) ; + $alignment = $m[1]; + if ($alignment) { $attrs[] = "align=$alignment"; - $this->log( " Image is contained within a DIV that specifies $alignment alignment" ); - $this->log( " Adding '$alignment' to [Image] markup attributes" ); + $this->log(" Image is contained within a DIV that specifies $alignment alignment"); + $this->log(" Adding '$alignment' to [Image] markup attributes"); } else { - $this->log( " Image is not contained within a DIV for alignment" ); + $this->log(" Image is not contained within a DIV for alignment"); } } else { - $this->log( " Image is not contained within a DIV" ); + $this->log(" Image is not contained within a DIV"); } if ($alignment) $attrs[] = "align=$alignment"; @@ -374,42 +396,42 @@ extends HtmlParser // image; it's needed if the specified width attribute // differs from the default size of the image // - if( $width = $node->getAttr('width') ) { - $this->log( " Image has WIDTH attribute of $width" ); - $this->log( " Checking whether resulting [Image] markup should specify a thumbnail..." ); + if ($width = $node->getAttr('width')) { + $this->log(" Image has WIDTH attribute of $width"); + $this->log(" Checking whether resulting [Image] markup should specify a thumbnail..."); // Download the image from the network and store - $abs_url = $this->absolute_url( $node->getAttr('src') ); - $this->log( " Fetching image '$abs_url' from the network" ); - list( $actual_w, $actual_h, $flag, $attr_str) = getimagesize( $abs_url ); + $abs_url = $this->absolute_url($node->getAttr('src')); + $this->log(" Fetching image '$abs_url' from the network"); + list($actual_w, $actual_h, $flag, $attr_str) = getimagesize($abs_url); // If the WIDTH attribute of the IMG tag is not equal // to the actual width of the image, then we need to // create a thumbnail - if( preg_match("/^\d+$/",$width) and $width != $actual_w ) { - $this->log( " IMG tag's WIDTH attribute ($width) differs from actual width of image ($actual_w)" ); - $this->log( " -- that means we're going to need a thumbnail" ); - $this->log( " Adding 'width' to list of attributes for [Image] markup" ); + if (preg_match("/^\d+$/", $width) and $width != $actual_w) { + $this->log(" IMG tag's WIDTH attribute ($width) differs from actual width of image ($actual_w)"); + $this->log(" -- that means we're going to need a thumbnail"); + $this->log(" Adding 'width' to list of attributes for [Image] markup"); $attrs[] = "width=$width"; $width_added = true; } $height = $node->getAttr('height'); - if( preg_match("/^\d+$/",$height) and $height != $height_h ) { - $this->log( " IMG tag's HEIGHT attribute ($height) differs from actual height of image ($actual_h)" ); - $this->log( " -- that means we're going to need a thumbnail" ); - $this->log( " Adding 'height' to list of attributes for [Image] markup" ); + if (preg_match("/^\d+$/", $height) and $height != $height_h) { + $this->log(" IMG tag's HEIGHT attribute ($height) differs from actual height of image ($actual_h)"); + $this->log(" -- that means we're going to need a thumbnail"); + $this->log(" Adding 'height' to list of attributes for [Image] markup"); if (isset($width_added)) - $attrs[count($attr)-1] = "size=".$width."x".$height; + $attrs[count($attr) - 1] = "size=" . $width . "x" . $height; else $attrs[] = "height=$height"; } } if ($alt = $node->getAttr('alt')) { - $this->log( " Adding alternate text '$alt' to [Image] markup" ); + $this->log(" Adding alternate text '$alt' to [Image] markup"); $attrs[] = "alt=$alt"; } $attr_str = join(' ', $attrs); - $this->log( "...done processing IMG tag\n" ); + $this->log("...done processing IMG tag\n"); return "[ $file $attr_str ]"; } } diff --git a/lib/HttpClient.php b/lib/HttpClient.php index 327e1dff6..fec498741 100644 --- a/lib/HttpClient.php +++ b/lib/HttpClient.php @@ -1,17 +1,18 @@ <?php /** - Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ ) - Manual: http://scripts.incutio.com/httpclient/ +Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ ) +Manual: http://scripts.incutio.com/httpclient/ - Copyright © 2003 Incutio Limited - License: http://www.opensource.org/licenses/artistic-license.php +Copyright © 2003 Incutio Limited +License: http://www.opensource.org/licenses/artistic-license.php - File upload and xmlrpc support by Reini Urban for PhpWiki, 2006-12-28 18:12:47 - Todo: proxy support -*/ +File upload and xmlrpc support by Reini Urban for PhpWiki, 2006-12-28 18:12:47 +Todo: proxy support + */ -class HttpClient { +class HttpClient +{ // Request vars var $host; var $port; @@ -28,14 +29,14 @@ class HttpClient { // Options var $timeout = 10; var $use_gzip = true; - var $persist_cookies = true; // If true, received cookies are placed in the $this->cookies array ready for the next request - // Note: This currently ignores the cookie path (and time) completely. Time is not important, - // but path could possibly lead to security problems. + var $persist_cookies = true; // If true, received cookies are placed in the $this->cookies array ready for the next request + // Note: This currently ignores the cookie path (and time) completely. Time is not important, + // but path could possibly lead to security problems. var $persist_referers = true; // For each request, sends path of last request as referer var $debug = false; var $handle_redirects = true; // Auaomtically redirect if Location or URI header is found var $max_redirects = 5; - var $headers_only = false; // If true, stops receiving once headers have been read. + var $headers_only = false; // If true, stops receiving once headers have been read. // Basic authorization variables var $username; var $password; @@ -48,49 +49,58 @@ class HttpClient { var $redirect_count = 0; var $cookie_host = ''; - function HttpClient($host='localhost', $port=80) { + function HttpClient($host = 'localhost', $port = 80) + { $this->host = $host; $this->port = $port; } - function get($path, $data = false) { + + function get($path, $data = false) + { $this->path = $path; $this->method = 'GET'; if ($data) { - $this->path .= '?'.$this->buildQueryString($data); + $this->path .= '?' . $this->buildQueryString($data); } return $this->doRequest(); } - function post($path, $data) { + + function post($path, $data) + { $this->path = $path; $this->method = 'POST'; $this->postdata = $this->buildQueryString($data); return $this->doRequest(); } - function postfile($path, $filename) { + + function postfile($path, $filename) + { $this->path = $path; $this->method = 'POST'; - $boundary = $this->boundary; //"httpclient_boundary"; - $headers[] = "Content-Type: multipart/form-data; boundary=\"$boundary\""; - $basename = basename($filename); - $this->postdata = - "\r\n--$boundary\r\n" - ."Content-Disposition: form-data; filename=\"$basename\"\r\n" - ."Content-Type: application/octet-stream\r\n\r\n"; - $this->postdata .= join("",file($filename)); - $this->postdata .= "\r\n\r\n--$boundary--\r\n"; + $boundary = $this->boundary; //"httpclient_boundary"; + $headers[] = "Content-Type: multipart/form-data; boundary=\"$boundary\""; + $basename = basename($filename); + $this->postdata = + "\r\n--$boundary\r\n" + . "Content-Disposition: form-data; filename=\"$basename\"\r\n" + . "Content-Type: application/octet-stream\r\n\r\n"; + $this->postdata .= join("", file($filename)); + $this->postdata .= "\r\n\r\n--$boundary--\r\n"; return $this->doRequest(); } - function buildQueryString($data) { + + function buildQueryString($data) + { $querystring = ''; if (is_array($data)) { // Change data in to postable data foreach ($data as $key => $val) { if (is_array($val)) { foreach ($val as $val2) { - $querystring .= urlencode($key).'='.urlencode($val2).'&'; + $querystring .= urlencode($key) . '=' . urlencode($val2) . '&'; } } else { - $querystring .= urlencode($key).'='.urlencode($val).'&'; + $querystring .= urlencode($key) . '=' . urlencode($val) . '&'; } } $querystring = substr($querystring, 0, -1); // Eliminate unnecessary & @@ -100,37 +110,38 @@ class HttpClient { return $querystring; } - function doRequest() { + function doRequest() + { // Performs the actual HTTP request, returning true or false depending on outcome // Ensure that the PHP timeout is longer than the socket timeout longer_timeout($this->timeout); if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) { // Set error message - switch($errno) { - case -3: - $this->errormsg = 'Socket creation failed (-3)'; - case -4: - $this->errormsg = 'DNS lookup failure (-4)'; - case -5: - $this->errormsg = 'Connection refused or timed out (-5)'; - default: - $this->errormsg = 'Connection failed ('.$errno.')'; - $this->errormsg .= ' '.$errstr; - $this->debug($this->errormsg); + switch ($errno) { + case -3: + $this->errormsg = 'Socket creation failed (-3)'; + case -4: + $this->errormsg = 'DNS lookup failure (-4)'; + case -5: + $this->errormsg = 'Connection refused or timed out (-5)'; + default: + $this->errormsg = 'Connection failed (' . $errno . ')'; + $this->errormsg .= ' ' . $errstr; + $this->debug($this->errormsg); } return false; } socket_set_timeout($fp, $this->timeout); - if ( $this->method == 'POST' and preg_match("/\<methodCall\>/", $this->postdata)) - $request = $this->buildRequest("text/xml"); //xmlrpc - else if ( $this->method == 'POST' and strstr("\r\nContent-Disposition: form-data; filename=", - $this->postdata)) - { - //file upload - $boundary = $this->boundary; - $request = $this->buildRequest("multipart/form-data; boundary=\"$boundary\""); - } else - $request = $this->buildRequest(); + if ($this->method == 'POST' and preg_match("/\<methodCall\>/", $this->postdata)) + $request = $this->buildRequest("text/xml"); //xmlrpc + else if ($this->method == 'POST' and strstr("\r\nContent-Disposition: form-data; filename=", + $this->postdata) + ) { + //file upload + $boundary = $this->boundary; + $request = $this->buildRequest("multipart/form-data; boundary=\"$boundary\""); + } else + $request = $this->buildRequest(); $this->debug('Request', $request); fwrite($fp, $request); // Reset all the variables that should not persist between requests @@ -147,11 +158,11 @@ class HttpClient { // Deal with first line of returned data $atStart = false; if ($line === false) { - $this->errormsg = "Empty ". $this->method. " response"; + $this->errormsg = "Empty " . $this->method . " response"; return false; } if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) { - $this->errormsg = "Status code line invalid: ".htmlentities($line); + $this->errormsg = "Status code line invalid: " . htmlentities($line); $this->debug($this->errormsg); return false; } @@ -218,13 +229,13 @@ class HttpClient { } // If $persist_referers, set the referer ready for the next request if (isset($this->persist_referers)) { - $this->debug('Persisting referer: '.$this->getRequestURL()); + $this->debug('Persisting referer: ' . $this->getRequestURL()); $this->referer = $this->getRequestURL(); } // Finally, if handle_redirects and a redirect is sent, do that if (isset($this->handle_redirects)) { if (++$this->redirect_count >= $this->max_redirects) { - $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')'; + $this->errormsg = 'Number of redirects exceeded maximum (' . $this->max_redirects . ')'; $this->debug($this->errormsg); $this->redirect_count = 0; return false; @@ -232,7 +243,7 @@ class HttpClient { $location = isset($this->headers['location']) ? $this->headers['location'] : ''; $uri = isset($this->headers['uri']) ? $this->headers['uri'] : ''; if ($location || $uri) { - $url = parse_url($location.$uri); + $url = parse_url($location . $uri); if ($this->method == 'POST') return $this->doRequest(); else @@ -243,9 +254,10 @@ class HttpClient { return true; } - function buildRequest($ContentType = 'application/x-www-form-urlencoded') { + function buildRequest($ContentType = 'application/x-www-form-urlencoded') + { $headers = array(); - // Using 1.1 leads to all manner of problems, such as "chunked" encoding + // Using 1.1 leads to all manner of problems, such as "chunked" encoding $headers[] = "{$this->method} {$this->path} HTTP/1.0"; $headers[] = "Host: {$this->host}"; $headers[] = "User-Agent: {$this->user_agent}"; @@ -267,26 +279,34 @@ class HttpClient { } // Basic authentication if (!empty($this->username) && !empty($this->password)) { - $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password); + $headers[] = 'Authorization: BASIC ' . base64_encode($this->username . ':' . $this->password); } // If this is a POST, set the content type and length if ($this->postdata) { - $headers[] = 'Content-Type: ' . $ContentType; - $headers[] = 'Content-Length: '.strlen($this->postdata); + $headers[] = 'Content-Type: ' . $ContentType; + $headers[] = 'Content-Length: ' . strlen($this->postdata); } - $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata; + $request = implode("\r\n", $headers) . "\r\n\r\n" . $this->postdata; return $request; } - function getStatus() { + + function getStatus() + { return $this->status; } - function getContent() { + + function getContent() + { return $this->content; } - function getHeaders() { + + function getHeaders() + { return $this->headers; } - function getHeader($header) { + + function getHeader($header) + { $header = strtolower($header); if (isset($this->headers[$header])) { return $this->headers[$header]; @@ -294,62 +314,90 @@ class HttpClient { return false; } } - function getError() { + + function getError() + { return $this->errormsg; } - function getCookies() { + + function getCookies() + { return $this->cookies; } - function getRequestURL() { - $url = 'http://'.$this->host; + + function getRequestURL() + { + $url = 'http://' . $this->host; if ($this->port != 80) { - $url = 'https://'.$this->host; - $url .= ':'.$this->port; + $url = 'https://' . $this->host; + $url .= ':' . $this->port; } $url .= $this->path; return $url; } + // Setter methods - function setUserAgent($string) { + function setUserAgent($string) + { $this->user_agent = $string; } - function setAuthorization($username, $password) { + + function setAuthorization($username, $password) + { $this->username = $username; $this->password = $password; } - function setCookies($array) { + + function setCookies($array) + { $this->cookies = $array; } + // Option setting methods - function useGzip($boolean) { + function useGzip($boolean) + { $this->use_gzip = $boolean; } - function setPersistCookies($boolean) { + + function setPersistCookies($boolean) + { $this->persist_cookies = $boolean; } - function setPersistReferers($boolean) { + + function setPersistReferers($boolean) + { $this->persist_referers = $boolean; } - function setHandleRedirects($boolean) { + + function setHandleRedirects($boolean) + { $this->handle_redirects = $boolean; } - function setMaxRedirects($num) { + + function setMaxRedirects($num) + { $this->max_redirects = $num; } - function setHeadersOnly($boolean) { + + function setHeadersOnly($boolean) + { $this->headers_only = $boolean; } - function setDebug($boolean) { + + function setDebug($boolean) + { $this->debug = $boolean; } + // "Quick" static methods - function quickGet($url) { + function quickGet($url) + { $bits = parse_url($url); $host = $bits['host']; $port = isset($bits['port']) ? $bits['port'] : 80; $path = isset($bits['path']) ? $bits['path'] : '/'; if (isset($bits['query'])) { - $path .= '?'.$bits['query']; + $path .= '?' . $bits['query']; } $client = new HttpClient($host, $port); if (!$client->get($path)) { @@ -358,7 +406,9 @@ class HttpClient { return $client->getContent(); } } - function quickPost($url, $data) { + + function quickPost($url, $data) + { $bits = parse_url($url); $host = $bits['host']; $port = isset($bits['port']) ? $bits['port'] : 80; @@ -370,15 +420,17 @@ class HttpClient { return $client->getContent(); } } - function debug($msg, $object = false) { + + function debug($msg, $object = false) + { if ($this->debug) { - print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg; + print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> ' . $msg; if ($object) { ob_start(); print_r($object); $content = htmlentities(ob_get_contents()); ob_end_clean(); - print '<pre>'.$content.'</pre>'; + print '<pre>' . $content . '</pre>'; } print '</div>'; } diff --git a/lib/IniConfig.php b/lib/IniConfig.php index a74b74a1b..70cbe46ad 100644 --- a/lib/IniConfig.php +++ b/lib/IniConfig.php @@ -59,8 +59,8 @@ * them as constants. */ -include_once (dirname(__FILE__)."/config.php"); -include_once (dirname(__FILE__)."/FileFinder.php"); +include_once (dirname(__FILE__) . "/config.php"); +include_once (dirname(__FILE__) . "/FileFinder.php"); /** * Speed-up iniconfig loading. @@ -69,49 +69,53 @@ include_once (dirname(__FILE__)."/FileFinder.php"); * The dynamic parts are then evaluated as before. * Requires write-permissions to config/config.php */ -function save_dump($file) { +function save_dump($file) +{ $vars =& $GLOBALS; // copy + unset not possible $ignore = array(); - foreach (array("SERVER","ENV","GET","POST","REQUEST","COOKIE","FILES") as $key) { - $ignore["HTTP_".$key."_VARS"]++; - $ignore["_".$key]++; + foreach (array("SERVER", "ENV", "GET", "POST", "REQUEST", "COOKIE", "FILES") as $key) { + $ignore["HTTP_" . $key . "_VARS"]++; + $ignore["_" . $key]++; } - foreach (array("HTTP_POST_FILES","GLOBALS","RUNTIMER","ErrorManager",'LANG', - 'HOME_PAGE','request','SCRIPT_NAME','VIRTUAL_PATH','SCRIPT_FILENAME') as $key) + foreach (array("HTTP_POST_FILES", "GLOBALS", "RUNTIMER", "ErrorManager", 'LANG', + 'HOME_PAGE', 'request', 'SCRIPT_NAME', 'VIRTUAL_PATH', 'SCRIPT_FILENAME') as $key) $ignore[$key]++; $fp = fopen($file, "wb"); - fwrite($fp,"<?php\n"); - fwrite($fp,"function wiki_configrestore(){\n"); + fwrite($fp, "<?php\n"); + fwrite($fp, "function wiki_configrestore(){\n"); //TODO: optimize this by removing ignore, big serialized array and merge into existing GLOBALS foreach ($vars as $var => $val) { if (!$ignore[$var]) - fwrite($fp, "\$GLOBALS['".$var."']=unserialize(\"" - .addslashes(serialize($val))."\");\n"); + fwrite($fp, "\$GLOBALS['" . $var . "']=unserialize(\"" + . addslashes(serialize($val)) . "\");\n"); } // cannot be optimized, maybe leave away predefined consts somehow foreach (get_defined_constants() as $var => $val) { - if (substr($var,0,4) != "PHP_" and substr($var,0,2) != "E_" - and substr($var,0,2) != "T_" and substr($var,0,2) != "M_") - fwrite($fp, "if(!defined('".$var."')) define('".$var."',unserialize(\"" - .addslashes(serialize($val))."\"));\n"); + if (substr($var, 0, 4) != "PHP_" and substr($var, 0, 2) != "E_" + and substr($var, 0, 2) != "T_" and substr($var, 0, 2) != "M_" + ) + fwrite($fp, "if(!defined('" . $var . "')) define('" . $var . "',unserialize(\"" + . addslashes(serialize($val)) . "\"));\n"); } fwrite($fp, "return 'noerr';}"); - fwrite($fp,"?>"); + fwrite($fp, "?>"); fclose($fp); } -function _check_int_constant(&$c) { - // if int value == string value, force int type - if (sprintf("%d",(int)$c) === $c) { // DEBUG & _DEBUG_bla - $c = (int)$c; - } +function _check_int_constant(&$c) +{ + // if int value == string value, force int type + if (sprintf("%d", (int)$c) === $c) { // DEBUG & _DEBUG_bla + $c = (int)$c; + } } -function IniConfig($file) { +function IniConfig($file) +{ // Optionally check config/config.php dump for faster startup - $dump = substr($file, 0, -3)."php"; - if (isWindows($dump)) $dump = str_replace("/","\\",$dump); + $dump = substr($file, 0, -3) . "php"; + if (isWindows($dump)) $dump = str_replace("/", "\\", $dump); if (file_exists($dump) and is_readable($dump) and filesize($dump) > 0 and sort_file_mtime($dump, $file) < 0) { @include($dump) or die("Error including " . $dump); if (function_exists('wiki_configrestore') and (wiki_configrestore() === 'noerr')) { @@ -126,7 +130,7 @@ function IniConfig($file) { // We need to DATA_PATH for configurator, or pass the posted values // somewhow to the script $GLOBALS['charset'] = 'utf-8'; - include_once(dirname(__FILE__)."/install.php"); + include_once(dirname(__FILE__) . "/install.php"); run_install("_part1"); if (!defined("_PHPWIKI_INSTALL_RUNNING")) trigger_error("Datasource file '$file' does not exist", E_USER_ERROR); @@ -136,80 +140,80 @@ function IniConfig($file) { // List of all valid config options to be define()d which take "values" (not // booleans). Needs to be categorised, and generally made a lot tidier. $_IC_VALID_VALUE = array - ('WIKI_NAME', 'ADMIN_USER', 'ADMIN_PASSWD', - 'DEFAULT_DUMP_DIR', 'HTML_DUMP_DIR', - 'HTML_DUMP_SUFFIX', 'MAX_UPLOAD_SIZE', 'MINOR_EDIT_TIMEOUT', - 'ACCESS_LOG', 'CACHE_CONTROL', 'CACHE_CONTROL_MAX_AGE', - 'COOKIE_EXPIRATION_DAYS', 'COOKIE_DOMAIN', - 'PASSWORD_LENGTH_MINIMUM', 'USER_AUTH_POLICY', - 'GROUP_METHOD', - 'EDITING_POLICY', 'THEME', 'CHARSET', - 'WIKI_PGSRC', 'DEFAULT_WIKI_PGSRC', - 'ALLOWED_PROTOCOLS', 'INLINE_IMAGES', 'SUBPAGE_SEPARATOR', /*'KEYWORDS',*/ - // extra logic: - //'DATABASE_PREFIX', 'DATABASE_DSN', 'DATABASE_TYPE', 'DATABASE_DBHANDLER', - 'DATABASE_OPTIMISE_FREQUENCY', - 'INTERWIKI_MAP_FILE', 'COPYRIGHTPAGE_TITLE', 'COPYRIGHTPAGE_URL', - 'AUTHORPAGE_TITLE', 'AUTHORPAGE_URL', - 'WIKI_NAME_REGEXP', - 'PLUGIN_CACHED_DATABASE', 'PLUGIN_CACHED_FILENAME_PREFIX', - 'PLUGIN_CACHED_HIGHWATER', 'PLUGIN_CACHED_LOWWATER', 'PLUGIN_CACHED_MAXLIFETIME', - 'PLUGIN_CACHED_MAXARGLEN', 'PLUGIN_CACHED_IMGTYPES', - 'WYSIWYG_BACKEND', 'PLUGIN_MARKUP_MAP', - // extra logic: - 'SERVER_NAME','SERVER_PORT','SCRIPT_NAME', 'DATA_PATH', 'PHPWIKI_DIR', 'VIRTUAL_PATH', - 'EXTERNAL_HTML2PDF_PAGELIST', 'PLUGIN_CACHED_CACHE_DIR' - ); + ('WIKI_NAME', 'ADMIN_USER', 'ADMIN_PASSWD', + 'DEFAULT_DUMP_DIR', 'HTML_DUMP_DIR', + 'HTML_DUMP_SUFFIX', 'MAX_UPLOAD_SIZE', 'MINOR_EDIT_TIMEOUT', + 'ACCESS_LOG', 'CACHE_CONTROL', 'CACHE_CONTROL_MAX_AGE', + 'COOKIE_EXPIRATION_DAYS', 'COOKIE_DOMAIN', + 'PASSWORD_LENGTH_MINIMUM', 'USER_AUTH_POLICY', + 'GROUP_METHOD', + 'EDITING_POLICY', 'THEME', 'CHARSET', + 'WIKI_PGSRC', 'DEFAULT_WIKI_PGSRC', + 'ALLOWED_PROTOCOLS', 'INLINE_IMAGES', 'SUBPAGE_SEPARATOR', /*'KEYWORDS',*/ + // extra logic: + //'DATABASE_PREFIX', 'DATABASE_DSN', 'DATABASE_TYPE', 'DATABASE_DBHANDLER', + 'DATABASE_OPTIMISE_FREQUENCY', + 'INTERWIKI_MAP_FILE', 'COPYRIGHTPAGE_TITLE', 'COPYRIGHTPAGE_URL', + 'AUTHORPAGE_TITLE', 'AUTHORPAGE_URL', + 'WIKI_NAME_REGEXP', + 'PLUGIN_CACHED_DATABASE', 'PLUGIN_CACHED_FILENAME_PREFIX', + 'PLUGIN_CACHED_HIGHWATER', 'PLUGIN_CACHED_LOWWATER', 'PLUGIN_CACHED_MAXLIFETIME', + 'PLUGIN_CACHED_MAXARGLEN', 'PLUGIN_CACHED_IMGTYPES', + 'WYSIWYG_BACKEND', 'PLUGIN_MARKUP_MAP', + // extra logic: + 'SERVER_NAME', 'SERVER_PORT', 'SCRIPT_NAME', 'DATA_PATH', 'PHPWIKI_DIR', 'VIRTUAL_PATH', + 'EXTERNAL_HTML2PDF_PAGELIST', 'PLUGIN_CACHED_CACHE_DIR' + ); // Optional values which need to be defined. // These are not defined in config-default.ini and empty if not defined. $_IC_OPTIONAL_VALUE = array - ( - 'DEBUG', 'TEMP_DIR', 'DEFAULT_LANGUAGE', - 'LDAP_AUTH_HOST','LDAP_SET_OPTION','LDAP_BASE_DN', 'LDAP_AUTH_USER', - 'LDAP_AUTH_PASSWORD','LDAP_SEARCH_FIELD','LDAP_OU_GROUP','LDAP_OU_USERS', - 'AUTH_USER_FILE','DBAUTH_AUTH_DSN', - 'IMAP_AUTH_HOST', 'POP3_AUTH_HOST', - 'AUTH_USER_FILE', 'AUTH_GROUP_FILE', 'AUTH_SESS_USER', 'AUTH_SESS_LEVEL', - 'GOOGLE_LICENSE_KEY','FORTUNE_DIR', - 'DISABLE_GETIMAGESIZE','DBADMIN_USER','DBADMIN_PASSWD', - 'SESSION_SAVE_PATH', - 'TOOLBAR_PAGELINK_PULLDOWN', 'TOOLBAR_TEMPLATE_PULLDOWN', 'TOOLBAR_IMAGE_PULLDOWN', - 'EXTERNAL_LINK_TARGET', 'ACCESS_LOG_SQL', 'USE_EXTERNAL_HTML2PDF', - 'LOGIN_LOG','LDAP_SEARCH_FILTER' - ); + ( + 'DEBUG', 'TEMP_DIR', 'DEFAULT_LANGUAGE', + 'LDAP_AUTH_HOST', 'LDAP_SET_OPTION', 'LDAP_BASE_DN', 'LDAP_AUTH_USER', + 'LDAP_AUTH_PASSWORD', 'LDAP_SEARCH_FIELD', 'LDAP_OU_GROUP', 'LDAP_OU_USERS', + 'AUTH_USER_FILE', 'DBAUTH_AUTH_DSN', + 'IMAP_AUTH_HOST', 'POP3_AUTH_HOST', + 'AUTH_USER_FILE', 'AUTH_GROUP_FILE', 'AUTH_SESS_USER', 'AUTH_SESS_LEVEL', + 'GOOGLE_LICENSE_KEY', 'FORTUNE_DIR', + 'DISABLE_GETIMAGESIZE', 'DBADMIN_USER', 'DBADMIN_PASSWD', + 'SESSION_SAVE_PATH', + 'TOOLBAR_PAGELINK_PULLDOWN', 'TOOLBAR_TEMPLATE_PULLDOWN', 'TOOLBAR_IMAGE_PULLDOWN', + 'EXTERNAL_LINK_TARGET', 'ACCESS_LOG_SQL', 'USE_EXTERNAL_HTML2PDF', + 'LOGIN_LOG', 'LDAP_SEARCH_FILTER' + ); // List of all valid config options to be define()d which take booleans. $_IC_VALID_BOOL = array - ('ENABLE_USER_NEW', 'ENABLE_PAGEPERM', 'ENABLE_EDIT_TOOLBAR', 'JS_SEARCHREPLACE', - 'ENABLE_XHTML_XML', 'ENABLE_DOUBLECLICKEDIT', 'ENABLE_LIVESEARCH', 'ENABLE_ACDROPDOWN', - 'USECACHE', 'WIKIDB_NOCACHE_MARKUP', - 'ENABLE_REVERSE_DNS', 'ENCRYPTED_PASSWD', 'ZIPDUMP_AUTH', - 'ENABLE_RAW_HTML', 'ENABLE_RAW_HTML_LOCKEDONLY', 'ENABLE_RAW_HTML_SAFE', - 'STRICT_MAILABLE_PAGEDUMPS', 'COMPRESS_OUTPUT', - 'ALLOW_ANON_USER', 'ALLOW_ANON_EDIT', - 'ALLOW_BOGO_LOGIN', 'ALLOW_USER_PASSWORDS', - 'AUTH_USER_FILE_STORABLE', 'ALLOW_HTTP_AUTH_LOGIN', - 'ALLOW_USER_LOGIN', 'ALLOW_LDAP_LOGIN', 'ALLOW_IMAP_LOGIN', - 'WARN_NONPUBLIC_INTERWIKIMAP', 'USE_PATH_INFO', - 'DISABLE_HTTP_REDIRECT', - 'PLUGIN_CACHED_USECACHE', 'PLUGIN_CACHED_FORCE_SYNCMAP', - 'BLOG_DEFAULT_EMPTY_PREFIX', 'DATABASE_PERSISTENT', - 'FUSIONFORGE', - 'ENABLE_DISCUSSION_LINK', 'ENABLE_CAPTCHA', - 'ENABLE_WYSIWYG', 'WYSIWYG_DEFAULT_PAGETYPE_HTML', - 'DISABLE_MARKUP_WIKIWORD', 'ENABLE_MARKUP_COLOR', 'ENABLE_MARKUP_TEMPLATE', - 'ENABLE_MARKUP_MEDIAWIKI_TABLE', - 'ENABLE_MARKUP_DIVSPAN', 'USE_BYTEA', 'UPLOAD_USERDIR', 'DISABLE_UNITS', - 'ENABLE_SEARCHHIGHLIGHT', 'DISABLE_UPLOAD_ONLY_ALLOWED_EXTENSIONS', - 'ENABLE_AUTH_OPENID', 'INSECURE_ACTIONS_LOCALHOST_ONLY', - 'ENABLE_MAILNOTIFY', 'ENABLE_RECENTCHANGESBOX', 'ENABLE_PAGE_PUBLIC', - 'ENABLE_AJAX', 'ENABLE_EXTERNAL_PAGES', - 'READONLY' - ); + ('ENABLE_USER_NEW', 'ENABLE_PAGEPERM', 'ENABLE_EDIT_TOOLBAR', 'JS_SEARCHREPLACE', + 'ENABLE_XHTML_XML', 'ENABLE_DOUBLECLICKEDIT', 'ENABLE_LIVESEARCH', 'ENABLE_ACDROPDOWN', + 'USECACHE', 'WIKIDB_NOCACHE_MARKUP', + 'ENABLE_REVERSE_DNS', 'ENCRYPTED_PASSWD', 'ZIPDUMP_AUTH', + 'ENABLE_RAW_HTML', 'ENABLE_RAW_HTML_LOCKEDONLY', 'ENABLE_RAW_HTML_SAFE', + 'STRICT_MAILABLE_PAGEDUMPS', 'COMPRESS_OUTPUT', + 'ALLOW_ANON_USER', 'ALLOW_ANON_EDIT', + 'ALLOW_BOGO_LOGIN', 'ALLOW_USER_PASSWORDS', + 'AUTH_USER_FILE_STORABLE', 'ALLOW_HTTP_AUTH_LOGIN', + 'ALLOW_USER_LOGIN', 'ALLOW_LDAP_LOGIN', 'ALLOW_IMAP_LOGIN', + 'WARN_NONPUBLIC_INTERWIKIMAP', 'USE_PATH_INFO', + 'DISABLE_HTTP_REDIRECT', + 'PLUGIN_CACHED_USECACHE', 'PLUGIN_CACHED_FORCE_SYNCMAP', + 'BLOG_DEFAULT_EMPTY_PREFIX', 'DATABASE_PERSISTENT', + 'FUSIONFORGE', + 'ENABLE_DISCUSSION_LINK', 'ENABLE_CAPTCHA', + 'ENABLE_WYSIWYG', 'WYSIWYG_DEFAULT_PAGETYPE_HTML', + 'DISABLE_MARKUP_WIKIWORD', 'ENABLE_MARKUP_COLOR', 'ENABLE_MARKUP_TEMPLATE', + 'ENABLE_MARKUP_MEDIAWIKI_TABLE', + 'ENABLE_MARKUP_DIVSPAN', 'USE_BYTEA', 'UPLOAD_USERDIR', 'DISABLE_UNITS', + 'ENABLE_SEARCHHIGHLIGHT', 'DISABLE_UPLOAD_ONLY_ALLOWED_EXTENSIONS', + 'ENABLE_AUTH_OPENID', 'INSECURE_ACTIONS_LOCALHOST_ONLY', + 'ENABLE_MAILNOTIFY', 'ENABLE_RECENTCHANGESBOX', 'ENABLE_PAGE_PUBLIC', + 'ENABLE_AJAX', 'ENABLE_EXTERNAL_PAGES', + 'READONLY' + ); $rs = @parse_ini_file($file); - $rsdef = @parse_ini_file(dirname(__FILE__)."/../config/config-default.ini"); + $rsdef = @parse_ini_file(dirname(__FILE__) . "/../config/config-default.ini"); foreach ($rsdef as $k => $v) { if (defined($k)) { $rs[$k] = constant($k); @@ -217,7 +221,8 @@ function IniConfig($file) { $rs[$k] = $v; } } - unset($k); unset($v); + unset($k); + unset($v); foreach ($_IC_VALID_VALUE as $item) { if (defined($item)) { @@ -228,18 +233,18 @@ function IniConfig($file) { _check_int_constant($rs[$item]); define($item, $rs[$item]); unset($rs[$item]); - //} elseif (array_key_exists($item, $rsdef)) { - // define($item, $rsdef[$item]); - // calculate them later or not at all: + //} elseif (array_key_exists($item, $rsdef)) { + // define($item, $rsdef[$item]); + // calculate them later or not at all: } elseif (in_array($item, - array('DATABASE_PREFIX', 'SERVER_NAME', 'SERVER_PORT', - 'SCRIPT_NAME', 'DATA_PATH', 'PHPWIKI_DIR', 'VIRTUAL_PATH', - 'LDAP_AUTH_HOST','IMAP_AUTH_HOST','POP3_AUTH_HOST', - 'PLUGIN_CACHED_CACHE_DIR','EXTERNAL_HTML2PDF_PAGELIST'))) - { + array('DATABASE_PREFIX', 'SERVER_NAME', 'SERVER_PORT', + 'SCRIPT_NAME', 'DATA_PATH', 'PHPWIKI_DIR', 'VIRTUAL_PATH', + 'LDAP_AUTH_HOST', 'IMAP_AUTH_HOST', 'POP3_AUTH_HOST', + 'PLUGIN_CACHED_CACHE_DIR', 'EXTERNAL_HTML2PDF_PAGELIST')) + ) { ; } elseif (!defined("_PHPWIKI_INSTALL_RUNNING")) { - trigger_error(sprintf("missing config setting for %s",$item)); + trigger_error(sprintf("missing config setting for %s", $item)); } } unset($item); @@ -255,8 +260,8 @@ function IniConfig($file) { } if (array_key_exists($item, $rs)) { $val = $rs[$item]; - //} elseif (array_key_exists($item, $rsdef)) { - // $val = $rsdef[$item]; + //} elseif (array_key_exists($item, $rsdef)) { + // $val = $rsdef[$item]; } else { $val = false; //trigger_error(sprintf("missing boolean config setting for %s",$item)); @@ -265,26 +270,24 @@ function IniConfig($file) { // calculate them later: old or dynamic constants if (!array_key_exists($item, $rs) and in_array($item, array('USE_PATH_INFO', 'USE_DB_SESSION', - 'ALLOW_HTTP_AUTH_LOGIN', 'ALLOW_LDAP_LOGIN', - 'ALLOW_IMAP_LOGIN', 'ALLOW_USER_LOGIN', - 'REQUIRE_SIGNIN_BEFORE_EDIT', - 'WIKIDB_NOCACHE_MARKUP', - 'COMPRESS_OUTPUT', 'USE_BYTEA', 'READONLY', - ))) - { + 'ALLOW_HTTP_AUTH_LOGIN', 'ALLOW_LDAP_LOGIN', + 'ALLOW_IMAP_LOGIN', 'ALLOW_USER_LOGIN', + 'REQUIRE_SIGNIN_BEFORE_EDIT', + 'WIKIDB_NOCACHE_MARKUP', + 'COMPRESS_OUTPUT', 'USE_BYTEA', 'READONLY', + )) + ) { ; - } - elseif (!$val) { + } elseif (!$val) { define($item, false); - } - elseif (strtolower($val) == 'false' || - strtolower($val) == 'no' || - $val == '' || - $val == false || - $val == '0') { + } elseif (strtolower($val) == 'false' || + strtolower($val) == 'no' || + $val == '' || + $val == false || + $val == '0' + ) { define($item, false); - } - else { + } else { define($item, true); } unset($rs[$item]); @@ -293,15 +296,14 @@ function IniConfig($file) { // Database global $DBParams; - foreach (array('DATABASE_TYPE' => 'dbtype', - 'DATABASE_DSN' => 'dsn', - 'DATABASE_SESSION_TABLE' => 'db_session_table', - 'DATABASE_DBA_HANDLER' => 'dba_handler', - 'DATABASE_DIRECTORY' => 'directory', - 'DATABASE_TIMEOUT' => 'timeout', - 'DATABASE_PREFIX' => 'prefix') - as $item => $k) - { + foreach (array('DATABASE_TYPE' => 'dbtype', + 'DATABASE_DSN' => 'dsn', + 'DATABASE_SESSION_TABLE' => 'db_session_table', + 'DATABASE_DBA_HANDLER' => 'dba_handler', + 'DATABASE_DIRECTORY' => 'directory', + 'DATABASE_TIMEOUT' => 'timeout', + 'DATABASE_PREFIX' => 'prefix') + as $item => $k) { if (defined($item)) { $DBParams[$k] = constant($item); unset($rs[$item]); @@ -315,22 +317,22 @@ function IniConfig($file) { unset($rsdef[$item]); } } - $valid_database_types = array('SQL','ADODB','PDO','dba','file','flatfile','cvs','cvsclient'); + $valid_database_types = array('SQL', 'ADODB', 'PDO', 'dba', 'file', 'flatfile', 'cvs', 'cvsclient'); if (!in_array(DATABASE_TYPE, $valid_database_types)) trigger_error(sprintf("Invalid DATABASE_TYPE=%s. Choose one of %s", - DATABASE_TYPE, join(",", $valid_database_types)), - E_USER_ERROR); + DATABASE_TYPE, join(",", $valid_database_types)), + E_USER_ERROR); unset($valid_database_types); if (DATABASE_TYPE == 'PDO') { if (!check_php_version(5)) trigger_error("Invalid DATABASE_TYPE=PDO. PDO requires at least php-5.0!", - E_USER_ERROR); + E_USER_ERROR); // try to load it dynamically (unix only) if (!loadPhpExtension("pdo")) { echo $GLOBALS['php_errormsg'], "<br>\n"; trigger_error(sprintf("dl() problem: Required extension '%s' could not be loaded!", - "pdo"), - E_USER_ERROR); + "pdo"), + E_USER_ERROR); } } // Detect readonly database, e.g. system mounted read-only for maintenance @@ -339,23 +341,24 @@ function IniConfig($file) { // USE_DB_SESSION default logic: if (!defined('USE_DB_SESSION')) { if ($DBParams['db_session_table'] - and in_array($DBParams['dbtype'], array('SQL','ADODB','PDO','dba'))) { + and in_array($DBParams['dbtype'], array('SQL', 'ADODB', 'PDO', 'dba')) + ) { define('USE_DB_SESSION', true); } else { define('USE_DB_SESSION', false); } } - unset($item); unset($k); + unset($item); + unset($k); // Expiry stuff global $ExpireParams; - foreach (array('major','minor','author') as $major) { - foreach (array('max_age','min_age','min_keep','keep','max_keep') as $max) { - $item = strtoupper($major) . '_'. strtoupper($max); + foreach (array('major', 'minor', 'author') as $major) { + foreach (array('max_age', 'min_age', 'min_keep', 'keep', 'max_keep') as $max) { + $item = strtoupper($major) . '_' . strtoupper($max); if (defined($item)) $val = constant($item); elseif (array_key_exists($item, $rs)) - $val = $rs[$item]; - elseif (array_key_exists($item, $rsdef)) + $val = $rs[$item]; elseif (array_key_exists($item, $rsdef)) $val = $rsdef[$item]; if (!isset($ExpireParams[$major])) $ExpireParams[$major] = array(); @@ -363,13 +366,15 @@ function IniConfig($file) { unset($rs[$item]); } } - unset($item); unset($major); unset($max); + unset($item); + unset($major); + unset($max); // User authentication if (!isset($GLOBALS['USER_AUTH_ORDER'])) { if (isset($rs['USER_AUTH_ORDER'])) $GLOBALS['USER_AUTH_ORDER'] = preg_split('/\s*:\s*/', - $rs['USER_AUTH_ORDER']); + $rs['USER_AUTH_ORDER']); else $GLOBALS['USER_AUTH_ORDER'] = array("PersonalPage"); } @@ -381,18 +386,18 @@ function IniConfig($file) { global $DBAuthParams; $DBAP_MAP = array('DBAUTH_AUTH_DSN' => 'auth_dsn', - 'DBAUTH_AUTH_CHECK' => 'auth_check', - 'DBAUTH_AUTH_USER_EXISTS' => 'auth_user_exists', - 'DBAUTH_AUTH_CRYPT_METHOD' => 'auth_crypt_method', - 'DBAUTH_AUTH_UPDATE' => 'auth_update', - 'DBAUTH_AUTH_CREATE' => 'auth_create', - 'DBAUTH_PREF_SELECT' => 'pref_select', - 'DBAUTH_PREF_INSERT' => 'pref_insert', - 'DBAUTH_PREF_UPDATE' => 'pref_update', - 'DBAUTH_IS_MEMBER' => 'is_member', - 'DBAUTH_GROUP_MEMBERS' => 'group_members', - 'DBAUTH_USER_GROUPS' => 'user_groups' - ); + 'DBAUTH_AUTH_CHECK' => 'auth_check', + 'DBAUTH_AUTH_USER_EXISTS' => 'auth_user_exists', + 'DBAUTH_AUTH_CRYPT_METHOD' => 'auth_crypt_method', + 'DBAUTH_AUTH_UPDATE' => 'auth_update', + 'DBAUTH_AUTH_CREATE' => 'auth_create', + 'DBAUTH_PREF_SELECT' => 'pref_select', + 'DBAUTH_PREF_INSERT' => 'pref_insert', + 'DBAUTH_PREF_UPDATE' => 'pref_update', + 'DBAUTH_IS_MEMBER' => 'is_member', + 'DBAUTH_GROUP_MEMBERS' => 'group_members', + 'DBAUTH_USER_GROUPS' => 'user_groups' + ); foreach ($DBAP_MAP as $rskey => $apkey) { if (defined($rskey)) { $DBAuthParams[$apkey] = constant($rskey); @@ -405,40 +410,44 @@ function IniConfig($file) { } unset($rs[$rskey]); } - unset($rskey); unset($apkey); + unset($rskey); + unset($apkey); // TODO: Currently unsupported on non-SQL. Nice to have for RhNavPlugin // CHECKME: PDO if (!defined('ACCESS_LOG_SQL')) { if (array_key_exists('ACCESS_LOG_SQL', $rs)) { // WikiDB_backend::isSql() not yet loaded - if (!in_array(DATABASE_TYPE, array('SQL','ADODB','PDO'))) { + if (!in_array(DATABASE_TYPE, array('SQL', 'ADODB', 'PDO'))) { // override false config setting on no SQL WikiDB database. define('ACCESS_LOG_SQL', 0); } - // SQL defaults to ACCESS_LOG_SQL = 2 + // SQL defaults to ACCESS_LOG_SQL = 2 } else { define('ACCESS_LOG_SQL', - in_array(DATABASE_TYPE, array('SQL','ADODB','PDO')) ? 2 : 0); + in_array(DATABASE_TYPE, array('SQL', 'ADODB', 'PDO')) ? 2 : 0); } } global $PLUGIN_MARKUP_MAP; $PLUGIN_MARKUP_MAP = array(); if (defined('PLUGIN_MARKUP_MAP') and trim(PLUGIN_MARKUP_MAP) != "") { - $_map = preg_split('/\s+/', PLUGIN_MARKUP_MAP); - foreach ($_map as $v) { - list($xml,$plugin) = explode(':', $v); - if (!empty($xml) and !empty($plugin)) - $PLUGIN_MARKUP_MAP[$xml] = $plugin; - } - unset($_map); unset($xml); unset($plugin); unset($v); + $_map = preg_split('/\s+/', PLUGIN_MARKUP_MAP); + foreach ($_map as $v) { + list($xml, $plugin) = explode(':', $v); + if (!empty($xml) and !empty($plugin)) + $PLUGIN_MARKUP_MAP[$xml] = $plugin; + } + unset($_map); + unset($xml); + unset($plugin); + unset($v); } if (empty($rs['TEMP_DIR'])) { - $rs['TEMP_DIR'] = "/tmp"; - if (getenv("TEMP")) - $rs['TEMP_DIR'] = getenv("TEMP"); + $rs['TEMP_DIR'] = "/tmp"; + if (getenv("TEMP")) + $rs['TEMP_DIR'] = getenv("TEMP"); } // optional values will be set to '' to simplify the logic. foreach ($_IC_OPTIONAL_VALUE as $item) { @@ -447,7 +456,7 @@ function IniConfig($file) { continue; } if (array_key_exists($item, $rs)) { - _check_int_constant($rs[$item]); + _check_int_constant($rs[$item]); define($item, $rs[$item]); unset($rs[$item]); } else @@ -455,7 +464,7 @@ function IniConfig($file) { } if (USE_EXTERNAL_HTML2PDF) { - $item = 'EXTERNAL_HTML2PDF_PAGELIST'; + $item = 'EXTERNAL_HTML2PDF_PAGELIST'; if (defined($item)) { unset($rs[$item]); } elseif (array_key_exists($item, $rs)) { @@ -463,7 +472,7 @@ function IniConfig($file) { unset($rs[$item]); } elseif (array_key_exists($item, $rsdef)) { define($item, $rsdef[$item]); - } + } } unset($item); @@ -477,12 +486,12 @@ function IniConfig($file) { if (is_string($bits[0]) and defined($bits[0])) $bits[0] = constant($bits[0]); $LDAP_SET_OPTION[$bits[0]] = $bits[1]; - } - else { + } else { // Possibly throw some sort of error? } } - unset($opt); unset($bits); + unset($opt); + unset($bits); } // Default Wiki pages to force loading from pgsrc @@ -494,7 +503,7 @@ function IniConfig($file) { global $WikiNameRegexp; $WikiNameRegexp = constant('WIKI_NAME_REGEXP'); if (!trim($WikiNameRegexp)) - $WikiNameRegexp = '(?<![[:alnum:]])(?:[[:upper:]][[:lower:]]+){2,}(?![[:alnum:]])'; + $WikiNameRegexp = '(?<![[:alnum:]])(?:[[:upper:]][[:lower:]]+){2,}(?![[:alnum:]])'; // Got rid of global $KeywordLinkRegexp by using a TextSearchQuery instead // of "Category:Topic" @@ -508,7 +517,8 @@ function IniConfig($file) { // TODO: can this be a constant? global $DisabledActions; if (!array_key_exists('DISABLED_ACTIONS', $rs) - and array_key_exists('DISABLED_ACTIONS', $rsdef)) + and array_key_exists('DISABLED_ACTIONS', $rsdef) + ) $rs['DISABLED_ACTIONS'] = @$rsdef['DISABLED_ACTIONS']; if (array_key_exists('DISABLED_ACTIONS', $rs)) $DisabledActions = preg_split('/\s*:\s*/', $rs['DISABLED_ACTIONS']); @@ -526,11 +536,11 @@ function IniConfig($file) { } $rs['PLUGIN_CACHED_CACHE_DIR'] = TEMP_DIR . '/cache'; if (!FindFile($rs['PLUGIN_CACHED_CACHE_DIR'], 1)) { // [29ms] - FindFile(TEMP_DIR, false, 1); // TEMP must exist! + FindFile(TEMP_DIR, false, 1); // TEMP must exist! mkdir($rs['PLUGIN_CACHED_CACHE_DIR'], 0777); } // will throw an error if not exists. - define('PLUGIN_CACHED_CACHE_DIR', FindFile($rs['PLUGIN_CACHED_CACHE_DIR'],false,1)); + define('PLUGIN_CACHED_CACHE_DIR', FindFile($rs['PLUGIN_CACHED_CACHE_DIR'], false, 1)); } else { define('PLUGIN_CACHED_CACHE_DIR', $rs['PLUGIN_CACHED_CACHE_DIR']); // will throw an error if not exists. @@ -543,11 +553,12 @@ function IniConfig($file) { if (defined($item)) { continue; } else { - _check_int_constant($v); + _check_int_constant($v); define($item, $v); } } - unset($item); unset($v); + unset($item); + unset($v); unset($rs); unset($rsdef); @@ -562,22 +573,25 @@ function IniConfig($file) { fixup_dynamic_configs($file); // [100ms] } -function _ignore_unknown_charset_warning(&$error) { +function _ignore_unknown_charset_warning(&$error) +{ //htmlspecialchars(): charset `iso-8859-2' not supported, assuming iso-8859-1 if (preg_match('/^htmlspecialchars\(\): charset \`.+\' not supported, assuming iso-8859-1/', - $error->errstr)) { + $error->errstr) + ) { $error->errno = 0; - return true; // Ignore error + return true; // Ignore error } return false; } // moved from lib/config.php [1ms] -function fixup_static_configs($file) { +function fixup_static_configs($file) +{ global $FieldSeparator, $charset, $WikiNameRegexp, $AllActionPages; global $HTTP_SERVER_VARS, $DBParams, $LANG, $ErrorManager; // init FileFinder to add proper include paths - FindFile("lib/interwiki.map",true); + FindFile("lib/interwiki.map", true); // "\x80"-"\x9f" (and "\x00" - "\x1f") are non-printing control // chars in iso-8859-* @@ -598,48 +612,48 @@ function fixup_static_configs($file) { // See <php-src>/ext/standard/html.c // For performance reasons we require a magic constant to ignore this warning. if (defined('IGNORE_CHARSET_NOT_SUPPORTED_WARNING') - and IGNORE_CHARSET_NOT_SUPPORTED_WARNING) - { + and IGNORE_CHARSET_NOT_SUPPORTED_WARNING + ) { $ErrorManager->pushErrorHandler - (new WikiFunctionCb('_ignore_unknown_charset_warning')); + (new WikiFunctionCb('_ignore_unknown_charset_warning')); } // All pages containing plugins of the same name as the filename $ActionPages = explode(':', - 'AllPages:AllUsers:AppendText:AuthorHistory:' - .'BackLinks:' - .'CreatePage:' - .'FullTextSearch:FuzzyPages:' - .'LikePages:LinkDatabase:LinkSearch:ListRelations:' - .'ModeratedPage:MostPopular:' - .'NewPagesPerUser:' - .'OrphanedPages:' - .'PageDump:PageHistory:PageInfo:PluginManager:' - .'RateIt:' // RateIt works only in wikilens derived themes - .'RandomPage:RecentChanges:RelatedChanges:RecentEdits:' - .'SearchHighlight:SemanticRelations:SemanticSearch:SystemInfo:' - .'TitleSearch:' - .'UpLoad:UserPreferences:' - .'UserRatings:' // UserRatings works only in wikilens derived themes - .'WantedPages:WatchPage:WhoIsOnline:WikiAdminSelect'); + 'AllPages:AllUsers:AppendText:AuthorHistory:' + . 'BackLinks:' + . 'CreatePage:' + . 'FullTextSearch:FuzzyPages:' + . 'LikePages:LinkDatabase:LinkSearch:ListRelations:' + . 'ModeratedPage:MostPopular:' + . 'NewPagesPerUser:' + . 'OrphanedPages:' + . 'PageDump:PageHistory:PageInfo:PluginManager:' + . 'RateIt:' // RateIt works only in wikilens derived themes + . 'RandomPage:RecentChanges:RelatedChanges:RecentEdits:' + . 'SearchHighlight:SemanticRelations:SemanticSearch:SystemInfo:' + . 'TitleSearch:' + . 'UpLoad:UserPreferences:' + . 'UserRatings:' // UserRatings works only in wikilens derived themes + . 'WantedPages:WatchPage:WhoIsOnline:WikiAdminSelect'); // The FUSIONFORGE theme omits them if (!FUSIONFORGE) { - // Add some some action pages depending on configuration - if (DEBUG) { - $ActionPages[] = 'DebugInfo'; - $ActionPages[] = 'EditMetaData'; - $ActionPages[] = 'SpellCheck'; // SpellCheck does not work - } - $ActionPages[] = 'BlogArchives'; - $ActionPages[] = 'BlogJournal'; - $ActionPages[] = 'InterWikiSearch'; - $ActionPages[] = 'LdapSearch'; - $ActionPages[] = 'PasswordReset'; - $ActionPages[] = 'RecentComments'; - $ActionPages[] = 'TranslateText'; - $ActionPages[] = 'UriResolver'; - $ActionPages[] = 'WikiBlog'; + // Add some some action pages depending on configuration + if (DEBUG) { + $ActionPages[] = 'DebugInfo'; + $ActionPages[] = 'EditMetaData'; + $ActionPages[] = 'SpellCheck'; // SpellCheck does not work + } + $ActionPages[] = 'BlogArchives'; + $ActionPages[] = 'BlogJournal'; + $ActionPages[] = 'InterWikiSearch'; + $ActionPages[] = 'LdapSearch'; + $ActionPages[] = 'PasswordReset'; + $ActionPages[] = 'RecentComments'; + $ActionPages[] = 'TranslateText'; + $ActionPages[] = 'UriResolver'; + $ActionPages[] = 'WikiBlog'; } global $AllAllowedPlugins; @@ -778,19 +792,19 @@ function fixup_static_configs($file) { // The FUSIONFORGE theme omits them if (!FUSIONFORGE) { - // Add some some action pages depending on configuration - if (DEBUG) { - $AllActionPages[] = 'PhpWikiAdministration/Chmod'; - } - $AllActionPages[] = 'PhpWikiAdministration/Markup'; + // Add some some action pages depending on configuration + if (DEBUG) { + $AllActionPages[] = 'PhpWikiAdministration/Chmod'; + } + $AllActionPages[] = 'PhpWikiAdministration/Markup'; } if (FUSIONFORGE) { - if (ENABLE_EXTERNAL_PAGES) { - $AllAllowedPlugins[] = 'WikiAdminSetExternal'; - $AllActionPages[] = 'PhpWikiAdministration/SetExternal'; - $AllActionPages[] = 'ExternalPages'; - } + if (ENABLE_EXTERNAL_PAGES) { + $AllAllowedPlugins[] = 'WikiAdminSetExternal'; + $AllActionPages[] = 'PhpWikiAdministration/SetExternal'; + $AllActionPages[] = 'ExternalPages'; + } } // If user has not defined PHPWIKI_DIR, and we need it @@ -806,7 +820,7 @@ function fixup_static_configs($file) { if (!defined('SCRIPT_NAME')) define('SCRIPT_NAME', deduce_script_name()); $temp = dirname(SCRIPT_NAME); - if ( ($temp == '/') || ($temp == '\\') ) + if (($temp == '/') || ($temp == '\\')) $temp = ''; define('DATA_PATH', $temp); /* @@ -830,10 +844,10 @@ function fixup_static_configs($file) { // check whether the crypt() function is needed and present if (defined('ENCRYPTED_PASSWD') && !function_exists('crypt')) { $error = sprintf("Encrypted passwords cannot be used: %s.", - "'function crypt()' not available in this version of php"); + "'function crypt()' not available in this version of php"); trigger_error($error, E_USER_WARNING); if (!preg_match("/config\-dist\.ini$/", $file)) { // protect against recursion - include_once(dirname(__FILE__)."/install.php"); + include_once(dirname(__FILE__) . "/install.php"); run_install("_part1"); exit(); } @@ -842,12 +856,12 @@ function fixup_static_configs($file) { // Basic configurator validation if (!defined('ADMIN_USER') or ADMIN_USER == '') { $error = sprintf("%s may not be empty. Please update your configuration.", - "ADMIN_USER"); + "ADMIN_USER"); // protect against recursion if (!preg_match("/config\-(dist|default)\.ini$/", $file) - and !defined("_PHPWIKI_INSTALL_RUNNING")) - { - include_once(dirname(__FILE__)."/install.php"); + and !defined("_PHPWIKI_INSTALL_RUNNING") + ) { + include_once(dirname(__FILE__) . "/install.php"); run_install("_part1"); trigger_error($error, E_USER_ERROR); exit(); @@ -858,12 +872,12 @@ function fixup_static_configs($file) { } if (!defined('ADMIN_PASSWD') or ADMIN_PASSWD == '') { $error = sprintf("%s may not be empty. Please update your configuration.", - "ADMIN_PASSWD"); + "ADMIN_PASSWD"); // protect against recursion if (!preg_match("/config\-(dist|default)\.ini$/", $file) - and !defined("_PHPWIKI_INSTALL_RUNNING")) - { - include_once(dirname(__FILE__)."/install.php"); + and !defined("_PHPWIKI_INSTALL_RUNNING") + ) { + include_once(dirname(__FILE__) . "/install.php"); run_install("_part1"); trigger_error($error, E_USER_ERROR); exit(); @@ -874,28 +888,28 @@ function fixup_static_configs($file) { } if (defined('USE_DB_SESSION') and USE_DB_SESSION) { - if (! $DBParams['db_session_table'] ) { + if (!$DBParams['db_session_table']) { $DBParams['db_session_table'] = @$DBParams['prefix'] . 'session'; trigger_error(sprintf("DATABASE_SESSION_TABLE configuration set to %s.", - $DBParams['db_session_table']), - E_USER_ERROR); + $DBParams['db_session_table']), + E_USER_ERROR); } } // legacy: - if (!defined('ENABLE_USER_NEW')) define('ENABLE_USER_NEW',true); + if (!defined('ENABLE_USER_NEW')) define('ENABLE_USER_NEW', true); if (!defined('ALLOW_USER_LOGIN')) define('ALLOW_USER_LOGIN', defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS); if (!defined('ALLOW_ANON_USER')) define('ALLOW_ANON_USER', true); if (!defined('ALLOW_ANON_EDIT')) define('ALLOW_ANON_EDIT', false); - if (!defined('REQUIRE_SIGNIN_BEFORE_EDIT')) define('REQUIRE_SIGNIN_BEFORE_EDIT', ! ALLOW_ANON_EDIT); + if (!defined('REQUIRE_SIGNIN_BEFORE_EDIT')) define('REQUIRE_SIGNIN_BEFORE_EDIT', !ALLOW_ANON_EDIT); if (!defined('ALLOW_BOGO_LOGIN')) define('ALLOW_BOGO_LOGIN', true); if (!ENABLE_USER_NEW) { - if (!defined('ALLOW_HTTP_AUTH_LOGIN')) - define('ALLOW_HTTP_AUTH_LOGIN', false); - if (!defined('ALLOW_LDAP_LOGIN')) - define('ALLOW_LDAP_LOGIN', function_exists('ldap_connect') and defined('LDAP_AUTH_HOST')); - if (!defined('ALLOW_IMAP_LOGIN')) - define('ALLOW_IMAP_LOGIN', function_exists('imap_open') and defined('IMAP_AUTH_HOST')); + if (!defined('ALLOW_HTTP_AUTH_LOGIN')) + define('ALLOW_HTTP_AUTH_LOGIN', false); + if (!defined('ALLOW_LDAP_LOGIN')) + define('ALLOW_LDAP_LOGIN', function_exists('ldap_connect') and defined('LDAP_AUTH_HOST')); + if (!defined('ALLOW_IMAP_LOGIN')) + define('ALLOW_IMAP_LOGIN', function_exists('imap_open') and defined('IMAP_AUTH_HOST')); } if (ALLOW_USER_LOGIN and !empty($DBAuthParams) and empty($DBAuthParams['auth_dsn'])) { @@ -909,7 +923,8 @@ function fixup_static_configs($file) { * Such as the language, and the virtual and server paths, which might be overridden * by startup scripts for wiki farms. */ -function fixup_dynamic_configs($file) { +function fixup_dynamic_configs($file) +{ global $WikiNameRegexp; global $HTTP_SERVER_VARS, $DBParams, $LANG; @@ -919,13 +934,13 @@ function fixup_dynamic_configs($file) { } if (defined('SESSION_SAVE_PATH') and SESSION_SAVE_PATH) @ini_set('session.save_path', SESSION_SAVE_PATH); - if (!defined('DEFAULT_LANGUAGE')) // not needed anymore + if (!defined('DEFAULT_LANGUAGE')) // not needed anymore define('DEFAULT_LANGUAGE', ''); // detect from client // FusionForge hack if (!FUSIONFORGE) { // Disable update_locale because Zend Debugger crash - if(! extension_loaded('Zend Debugger')) { + if (!extension_loaded('Zend Debugger')) { update_locale(isset($LANG) ? $LANG : DEFAULT_LANGUAGE); } } @@ -934,32 +949,33 @@ function fixup_dynamic_configs($file) { if (!defined("DEFAULT_LANGUAGE") or !DEFAULT_LANGUAGE) { // TODO: defer this to WikiRequest::initializeLang() $LANG = guessing_lang(); - guessing_setlocale (LC_ALL,$LANG); - } - else + guessing_setlocale(LC_ALL, $LANG); + } else $LANG = DEFAULT_LANGUAGE; } // Set up (possibly fake) gettext() // Todo: this could be moved to fixup_static_configs() // Bug #1381464 with php-5.1.1 - if (!function_exists ('bindtextdomain') - and !function_exists ('gettext') - and !function_exists ('_')) - { + if (!function_exists('bindtextdomain') + and !function_exists('gettext') + and !function_exists('_') + ) { $locale = array(); - function gettext ($text) { + function gettext($text) + { global $locale; if (!empty ($locale[$text])) return $locale[$text]; return $text; } - function _ ($text) { + + function _($text) + { return gettext($text); } - } - else { + } else { $chback = 0; if ($LANG != 'en') { @@ -991,7 +1007,7 @@ function fixup_dynamic_configs($file) { // language dependent updates: if (!defined('CATEGORY_GROUP_PAGE')) - define('CATEGORY_GROUP_PAGE',_("CategoryGroup")); + define('CATEGORY_GROUP_PAGE', _("CategoryGroup")); if (!defined('WIKI_NAME')) define('WIKI_NAME', _("An unnamed PhpWiki")); if (!defined('HOME_PAGE')) @@ -1000,13 +1016,14 @@ function fixup_dynamic_configs($file) { ////////////////////////////////////////////////////////////////// // Autodetect URL settings: // - foreach (array('SERVER_NAME','SERVER_PORT') as $var) { + foreach (array('SERVER_NAME', 'SERVER_PORT') as $var) { //FIXME: for CGI without _SERVER if (!defined($var) and !empty($HTTP_SERVER_VARS[$var])) // IPV6 fix by matt brown, #1546571 // An IPv6 address must be surrounded by square brackets to form a valid server name. if ($var == 'SERVER_NAME' && - strstr($HTTP_SERVER_VARS[$var], ':')) { + strstr($HTTP_SERVER_VARS[$var], ':') + ) { define($var, '[' . $HTTP_SERVER_VARS[$var] . ']'); } else { define($var, $HTTP_SERVER_VARS[$var]); @@ -1038,29 +1055,29 @@ function fixup_dynamic_configs($file) { * php script is...) */ switch (php_sapi_name()) { - case 'apache': - case 'apache2handler': - define('USE_PATH_INFO', true); - break; - case 'cgi': - case 'apache2filter': - define('USE_PATH_INFO', false); - break; - default: - define('USE_PATH_INFO', ereg('\.(php3?|cgi)$', SCRIPT_NAME)); - break; + case 'apache': + case 'apache2handler': + define('USE_PATH_INFO', true); + break; + case 'cgi': + case 'apache2filter': + define('USE_PATH_INFO', false); + break; + default: + define('USE_PATH_INFO', ereg('\.(php3?|cgi)$', SCRIPT_NAME)); + break; } } } if (SERVER_PORT - && SERVER_PORT != (SERVER_PROTOCOL == 'https' ? 443 : 80)) { + && SERVER_PORT != (SERVER_PROTOCOL == 'https' ? 443 : 80) + ) { define('SERVER_URL', - SERVER_PROTOCOL . '://' . SERVER_NAME . ':' . SERVER_PORT); - } - else { + SERVER_PROTOCOL . '://' . SERVER_NAME . ':' . SERVER_PORT); + } else { define('SERVER_URL', - SERVER_PROTOCOL . '://' . SERVER_NAME); + SERVER_PROTOCOL . '://' . SERVER_NAME); } if (!defined('VIRTUAL_PATH')) { @@ -1086,11 +1103,12 @@ function fixup_dynamic_configs($file) { $REDIRECT_URL = &$HTTP_SERVER_VARS['REDIRECT_URL']; if (USE_PATH_INFO and isset($REDIRECT_URL) - and ! IsProbablyRedirectToIndex()) { + and !IsProbablyRedirectToIndex() + ) { // FIXME: This is a hack, and won't work if the requested // pagename has a slash in it. - $temp = strtr(dirname($REDIRECT_URL . 'x'),"\\",'/'); - if ( ($temp == '/') || ($temp == '\\') ) + $temp = strtr(dirname($REDIRECT_URL . 'x'), "\\", '/'); + if (($temp == '/') || ($temp == '\\')) $temp = ''; define('VIRTUAL_PATH', $temp); } else { @@ -1108,7 +1126,7 @@ function fixup_dynamic_configs($file) { } define('PHPWIKI_BASE_URL', - SERVER_URL . (USE_PATH_INFO ? VIRTUAL_PATH . '/' : SCRIPT_NAME)); + SERVER_URL . (USE_PATH_INFO ? VIRTUAL_PATH . '/' : SCRIPT_NAME)); // Detect PrettyWiki setup (not loading index.php directly) // $SCRIPT_FILENAME should be the same as __FILE__ in index.php @@ -1117,15 +1135,16 @@ function fixup_dynamic_configs($file) { if (!isset($SCRIPT_FILENAME)) $SCRIPT_FILENAME = @$HTTP_ENV_VARS['SCRIPT_FILENAME']; if (!isset($SCRIPT_FILENAME)) - $SCRIPT_FILENAME = dirname(__FILE__.'/../') . '/index.php'; + $SCRIPT_FILENAME = dirname(__FILE__ . '/../') . '/index.php'; if (isWindows()) - $SCRIPT_FILENAME = str_replace('\\\\','\\',strtr($SCRIPT_FILENAME, '/', '\\')); + $SCRIPT_FILENAME = str_replace('\\\\', '\\', strtr($SCRIPT_FILENAME, '/', '\\')); define('SCRIPT_FILENAME', $SCRIPT_FILENAME); // Get remote host name, if Apache hasn't done it for us if (empty($HTTP_SERVER_VARS['REMOTE_HOST']) and !empty($HTTP_SERVER_VARS['REMOTE_ADDR']) - and ENABLE_REVERSE_DNS) + and ENABLE_REVERSE_DNS + ) $HTTP_SERVER_VARS['REMOTE_HOST'] = gethostbyaddr($HTTP_SERVER_VARS['REMOTE_ADDR']); } diff --git a/lib/InlineParser.php b/lib/InlineParser.php index 70203fe94..5a38c6353 100644 --- a/lib/InlineParser.php +++ b/lib/InlineParser.php @@ -35,13 +35,15 @@ define('ESCAPE_CHAR', '~'); require_once 'lib/CachedMarkup.php'; -require_once(dirname(__FILE__).'/stdlib.php'); +require_once(dirname(__FILE__) . '/stdlib.php'); -function WikiEscape($text) { +function WikiEscape($text) +{ return str_replace('#', ESCAPE_CHAR . '#', $text); } -function UnWikiEscape($text) { +function UnWikiEscape($text) +{ return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text); } @@ -50,7 +52,8 @@ function UnWikiEscape($text) { * * @see RegexpSet */ -class RegexpSet_match { +class RegexpSet_match +{ /** * The text leading up the the next match. */ @@ -83,10 +86,11 @@ class RegexpSet * "(...)". (Anonymous groups, like "(?:...)", as well as * look-ahead and look-behind assertions are okay.) */ - function RegexpSet ($regexps) { + function RegexpSet($regexps) + { assert($regexps); $this->_regexps = array_unique($regexps); - if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION',0); + if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION', 0); } /** @@ -96,7 +100,8 @@ class RegexpSet * * @return RegexpSet_match A RegexpSet_match object, or false if no match. */ - function match ($text) { + function match($text) + { return $this->_match($text, $this->_regexps, '*?'); } @@ -118,13 +123,14 @@ class RegexpSet * * @return RegexpSet_match A RegexpSet_match object, or false if no match. */ - function nextMatch ($text, $prevMatch) { + function nextMatch($text, $prevMatch) + { // Try to find match at same position. $pos = strlen($prevMatch->prematch); $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1); if ($regexps) { $repeat = sprintf('{%d}', $pos); - if ( ($match = $this->_match($text, $regexps, $repeat)) ) { + if (($match = $this->_match($text, $regexps, $repeat))) { $match->regexp_ind += $prevMatch->regexp_ind + 1; return $match; } @@ -141,45 +147,47 @@ class RegexpSet // s - DOTALL // A - ANCHORED // S - STUDY - function _match ($text, $regexps, $repeat) { + function _match($text, $regexps, $repeat) + { // If one of the regexps is an empty string, php will crash here: // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted // (tried to allocate 634 bytes) if (_INLINE_OPTIMIZATION) { // disabled, wrong - // So we try to minize memory usage, by looping explicitly, - // and storing only those regexp which actually match. - // There may be more than one, so we have to find the longest, - // and match inside until the shortest is empty. - $matched = array(); $matched_ind = array(); - for ($i=0; $i<count($regexps); $i++) { - if (!trim($regexps[$i])) { - trigger_error("empty regexp $i", E_USER_WARNING); - continue; - } - $pat= "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x"; - if (preg_match($pat, $text, $_m)) { - $m = $_m; // FIXME: prematch, postmatch is wrong - $matched[] = $regexps[$i]; - $matched_ind[] = $i; - $regexp_ind = $i; - } - } - // To overcome ANCHORED: - // We could sort by longest match and iterate over these. - if (empty($matched)) return false; + // So we try to minize memory usage, by looping explicitly, + // and storing only those regexp which actually match. + // There may be more than one, so we have to find the longest, + // and match inside until the shortest is empty. + $matched = array(); + $matched_ind = array(); + for ($i = 0; $i < count($regexps); $i++) { + if (!trim($regexps[$i])) { + trigger_error("empty regexp $i", E_USER_WARNING); + continue; + } + $pat = "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x"; + if (preg_match($pat, $text, $_m)) { + $m = $_m; // FIXME: prematch, postmatch is wrong + $matched[] = $regexps[$i]; + $matched_ind[] = $i; + $regexp_ind = $i; + } + } + // To overcome ANCHORED: + // We could sort by longest match and iterate over these. + if (empty($matched)) return false; } $match = new RegexpSet_match; // Optimization: if the matches are only "$" and another, then omit "$" - if (! _INLINE_OPTIMIZATION or count($matched) > 2) { + if (!_INLINE_OPTIMIZATION or count($matched) > 2) { assert(!empty($repeat)); assert(!empty($regexps)); // We could do much better, if we would know the matching markup for the // longest regexp match: - $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx"; + $hugepat = "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx"; // Proposed premature optimization 1: //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx"; - if (! preg_match($hugepat, $text, $m)) { + if (!preg_match($hugepat, $text, $m)) { return false; } // Proposed premature optimization 1: @@ -195,25 +203,25 @@ class RegexpSet /* DEBUGGING */ if (DEBUG & _DEBUG_PARSER) { - static $_already_dumped = 0; - if (!$_already_dumped) { - var_dump($regexps); - if (_INLINE_OPTIMIZATION) - var_dump($matched); - var_dump($matched_ind); - } - $_already_dumped = 1; - PrintXML(HTML::dl(HTML::dt("input"), - HTML::dd(HTML::pre($text)), - HTML::dt("regexp"), - HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])), - HTML::dt("prematch"), - HTML::dd(HTML::pre($match->prematch)), - HTML::dt("match"), - HTML::dd(HTML::pre($match->match)), - HTML::dt("postmatch"), - HTML::dd(HTML::pre($match->postmatch)) - )); + static $_already_dumped = 0; + if (!$_already_dumped) { + var_dump($regexps); + if (_INLINE_OPTIMIZATION) + var_dump($matched); + var_dump($matched_ind); + } + $_already_dumped = 1; + PrintXML(HTML::dl(HTML::dt("input"), + HTML::dd(HTML::pre($text)), + HTML::dt("regexp"), + HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])), + HTML::dt("prematch"), + HTML::dd(HTML::pre($match->prematch)), + HTML::dt("match"), + HTML::dd(HTML::pre($match->match)), + HTML::dt("postmatch"), + HTML::dd(HTML::pre($match->postmatch)) + )); } return $match; } @@ -235,7 +243,8 @@ class SimpleMarkup * * @return string Regexp which matches this token. */ - function getMatchRegexp () { + function getMatchRegexp() + { return $this->_match_regexp; } @@ -246,7 +255,8 @@ class SimpleMarkup * * @return mixed The expansion of the matched text. */ - function markup ($match /*, $body */) { + function markup($match /*, $body */) + { trigger_error("pure virtual", E_USER_ERROR); } } @@ -264,7 +274,8 @@ class BalancedMarkup * * @return string The starting regexp. */ - function getStartRegexp () { + function getStartRegexp() + { return $this->_start_regexp; } @@ -274,7 +285,8 @@ class BalancedMarkup * * @return string The ending regexp. */ - function getEndRegexp ($match) { + function getEndRegexp($match) + { return $this->_end_regexp; } @@ -287,18 +299,21 @@ class BalancedMarkup * * @return mixed The expansion of the matched text. */ - function markup ($match, $body) { + function markup($match, $body) + { trigger_error("pure virtual", E_USER_ERROR); } } -class Markup_escape extends SimpleMarkup +class Markup_escape extends SimpleMarkup { - function getMatchRegexp () { + function getMatchRegexp() + { return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)'; } - function markup ($match) { + function markup($match) + { assert(strlen($match) >= 2); return substr($match, 1); } @@ -312,33 +327,35 @@ class Markup_escape extends SimpleMarkup * width=n, height=n * title, lang, id, alt */ -function isImageLink($link) { +function isImageLink($link) +{ if (!$link) return false; assert(defined('INLINE_IMAGES')); return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link) or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace|type|data|width|height|title|lang|id|alt)=/i", $link); } -function LinkBracketLink($bracketlink) { +function LinkBracketLink($bracketlink) +{ // $bracketlink will start and end with brackets; in between will // be either a page name, a URL or both separated by a pipe. - $wikicreolesyntax = false; + $wikicreolesyntax = false; - if (string_starts_with($bracketlink, "[[") or string_starts_with($bracketlink, "#[[")) { - $wikicreolesyntax = true; - $bracketlink = str_replace("[[", "[", $bracketlink); - $bracketlink = str_replace("]]", "]", $bracketlink); - } + if (string_starts_with($bracketlink, "[[") or string_starts_with($bracketlink, "#[[")) { + $wikicreolesyntax = true; + $bracketlink = str_replace("[[", "[", $bracketlink); + $bracketlink = str_replace("]]", "]", $bracketlink); + } // Strip brackets and leading space // bug#1904088 Some brackets links on 2 lines cause the parser to crash preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x', - str_replace("\n", " ", $bracketlink), $matches); + str_replace("\n", " ", $bracketlink), $matches); if (count($matches) < 4) { // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]" - trigger_error(_("Invalid [] syntax ignored")._(": ").$bracketlink, E_USER_WARNING); + trigger_error(_("Invalid [] syntax ignored") . _(": ") . $bracketlink, E_USER_WARNING); return new Cached_Link; } list (, $hash, $label, $bar, $rawlink) = $matches; @@ -374,31 +391,31 @@ function LinkBracketLink($bracketlink) { * "[http:/server/~name/]" will work as expected * "http:/server/~name/" will NOT work as expected, will remove the ~ */ - if ( string_starts_with ($rawlink, "http://") - or string_starts_with ($rawlink, "https://") ) - { + if (string_starts_with($rawlink, "http://") + or string_starts_with($rawlink, "https://") + ) { $link = $rawlink; // Mozilla Browser URI Obfuscation Weakness 2004-06-14 // http://www.securityfocus.com/bid/10532/ // goodurl+"%2F%20%20%20."+badurl if (preg_match("/%2F(%20)+\./i", $rawlink)) { - $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink); + $rawlink = preg_replace("/%2F(%20)+\./i", "%2F.", $rawlink); } } else { // Check page name lenght if (!string_starts_with($rawlink, "Upload:")) { if (strlen($rawlink) > MAX_PAGENAME_LENGTH) { return HTML::span(array('class' => 'error'), - _('Page name too long')); + _('Page name too long')); } } // Check illegal characters in page names: <>[]{}|" if (preg_match("/[<\[\{\|\"\}\]>]/", $rawlink, $matches) > 0) { return HTML::span(array('class' => 'error'), - sprintf(_("Illegal character '%s' in page name."), - $matches[0])); + sprintf(_("Illegal character '%s' in page name."), + $matches[0])); } - $link = UnWikiEscape($rawlink); + $link = UnWikiEscape($rawlink); } /* Relatives links by Joel Schaubert. @@ -426,29 +443,29 @@ function LinkBracketLink($bracketlink) { } } else - // [label|link] - // If label looks like a url to an image or object, we want an image link. - if (isImageLink($label)) { - $imgurl = $label; - $intermap = getInterwikiMap(); - if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) { - $imgurl = $intermap->link($label); - $imgurl = $imgurl->getAttr('href'); - } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) { - // local theme linkname like 'images/next.gif'. - global $WikiTheme; - $imgurl = $WikiTheme->getImageURL($imgurl); + // [label|link] + // If label looks like a url to an image or object, we want an image link. + if (isImageLink($label)) { + $imgurl = $label; + $intermap = getInterwikiMap(); + if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) { + $imgurl = $intermap->link($label); + $imgurl = $imgurl->getAttr('href'); + } elseif (!preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) { + // local theme linkname like 'images/next.gif'. + global $WikiTheme; + $imgurl = $WikiTheme->getImageURL($imgurl); + } + // for objects (non-images) the link is taken as alt tag, + // which is in return taken as alternative img + $label = LinkImage($imgurl, $link); } - // for objects (non-images) the link is taken as alt tag, - // which is in return taken as alternative img - $label = LinkImage($imgurl, $link); - } if ($hash) { // It's an anchor, not a link... $id = MangleXmlIdentifier($link); return HTML::a(array('name' => $id, 'id' => $id), - $bar ? $label : $link); + $bar ? $label : $link); } if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) { @@ -457,22 +474,15 @@ function LinkBracketLink($bracketlink) { return LinkImage($link, $label); else return new Cached_ExternalLink($link, $label); - } - elseif (substr($link,0,8) == 'phpwiki:') - return new Cached_PhpwikiURL($link, $label); - - /* Semantic relations and attributes. + } elseif (substr($link, 0, 8) == 'phpwiki:') + return new Cached_PhpwikiURL($link, $label); /* Semantic relations and attributes. * Relation and attribute names must be word chars only, no space. * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ... */ elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link)) - return new Cached_SemanticLink($link, $label); - - /* Do not store the link */ - elseif (substr($link,0,1) == ':') - return new Cached_WikiLink($link, $label); - - /* + return new Cached_SemanticLink($link, $label); /* Do not store the link */ + elseif (substr($link, 0, 1) == ':') + return new Cached_WikiLink($link, $label); /* * Inline images in Interwiki urls's: * [File:my_image.gif] inlines the image, * File:my_image.gif shows a plain inter-wiki link, @@ -482,10 +492,10 @@ function LinkBracketLink($bracketlink) { * Note that for simplicity we will accept embedded object tags (non-images) * here also, and seperate them later in LinkImage() */ - elseif (strstr($link,':') - and ($intermap = getInterwikiMap()) - and preg_match("/^" . $intermap->getRegexp() . ":/", $link)) - { + elseif (strstr($link, ':') + and ($intermap = getInterwikiMap()) + and preg_match("/^" . $intermap->getRegexp() . ":/", $link) + ) { // trigger_error("label: $label link: $link", E_USER_WARNING); if (empty($label) and isImageLink($link)) { // if without label => inlined image [File:xx.gif] @@ -495,14 +505,13 @@ function LinkBracketLink($bracketlink) { return new Cached_InterwikiLink($link, $label); } else { // Split anchor off end of pagename. - if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) { - list(,$rawlink,$anchor) = $m; + if (preg_match('/\A(.*)(?<!' . ESCAPE_CHAR . ')#(.*?)\Z/', $rawlink, $m)) { + list(, $rawlink, $anchor) = $m; $pagename = UnWikiEscape($rawlink); $anchor = UnWikiEscape($anchor); if (!$label) $label = $link; - } - else { + } else { $pagename = $link; $anchor = false; } @@ -510,22 +519,24 @@ function LinkBracketLink($bracketlink) { } } -class Markup_wikicreolebracketlink extends SimpleMarkup +class Markup_wikicreolebracketlink extends SimpleMarkup { var $_match_regexp = "\\#? \\[\\[ .*? [^]\\s] .*? \\]\\]"; - function markup ($match) { + function markup($match) + { $link = LinkBracketLink($match); assert($link->isInlineElement()); return $link; } } -class Markup_bracketlink extends SimpleMarkup +class Markup_bracketlink extends SimpleMarkup { var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]"; - function markup ($match) { + function markup($match) + { $link = LinkBracketLink($match); assert($link->isInlineElement()); return $link; @@ -534,17 +545,21 @@ class Markup_bracketlink extends SimpleMarkup class Markup_spellcheck extends SimpleMarkup { - function Markup_spellcheck () { - $this->suggestions = $GLOBALS['request']->getArg('suggestions'); + function Markup_spellcheck() + { + $this->suggestions = $GLOBALS['request']->getArg('suggestions'); } - function getMatchRegexp () { + + function getMatchRegexp() + { if (empty($this->suggestions)) return "(?# false )"; - $words = array_keys($this->suggestions); + $words = array_keys($this->suggestions); return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )"; } - function markup ($match) { + function markup($match) + { if (empty($this->suggestions) or empty($this->suggestions[$match])) return $match; return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]); @@ -553,40 +568,49 @@ class Markup_spellcheck extends SimpleMarkup class Markup_searchhighlight extends SimpleMarkup { - function Markup_searchhighlight () { + function Markup_searchhighlight() + { $result = $GLOBALS['request']->_searchhighlight; require_once 'lib/TextSearchQuery.php'; $query = new TextSearchQuery($result['query']); $this->hilight_re = $query->getHighlightRegexp(); $this->engine = $result['engine']; } - function getMatchRegexp () { + + function getMatchRegexp() + { return $this->hilight_re; } - function markup ($match) { + + function markup($match) + { return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine); } } class Markup_url extends SimpleMarkup { - function getMatchRegexp () { + function getMatchRegexp() + { return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])"; } - function markup ($match) { + function markup($match) + { return new Cached_ExternalLink(UnWikiEscape($match)); } } class Markup_interwiki extends SimpleMarkup { - function getMatchRegexp () { + function getMatchRegexp() + { $map = getInterwikiMap(); - return "(?<! [[:alnum:]])" . $map->getRegexp(). ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])"; + return "(?<! [[:alnum:]])" . $map->getRegexp() . ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])"; } - function markup ($match) { + function markup($match) + { return new Cached_InterwikiLink(UnWikiEscape($match)); } } @@ -599,20 +623,23 @@ class Markup_semanticlink extends SimpleMarkup // Ending dots or comma are not part of the link. var $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))"; - function markup ($match) { + function markup($match) + { return new Cached_SemanticLink(UnWikiEscape($match)); } } class Markup_wikiword extends SimpleMarkup { - function getMatchRegexp () { + function getMatchRegexp() + { global $WikiNameRegexp; if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP; return " $WikiNameRegexp"; } - function markup ($match) { + function markup($match) + { if (!$match) return false; if ($this->_isWikiUserPage($match)) return new Cached_UserLink($match); //$this->_UserLink($match); @@ -621,7 +648,8 @@ class Markup_wikiword extends SimpleMarkup } // FIXME: there's probably a more useful place to put these two functions - function _isWikiUserPage ($page) { + function _isWikiUserPage($page) + { global $request; $dbi = $request->getDbh(); $page_handle = $dbi->getPage($page); @@ -631,7 +659,8 @@ class Markup_wikiword extends SimpleMarkup return false; } - function _UserLink($PageName) { + function _UserLink($PageName) + { $link = HTML::a(array('href' => $PageName)); $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName)); $link->setAttr('class', 'wikiuser'); @@ -643,7 +672,8 @@ class Markup_linebreak extends SimpleMarkup { var $_match_regexp = "(?: (?<! %) %%% (?! %) | \\\\\\\\ | <\s*(?:br|BR)\s*> | <\s*(?:br|BR)\s*\/\s*> )"; - function markup ($match) { + function markup($match) + { return HTML::br(); } } @@ -652,11 +682,13 @@ class Markup_wikicreole_italics extends BalancedMarkup { var $_start_regexp = "\\/\\/"; - function getEndRegexp ($match) { + function getEndRegexp($match) + { return "\\/\\/"; } - function markup ($match, $body) { + function markup($match, $body) + { $tag = 'em'; return new HtmlElement($tag, $body); } @@ -666,11 +698,13 @@ class Markup_wikicreole_bold extends BalancedMarkup { var $_start_regexp = "\\*\\*"; - function getEndRegexp ($match) { + function getEndRegexp($match) + { return "\\*\\*"; } - function markup ($match, $body) { + function markup($match, $body) + { $tag = 'strong'; return new HtmlElement($tag, $body); } @@ -680,11 +714,13 @@ class Markup_wikicreole_monospace extends BalancedMarkup { var $_start_regexp = "\\#\\#"; - function getEndRegexp ($match) { + function getEndRegexp($match) + { return "\\#\\#"; } - function markup ($match, $body) { + function markup($match, $body) + { return new HtmlElement('span', array('class' => 'tt'), $body); } } @@ -693,11 +729,13 @@ class Markup_wikicreole_underline extends BalancedMarkup { var $_start_regexp = "\\_\\_"; - function getEndRegexp ($match) { + function getEndRegexp($match) + { return "\\_\\_"; } - function markup ($match, $body) { + function markup($match, $body) + { $tag = 'u'; return new HtmlElement($tag, $body); } @@ -707,11 +745,13 @@ class Markup_wikicreole_superscript extends BalancedMarkup { var $_start_regexp = "\\^\\^"; - function getEndRegexp ($match) { + function getEndRegexp($match) + { return "\\^\\^"; } - function markup ($match, $body) { + function markup($match, $body) + { $tag = 'sup'; return new HtmlElement($tag, $body); } @@ -721,25 +761,29 @@ class Markup_wikicreole_subscript extends BalancedMarkup { var $_start_regexp = ",,"; - function getEndRegexp ($match) { + function getEndRegexp($match) + { return $match; } - function markup ($match, $body) { + function markup($match, $body) + { $tag = 'sub'; return new HtmlElement($tag, $body); } } -class Markup_old_emphasis extends BalancedMarkup +class Markup_old_emphasis extends BalancedMarkup { var $_start_regexp = "''"; - function getEndRegexp ($match) { + function getEndRegexp($match) + { return $match; } - function markup ($match, $body) { + function markup($match, $body) + { $tag = 'em'; return new HtmlElement($tag, $body); } @@ -747,53 +791,59 @@ class Markup_old_emphasis extends BalancedMarkup class Markup_nestled_emphasis extends BalancedMarkup { - function getStartRegexp() { - static $start_regexp = false; + function getStartRegexp() + { + static $start_regexp = false; - if (!$start_regexp) { - // The three possible delimiters + if (!$start_regexp) { + // The three possible delimiters // (none of which can be followed by itself.) - $i = "_ (?! _)"; - $b = "\\* (?! \\*)"; - $tt = "= (?! =)"; + $i = "_ (?! _)"; + $b = "\\* (?! \\*)"; + $tt = "= (?! =)"; - $any = "(?: ${i}|${b}|${tt})"; // any of the three. + $any = "(?: ${i}|${b}|${tt})"; // any of the three. - // Any of [_*=] is okay if preceded by space or one of [-"'/:] - $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}"; + // Any of [_*=] is okay if preceded by space or one of [-"'/:] + $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}"; - // _ or * is okay after = as long as not immediately followed by = - $start[] = "(?<= =) (?: ${i}|${b}) (?! =)"; - // etc... - $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)"; - $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)"; + // _ or * is okay after = as long as not immediately followed by = + $start[] = "(?<= =) (?: ${i}|${b}) (?! =)"; + // etc... + $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)"; + $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)"; - // any delimiter okay after an opening brace ( [{<(] ) - // as long as it's not immediately followed by the matching closing - // brace. - $start[] = "(?<= { ) ${any} (?! } )"; - $start[] = "(?<= < ) ${any} (?! > )"; - $start[] = "(?<= \\( ) ${any} (?! \\) )"; + // any delimiter okay after an opening brace ( [{<(] ) + // as long as it's not immediately followed by the matching closing + // brace. + $start[] = "(?<= { ) ${any} (?! } )"; + $start[] = "(?<= < ) ${any} (?! > )"; + $start[] = "(?<= \\( ) ${any} (?! \\) )"; - $start = "(?:" . join('|', $start) . ")"; + $start = "(?:" . join('|', $start) . ")"; - // Any of the above must be immediately followed by non-whitespace. - $start_regexp = $start . "(?= \S)"; - } + // Any of the above must be immediately followed by non-whitespace. + $start_regexp = $start . "(?= \S)"; + } - return $start_regexp; + return $start_regexp; } - function getEndRegexp ($match) { + function getEndRegexp($match) + { $chr = preg_quote($match); return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)"; } - function markup ($match, $body) { + function markup($match, $body) + { switch ($match) { - case '*': return new HtmlElement('b', $body); - case '=': return new HtmlElement('span', array('class' => 'tt'), $body); - case '_': return new HtmlElement('i', $body); + case '*': + return new HtmlElement('b', $body); + case '=': + return new HtmlElement('span', array('class' => 'tt'), $body); + case '_': + return new HtmlElement('i', $body); } } } @@ -803,11 +853,13 @@ class Markup_html_emphasis extends BalancedMarkup var $_start_regexp = "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>"; - function getEndRegexp ($match) { + function getEndRegexp($match) + { return "<\\/" . substr($match, 1); } - function markup ($match, $body) { + function markup($match, $body) + { $tag = substr($match, 1, -1); return new HtmlElement($tag, $body); } @@ -818,20 +870,22 @@ class Markup_html_divspan extends BalancedMarkup var $_start_regexp = "<(?: div|span )(?: \s[^>]*)?>"; - function getEndRegexp ($match) { - if (substr($match,1,4) == 'span') + function getEndRegexp($match) + { + if (substr($match, 1, 4) == 'span') $tag = 'span'; else $tag = 'div'; return "<\\/" . $tag . '>'; } - function markup ($match, $body) { - if (substr($match,1,4) == 'span') + function markup($match, $body) + { + if (substr($match, 1, 4) == 'span') $tag = 'span'; else $tag = 'div'; - $rest = substr($match,1+strlen($tag),-1); + $rest = substr($match, 1 + strlen($tag), -1); if (!empty($rest)) { $args = parse_attributes($rest); } else { @@ -848,25 +902,27 @@ class Markup_html_abbr extends BalancedMarkup //sf.net bug #728595 var $_start_regexp = "<(?: abbr|acronym )(?: [^>]*)?>"; - function getEndRegexp ($match) { - if (substr($match,1,4) == 'abbr') + function getEndRegexp($match) + { + if (substr($match, 1, 4) == 'abbr') $tag = 'abbr'; else $tag = 'acronym'; return "<\\/" . $tag . '>'; } - function markup ($match, $body) { - if (substr($match,1,4) == 'abbr') + function markup($match, $body) + { + if (substr($match, 1, 4) == 'abbr') $tag = 'abbr'; else $tag = 'acronym'; - $rest = substr($match,1+strlen($tag),-1); + $rest = substr($match, 1 + strlen($tag), -1); $attrs = parse_attributes($rest); // Remove attributes other than title and lang $allowedargs = array(); foreach ($attrs as $key => $value) { - if (in_array ($key, array("title", "lang"))) { + if (in_array($key, array("title", "lang"))) { $allowedargs[$key] = $value; } } @@ -878,29 +934,31 @@ class Markup_html_abbr extends BalancedMarkup * See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and * http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html */ -class Markup_color extends BalancedMarkup { +class Markup_color extends BalancedMarkup +{ // %color=blue% blue text %% and back to normal var $_start_regexp = "%color=(?: [^%]*)%"; var $_end_regexp = "%%"; - function markup ($match, $body) { + function markup($match, $body) + { $color = strtolower(substr($match, 7, -1)); $morecolors = array('beige' => '#f5f5dc', - 'brown' => '#a52a2a', - 'chocolate' => '#d2691e', - 'cyan' => '#00ffff', - 'gold' => '#ffd700', - 'ivory' => '#fffff0', - 'indigo' => '#4b0082', - 'magenta' => '#ff00ff', - 'orange' => '#ffa500', - 'pink' => '#ffc0cb', - 'salmon' => '#fa8072', - 'snow' => '#fffafa', - 'turquoise' => '#40e0d0', - 'violet' => '#ee82ee', - ); + 'brown' => '#a52a2a', + 'chocolate' => '#d2691e', + 'cyan' => '#00ffff', + 'gold' => '#ffd700', + 'ivory' => '#fffff0', + 'indigo' => '#4b0082', + 'magenta' => '#ff00ff', + 'orange' => '#ffa500', + 'pink' => '#ffc0cb', + 'salmon' => '#fa8072', + 'snow' => '#fffafa', + 'turquoise' => '#40e0d0', + 'violet' => '#ee82ee', + ); if (isset($morecolors[$color])) { $color = $morecolors[$color]; @@ -908,16 +966,17 @@ class Markup_color extends BalancedMarkup { // HTML 4 defines the following 16 colors if (in_array($color, array('aqua', 'black', 'blue', 'fuchsia', - 'gray', 'green', 'lime', 'maroon', - 'navy', 'olive', 'purple', 'red', - 'silver', 'teal', 'white', 'yellow')) - or ((substr($color,0,1) == '#') - and ((strlen($color) == 4) or (strlen($color) == 7)) - and (strspn(substr($color,1),'0123456789abcdef') == strlen($color)-1))) { + 'gray', 'green', 'lime', 'maroon', + 'navy', 'olive', 'purple', 'red', + 'silver', 'teal', 'white', 'yellow')) + or ((substr($color, 0, 1) == '#') + and ((strlen($color) == 4) or (strlen($color) == 7)) + and (strspn(substr($color, 1), '0123456789abcdef') == strlen($color) - 1)) + ) { return new HtmlElement('span', array('style' => "color: $color"), $body); } else { return new HtmlElement('span', array('class' => 'error'), - sprintf(_("unknown color %s ignored"), substr($match, 7, -1))); + sprintf(_("unknown color %s ignored"), substr($match, 7, -1))); } } } @@ -928,7 +987,8 @@ class Markup_placeholder extends SimpleMarkup { var $_match_regexp = '<<<.*?>>>'; - function markup ($match) { + function markup($match) + { return HTML::span($match); } } @@ -939,7 +999,8 @@ class Markup_html_comment extends SimpleMarkup { var $_match_regexp = '<!--.*?-->'; - function markup ($match) { + function markup($match) + { return HTML::raw(''); } } @@ -950,8 +1011,9 @@ class Markup_plugin extends SimpleMarkup { var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>'; - function markup ($match) { - return new Cached_PluginInvocation($match); + function markup($match) + { + return new Cached_PluginInvocation($match); } } @@ -960,10 +1022,11 @@ class Markup_plugin_wikicreole extends SimpleMarkup { var $_match_regexp = '<<[^\n]+?>>'; - function markup ($match) { + function markup($match) + { $pi = str_replace("<<", "<?plugin ", $match); $pi = str_replace(">>", " ?>", $pi); - return new Cached_PluginInvocation($pi); + return new Cached_PluginInvocation($pi); } } @@ -974,22 +1037,27 @@ class Markup_xml_plugin extends BalancedMarkup { //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>"; - function getStartRegexp () { - global $PLUGIN_MARKUP_MAP; + function getStartRegexp() + { + global $PLUGIN_MARKUP_MAP; static $_start_regexp; if ($_start_regexp) return $_start_regexp; if (empty($PLUGIN_MARKUP_MAP)) return ''; //"<(?: html|search|extsearch|dot|toc|math|richtable|include|tex )(?: \s[^>]*)>" - $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]*|\\/ )>"; + $_start_regexp = "<(?: " . join('|', array_keys($PLUGIN_MARKUP_MAP)) . " )(?: \s[^>]*|\\/ )>"; return $_start_regexp; } - function getEndRegexp ($match) { + + function getEndRegexp($match) + { return "<\\/" . $match . '>'; } - function markup ($match, $body) { - global $PLUGIN_MARKUP_MAP; - $name = substr($match,2,-2); - $vars = ''; + + function markup($match, $body) + { + global $PLUGIN_MARKUP_MAP; + $name = substr($match, 2, -2); + $vars = ''; if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) { $name = $_m[1]; $vars = $_m[2]; //str_replace(' ', '&', $_m[2]); @@ -999,7 +1067,7 @@ class Markup_xml_plugin extends BalancedMarkup return ""; } $plugin = $PLUGIN_MARKUP_MAP[$name]; - return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">"); + return new Cached_PluginInvocation("<" . "?plugin $plugin $vars $body ?" . ">"); } } @@ -1011,7 +1079,8 @@ class Markup_nowiki extends SimpleMarkup { var $_match_regexp = '<nowiki>.*?<\/nowiki>'; - function markup ($match) { + function markup($match) + { // Remove <nowiki> and </nowiki> return HTML::raw(substr($match, 8, -9)); } @@ -1026,7 +1095,8 @@ class Markup_wikicreole_preformatted extends SimpleMarkup { var $_match_regexp = '\{\{\{.*?\}\}\}'; - function markup ($match) { + function markup($match) + { // Remove {{{ and }}} return new HtmlElement('span', array('class' => 'tt'), substr($match, 3, -3)); } @@ -1044,39 +1114,40 @@ class Markup_wikicreole_preformatted extends SimpleMarkup * - videos * - predefined icons */ -class Markup_template_plugin extends SimpleMarkup +class Markup_template_plugin extends SimpleMarkup { // patch #1732793: allow \n, mult. {{ }} in one line, and single letters var $_match_regexp = '\{\{.*?\}\}'; - function markup ($match) { + function markup($match) + { - $page = substr($match,2,-2); + $page = substr($match, 2, -2); $page = trim($page); // Check for predefined icons. $predefinedicons = array(":)" => "ic_smile.png", - ":(" => "ic_sad.png", - ":P" => "ic_tongue.png", - ":D" => "ic_biggrin.png", - ";)" => "ic_wink.png", - "(y)" => "ic_handyes.png", - "(n)" => "ic_handno.png", - "(i)" => "ic_info.png", - "(/)" => "ic_check.png", - "(x)" => "ic_cross.png", - "(!)" => "ic_danger.png", - "(+)" => "ic_plus.png", - "(-)" => "ic_minus.png", - "(?)" => "ic_help.png", - "(on)" => "ic_lighton.png", - "(off)" => "ic_lightoff.png", - "(*)" => "ic_yellowstar.png", - "(*r)" => "ic_redstar.png", - "(*g)" => "ic_greenstar.png", - "(*b)" => "ic_bluestar.png", - "(*y)" => "ic_yellowstar.png", - ); + ":(" => "ic_sad.png", + ":P" => "ic_tongue.png", + ":D" => "ic_biggrin.png", + ";)" => "ic_wink.png", + "(y)" => "ic_handyes.png", + "(n)" => "ic_handno.png", + "(i)" => "ic_info.png", + "(/)" => "ic_check.png", + "(x)" => "ic_cross.png", + "(!)" => "ic_danger.png", + "(+)" => "ic_plus.png", + "(-)" => "ic_minus.png", + "(?)" => "ic_help.png", + "(on)" => "ic_lighton.png", + "(off)" => "ic_lightoff.png", + "(*)" => "ic_yellowstar.png", + "(*r)" => "ic_redstar.png", + "(*g)" => "ic_greenstar.png", + "(*b)" => "ic_bluestar.png", + "(*y)" => "ic_yellowstar.png", + ); foreach ($predefinedicons as $ascii => $icon) { if ($page == $ascii) { return LinkImage(DATA_PATH . "/themes/default/images/$icon", $page); @@ -1104,8 +1175,8 @@ class Markup_template_plugin extends SimpleMarkup // It's a video if (is_video($imagename)) { - $s = '<'.'?plugin Video file="' . $imagename . '" ?'.'>'; - return new Cached_PluginInvocation($s); + $s = '<' . '?plugin Video file="' . $imagename . '" ?' . '>'; + return new Cached_PluginInvocation($s); } $page = str_replace("\n", "", $page); @@ -1130,10 +1201,10 @@ class Markup_template_plugin extends SimpleMarkup } if ($vars) - $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>'; + $s = '<' . '?plugin Template page="' . $page . '" ' . $vars . ' ?' . '>'; else - $s = '<'.'?plugin Template page="' . $page . '" ?'.'>'; - return new Cached_PluginInvocation($s); + $s = '<' . '?plugin Template page="' . $page . '" ?' . '>'; + return new Cached_PluginInvocation($s); } } @@ -1141,41 +1212,48 @@ class Markup_template_plugin extends SimpleMarkup // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash // TODO: "--" => "&emdash;" browser specific display (not cached?) -class Markup_html_entities extends SimpleMarkup { +class Markup_html_entities extends SimpleMarkup +{ //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )'; - function Markup_html_entities() { - $this->_entities = array('...' => '…', - '--' => '–', - '---' => '—', - '(C)' => '©', - '©' => '©', - '™' => '™', - ); + function Markup_html_entities() + { + $this->_entities = array('...' => '…', + '--' => '–', + '---' => '—', + '(C)' => '©', + '©' => '©', + '™' => '™', + ); $this->_match_regexp = '(: ' . - join('|', array_map('preg_quote', array_keys($this->_entities))) . - ' )'; + join('|', array_map('preg_quote', array_keys($this->_entities))) . + ' )'; } - function markup ($match) { + function markup($match) + { return HTML::Raw($this->_entities[$match]); } } -class Markup_isonumchars extends SimpleMarkup { +class Markup_isonumchars extends SimpleMarkup +{ var $_match_regexp = '\&\#\d{2,5};'; - function markup ($match) { + function markup($match) + { return HTML::Raw($match); } } -class Markup_isohexchars extends SimpleMarkup { +class Markup_isohexchars extends SimpleMarkup +{ // hexnums, like ¤ <=> ¤ var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};'; - function markup ($match) { + function markup($match) + { return HTML::Raw($match); } } @@ -1187,41 +1265,40 @@ class InlineTransformer var $_regexps = array(); var $_markup = array(); - function InlineTransformer ($markup_types = false) { + function InlineTransformer($markup_types = false) + { global $request; - // We need to extend the inline parsers by certain actions, like SearchHighlight, - // SpellCheck and maybe CreateToc. + // We need to extend the inline parsers by certain actions, like SearchHighlight, + // SpellCheck and maybe CreateToc. if (!$markup_types) { $non_default = false; $markup_types = array - ('escape', 'wikicreolebracketlink', 'bracketlink', 'url', - 'html_comment', 'placeholder', - 'interwiki', 'semanticlink', 'wikiword', 'linebreak', - 'wikicreole_superscript', - 'wikicreole_subscript', - 'wikicreole_italics', 'wikicreole_bold', - 'wikicreole_monospace', - 'wikicreole_underline', - 'old_emphasis', 'nestled_emphasis', - 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole', - 'isonumchars', 'isohexchars', /*'html_entities'*/ - ); - if (DISABLE_MARKUP_WIKIWORD) + ('escape', 'wikicreolebracketlink', 'bracketlink', 'url', + 'html_comment', 'placeholder', + 'interwiki', 'semanticlink', 'wikiword', 'linebreak', + 'wikicreole_superscript', + 'wikicreole_subscript', + 'wikicreole_italics', 'wikicreole_bold', + 'wikicreole_monospace', + 'wikicreole_underline', + 'old_emphasis', 'nestled_emphasis', + 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole', + 'isonumchars', 'isohexchars', /*'html_entities'*/ + ); + if (DISABLE_MARKUP_WIKIWORD) $markup_types = array_remove($markup_types, 'wikiword'); - $action = $request->getArg('action'); - if ($action == 'SpellCheck' and $request->getArg('suggestions')) - { // insert it after url - array_splice($markup_types, 2, 1, array('url','spellcheck')); - } - if (isset($request->_searchhighlight)) - { // insert it after url - array_splice($markup_types, 2, 1, array('url','searchhighlight')); + $action = $request->getArg('action'); + if ($action == 'SpellCheck' and $request->getArg('suggestions')) { // insert it after url + array_splice($markup_types, 2, 1, array('url', 'spellcheck')); + } + if (isset($request->_searchhighlight)) { // insert it after url + array_splice($markup_types, 2, 1, array('url', 'searchhighlight')); //$request->setArg('searchhighlight', false); - } + } } else { $non_default = true; - } + } foreach ($markup_types as $mtype) { $class = "Markup_$mtype"; $this->_addMarkup(new $class); @@ -1240,19 +1317,21 @@ class InlineTransformer $this->_addMarkup(new Markup_xml_plugin); } - function _addMarkup ($markup) { + function _addMarkup($markup) + { if (isa($markup, 'SimpleMarkup')) $regexp = $markup->getMatchRegexp(); else $regexp = $markup->getStartRegexp(); - assert( !isset($this->_markup[$regexp]) ); - assert( strlen(trim($regexp)) > 0 ); + assert(!isset($this->_markup[$regexp])); + assert(strlen(trim($regexp)) > 0); $this->_regexps[] = $regexp; $this->_markup[] = $markup; } - function parse (&$text, $end_regexps = array('$')) { + function parse(&$text, $end_regexps = array('$')) + { $regexps = $this->_regexps; // $end_re takes precedence: "favor reduce over shift" @@ -1270,10 +1349,10 @@ class InlineTransformer // No start pattern found before end pattern. // We're all done! if (isset($markup) and is_object($markup) - and isa($markup,'Markup_plugin')) - { - $current =& $output->_content[count($output->_content)-1]; - $current->setTightness(true,true); + and isa($markup, 'Markup_plugin') + ) { + $current =& $output->_content[count($output->_content) - 1]; + $current->setTightness(true, true); } $output->pushContent($match->prematch); $text = $match->postmatch; @@ -1282,7 +1361,7 @@ class InlineTransformer $markup = $this->_markup[$match->regexp_ind - 1]; $body = $this->_parse_markup_body($markup, $match->match, - $match->postmatch, $end_regexps); + $match->postmatch, $end_regexps); if (!$body) { // Couldn't match balanced expression. // Ignore and look for next matching start regexp. @@ -1298,9 +1377,9 @@ class InlineTransformer $current = $markup->markup($match->match, $body); $input = $match->postmatch; if (isset($markup) and is_object($markup) - and isa($markup,'Markup_plugin')) - { - $current->setTightness(true,true); + and isa($markup, 'Markup_plugin') + ) { + $current->setTightness(true, true); } $output->pushContent($match->prematch, $current); @@ -1312,9 +1391,10 @@ class InlineTransformer return false; } - function _parse_markup_body ($markup, $match, &$text, $end_regexps) { + function _parse_markup_body($markup, $match, &$text, $end_regexps) + { if (isa($markup, 'SimpleMarkup')) - return true; // Done. SimpleMarkup is simple. + return true; // Done. SimpleMarkup is simple. if (!is_object($markup)) return false; // Some error: Should assert array_unshift($end_regexps, $markup->getEndRegexp($match)); @@ -1332,25 +1412,28 @@ class InlineTransformer class LinkTransformer extends InlineTransformer { - function LinkTransformer () { + function LinkTransformer() + { $this->InlineTransformer(array('escape', 'wikicreolebracketlink', 'bracketlink', 'url', - 'semanticlink', 'interwiki', 'wikiword', - )); + 'semanticlink', 'interwiki', 'wikiword', + )); } } class NowikiTransformer extends InlineTransformer { - function NowikiTransformer () { + function NowikiTransformer() + { $this->InlineTransformer - (array('linebreak', - 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole', - 'isonumchars', 'isohexchars', /*'html_entities',*/ - )); + (array('linebreak', + 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole', + 'isonumchars', 'isohexchars', /*'html_entities',*/ + )); } } -function TransformInline($text, $markup = 2.0, $basepage=false) { +function TransformInline($text, $markup = 2.0, $basepage = false) +{ static $trfm; $action = $GLOBALS['request']->getArg('action'); if (empty($trfm) or $action == 'SpellCheck') { @@ -1367,7 +1450,8 @@ function TransformInline($text, $markup = 2.0, $basepage=false) { return $trfm->parse($text); } -function TransformLinks($text, $markup = 2.0, $basepage = false) { +function TransformLinks($text, $markup = 2.0, $basepage = false) +{ static $trfm; if (empty($trfm)) { @@ -1387,7 +1471,8 @@ function TransformLinks($text, $markup = 2.0, $basepage = false) { /** * Transform only html markup and entities. */ -function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) { +function TransformInlineNowiki($text, $markup = 2.0, $basepage = false) +{ static $trfm; if (empty($trfm)) { diff --git a/lib/MailNotify.php b/lib/MailNotify.php index 8e7ebd51c..28b1ddbaa 100644 --- a/lib/MailNotify.php +++ b/lib/MailNotify.php @@ -50,32 +50,37 @@ if (!defined("MAILER_LOG")) { } } -class MailNotify { +class MailNotify +{ - function MailNotify($pagename) { + function MailNotify($pagename) + { $this->pagename = $pagename; /* which page */ - $this->emails = array(); /* to which addresses */ - $this->userids = array(); /* corresponding array of displayed names, + $this->emails = array(); /* to which addresses */ + $this->userids = array(); /* corresponding array of displayed names, don't display the email addresses */ /* From: from whom the mail appears to be */ $this->from = $this->fromId(); } - function fromId() { + function fromId() + { global $request; if (FUSIONFORGE) { return $request->_user->getId(); } else { - return $request->_user->getId() . '@' . $request->get('REMOTE_HOST'); + return $request->_user->getId() . '@' . $request->get('REMOTE_HOST'); } } - function fromEmail() { + function fromEmail() + { global $request; return $this->userEmail($request->_user->getId(), false); } - function userEmail($userid, $doverify = true) { + function userEmail($userid, $doverify = true) + { global $request; // Disable verification of emails for corporate env. @@ -91,7 +96,7 @@ class MailNotify { if ($doverify and !$request->_prefs->get('emailVerified')) { $email = ''; } - } else { // not current user + } else { // not current user if (ENABLE_USER_NEW) { $u = WikiUser($userid); $u->getPreferences(); @@ -114,9 +119,11 @@ class MailNotify { * @return array * unique array of ($emails, $userids) */ - function getPageChangeEmails($notify) { + function getPageChangeEmails($notify) + { global $request; - $emails = array(); $userids = array(); + $emails = array(); + $userids = array(); foreach ($notify as $page => $users) { if (glob_match($page, $this->pagename)) { @@ -133,7 +140,8 @@ class MailNotify { $usermail = $user['email']; if (($usermail == $curuserprefsemail) - and ($ownModifications)) { + and ($ownModifications) + ) { // It's my own modification // and I do not want to receive it continue; @@ -151,12 +159,12 @@ class MailNotify { } if (!$user) { // handle the case for ModeratePage: - // no prefs, just userid's. + // no prefs, just userid's. $emails[] = $this->userEmail($userid, false); $userids[] = $userid; } else { if (!empty($user['verified']) and !empty($user['email'])) { - $emails[] = $user['email']; + $emails[] = $user['email']; $userids[] = $userid; } elseif (!empty($user['email'])) { // do a dynamic emailVerified check update @@ -190,7 +198,7 @@ class MailNotify { $silent = true) { // Add WIKI_NAME to Subject - $subject = "[".WIKI_NAME."] ".$subject; + $subject = "[" . WIKI_NAME . "] " . $subject; // Encode $subject if needed $encoded_subject = $this->subject_encode($subject); $emails = $this->emails; @@ -203,52 +211,52 @@ class MailNotify { } $from = $this->fromEmail(); $headers = "From: $from\r\n" . - "Bcc: ".join(',', $emails)."\r\n" . - "MIME-Version: 1.0\r\n" . - "Content-Type: text/plain; charset=".CHARSET."; format=flowed\r\n" . - "Content-Transfer-Encoding: 8bit"; + "Bcc: " . join(',', $emails) . "\r\n" . + "MIME-Version: 1.0\r\n" . + "Content-Type: text/plain; charset=" . CHARSET . "; format=flowed\r\n" . + "Content-Transfer-Encoding: 8bit"; $ok = mail(($to = array_shift($emails)), - $encoded_subject, - $subject."\n".$content, - $headers - ); + $encoded_subject, + $subject . "\n" . $content, + $headers + ); if (MAILER_LOG and is_writable(MAILER_LOG)) { global $ErrorManager; $f = fopen(MAILER_LOG, "a"); fwrite($f, "\n\nX-MailSentOK: " . $ok ? 'OK' : 'FAILED'); - if (!$ok && isset($ErrorManager->_postponed_errors[count($ErrorManager->_postponed_errors)-1])) { + if (!$ok && isset($ErrorManager->_postponed_errors[count($ErrorManager->_postponed_errors) - 1])) { // get last error message - $last_err = $ErrorManager->_postponed_errors[count($ErrorManager->_postponed_errors)-1]; + $last_err = $ErrorManager->_postponed_errors[count($ErrorManager->_postponed_errors) - 1]; fwrite($f, "\nX-MailFailure: " . - "errno: " . $last_err->errno . ", " . - "errstr: " . $last_err->errstr . ", " . - "errfile: " . $last_err->errfile . ", " . - "errline: " . $last_err->errline); + "errno: " . $last_err->errno . ", " . + "errstr: " . $last_err->errstr . ", " . + "errfile: " . $last_err->errfile . ", " . + "errline: " . $last_err->errline); } fwrite($f, "\nDate: " . CTime()); fwrite($f, "\nSubject: $encoded_subject"); fwrite($f, "\nFrom: $from"); fwrite($f, "\nTo: $to"); - fwrite($f, "\nBcc: ".join(',', $emails)); - fwrite($f, "\n\n". $content); + fwrite($f, "\nBcc: " . join(',', $emails)); + fwrite($f, "\n\n" . $content); fclose($f); } if ($ok) { if (!$silent) trigger_error(sprintf($notice, $this->pagename) - . " " - . sprintf(_("sent to %s"), join(',',$this->userids)), - E_USER_NOTICE); + . " " + . sprintf(_("sent to %s"), join(',', $this->userids)), + E_USER_NOTICE); return true; } else { trigger_error(sprintf($notice, $this->pagename) - . " " - . sprintf(_("Error: Couldn't send %s to %s"), - $subject."\n".$content, join(',',$this->userids)), - E_USER_WARNING); + . " " + . sprintf(_("Error: Couldn't send %s to %s"), + $subject . "\n" . $content, join(',', $this->userids)), + E_USER_WARNING); return false; } } @@ -257,7 +265,8 @@ class MailNotify { * Send udiff for a changed page to multiple users. * See rename and remove methods also */ - function sendPageChangeNotification(&$wikitext, $version, &$meta) { + function sendPageChangeNotification(&$wikitext, $version, &$meta) + { global $request; @@ -274,8 +283,8 @@ class MailNotify { } if ($previous) { // Page existed, and was modified - $subject = _("Page change").' '.($this->pagename); - $difflink = WikiURL($this->pagename, array('action'=>'diff'), true); + $subject = _("Page change") . ' ' . ($this->pagename); + $difflink = WikiURL($this->pagename, array('action' => 'diff'), true); $cache = &$request->_dbi->_cache; $this_content = explode("\n", $wikitext); $prevdata = $cache->get_versiondata($this->pagename, $previous, true); @@ -288,8 +297,8 @@ class MailNotify { $diff2 = new Diff($other_content, $this_content); //$context_lines = max(4, count($other_content) + 1, // count($this_content) + 1); - $fmt = new UnifiedDiffFormatter(/*$context_lines*/); - $content = $this->pagename . " " . $previous . " " . + $fmt = new UnifiedDiffFormatter( /*$context_lines*/); + $content = $this->pagename . " " . $previous . " " . Iso8601DateTime($prevdata['mtime']) . "\n"; $content .= $this->pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n"; @@ -297,8 +306,8 @@ class MailNotify { $editedby = sprintf(_("Edited by: %s"), $this->fromId()); } else { // Page did not exist, and was created - $subject = _("Page creation").' '.($this->pagename); - $difflink = WikiURL($this->pagename,array(),true); + $subject = _("Page creation") . ' ' . ($this->pagename); + $difflink = WikiURL($this->pagename, array(), true); $content = $this->pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n"; $content .= _("New page"); @@ -308,27 +317,29 @@ class MailNotify { } $summary = sprintf(_("Summary: %s"), $meta['summary']); $this->sendMail($subject, - $editedby."\n".$summary."\n".$difflink."\n\n".$content); + $editedby . "\n" . $summary . "\n" . $difflink . "\n\n" . $content); } /** * Support mass rename / remove (TBD) */ - function sendPageRenameNotification ($to, &$meta) { + function sendPageRenameNotification($to, &$meta) + { $pagename = $this->pagename; $editedby = sprintf(_("Renamed by: %s"), $this->fromId()); $subject = sprintf(_("Page rename %s to %s"), $pagename, $to); $link = WikiURL($to, true); $this->sendMail($subject, - $editedby."\n".$link."\n\n"."Renamed $pagename to $to"); + $editedby . "\n" . $link . "\n\n" . "Renamed $pagename to $to"); } /** * The handlers: */ - function onChangePage (&$wikidb, &$wikitext, $version, &$meta) { + function onChangePage(&$wikidb, &$wikitext, $version, &$meta) + { $result = true; - if (!isa($GLOBALS['request'],'MockRequest')) { + if (!isa($GLOBALS['request'], 'MockRequest')) { $notify = $wikidb->get('notify'); /* Generate notification emails? */ if (!empty($notify) and is_array($notify)) { @@ -344,24 +355,26 @@ class MailNotify { return $result; } - function onDeletePage (&$wikidb, $pagename) { + function onDeletePage(&$wikidb, $pagename) + { $result = true; /* Generate notification emails? */ - if (! $wikidb->isWikiPage($pagename) and !isa($GLOBALS['request'],'MockRequest')) { + if (!$wikidb->isWikiPage($pagename) and !isa($GLOBALS['request'], 'MockRequest')) { $notify = $wikidb->get('notify'); if (!empty($notify) and is_array($notify)) { //TODO: deferr it (quite a massive load if you remove some pages). $this->getPageChangeEmails($notify); if (!empty($this->emails)) { $subject = sprintf(_("User %s removed page %s"), $this->fromId(), $pagename); - $result = $this->sendMail($subject, $subject."\n\n"); + $result = $this->sendMail($subject, $subject . "\n\n"); } } } return $result; } - function onRenamePage (&$wikidb, $oldpage, $new_pagename) { + function onRenamePage(&$wikidb, $oldpage, $new_pagename) + { $result = true; if (!isa($GLOBALS['request'], 'MockRequest')) { $notify = $wikidb->get('notify'); @@ -382,16 +395,17 @@ class MailNotify { * Send mail to user and store the cookie in the db * wikiurl?action=ConfirmEmail&id=bla */ - function sendEmailConfirmation ($email, $userid) { + function sendEmailConfirmation($email, $userid) + { $id = rand_ascii_readable(16); $wikidb = $GLOBALS['request']->getDbh(); $data = $wikidb->get('ConfirmEmail'); - while(!empty($data[$id])) { // id collision + while (!empty($data[$id])) { // id collision $id = rand_ascii_readable(16); } $subject = _("E-mail address confirmation"); $ip = $request->get('REMOTE_HOST'); - $expire_date = time() + 7*86400; + $expire_date = time() + 7 * 86400; $content = fmt("Someone, probably you from IP address %s, has registered an account \"%s\" with this e-mail address on %s. @@ -402,27 +416,28 @@ e-mail features on %s, open this link in your browser: If this is *not* you, don't follow the link. This confirmation code will expire at %s.", - $ip, $userid, WIKI_NAME, WIKI_NAME, - WikiURL(HOME_PAGE, array('action' => 'ConfirmEmail', - 'id' => $id), - true), - CTime($expire_date)); + $ip, $userid, WIKI_NAME, WIKI_NAME, + WikiURL(HOME_PAGE, array('action' => 'ConfirmEmail', + 'id' => $id), + true), + CTime($expire_date)); $this->sendMail($subject, $content, "", true); $data[$id] = array('email' => $email, - 'userid' => $userid, - 'expire' => $expire_date); + 'userid' => $userid, + 'expire' => $expire_date); $wikidb->set('ConfirmEmail', $data); return ''; } - function checkEmailConfirmation () { + function checkEmailConfirmation() + { global $request; $wikidb = $request->getDbh(); $data = $wikidb->get('ConfirmEmail'); $id = $request->getArg('id'); if (empty($data[$id])) { // id not found return HTML(HTML::h1("Confirm E-mail address"), - HTML::h1("Sorry! Wrong URL")); + HTML::h1("Sorry! Wrong URL")); } // upgrade the user $userid = $data['userid']; @@ -432,7 +447,7 @@ will expire at %s.", $prefs = $u->getPreferences(); $request->_user->_level = WIKIAUTH_USER; $request->_prefs->set('emailVerified', true); - } else { // not current user + } else { // not current user if (ENABLE_USER_NEW) { $u = WikiUser($userid); $u->getPreferences(); @@ -448,10 +463,11 @@ will expire at %s.", unset($data[$id]); $wikidb->set('ConfirmEmail', $data); return HTML(HTML::h1("Confirm E-mail address"), - HTML::p("Your e-mail address has now been confirmed.")); + HTML::p("Your e-mail address has now been confirmed.")); } - function subject_encode ($subject) { + function subject_encode($subject) + { // We need to encode the subject if it contains non-ASCII characters // The page name may contain non-ASCII characters, as well as // the translation of the messages, e.g. _("PageChange Notification of %s"); @@ -463,11 +479,11 @@ will expire at %s.", // Let us try quoted printable first if (function_exists('quoted_printable_encode')) { // PHP 5.3 - return "=?UTF-8?Q?".quoted_printable_encode($subject)."?="; + return "=?UTF-8?Q?" . quoted_printable_encode($subject) . "?="; } // If not, encode in base64 (less human-readable) - return "=?UTF-8?B?".base64_encode($subject)."?="; + return "=?UTF-8?B?" . base64_encode($subject) . "?="; } } diff --git a/lib/PageList.php b/lib/PageList.php index 85218d95e..e969009e1 100644 --- a/lib/PageList.php +++ b/lib/PageList.php @@ -48,10 +48,12 @@ * fix memory exhaustion on large pagelists with old --memory-limit php's only. * Status: improved 2004-06-25 16:19:36 rurban */ -class _PageList_Column_base { +class _PageList_Column_base +{ var $_tdattr = array(); - function _PageList_Column_base ($default_heading, $align = false) { + function _PageList_Column_base($default_heading, $align = false) + { $this->_heading = $default_heading; if ($align) { @@ -59,24 +61,28 @@ class _PageList_Column_base { } } - function format ($pagelist, $page_handle, &$revision_handle) { + function format($pagelist, $page_handle, &$revision_handle) + { $nbsp = HTML::raw(' '); return HTML::td($this->_tdattr, - $nbsp, - $this->_getValue($page_handle, $revision_handle), - $nbsp); + $nbsp, + $this->_getValue($page_handle, $revision_handle), + $nbsp); } - function getHeading () { + function getHeading() + { return $this->_heading; } - function setHeading ($heading) { + function setHeading($heading) + { $this->_heading = $heading; } // old-style heading - function heading () { + function heading() + { global $request; $nbsp = HTML::raw(' '); // allow sorting? @@ -87,19 +93,20 @@ class _PageList_Column_base { //Fixme: pass all also other GET args along. (limit, p[]) //TODO: support GET and POST $s = HTML::a(array('href' => - $request->GetURLtoSelf(array('sortby' => $sortby)), - 'class' => 'pagetitle', - 'title' => sprintf(_("Sort by %s"), $this->_field)), - $nbsp, HTML::u($this->_heading), $nbsp); + $request->GetURLtoSelf(array('sortby' => $sortby)), + 'class' => 'pagetitle', + 'title' => sprintf(_("Sort by %s"), $this->_field)), + $nbsp, HTML::u($this->_heading), $nbsp); } else { $s = HTML($nbsp, HTML::u($this->_heading), $nbsp); } - return HTML::th(array('align' => 'center'),$s); + return HTML::th(array('align' => 'center'), $s); } // new grid-style sortable heading // TODO: via activeui.js ? (fast dhtml sorting) - function button_heading (&$pagelist, $colNum) { + function button_heading(&$pagelist, $colNum) + { global $WikiTheme, $request; // allow sorting? $nbsp = HTML::raw(' '); @@ -108,15 +115,15 @@ class _PageList_Column_base { $src = false; $noimg_src = $WikiTheme->getButtonURL('no_order'); if ($noimg_src) - $noimg = HTML::img(array('src' => $noimg_src, - 'alt' => '.')); + $noimg = HTML::img(array('src' => $noimg_src, + 'alt' => '.')); else $noimg = $nbsp; if ($pagelist->sortby($colNum, 'check')) { // show icon? request or plugin arg $sortby = $pagelist->sortby($colNum, 'flip_order'); - $desc = (substr($sortby,0,1) == '-'); // +pagename or -pagename + $desc = (substr($sortby, 0, 1) == '-'); // +pagename or -pagename $src = $WikiTheme->getButtonURL($desc ? 'asc_order' : 'desc_order'); - $reverse = $desc ? _("reverse")." " : ""; + $reverse = $desc ? _("reverse") . " " : ""; } else { // initially unsorted $sortby = $pagelist->sortby($colNum, 'get'); @@ -127,22 +134,22 @@ class _PageList_Column_base { $img->setAttr('alt', "."); } else { $img = HTML::img(array('src' => $src, - 'alt' => _("Click to reverse sort order"))); + 'alt' => _("Click to reverse sort order"))); } $s = HTML::a(array('href' => - //Fixme: pass all also other GET args along. (limit is ok, p[]) - $request->GetURLtoSelf(array('sortby' => $sortby, - 'id' => $pagelist->id)), - 'class' => 'gridbutton', - 'title' => sprintf(_("Click to sort by %s"), $reverse . $this->_field)), - $nbsp, $this->_heading, - $nbsp, $img, - $nbsp); + //Fixme: pass all also other GET args along. (limit is ok, p[]) + $request->GetURLtoSelf(array('sortby' => $sortby, + 'id' => $pagelist->id)), + 'class' => 'gridbutton', + 'title' => sprintf(_("Click to sort by %s"), $reverse . $this->_field)), + $nbsp, $this->_heading, + $nbsp, $img, + $nbsp); } else { $s = HTML($nbsp, $this->_heading, $nbsp); } return HTML::th(array('align' => 'center', 'valign' => 'middle', - 'class' => 'gridbutton'), $s); + 'class' => 'gridbutton'), $s); } /** @@ -155,9 +162,10 @@ class _PageList_Column_base { * * @return -1 if $a < $b, 1 if $a > $b, 0 otherwise. */ - function _compare($colvala, $colvalb) { + function _compare($colvala, $colvalb) + { if (is_string($colvala)) - return strcmp($colvala,$colvalb); + return strcmp($colvala, $colvalb); $ret = 0; if (($colvala === $colvalb) || (!isset($colvala) && !isset($colvalb))) { ; @@ -166,69 +174,79 @@ class _PageList_Column_base { } return $ret; } -}; +} -class _PageList_Column extends _PageList_Column_base { - function _PageList_Column ($field, $default_heading, $align = false) { +; + +class _PageList_Column extends _PageList_Column_base +{ + function _PageList_Column($field, $default_heading, $align = false) + { $this->_PageList_Column_base($default_heading, $align); $this->_need_rev = substr($field, 0, 4) == 'rev:'; $this->_iscustom = substr($field, 0, 7) == 'custom:'; if ($this->_iscustom) { $this->_field = substr($field, 7); - } - elseif ($this->_need_rev) - $this->_field = substr($field, 4); - else + } elseif ($this->_need_rev) + $this->_field = substr($field, 4); else $this->_field = $field; } - function _getValue ($page_handle, &$revision_handle) { + function _getValue($page_handle, &$revision_handle) + { if ($this->_need_rev) { if (!$revision_handle) // columns which need the %content should override this. (size, hi_content) $revision_handle = $page_handle->getCurrentRevision(false); return $revision_handle->get($this->_field); - } - else { + } else { return $page_handle->get($this->_field); } } - function _getSortableValue ($page_handle, &$revision_handle) { + function _getSortableValue($page_handle, &$revision_handle) + { $val = $this->_getValue($page_handle, $revision_handle); if ($this->_field == 'hits') - return (int) $val; + return (int)$val; elseif (is_object($val) && method_exists($val, 'asString')) - return $val->asString(); - else - return (string) $val; + return $val->asString(); else + return (string)$val; } -}; +} + +; /* overcome a call_user_func limitation by not being able to do: * call_user_func_array(array(&$class, $class_name), $params); * So we need $class = new $classname($params); * And we add a 4th param to get at the parent $pagelist object */ -class _PageList_Column_custom extends _PageList_Column { - function _PageList_Column_custom($params) { +class _PageList_Column_custom extends _PageList_Column +{ + function _PageList_Column_custom($params) + { $this->_pagelist =& $params[3]; $this->_PageList_Column($params[0], $params[1], $params[2]); } } -class _PageList_Column_size extends _PageList_Column { - function format (&$pagelist, $page_handle, &$revision_handle) { +class _PageList_Column_size extends _PageList_Column +{ + function format(&$pagelist, $page_handle, &$revision_handle) + { return HTML::td($this->_tdattr, - HTML::raw(' '), - $this->_getValue($pagelist, $page_handle, $revision_handle), - HTML::raw(' ')); + HTML::raw(' '), + $this->_getValue($pagelist, $page_handle, $revision_handle), + HTML::raw(' ')); } - function _getValue (&$pagelist, $page_handle, &$revision_handle) { + function _getValue(&$pagelist, $page_handle, &$revision_handle) + { if (!$revision_handle or (!$revision_handle->_data['%content'] - or $revision_handle->_data['%content'] === true)) { + or $revision_handle->_data['%content'] === true) + ) { $revision_handle = $page_handle->getCurrentRevision(true); unset($revision_handle->_data['%pagedata']['_cached_html']); } @@ -239,106 +257,134 @@ class _PageList_Column_size extends _PageList_Column { return $size; } - function _getSortableValue ($page_handle, &$revision_handle) { + function _getSortableValue($page_handle, &$revision_handle) + { if (!$revision_handle) $revision_handle = $page_handle->getCurrentRevision(true); return (empty($revision_handle->_data['%content'])) - ? 0 : strlen($revision_handle->_data['%content']); + ? 0 : strlen($revision_handle->_data['%content']); } - function _getSize($revision_handle) { + function _getSize($revision_handle) + { $bytes = @strlen($revision_handle->_data['%content']); return ByteFormatter($bytes); } } -class _PageList_Column_bool extends _PageList_Column { - function _PageList_Column_bool ($field, $default_heading, $text = 'yes') { +class _PageList_Column_bool extends _PageList_Column +{ + function _PageList_Column_bool($field, $default_heading, $text = 'yes') + { $this->_PageList_Column($field, $default_heading, 'center'); $this->_textIfTrue = $text; $this->_textIfFalse = new RawXml('—'); //mdash } - function _getValue ($page_handle, &$revision_handle) { + function _getValue($page_handle, &$revision_handle) + { //FIXME: check if $this is available in the parent (->need_rev) $val = _PageList_Column::_getValue($page_handle, $revision_handle); return $val ? $this->_textIfTrue : $this->_textIfFalse; } -}; +} -class _PageList_Column_checkbox extends _PageList_Column { - function _PageList_Column_checkbox ($field, $default_heading, $name='p') { +; + +class _PageList_Column_checkbox extends _PageList_Column +{ + function _PageList_Column_checkbox($field, $default_heading, $name = 'p') + { $this->_name = $name; - $heading = HTML::input(array('type' => 'button', - 'title' => _("Click to de-/select all pages"), - 'name' => $default_heading, - 'value' => $default_heading, - 'onclick' => "flipAll(this.form)" - )); + $heading = HTML::input(array('type' => 'button', + 'title' => _("Click to de-/select all pages"), + 'name' => $default_heading, + 'value' => $default_heading, + 'onclick' => "flipAll(this.form)" + )); $this->_PageList_Column($field, $heading, 'center'); } - function _getValue ($pagelist, $page_handle, &$revision_handle) { + + function _getValue($pagelist, $page_handle, &$revision_handle) + { $pagename = $page_handle->getName(); $selected = !empty($pagelist->_selected[$pagename]); - if (strstr($pagename,'[') or strstr($pagename,']')) { - $pagename = str_replace(array('[',']'),array('%5B','%5D'),$pagename); + if (strstr($pagename, '[') or strstr($pagename, ']')) { + $pagename = str_replace(array('[', ']'), array('%5B', '%5D'), $pagename); } if ($selected) { return HTML::input(array('type' => 'checkbox', - 'name' => $this->_name . "[$pagename]", - 'value' => 1, - 'checked' => 'checked')); + 'name' => $this->_name . "[$pagename]", + 'value' => 1, + 'checked' => 'checked')); } else { return HTML::input(array('type' => 'checkbox', - 'name' => $this->_name . "[$pagename]", - 'value' => 1)); + 'name' => $this->_name . "[$pagename]", + 'value' => 1)); } } - function format ($pagelist, $page_handle, &$revision_handle) { + + function format($pagelist, $page_handle, &$revision_handle) + { return HTML::td($this->_tdattr, - HTML::raw(' '), - $this->_getValue($pagelist, $page_handle, $revision_handle), - HTML::raw(' ')); + HTML::raw(' '), + $this->_getValue($pagelist, $page_handle, $revision_handle), + HTML::raw(' ')); } + // don't sort this javascript button - function button_heading ($pagelist, $colNum) { + function button_heading($pagelist, $colNum) + { $s = HTML(HTML::raw(' '), $this->_heading, HTML::raw(' ')); return HTML::th(array('align' => 'center', 'valign' => 'middle', - 'class' => 'gridbutton'), $s); + 'class' => 'gridbutton'), $s); } -}; +} -class _PageList_Column_time extends _PageList_Column { - function _PageList_Column_time ($field, $default_heading) { +; + +class _PageList_Column_time extends _PageList_Column +{ + function _PageList_Column_time($field, $default_heading) + { $this->_PageList_Column($field, $default_heading, 'right'); global $WikiTheme; $this->WikiTheme = &$WikiTheme; } - function _getValue ($page_handle, &$revision_handle) { + function _getValue($page_handle, &$revision_handle) + { $time = _PageList_Column::_getValue($page_handle, $revision_handle); return $this->WikiTheme->formatDateTime($time); } - function _getSortableValue ($page_handle, &$revision_handle) { + function _getSortableValue($page_handle, &$revision_handle) + { return _PageList_Column::_getValue($page_handle, $revision_handle); } -}; +} -class _PageList_Column_version extends _PageList_Column { - function _getValue ($page_handle, &$revision_handle) { +; + +class _PageList_Column_version extends _PageList_Column +{ + function _getValue($page_handle, &$revision_handle) + { if (!$revision_handle) $revision_handle = $page_handle->getCurrentRevision(); return $revision_handle->getVersion(); } -}; +} + +; // Output is hardcoded to limit of first 50 bytes. Otherwise // on very large Wikis this will fail if used with AllPages // (PHP memory limit exceeded) -class _PageList_Column_content extends _PageList_Column { - function _PageList_Column_content ($field, $default_heading, $align=false, - $search=false, $hilight_re=false) +class _PageList_Column_content extends _PageList_Column +{ + function _PageList_Column_content($field, $default_heading, $align = false, + $search = false, $hilight_re = false) { $this->_PageList_Column($field, $default_heading, $align); $this->bytes = 50; @@ -346,20 +392,22 @@ class _PageList_Column_content extends _PageList_Column { $this->hilight_re = $hilight_re; if ($field == 'content') { $this->_heading .= sprintf(_(" ... first %d bytes"), - $this->bytes); + $this->bytes); } elseif ($field == 'rev:hi_content') { global $HTTP_POST_VARS; if (!$this->search and !empty($HTTP_POST_VARS['admin_replace'])) { $this->search = $HTTP_POST_VARS['admin_replace']['from']; } $this->_heading .= sprintf(_(" ... around %s"), - '»'.$this->search.'«'); + '»' . $this->search . '«'); } } - function _getValue ($page_handle, &$revision_handle) { + function _getValue($page_handle, &$revision_handle) + { if (!$revision_handle or (!$revision_handle->_data['%content'] - or $revision_handle->_data['%content'] === true)) { + or $revision_handle->_data['%content'] === true) + ) { $revision_handle = $page_handle->getCurrentRevision(true); } @@ -379,7 +427,7 @@ class _PageList_Column_content extends _PageList_Column { if ($search and $hilight_re) { $matches = preg_grep("/$hilight_re/i", $revision_handle->getContent()); $html = array(); - foreach (array_slice($matches,0,5) as $line) { + foreach (array_slice($matches, 0, 5) as $line) { $line = WikiPlugin_FullTextSearch::highlight_line($line, $hilight_re); $html[] = HTML::p(HTML::small(array('class' => 'search-context'), $line)); } @@ -395,21 +443,21 @@ class _PageList_Column_content extends _PageList_Column { $l = strlen($search); $j = max(0, $i - ($this->bytes / 2)); return HTML::div(array('style' => 'font-size:x-small'), - HTML::div(array('class' => 'transclusion'), - HTML::span(($j ? '...' : '') - .substr($c, $j, ($j ? $this->bytes / 2 : $i))), - HTML::span(array("style"=>"background:yellow"), - substr($c, $i, $l)), - HTML::span(substr($c, $i+$l, ($this->bytes / 2)) - ."..."." " - .($score ? sprintf("[%0.1f]",$score):"")))); + HTML::div(array('class' => 'transclusion'), + HTML::span(($j ? '...' : '') + . substr($c, $j, ($j ? $this->bytes / 2 : $i))), + HTML::span(array("style" => "background:yellow"), + substr($c, $i, $l)), + HTML::span(substr($c, $i + $l, ($this->bytes / 2)) + . "..." . " " + . ($score ? sprintf("[%0.1f]", $score) : "")))); } else { - if (strpos($c," ") !== false) + if (strpos($c, " ") !== false) $c = ""; else - $c = sprintf(_("%s not found"), '»'.$search.'«'); - return HTML::div(array('style' => 'font-size:x-small','align'=>'center'), - $c." ".($score ? sprintf("[%0.1f]",$score):"")); + $c = sprintf(_("%s not found"), '»' . $search . '«'); + return HTML::div(array('style' => 'font-size:x-small', 'align' => 'center'), + $c . " " . ($score ? sprintf("[%0.1f]", $score) : "")); } } elseif (($len = strlen($c)) > $this->bytes) { $c = substr($c, 0, $this->bytes); @@ -420,30 +468,36 @@ class _PageList_Column_content extends _PageList_Column { if (empty($pagelist->_sortby[$this->_field])) unset($revision_handle->_data['%pagedata']['_cached_html']); return HTML::div(array('style' => 'font-size:x-small'), - HTML::div(array('class' => 'transclusion'), $ct), - // Don't show bytes here if size column present too - ($this->parent->_columns_seen['size'] or !$len) ? "" : - ByteFormatter($len, /*$longformat = */true)); + HTML::div(array('class' => 'transclusion'), $ct), + // Don't show bytes here if size column present too + ($this->parent->_columns_seen['size'] or !$len) ? "" : + ByteFormatter($len, /*$longformat = */ + true)); } - function _getSortableValue ($page_handle, &$revision_handle) { + function _getSortableValue($page_handle, &$revision_handle) + { if (is_object($page_handle) and !empty($page_handle->score)) return $page_handle->score; elseif (is_array($page_handle) and !empty($page_handle['score'])) - return $page_handle['score']; - else - return substr(_PageList_Column::_getValue($page_handle, $revision_handle),0,50); + return $page_handle['score']; else + return substr(_PageList_Column::_getValue($page_handle, $revision_handle), 0, 50); } -}; +} + +; -class _PageList_Column_author extends _PageList_Column { - function _PageList_Column_author ($field, $default_heading, $align = false) { +class _PageList_Column_author extends _PageList_Column +{ + function _PageList_Column_author($field, $default_heading, $align = false) + { _PageList_Column::_PageList_Column($field, $default_heading, $align); $this->dbi =& $GLOBALS['request']->getDbh(); } - function _getValue ($page_handle, &$revision_handle) { + function _getValue($page_handle, &$revision_handle) + { $author = _PageList_Column::_getValue($page_handle, $revision_handle); if ($this->dbi->isWikiPage($author)) return WikiLink($author); @@ -451,76 +505,104 @@ class _PageList_Column_author extends _PageList_Column { return $author; } - function _getSortableValue ($page_handle, &$revision_handle) { + function _getSortableValue($page_handle, &$revision_handle) + { return _PageList_Column::_getValue($page_handle, $revision_handle); } -}; +} + +; -class _PageList_Column_owner extends _PageList_Column_author { - function _getValue ($page_handle, &$revision_handle) { +class _PageList_Column_owner extends _PageList_Column_author +{ + function _getValue($page_handle, &$revision_handle) + { $author = $page_handle->getOwner(); if ($this->dbi->isWikiPage($author)) return WikiLink($author); else return $author; } - function _getSortableValue ($page_handle, &$revision_handle) { + + function _getSortableValue($page_handle, &$revision_handle) + { return _PageList_Column::_getValue($page_handle, $revision_handle); } -}; +} + +; -class _PageList_Column_creator extends _PageList_Column_author { - function _getValue ($page_handle, &$revision_handle) { +class _PageList_Column_creator extends _PageList_Column_author +{ + function _getValue($page_handle, &$revision_handle) + { $author = $page_handle->getCreator(); if ($this->dbi->isWikiPage($author)) return WikiLink($author); else return $author; } - function _getSortableValue ($page_handle, &$revision_handle) { + + function _getSortableValue($page_handle, &$revision_handle) + { return _PageList_Column::_getValue($page_handle, $revision_handle); } -}; +} + +; -class _PageList_Column_pagename extends _PageList_Column_base { +class _PageList_Column_pagename extends _PageList_Column_base +{ var $_field = 'pagename'; - function _PageList_Column_pagename () { + function _PageList_Column_pagename() + { $this->_PageList_Column_base(_("Page Name")); global $request; $this->dbi = &$request->getDbh(); } - function _getValue ($page_handle, &$revision_handle) { + function _getValue($page_handle, &$revision_handle) + { if ($this->dbi->isWikiPage($page_handle->getName())) return WikiLink($page_handle, 'known'); else return WikiLink($page_handle, 'unknown'); } - function _getSortableValue ($page_handle, &$revision_handle) { + function _getSortableValue($page_handle, &$revision_handle) + { return $page_handle->getName(); } /** * Compare two pagenames for sorting. See _PageList_Column::_compare. **/ - function _compare($colvala, $colvalb) { + function _compare($colvala, $colvalb) + { return strcmp($colvala, $colvalb); } -}; +} -class _PageList_Column_perm extends _PageList_Column { - function _getValue ($page_handle, &$revision_handle) { +; + +class _PageList_Column_perm extends _PageList_Column +{ + function _getValue($page_handle, &$revision_handle) + { $perm_array = pagePermissions($page_handle->_pagename); return pagePermissionsSimpleFormat($perm_array, - $page_handle->get('author'), - $page_handle->get('group')); + $page_handle->get('author'), + $page_handle->get('group')); } -}; +} + +; -class _PageList_Column_acl extends _PageList_Column { - function _getValue ($page_handle, &$revision_handle) { +class _PageList_Column_acl extends _PageList_Column +{ + function _getValue($page_handle, &$revision_handle) + { $perm_tree = pagePermissions($page_handle->_pagename); list($type, $perm) = pagePermissionsAcl($perm_tree[0], $perm_tree); @@ -537,12 +619,15 @@ class _PageList_Column_acl extends _PageList_Column { $result->pushContent($perm->asAclLines()); return $result; } -}; +} -class PageList { +; + +class PageList +{ var $_group_rows = 3; var $_columns = array(); - var $_columnsMap = array(); // Maps column name to column number. + var $_columnsMap = array(); // Maps column name to column number. var $_excluded_pages = array(); var $_pages = array(); var $_caption = ""; @@ -553,7 +638,8 @@ class PageList { var $_sortby = array(); var $_maxlen = 0; - function PageList ($columns = false, $exclude = false, $options = false) { + function PageList($columns = false, $exclude = false, $options = false) + { // unique id per pagelist on each page. if (!isset($GLOBALS['request']->_pagelist)) $GLOBALS['request']->_pagelist = 0; @@ -569,30 +655,31 @@ class PageList { // let plugins predefine only certain objects, such its own custom pagelist columns $symbolic_columns = array( - 'all' => array_diff(array_keys($this->_types), // all but... - array('checkbox','remove','renamed_pagename', - 'content','hi_content','perm','acl')), - 'most' => array('pagename','mtime','author','hits'), - 'some' => array('pagename','mtime','author') - ); + 'all' => array_diff(array_keys($this->_types), // all but... + array('checkbox', 'remove', 'renamed_pagename', + 'content', 'hi_content', 'perm', 'acl')), + 'most' => array('pagename', 'mtime', 'author', 'hits'), + 'some' => array('pagename', 'mtime', 'author') + ); if (isset($this->_options['listtype']) - and $this->_options['listtype'] == 'dl') + and $this->_options['listtype'] == 'dl' + ) $this->_options['nopage'] = 1; if ($columns) { if (!is_array($columns)) $columns = explode(',', $columns); // expand symbolic columns: foreach ($symbolic_columns as $symbol => $cols) { - if (in_array($symbol,$columns)) { // e.g. 'checkbox,all' - $columns = array_diff(array_merge($columns,$cols),array($symbol)); + if (in_array($symbol, $columns)) { // e.g. 'checkbox,all' + $columns = array_diff(array_merge($columns, $cols), array($symbol)); } } unset($cols); - if (empty($this->_options['nopage']) and !in_array('pagename',$columns)) + if (empty($this->_options['nopage']) and !in_array('pagename', $columns)) $this->_addColumn('pagename'); foreach ($columns as $col) { if (!empty($col)) - $this->_addColumn($col); + $this->_addColumn($col); } unset($col); } @@ -612,8 +699,8 @@ class PageList { // explicit header options: ?id=x&sortby=... override options[] // support multiple sorts. check multiple, no nested elseif if (($this->id == $request->getArg("id")) - and $request->getArg('sortby')) - { + and $request->getArg('sortby') + ) { // add it to the front of the sortby array $this->sortby($request->getArg('sortby'), 'init'); $this->_options['sortby'] = $request->getArg('sortby'); @@ -624,8 +711,8 @@ class PageList { $this->sortby($options['sortby'], 'init'); } // global options if (!isset($request->args["id"]) and $request->getArg('sortby') - and empty($this->_options['sortby'])) - { + and empty($this->_options['sortby']) + ) { $this->_options['sortby'] = $request->getArg('sortby'); $this->sortby($this->_options['sortby'], 'init'); } @@ -633,8 +720,8 @@ class PageList { foreach ($this->pagingArgs() as $key) { if ($key == 'sortby') continue; if (($this->id == $request->getArg("id")) - and $request->getArg($key)) - { + and $request->getArg($key) + ) { $this->_options[$key] = $request->getArg($key); } // plugin options elseif (!empty($options) and !empty($options[$key])) { @@ -642,15 +729,14 @@ class PageList { } // global options elseif (!isset($request->args["id"]) and $request->getArg($key)) { $this->_options[$key] = $request->getArg($key); - } - else + } else $this->_options[$key] = false; } if ($exclude) { if (is_string($exclude) and !is_array($exclude)) $exclude = $this->explodePageList($exclude, false, - $this->_options['sortby'], - $this->_options['limit']); + $this->_options['sortby'], + $this->_options['limit']); $this->_excluded_pages = $exclude; } $this->_messageIfEmpty = _("<no matches>"); @@ -660,64 +746,67 @@ class PageList { // 1: info, 2: exclude, 3: hash of options // Here we declare which options are supported, so that // the calling plugin may simply merge this with its own default arguments - function supportedArgs () { + function supportedArgs() + { // Todo: add all supported Columns, like locked, minor, ... - return array(// Currently supported options: - /* what columns, what pages */ - 'info' => 'pagename', - 'exclude' => '', // also wildcards, comma-seperated lists - // and <!plugin-list !> arrays - /* select pages by meta-data: */ - 'author' => false, // current user by [] - 'owner' => false, // current user by [] - 'creator' => false, // current user by [] - - /* for the sort buttons in <th> */ - 'sortby' => '', // same as for WikiDB::getAllPages - // (unsorted is faster) - - /* PageList pager options: - * These options may also be given to _generate(List|Table) later - * But limit and offset might help the query WikiDB::getAllPages() - */ - 'limit' => 50, // number of rows (pagesize) - 'paging' => 'auto', // 'auto' top + bottom rows if applicable - // // 'top' top only if applicable - // // 'bottom' bottom only if applicable - // // 'none' don't page at all - // (TODO: clarify what if $paging==false ?) - - /* list-style options (with single pagename column only so far) */ - 'cols' => 1, // side-by-side display of list (1-3) - 'azhead' => 0, // 1: group by initials - // 2: provide shortcut links to initials also - 'comma' => 0, // condensed comma-seperated list, - // 1 if without links, 2 if with - 'commasep' => false, // Default: ', ' - 'listtype' => '', // ul (default), ol, dl, comma - 'ordered' => false, // OL or just UL lists (ignored for comma) - 'linkmore' => '', // If count>0 and limit>0 display a link with - // the number of all results, linked to the given pagename. - - 'nopage' => false, // for info=col omit the pagename column - // array_keys($this->_types). filter by columns: e.g. locked=1 - 'pagename' => null, // string regex - 'locked' => null, - 'minor' => null, - 'mtime' => null, - 'hits' => null, - 'size' => null, - 'version' => null, - 'markup' => null, - 'external' => null, - ); - } - - function pagingArgs() { - return array('sortby','limit','paging','count','dosort'); - } - - function clearArg($arg_name) { + return array( // Currently supported options: + /* what columns, what pages */ + 'info' => 'pagename', + 'exclude' => '', // also wildcards, comma-seperated lists + // and <!plugin-list !> arrays + /* select pages by meta-data: */ + 'author' => false, // current user by [] + 'owner' => false, // current user by [] + 'creator' => false, // current user by [] + + /* for the sort buttons in <th> */ + 'sortby' => '', // same as for WikiDB::getAllPages + // (unsorted is faster) + + /* PageList pager options: + * These options may also be given to _generate(List|Table) later + * But limit and offset might help the query WikiDB::getAllPages() + */ + 'limit' => 50, // number of rows (pagesize) + 'paging' => 'auto', // 'auto' top + bottom rows if applicable + // // 'top' top only if applicable + // // 'bottom' bottom only if applicable + // // 'none' don't page at all + // (TODO: clarify what if $paging==false ?) + + /* list-style options (with single pagename column only so far) */ + 'cols' => 1, // side-by-side display of list (1-3) + 'azhead' => 0, // 1: group by initials + // 2: provide shortcut links to initials also + 'comma' => 0, // condensed comma-seperated list, + // 1 if without links, 2 if with + 'commasep' => false, // Default: ', ' + 'listtype' => '', // ul (default), ol, dl, comma + 'ordered' => false, // OL or just UL lists (ignored for comma) + 'linkmore' => '', // If count>0 and limit>0 display a link with + // the number of all results, linked to the given pagename. + + 'nopage' => false, // for info=col omit the pagename column + // array_keys($this->_types). filter by columns: e.g. locked=1 + 'pagename' => null, // string regex + 'locked' => null, + 'minor' => null, + 'mtime' => null, + 'hits' => null, + 'size' => null, + 'version' => null, + 'markup' => null, + 'external' => null, + ); + } + + function pagingArgs() + { + return array('sortby', 'limit', 'paging', 'count', 'dosort'); + } + + function clearArg($arg_name) + { if (isset($this->_options[$arg_name])) unset($this->_options[$arg_name]); } @@ -725,48 +814,57 @@ class PageList { /** * @param caption string or HTML */ - function setCaption ($caption) { + function setCaption($caption) + { $this->_caption = $caption; } /** * @param caption string or HTML */ - function addCaption ($caption) { - $this->_caption = HTML($this->_caption," ",$caption); + function addCaption($caption) + { + $this->_caption = HTML($this->_caption, " ", $caption); } - function getCaption () { + function getCaption() + { // put the total into the caption if needed if (is_string($this->_caption) && strstr($this->_caption, '%d')) return sprintf($this->_caption, $this->getTotal()); return $this->_caption; } - function setMessageIfEmpty ($msg) { + function setMessageIfEmpty($msg) + { $this->_messageIfEmpty = $msg; } - function getTotal () { + function getTotal() + { return !empty($this->_options['count']) - ? (integer) $this->_options['count'] : count($this->_pages); + ? (integer)$this->_options['count'] : count($this->_pages); } - function isEmpty () { + function isEmpty() + { return empty($this->_pages); } - function addPage($page_handle) { + function addPage($page_handle) + { if (!empty($this->_excluded_pages)) { if (!in_array((is_string($page_handle) ? $page_handle : $page_handle->getName()), - $this->_excluded_pages)) + $this->_excluded_pages) + ) $this->_pages[] = $page_handle; } else { $this->_pages[] = $page_handle; } } - function pageNames() { + function pageNames() + { $pages = array(); $limit = @$this->_options['limit']; foreach ($this->_pages as $page_handle) { @@ -777,7 +875,8 @@ class PageList { return $pages; } - function _getPageFromHandle($page_handle) { + function _getPageFromHandle($page_handle) + { if (is_string($page_handle)) { if (empty($page_handle)) return $page_handle; $page_handle = $GLOBALS['request']->_dbi->getPage($page_handle); @@ -789,7 +888,8 @@ class PageList { * Take a PageList_Page object, and return an HTML object to display * it in a table or list row. */ - function _renderPageRow (&$page_handle, $i = 0) { + function _renderPageRow(&$page_handle, $i = 0) + { $page_handle = $this->_getPageFromHandle($page_handle); //FIXME. only on sf.net if (!is_object($page_handle)) { @@ -799,7 +899,8 @@ class PageList { if (!isset($page_handle) or empty($page_handle) or (!empty($this->_excluded_pages) - and in_array($page_handle->getName(), $this->_excluded_pages))) + and in_array($page_handle->getName(), $this->_excluded_pages)) + ) return; // exclude page. // enforce view permission @@ -831,63 +932,66 @@ class PageList { } /* ignore from, but honor limit */ - function addPages ($page_iter) { + function addPages($page_iter) + { // TODO: if limit check max(strlen(pagename)) - $limit = $page_iter->limit(); + $limit = $page_iter->limit(); $i = 0; - if ($limit) { - list($from, $limit) = $this->limit($limit); - $this->_options['slice'] = 0; - $limit += $from; + if ($limit) { + list($from, $limit) = $this->limit($limit); + $this->_options['slice'] = 0; + $limit += $from; while ($page = $page_iter->next()) { $i++; if ($from and $i < $from) continue; - if (!$limit or ($limit and $i < $limit)) - $this->addPage($page); + if (!$limit or ($limit and $i < $limit)) + $this->addPage($page); } - } else { - $this->_options['slice'] = 0; + } else { + $this->_options['slice'] = 0; while ($page = $page_iter->next()) { - $this->addPage($page); + $this->addPage($page); } - } - if (! is_array($page_iter->_options) || ! array_key_exists('limit_by_db', $page_iter->_options) || ! $page_iter->_options['limit_by_db']) - $this->_options['slice'] = 1; - if ($i and empty($this->_options['count'])) - $this->_options['count'] = $i; + } + if (!is_array($page_iter->_options) || !array_key_exists('limit_by_db', $page_iter->_options) || !$page_iter->_options['limit_by_db']) + $this->_options['slice'] = 1; + if ($i and empty($this->_options['count'])) + $this->_options['count'] = $i; } - function addPageList (&$list) { - if (empty($list)) return; // Protect reset from a null arg + function addPageList(&$list) + { + if (empty($list)) return; // Protect reset from a null arg if (isset($this->_options['limit'])) { // extract from,count from limit - list($from, $limit) = WikiDB_backend::limit($this->_options['limit']); - $limit += $from; + list($from, $limit) = WikiDB_backend::limit($this->_options['limit']); + $limit += $from; } else { - $limit = 0; + $limit = 0; } - $this->_options['slice'] = 0; + $this->_options['slice'] = 0; $i = 0; foreach ($list as $page) { $i++; if ($from and $i < $from) continue; - if (!$limit or ($limit and $i < $limit)) { + if (!$limit or ($limit and $i < $limit)) { if (is_object($page)) $page = $page->_pagename; $this->addPage((string)$page); - } + } } } - function maxLen() { + function maxLen() + { global $request; $dbi =& $request->getDbh(); - if (isa($dbi,'WikiDB_SQL')) { + if (isa($dbi, 'WikiDB_SQL')) { extract($dbi->_backend->_table_names); $res = $dbi->_backend->_dbh->getOne("SELECT max(length(pagename)) FROM $page_tbl"); if (DB::isError($res) || empty($res)) return false; else return $res; - } elseif (isa($dbi,'WikiDB_ADODB')) { + } elseif (isa($dbi, 'WikiDB_ADODB')) { extract($dbi->_backend->_table_names); $row = $dbi->_backend->_dbh->getRow("SELECT max(length(pagename)) FROM $page_tbl"); return $row ? $row[0] : false; @@ -895,33 +999,36 @@ class PageList { return false; } - function first() { + function first() + { if (count($this->_pages) > 0) { return $this->_pages[0]; } return false; } - function getContent() { + function getContent() + { // Note that the <caption> element wants inline content. $caption = $this->getCaption(); if ($this->isEmpty()) return $this->_emptyList($caption); elseif (isset($this->_options['listtype']) - and in_array($this->_options['listtype'], array('ol','ul','comma','dl'))) - return $this->_generateList($caption); - elseif (count($this->_columns) == 1) - return $this->_generateList($caption); - else + and in_array($this->_options['listtype'], array('ol', 'ul', 'comma', 'dl')) + ) + return $this->_generateList($caption); elseif (count($this->_columns) == 1) + return $this->_generateList($caption); else return $this->_generateTable($caption); } - function printXML() { + function printXML() + { PrintXML($this->getContent()); } - function asXML() { + function asXML() + { return AsXML($this->getContent()); } @@ -938,7 +1045,8 @@ class PageList { * Now all columns are sortable. (patch by DanFr) * Some columns have native DB backend methods, some not. */ - function sortby ($column, $action, $valid_fields=false) { + function sortby($column, $action, $valid_fields = false) + { global $request; if (empty($column)) return ''; @@ -963,17 +1071,19 @@ class PageList { else return join(",", $result); } - if (substr($column,0,1) == '+') { - $order = '+'; $column = substr($column,1); - } elseif (substr($column,0,1) == '-') { - $order = '-'; $column = substr($column,1); + if (substr($column, 0, 1) == '+') { + $order = '+'; + $column = substr($column, 1); + } elseif (substr($column, 0, 1) == '-') { + $order = '-'; + $column = substr($column, 1); } // default initial order: +pagename, -mtime, -hits if (empty($order)) { if (!empty($this->_sortby[$column])) $order = $this->_sortby[$column]; else { - if (in_array($column, array('mtime','hits'))) + if (in_array($column, array('mtime', 'hits'))) $order = '-'; else $order = '+'; @@ -983,7 +1093,7 @@ class PageList { return $order . $column; } elseif ($action == 'flip_order') { if (0 and DEBUG) - trigger_error("flip $order $column ".$this->id, E_USER_NOTICE); + trigger_error("flip $order $column " . $this->id, E_USER_NOTICE); return ($order == '+' ? '-' : '+') . $column; } elseif ($action == 'init') { // only allowed from PageList::PageList if (0 and DEBUG) { @@ -993,25 +1103,26 @@ class PageList { } $this->_sortby[$column] = $order; // forces show icon return $order . $column; - } elseif ($action == 'check') { // show icon? + } elseif ($action == 'check') { // show icon? //if specified via arg or if clicked $show = (!empty($this->_sortby[$column]) or $this->sortby($column, 'clicked')); if (0 and $show and DEBUG) { - trigger_error("show $order $column ".$this->id, E_USER_NOTICE); + trigger_error("show $order $column " . $this->id, E_USER_NOTICE); } return $show; } elseif ($action == 'clicked') { // flip sort order? global $request; $arg = $request->getArg('sortby'); return ($arg - and strstr($arg, $column) + and strstr($arg, $column) and (!isset($request->args['id']) - or $this->id == $request->getArg('id'))); + or $this->id == $request->getArg('id'))); } elseif ($action == 'db') { // Performance enhancement: use native DB sort if possible. if (($valid_fields and in_array($column, $valid_fields)) or (method_exists($request->_dbi->_backend, 'sortable_columns') - and (in_array($column, $request->_dbi->_backend->sortable_columns())))) { + and (in_array($column, $request->_dbi->_backend->sortable_columns()))) + ) { // omit this sort method from the _sortPages call at rendering // asc or desc: +pagename, -pagename return $column . ($order == '+' ? ' ASC' : ' DESC'); @@ -1029,16 +1140,16 @@ class PageList { * * echo implode(":",explodeList("Test*",array("xx","Test1","Test2"))); */ - function explodePageList($input, $include_empty=false, $sortby='', - $limit='', $exclude='') + function explodePageList($input, $include_empty = false, $sortby = '', + $limit = '', $exclude = '') { if (empty($input)) return array(); if (is_array($input)) return $input; // expand wildcards from list of all pages - if (preg_match('/[\?\*]/', $input) or substr($input,0,1) == "^") { + if (preg_match('/[\?\*]/', $input) or substr($input, 0, 1) == "^") { include_once 'lib/TextSearchQuery.php'; $search = new TextSearchQuery(str_replace(",", " or ", $input), true, - (substr($input,0,1) == "^") ? 'posix' : 'glob'); + (substr($input, 0, 1) == "^") ? 'posix' : 'glob'); $dbi = $GLOBALS['request']->getDbh(); $iter = $dbi->titleSearch($search, $sortby, $limit, $exclude); $pages = array(); @@ -1053,8 +1164,8 @@ class PageList { } // TODO: optimize getTotal => store in count - function allPagesByAuthor($wildcard, $include_empty=false, $sortby='', - $limit='', $exclude='') + function allPagesByAuthor($wildcard, $include_empty = false, $sortby = '', + $limit = '', $exclude = '') { $dbi = $GLOBALS['request']->getDbh(); $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude); @@ -1072,7 +1183,7 @@ class PageList { if (glob_match($wildcard, $author)) $allPages[] = $name; } elseif ($wildcard == $author) { - $allPages[] = $name; + $allPages[] = $name; } } // TODO: purge versiondata_cache @@ -1080,8 +1191,9 @@ class PageList { return $allPages; } - function allPagesByOwner($wildcard, $include_empty=false, $sortby='', - $limit='', $exclude='') { + function allPagesByOwner($wildcard, $include_empty = false, $sortby = '', + $limit = '', $exclude = '') + { $dbi = $GLOBALS['request']->getDbh(); $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude); $allPages = array(); @@ -1098,15 +1210,16 @@ class PageList { if (glob_match($wildcard, $owner)) $allPages[] = $name; } elseif ($wildcard == $owner) { - $allPages[] = $name; + $allPages[] = $name; } } } return $allPages; } - function allPagesByCreator($wildcard, $include_empty=false, $sortby='', - $limit='', $exclude='') { + function allPagesByCreator($wildcard, $include_empty = false, $sortby = '', + $limit = '', $exclude = '') + { $dbi = $GLOBALS['request']->getDbh(); $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude); $allPages = array(); @@ -1123,7 +1236,7 @@ class PageList { if (glob_match($wildcard, $creator)) $allPages[] = $name; } elseif ($wildcard == $creator) { - $allPages[] = $name; + $allPages[] = $name; } } } @@ -1131,8 +1244,9 @@ class PageList { } // UserPages are pages NOT owned by ADMIN_USER - function allUserPages($include_empty=false, $sortby='', - $limit='', $exclude='') { + function allUserPages($include_empty = false, $sortby = '', + $limit = '', $exclude = '') + { $dbi = $GLOBALS['request']->getDbh(); $allPagehandles = $dbi->getAllPages($include_empty, $sortby, $limit, $exclude); $allPages = array(); @@ -1140,7 +1254,7 @@ class PageList { $name = $pagehandle->getName(); $owner = $pagehandle->getOwner(); if ($owner !== ADMIN_USER) { - $allPages[] = $name; + $allPages[] = $name; } } return $allPages; @@ -1153,69 +1267,70 @@ class PageList { * If the pageList is initialized with $options['types'] these types are also initialized, * overriding the standard types. */ - function _initAvailableColumns() { + function _initAvailableColumns() + { global $customPageListColumns; $standard_types = array( - 'content' - => new _PageList_Column_content('rev:content', _("Content")), - // new: plugin specific column types initialised by the relevant plugins - /* - 'hi_content' // with highlighted search for SearchReplace - => new _PageList_Column_content('rev:hi_content', _("Content")), - 'remove' - => new _PageList_Column_remove('remove', _("Remove")), - // initialised by the plugin - 'renamed_pagename' - => new _PageList_Column_renamed_pagename('rename', _("Rename to")), - */ - 'perm' - => new _PageList_Column_perm('perm', _("Permission")), - 'acl' - => new _PageList_Column_acl('acl', _("ACL")), - 'checkbox' - => new _PageList_Column_checkbox('p', _("All")), - 'pagename' - => new _PageList_Column_pagename, - 'mtime' - => new _PageList_Column_time('rev:mtime', _("Last Modified")), - 'hits' - => new _PageList_Column('hits', _("Hits"), 'right'), - 'size' - => new _PageList_Column_size('rev:size', _("Size"), 'right'), - /*array('align' => 'char', 'char' => ' ')*/ - 'summary' - => new _PageList_Column('rev:summary', _("Last Summary")), - 'version' - => new _PageList_Column_version('rev:version', _("Version"), - 'right'), - 'author' - => new _PageList_Column_author('rev:author', _("Last Author")), - 'owner' - => new _PageList_Column_owner('author_id', _("Owner")), - 'creator' - => new _PageList_Column_creator('author_id', _("Creator")), - /* - 'group' - => new _PageList_Column_author('group', _("Group")), - */ - 'locked' - => new _PageList_Column_bool('locked', _("Locked"), - _("locked")), - 'external' - => new _PageList_Column_bool('external', _("External"), - _("external")), - 'minor' - => new _PageList_Column_bool('rev:is_minor_edit', - _("Minor Edit"), _("minor")), - 'markup' - => new _PageList_Column('rev:markup', _("Markup")), - // 'rating' initialised by the wikilens theme hook: addPageListColumn - /* - 'rating' - => new _PageList_Column_rating('rating', _("Rate")), - */ - ); + 'content' + => new _PageList_Column_content('rev:content', _("Content")), + // new: plugin specific column types initialised by the relevant plugins + /* + 'hi_content' // with highlighted search for SearchReplace + => new _PageList_Column_content('rev:hi_content', _("Content")), + 'remove' + => new _PageList_Column_remove('remove', _("Remove")), + // initialised by the plugin + 'renamed_pagename' + => new _PageList_Column_renamed_pagename('rename', _("Rename to")), + */ + 'perm' + => new _PageList_Column_perm('perm', _("Permission")), + 'acl' + => new _PageList_Column_acl('acl', _("ACL")), + 'checkbox' + => new _PageList_Column_checkbox('p', _("All")), + 'pagename' + => new _PageList_Column_pagename, + 'mtime' + => new _PageList_Column_time('rev:mtime', _("Last Modified")), + 'hits' + => new _PageList_Column('hits', _("Hits"), 'right'), + 'size' + => new _PageList_Column_size('rev:size', _("Size"), 'right'), + /*array('align' => 'char', 'char' => ' ')*/ + 'summary' + => new _PageList_Column('rev:summary', _("Last Summary")), + 'version' + => new _PageList_Column_version('rev:version', _("Version"), + 'right'), + 'author' + => new _PageList_Column_author('rev:author', _("Last Author")), + 'owner' + => new _PageList_Column_owner('author_id', _("Owner")), + 'creator' + => new _PageList_Column_creator('author_id', _("Creator")), + /* + 'group' + => new _PageList_Column_author('group', _("Group")), + */ + 'locked' + => new _PageList_Column_bool('locked', _("Locked"), + _("locked")), + 'external' + => new _PageList_Column_bool('external', _("External"), + _("external")), + 'minor' + => new _PageList_Column_bool('rev:is_minor_edit', + _("Minor Edit"), _("minor")), + 'markup' + => new _PageList_Column('rev:markup', _("Markup")), + // 'rating' initialised by the wikilens theme hook: addPageListColumn + /* + 'rating' + => new _PageList_Column_rating('rating', _("Rate")), + */ + ); if (empty($this->_types)) $this->_types = array(); // add plugin specific pageList columns, initialized by $options['types'] @@ -1232,11 +1347,11 @@ class PageList { } } - function getOption($option) { + function getOption($option) + { if (array_key_exists($option, $this->_options)) { return $this->_options[$option]; - } - else { + } else { return null; } } @@ -1257,9 +1372,10 @@ class PageList { * @param column name * @return true if column is added, false otherwise */ - function _addColumn ($column) { + function _addColumn($column) + { if (isset($this->_columns_seen[$column])) - return false; // Already have this one. + return false; // Already have this one. if (!isset($this->_types[$column])) $this->_initAvailableColumns(); $this->_columns_seen[$column] = true; @@ -1271,10 +1387,10 @@ class PageList { // Omitting this warning should be overridable by the extension if (!isset($this->_types[$column])) { $silently_ignore = array('numbacklinks', - 'rating','ratingvalue', - 'coagreement', 'minmisery', - 'averagerating', 'top3recs', - 'relation', 'linkto'); + 'rating', 'ratingvalue', + 'coagreement', 'minmisery', + 'averagerating', 'top3recs', + 'relation', 'linkto'); if (!in_array($column, $silently_ignore)) trigger_error(sprintf("%s: Bad column", $column), E_USER_NOTICE); return false; @@ -1297,8 +1413,9 @@ class PageList { * * @param $col object An object derived from _PageList_Column. **/ - function addColumnObject($col) { - if (is_array($col)) {// custom column object + function addColumnObject($col) + { + if (is_array($col)) { // custom column object $params =& $col; $class_name = array_shift($params); $params[3] =& $this; @@ -1315,15 +1432,15 @@ class PageList { /** * Compare _PageList_Page objects. **/ - function _pageCompare(&$a, &$b) { + function _pageCompare(&$a, &$b) + { if (empty($this->_sortby) or count($this->_sortby) == 0) { // No columns to sort by return 0; - } - else { - $pagea = $this->_getPageFromHandle($a); // If a string, convert to page + } else { + $pagea = $this->_getPageFromHandle($a); // If a string, convert to page assert(isa($pagea, 'WikiDB_Page')); - $pageb = $this->_getPageFromHandle($b); // If a string, convert to page + $pageb = $this->_getPageFromHandle($b); // If a string, convert to page assert(isa($pageb, 'WikiDB_Page')); foreach ($this->_sortby as $colNum => $direction) { // get column type object @@ -1333,7 +1450,7 @@ class PageList { elseif (isset($this->_types[$colNum])) $col = $this->_types[$colNum]; } - if (empty($col)){ + if (empty($col)) { return 0; } assert(isset($col)); @@ -1343,7 +1460,7 @@ class PageList { $bval = $col->_getSortableValue($pageb, $revision_handle); $cmp = $col->_compare($aval, $bval); - if ($direction === "-") // Reverse the sense of the comparison + if ($direction === "-") // Reverse the sense of the comparison $cmp *= -1; if ($cmp !== 0) @@ -1359,14 +1476,15 @@ class PageList { * If the sortby cols are already sorted by the DB call, don't do usort. * TODO: optimize for multiple sortable cols */ - function _sortPages() { + function _sortPages() + { if (count($this->_sortby) > 0) { $need_sort = $this->_options['dosort']; if (!$need_sort) - foreach ($this->_sortby as $col => $dir) { - if (! $this->sortby($col, 'db')) - $need_sort = true; - } + foreach ($this->_sortby as $col => $dir) { + if (!$this->sortby($col, 'db')) + $need_sort = true; + } if ($need_sort) { // There are some columns to sort by // TODO: consider nopage usort($this->_pages, array($this, '_pageCompare')); @@ -1374,7 +1492,8 @@ class PageList { } } - function limit($limit) { + function limit($limit) + { if (is_array($limit)) { list($from, $count) = $limit; if ((!empty($from) && !is_numeric($from)) or (!empty($count) && !is_numeric($count))) { @@ -1388,8 +1507,7 @@ class PageList { return $this->error(_("Illegal 'limit' argument: must be numeric")); } return array($from, $limit); - } - else { + } else { if (!empty($limit) && !is_numeric($limit)) { return $this->error(_("Illegal 'limit' argument: must be numeric")); } @@ -1397,7 +1515,8 @@ class PageList { } } - function pagingTokens($numrows = false, $ncolumns = false, $limit = false) { + function pagingTokens($numrows = false, $ncolumns = false, $limit = false) + { if ($numrows === false) $numrows = $this->getTotal(); if ($limit === false) @@ -1408,7 +1527,8 @@ class PageList { list($offset, $pagesize) = $this->limit($limit); if (!$pagesize or (!$offset and $numrows < $pagesize) or - (($offset + $pagesize) < 0)) + (($offset + $pagesize) < 0) + ) return false; $request = &$GLOBALS['request']; @@ -1421,13 +1541,14 @@ class PageList { $prev = $defargs; $tokens = array(); - $tokens['PREV'] = false; $tokens['PREV_LINK'] = ""; + $tokens['PREV'] = false; + $tokens['PREV_LINK'] = ""; $tokens['COLS'] = $ncolumns; $tokens['COUNT'] = $numrows; $tokens['OFFSET'] = $offset; $tokens['SIZE'] = $pagesize; - $tokens['NUMPAGES'] = (int) ceil($numrows / $pagesize); - $tokens['ACTPAGE'] = (int) ceil(($offset / $pagesize)+1); + $tokens['NUMPAGES'] = (int)ceil($numrows / $pagesize); + $tokens['ACTPAGE'] = (int)ceil(($offset / $pagesize) + 1); if ($offset > 0) { $prev['limit'] = max(0, $offset - $pagesize) . ",$pagesize"; $prev['count'] = $numrows; @@ -1438,10 +1559,11 @@ class PageList { $tokens['FIRST_LINK'] = WikiURL($pagename, $prev); } $next = $defargs; - $tokens['NEXT'] = false; $tokens['NEXT_LINK'] = ""; + $tokens['NEXT'] = false; + $tokens['NEXT_LINK'] = ""; if (($offset + $pagesize) < $numrows) { $next['limit'] = min($offset + $pagesize, $numrows - $pagesize) - . ",$pagesize"; + . ",$pagesize"; $next['count'] = $numrows; $tokens['LIMIT'] = $next['limit']; $tokens['NEXT'] = true; @@ -1453,21 +1575,22 @@ class PageList { } // make a table given the caption - function _generateTable($caption) { + function _generateTable($caption) + { if (count($this->_sortby) > 0) $this->_sortPages(); // wikiadminutils hack. that's a way to pagelist non-pages $rows = isset($this->_rows) ? $this->_rows : array(); $i = 0; $count = $this->getTotal(); - $do_paging = ( isset($this->_options['paging']) - and !empty($this->_options['limit']) - and $count - and $this->_options['paging'] != 'none' ); + $do_paging = (isset($this->_options['paging']) + and !empty($this->_options['limit']) + and $count + and $this->_options['paging'] != 'none'); if ($do_paging) { $tokens = $this->pagingTokens($count, - count($this->_columns), - $this->_options['limit']); + count($this->_columns), + $this->_options['limit']); if ($tokens and !empty($this->_options['slice'])) $this->_pages = array_slice($this->_pages, $tokens['OFFSET'], $tokens['SIZE']); } @@ -1476,12 +1599,12 @@ class PageList { $rows[] = $one_row; } $table = HTML::table(array('cellpadding' => 0, - 'cellspacing' => 1, - 'border' => 0, - 'width' => '100%', - 'class' => 'pagelist')); + 'cellspacing' => 1, + 'border' => 0, + 'width' => '100%', + 'class' => 'pagelist')); if ($caption) { - $table->pushContent(HTML::caption(array('align'=>'top'), $caption)); + $table->pushContent(HTML::caption(array('align' => 'top'), $caption)); } $row = HTML::tr(); @@ -1489,10 +1612,11 @@ class PageList { $i = 1; // start with 1! foreach ($this->_columns as $col) { $heading = $col->button_heading($this, $i); - if ( $do_paging - and isset($col->_field) - and $col->_field == 'pagename' - and ($maxlen = $this->maxLen())) { + if ($do_paging + and isset($col->_field) + and $col->_field == 'pagename' + and ($maxlen = $this->maxLen()) + ) { } $row->pushContent($heading); if (is_string($col->getHeading())) @@ -1501,12 +1625,12 @@ class PageList { } // Table summary for non-visual browsers. $table->setAttr('summary', sprintf(_("Columns: %s."), - join(", ", $table_summary))); + join(", ", $table_summary))); $table->pushContent(HTML::colgroup(array('span' => count($this->_columns)))); - if ( $do_paging ) { + if ($do_paging) { if ($tokens === false) { $table->pushContent(HTML::thead($row), - HTML::tbody(false, $rows)); + HTML::tbody(false, $rows)); return $table; } @@ -1519,13 +1643,14 @@ class PageList { return $table; } else { $table->pushContent(HTML::thead($row), - HTML::tbody(false, $rows)); + HTML::tbody(false, $rows)); return $table; } } /* recursive stack for private sublist options (azhead, cols) */ - function _saveOptions($opts) { + function _saveOptions($opts) + { $stack = array('pages' => $this->_pages); foreach ($opts as $k => $v) { $stack[$k] = $this->_options[$k]; @@ -1535,7 +1660,9 @@ class PageList { $this->_stack = new Stack(); $this->_stack->push($stack); } - function _restoreOptions() { + + function _restoreOptions() + { assert($this->_stack); $stack = $this->_stack->pop(); $this->_pages = $stack['pages']; @@ -1550,7 +1677,8 @@ class PageList { // 'ordered' - OL or UL list (not yet inherited to all plugins) // 'comma' - condensed comma-list only, 1: no links, >1: with links // FIXME: only unique list entries, esp. with nopage - function _generateList($caption='') { + function _generateList($caption = '') + { if (empty($this->_pages)) return; // stop recursion if (!isset($this->_options['listtype'])) $this->_options['listtype'] = ''; @@ -1569,24 +1697,25 @@ class PageList { } if (count($this->_sortby) > 0) $this->_sortPages(); $count = $this->getTotal(); - $do_paging = ( isset($this->_options['paging']) - and !empty($this->_options['limit']) - and $count - and $this->_options['paging'] != 'none' ); - if ( $do_paging ) { + $do_paging = (isset($this->_options['paging']) + and !empty($this->_options['limit']) + and $count + and $this->_options['paging'] != 'none'); + if ($do_paging) { $tokens = $this->pagingTokens($count, - count($this->_columns), - $this->_options['limit']); + count($this->_columns), + $this->_options['limit']); if ($tokens) { $paging = Template("pagelink", $tokens); - $out->pushContent(HTML::table(array('width'=>'100%'), $paging)); + $out->pushContent(HTML::table(array('width' => '100%'), $paging)); } } if (!empty($this->_options['limit']) and !empty($this->_options['slice'])) { list($offset, $count) = $this->limit($this->_options['limit']); } else { - $offset = 0; $count = count($this->_pages); + $offset = 0; + $count = count($this->_pages); } // need a recursive switch here for the azhead and cols grouping. if (!empty($this->_options['cols']) and $this->_options['cols'] > 1) { @@ -1596,18 +1725,18 @@ class PageList { if (($length * ($this->_options['cols'])) != $count) { $length += 1; } - $width = sprintf("%d", 100 / $this->_options['cols']).'%'; + $width = sprintf("%d", 100 / $this->_options['cols']) . '%'; $cols = HTML::tr(array('valign' => 'top')); - for ($i=$offset; $i < $offset+$count; $i += $length) { + for ($i = $offset; $i < $offset + $count; $i += $length) { $this->_saveOptions(array('cols' => 0, 'paging' => 'none')); $this->_pages = array_slice($this->_pages, $i, $length); - $cols->pushContent(HTML::td(/*array('width' => $width),*/ - $this->_generateList())); + $cols->pushContent(HTML::td( /*array('width' => $width),*/ + $this->_generateList())); $this->_restoreOptions(); } // speed up table rendering by defining colgroups $out->pushContent(HTML::table(HTML::colgroup - (array('span' => $this->_options['cols'], 'width' => $width)), + (array('span' => $this->_options['cols'], 'width' => $width)), $cols)); return $out; } @@ -1615,17 +1744,16 @@ class PageList { // Ignore azhead if not sorted by pagename if (!empty($this->_options['azhead']) and strstr($this->sortby($this->_options['sortby'], 'init'), "pagename") - ) - { + ) { $cur_h = substr($this->_pages[0]->getName(), 0, 1); $out->pushContent(HTML::h3($cur_h)); // group those pages together with same $h $j = 0; - for ($i=0; $i < count($this->_pages); $i++) { + for ($i = 0; $i < count($this->_pages); $i++) { $page =& $this->_pages[$i]; $h = substr($page->getName(), 0, 1); if ($h != $cur_h and $i > $j) { - $this->_saveOptions(array('cols' => 0, 'azhead' => 0, 'ordered' => $j+1)); + $this->_saveOptions(array('cols' => 0, 'azhead' => 0, 'ordered' => $j + 1)); $this->_pages = array_slice($this->_pages, $j, $i - $j); $out->pushContent($this->_generateList()); $this->_restoreOptions(); @@ -1635,7 +1763,7 @@ class PageList { } } if ($i > $j) { // flush the rest - $this->_saveOptions(array('cols' => 0, 'azhead' => 0, 'ordered' => $j+1)); + $this->_saveOptions(array('cols' => 0, 'azhead' => 0, 'ordered' => $j + 1)); $this->_pages = array_slice($this->_pages, $j, $i - $j); $out->pushContent($this->_generateList()); $this->_restoreOptions(); @@ -1655,13 +1783,13 @@ class PageList { if ($this->_options['listtype'] == 'ol') { if (empty($this->_options['ordered'])) { - $this->_options['ordered'] = $offset+1; + $this->_options['ordered'] = $offset + 1; } } elseif ($this->_options['listtype'] == 'ul') $this->_options['ordered'] = 0; if ($this->_options['listtype'] == 'ol' and !empty($this->_options['ordered'])) { $list = HTML::ol(array('class' => 'pagelist', - 'start' => $this->_options['ordered'])); + 'start' => $this->_options['ordered'])); } elseif ($this->_options['listtype'] == 'dl') { $list = HTML::dl(array('class' => 'pagelist')); } else { @@ -1672,7 +1800,7 @@ class PageList { if (!empty($this->_options['limit'])) list($offset, $pagesize) = $this->limit($this->_options['limit']); else - $pagesize=0; + $pagesize = 0; foreach (array_reverse($rows) as $one_row) { $pagehtml = $one_row['render']; if (!$pagehtml) continue; @@ -1683,14 +1811,14 @@ class PageList { if ($this->_options['listtype'] == 'dl') { $header = $one_row['header']; $list->pushContent(HTML::dt(array('class' => $class), $header), - HTML::dd(array('class' => $class), $pagehtml)); + HTML::dd(array('class' => $class), $pagehtml)); } else $list->pushContent(HTML::li(array('class' => $class), $pagehtml)); if ($pagesize and $i > $pagesize) break; } $out->pushContent($list); - if ( $do_paging and $tokens ) { - $out->pushContent(HTML::table(array('width'=>'100%'), $paging)); + if ($do_paging and $tokens) { + $out->pushContent(HTML::table(array('width' => '100%'), $paging)); } return $out; } @@ -1699,7 +1827,8 @@ class PageList { // Condense list without a href links: "Page1, Page2, ..." // Alternative $seperator = HTML::Raw(' · ') // FIXME: only unique list entries, esp. with nopage - function _generateCommaListAsString() { + function _generateCommaListAsString() + { if (defined($this->_options['commasep'])) $seperator = $this->_options['commasep']; else @@ -1707,7 +1836,7 @@ class PageList { $pages = array(); foreach ($this->_pages as $pagenum => $page) { if ($s = $this->_renderPageRow($page)) // some pages are not viewable - $pages[] = is_string($s) ? $s : $s->asString(); + $pages[] = is_string($s) ? $s : $s->asString(); } return HTML(join($seperator, $pages)); } @@ -1717,7 +1846,8 @@ class PageList { // Future: 1 = reserved for plain string (see above) // 2 and more => HTML link specialization? // FIXME: only unique list entries, esp. with nopage - function _generateCommaList($style = false) { + function _generateCommaList($style = false) + { if (defined($this->_options['commasep'])) $seperator = HTLM::Raw($this->_options['commasep']); else @@ -1732,7 +1862,8 @@ class PageList { return $html; } - function _emptyList($caption) { + function _emptyList($caption) + { $html = HTML(); if ($caption) { $html->pushContent(HTML::p($caption)); @@ -1742,43 +1873,51 @@ class PageList { return $html; } -}; +} + +; /* List pages with checkboxes to select from. * The [Select] button toggles via Javascript flipAll */ class PageList_Selectable -extends PageList { + extends PageList +{ - function PageList_Selectable ($columns=false, $exclude='', $options = false) { + function PageList_Selectable($columns = false, $exclude = '', $options = false) + { if ($columns) { if (!is_array($columns)) $columns = explode(',', $columns); - if (!in_array('checkbox',$columns)) - array_unshift($columns,'checkbox'); + if (!in_array('checkbox', $columns)) + array_unshift($columns, 'checkbox'); } else { - $columns = array('checkbox','pagename'); + $columns = array('checkbox', 'pagename'); } $this->PageList($columns, $exclude, $options); } - function addPageList ($array) { - while (list($pagename,$selected) = each($array)) { + function addPageList($array) + { + while (list($pagename, $selected) = each($array)) { if ($selected) $this->addPageSelected((string)$pagename); $this->addPage((string)$pagename); } } - function addPageSelected ($pagename) { + function addPageSelected($pagename) + { $this->_selected[$pagename] = 1; } } class PageList_Unselectable -extends PageList { + extends PageList +{ - function PageList_Unselectable ($columns=false, $exclude='', $options = false) { + function PageList_Unselectable($columns = false, $exclude = '', $options = false) + { if ($columns) { if (!is_array($columns)) $columns = explode(',', $columns); @@ -1788,14 +1927,16 @@ extends PageList { $this->PageList($columns, $exclude, $options); } - function addPageList ($array) { - while (list($pagename,$selected) = each($array)) { + function addPageList($array) + { + while (list($pagename, $selected) = each($array)) { if ($selected) $this->addPageSelected((string)$pagename); $this->addPage((string)$pagename); } } - function addPageSelected ($pagename) { + function addPageSelected($pagename) + { $this->_selected[$pagename] = 1; } } diff --git a/lib/PagePerm.php b/lib/PagePerm.php index d146878a9..9ebf56fc1 100644 --- a/lib/PagePerm.php +++ b/lib/PagePerm.php @@ -62,25 +62,26 @@ */ /* Symbolic special ACL groups. Untranslated to be stored in page metadata*/ -define('ACL_EVERY', '_EVERY'); -define('ACL_ANONYMOUS', '_ANONYMOUS'); -define('ACL_BOGOUSER', '_BOGOUSER'); -define('ACL_HASHOMEPAGE', '_HASHOMEPAGE'); -define('ACL_SIGNED', '_SIGNED'); -define('ACL_AUTHENTICATED','_AUTHENTICATED'); -define('ACL_ADMIN', '_ADMIN'); -define('ACL_OWNER', '_OWNER'); -define('ACL_CREATOR', '_CREATOR'); +define('ACL_EVERY', '_EVERY'); +define('ACL_ANONYMOUS', '_ANONYMOUS'); +define('ACL_BOGOUSER', '_BOGOUSER'); +define('ACL_HASHOMEPAGE', '_HASHOMEPAGE'); +define('ACL_SIGNED', '_SIGNED'); +define('ACL_AUTHENTICATED', '_AUTHENTICATED'); +define('ACL_ADMIN', '_ADMIN'); +define('ACL_OWNER', '_OWNER'); +define('ACL_CREATOR', '_CREATOR'); // Return an page permissions array for this page. // To provide ui helpers to view and change page permissions: // <tr><th>Group</th><th>Access</th><th>Allow or Forbid</th></tr> // <tr><td>$group</td><td>_($access)</td><td> [ ] </td></tr> -function pagePermissions($pagename) { +function pagePermissions($pagename) +{ global $request; $page = $request->getPage($pagename); // Page not found (new page); returned inherited permissions, to be displayed in gray - if (! $page->exists() ) { + if (!$page->exists()) { if ($pagename == '.') // stop recursion return array('default', new PagePermission()); else { @@ -88,7 +89,7 @@ function pagePermissions($pagename) { } } elseif ($perm = getPagePermissions($page)) { return array('page', $perm); - // or no permissions defined; returned inherited permissions, to be displayed in gray + // or no permissions defined; returned inherited permissions, to be displayed in gray } elseif ($pagename == '.') { // stop recursion in pathological case. // "." defined, without any acl return array('default', new PagePermission()); @@ -97,8 +98,9 @@ function pagePermissions($pagename) { } } -function pagePermissionsSimpleFormat($perm_tree, $owner, $group=false) { - list($type,$perm) = pagePermissionsAcl($perm_tree[0], $perm_tree); +function pagePermissionsSimpleFormat($perm_tree, $owner, $group = false) +{ + list($type, $perm) = pagePermissionsAcl($perm_tree[0], $perm_tree); /* $type = $perm_tree[0]; $perm = pagePermissionsAcl($perm_tree); @@ -115,26 +117,27 @@ function pagePermissionsSimpleFormat($perm_tree, $owner, $group=false) { if ($type == 'page') return HTML::tt(HTML::strong($perm->asRwxString($owner, $group))); elseif ($type == 'default') - return HTML::tt($perm->asRwxString($owner, $group)); - elseif ($type == 'inherited') { - return HTML::tt(array('class'=>'inherited', 'style'=>'color:#aaa;'), - $perm->asRwxString($owner, $group)); + return HTML::tt($perm->asRwxString($owner, $group)); elseif ($type == 'inherited') { + return HTML::tt(array('class' => 'inherited', 'style' => 'color:#aaa;'), + $perm->asRwxString($owner, $group)); } } -function pagePermissionsAcl($type,$perm_tree) { +function pagePermissionsAcl($type, $perm_tree) +{ $perm = $perm_tree[1]; while (!is_object($perm)) { $perm_tree = pagePermissionsAcl($type, $perm); $perm = $perm_tree[1]; } - return array($type,$perm); + return array($type, $perm); } // view => who // edit => who -function pagePermissionsAclFormat($perm_tree, $editable=false) { - list($type,$perm) = pagePermissionsAcl($perm_tree[0], $perm_tree); +function pagePermissionsAclFormat($perm_tree, $editable = false) +{ + list($type, $perm) = pagePermissionsAcl($perm_tree[0], $perm_tree); if ($editable) return $perm->asEditableTable($type); else @@ -148,10 +151,11 @@ function pagePermissionsAclFormat($perm_tree, $editable=false) { * overruled by more specific forbid rules. * Todo: cache result per access and page in session? */ -function requiredAuthorityForPage ($action) { +function requiredAuthorityForPage($action) +{ global $request; $auth = _requiredAuthorityForPagename(action2access($action), - $request->getArg('pagename')); + $request->getArg('pagename')); assert($auth !== -1); if ($auth) return $request->_user->_level; @@ -160,71 +164,74 @@ function requiredAuthorityForPage ($action) { } // Translate action or plugin to the simplier access types: -function action2access ($action) { +function action2access($action) +{ global $request; switch ($action) { - case 'browse': - case 'viewsource': - case 'diff': - case 'select': - case 'search': - case 'pdf': - case 'captcha': - return 'view'; - - // performance and security relevant - case 'xmlrpc': - case 'soap': - case 'zip': - case 'ziphtml': - case 'dumphtml': - case 'dumpserial': - return 'dump'; - - // invent a new access-perm massedit? or switch back to change, or keep it at edit? - case _("PhpWikiAdministration")."/"._("Rename"): - case _("PhpWikiAdministration")."/"._("SearchReplace"): - case 'replace': - case 'rename': - case 'revert': - case 'edit': - return 'edit'; - case 'create': - $page = $request->getPage(); - if (!$page->exists()) - return 'create'; - else - return 'view'; - break; - case 'upload': - case 'loadfile': - // probably create/edit but we cannot check all page permissions, can we? - case 'remove': - case 'purge': - case 'lock': - case 'unlock': - case 'upgrade': - case 'chown': - case 'setacl': - return 'change'; - default: - //Todo: Plugins should be able to override its access type - if (isWikiWord($action)) + case 'browse': + case 'viewsource': + case 'diff': + case 'select': + case 'search': + case 'pdf': + case 'captcha': return 'view'; - else + + // performance and security relevant + case 'xmlrpc': + case 'soap': + case 'zip': + case 'ziphtml': + case 'dumphtml': + case 'dumpserial': + return 'dump'; + + // invent a new access-perm massedit? or switch back to change, or keep it at edit? + case _("PhpWikiAdministration") . "/" . _("Rename"): + case _("PhpWikiAdministration") . "/" . _("SearchReplace"): + case 'replace': + case 'rename': + case 'revert': + case 'edit': + return 'edit'; + case 'create': + $page = $request->getPage(); + if (!$page->exists()) + return 'create'; + else + return 'view'; + break; + case 'upload': + case 'loadfile': + // probably create/edit but we cannot check all page permissions, can we? + case 'remove': + case 'purge': + case 'lock': + case 'unlock': + case 'upgrade': + case 'chown': + case 'setacl': return 'change'; - break; + default: + //Todo: Plugins should be able to override its access type + if (isWikiWord($action)) + return 'view'; + else + return 'change'; + break; } } // Recursive helper to do the real work. // Using a simple perm cache for page-access pairs. // Maybe page-(current+edit+change?)action pairs will help -function _requiredAuthorityForPagename($access, $pagename) { +function _requiredAuthorityForPagename($access, $pagename) +{ static $permcache = array(); if (array_key_exists($pagename, $permcache) - and array_key_exists($access, $permcache[$pagename])) + and array_key_exists($access, $permcache[$pagename]) + ) return $permcache[$pagename][$access]; global $request; @@ -232,32 +239,32 @@ function _requiredAuthorityForPagename($access, $pagename) { // Exceptions: if (FUSIONFORGE) { - if ($pagename != '.' && isset($request->_user->_is_external) && $request->_user->_is_external && ! $page->get('external')) { + if ($pagename != '.' && isset($request->_user->_is_external) && $request->_user->_is_external && !$page->get('external')) { $permcache[$pagename][$access] = 0; return 0; } } if ((READONLY or $request->_dbi->readonly) - and in_array($access, array('edit','create','change'))) - { + and in_array($access, array('edit', 'create', 'change')) + ) { return 0; } // Page not found; check against default permissions - if (! $page->exists() ) { + if (!$page->exists()) { $perm = new PagePermission(); $result = ($perm->isAuthorized($access, $request->_user) === true); $permcache[$pagename][$access] = $result; return $result; } // no ACL defined; check for special dotfile or walk down - if (! ($perm = getPagePermissions($page))) { + if (!($perm = getPagePermissions($page))) { if ($pagename == '.') { $perm = new PagePermission(); if ($perm->isAuthorized('change', $request->_user)) { // warn the user to set ACL of ".", if he has permissions to do so. - trigger_error(". (dotpage == rootpage for inheriting pageperm ACLs) exists without any ACL!\n". - "Please do ?action=setacl&pagename=.", E_USER_WARNING); + trigger_error(". (dotpage == rootpage for inheriting pageperm ACLs) exists without any ACL!\n" . + "Please do ?action=setacl&pagename=.", E_USER_WARNING); } $result = ($perm->isAuthorized($access, $request->_user) === true); $permcache[$pagename][$access] = $result; @@ -286,7 +293,8 @@ function _requiredAuthorityForPagename($access, $pagename) { * @param string $pagename page from which the parent page is searched. * @return string parent pagename or the (possibly pseudo) dot-pagename. */ -function getParentPage($pagename) { +function getParentPage($pagename) +{ if (isSubPage($pagename)) { return subPageSlice($pagename, 0); } else { @@ -297,31 +305,34 @@ function getParentPage($pagename) { // Read the ACL from the page // Done: Not existing pages should NOT be queried. // Check the parent page instead and don't take the default ACL's -function getPagePermissions ($page) { - if ($hash = $page->get('perm')) // hash => object +function getPagePermissions($page) +{ + if ($hash = $page->get('perm')) // hash => object return new PagePermission(unserialize($hash)); else return false; } // Store the ACL in the page -function setPagePermissions ($page,$perm) { +function setPagePermissions($page, $perm) +{ $perm->store($page); } -function getAccessDescription($access) { +function getAccessDescription($access) +{ static $accessDescriptions; - if (! $accessDescriptions) { + if (!$accessDescriptions) { $accessDescriptions = array( - 'list' => _("List this page and all subpages"), - 'view' => _("View this page and all subpages"), - 'edit' => _("Edit this page and all subpages"), - 'create' => _("Create a new (sub)page"), - 'dump' => _("Download page contents"), - 'change' => _("Change page attributes"), - 'remove' => _("Remove this page"), - 'purge' => _("Purge this page"), - ); + 'list' => _("List this page and all subpages"), + 'view' => _("View this page and all subpages"), + 'edit' => _("Edit this page and all subpages"), + 'create' => _("Create a new (sub)page"), + 'dump' => _("Download page contents"), + 'change' => _("Change page attributes"), + 'remove' => _("Remove this page"), + 'purge' => _("Purge this page"), + ); } if (in_array($access, array_keys($accessDescriptions))) return $accessDescriptions[$access]; @@ -339,10 +350,12 @@ function getAccessDescription($access) { * * Define any special rules here, like don't list dot-pages. */ -class PagePermission { +class PagePermission +{ var $perm; - function PagePermission($hash = array()) { + function PagePermission($hash = array()) + { $this->_group = &$GLOBALS['request']->getGroup(); if (is_array($hash) and !empty($hash)) { $accessTypes = $this->accessTypes(); @@ -351,7 +364,7 @@ class PagePermission { $this->perm[$access] = $requires; else trigger_error(sprintf(_("Unsupported ACL access type %s ignored."), $access), - E_USER_WARNING); + E_USER_WARNING); } } else { // set default permissions, the so called dot-file acl's @@ -365,7 +378,8 @@ class PagePermission { * Must translate the various special groups to the actual users settings * (userid, group membership). */ - function isAuthorized($access, $user) { + function isAuthorized($access, $user) + { $allow = -1; if (!empty($this->perm{$access})) { foreach ($this->perm[$access] as $group => $bool) { @@ -383,22 +397,23 @@ class PagePermission { * Translate the various special groups to the actual users settings * (userid, group membership). */ - function isMember($user, $group) { + function isMember($user, $group) + { global $request; if ($group === ACL_EVERY) return true; if (!isset($this->_group)) $member =& $request->getGroup(); else $member =& $this->_group; //$user = & $request->_user; - if ($group === ACL_ADMIN) // WIKI_ADMIN or member of _("Administrators") + if ($group === ACL_ADMIN) // WIKI_ADMIN or member of _("Administrators") return $user->isAdmin() or - ($user->isAuthenticated() and - $member->isMember(GROUP_ADMIN)); + ($user->isAuthenticated() and + $member->isMember(GROUP_ADMIN)); if ($group === ACL_ANONYMOUS) - return ! $user->isSignedIn(); + return !$user->isSignedIn(); if ($group === ACL_BOGOUSER) if (ENABLE_USER_NEW) - return isa($user,'_BogoUser') or - (isWikiWord($user->_userid) and $user->_level >= WIKIAUTH_BOGO); + return isa($user, '_BogoUser') or + (isWikiWord($user->_userid) and $user->_level >= WIKIAUTH_BOGO); else return isWikiWord($user->UserName()); if ($group === ACL_HASHOMEPAGE) return $user->hasHomePage(); @@ -411,52 +426,52 @@ class PagePermission { $page = $request->getPage(); $owner = $page->getOwner(); return ($owner === $user->UserName() - or $member->isMember($owner)); + or $member->isMember($owner)); } if ($group === ACL_CREATOR) { if (!$user->isAuthenticated()) return false; $page = $request->getPage(); $creator = $page->getCreator(); return ($creator === $user->UserName() - or $member->isMember($creator)); + or $member->isMember($creator)); } /* Or named groups or usernames. Note: We don't seperate groups and users here. Users overrides groups with the same name. */ return $user->UserName() === $group or - $member->isMember($group); + $member->isMember($group); } /** * returns hash of default permissions. * check if the page '.' exists and returns this instead. */ - function defaultPerms() { + function defaultPerms() + { //Todo: check for the existance of '.' and take this instead. //Todo: honor more config.ini auth settings here - $perm = array('view' => array(ACL_EVERY => true), - 'edit' => array(ACL_EVERY => true), - 'create' => array(ACL_EVERY => true), - 'list' => array(ACL_EVERY => true), - 'remove' => array(ACL_ADMIN => true, - ACL_OWNER => true), - 'purge' => array(ACL_ADMIN => true, - ACL_OWNER => true), - 'dump' => array(ACL_ADMIN => true, - ACL_OWNER => true), - 'change' => array(ACL_ADMIN => true, - ACL_OWNER => true)); + $perm = array('view' => array(ACL_EVERY => true), + 'edit' => array(ACL_EVERY => true), + 'create' => array(ACL_EVERY => true), + 'list' => array(ACL_EVERY => true), + 'remove' => array(ACL_ADMIN => true, + ACL_OWNER => true), + 'purge' => array(ACL_ADMIN => true, + ACL_OWNER => true), + 'dump' => array(ACL_ADMIN => true, + ACL_OWNER => true), + 'change' => array(ACL_ADMIN => true, + ACL_OWNER => true)); if (ZIPDUMP_AUTH) $perm['dump'] = array(ACL_ADMIN => true, - ACL_OWNER => true); + ACL_OWNER => true); elseif (INSECURE_ACTIONS_LOCALHOST_ONLY) { if (is_localhost()) $perm['dump'] = array(ACL_EVERY => true); else $perm['dump'] = array(ACL_ADMIN => true); - } - else + } else $perm['dump'] = array(ACL_EVERY => true); if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT) $perm['edit'] = array(ACL_SIGNED => true); @@ -483,10 +498,11 @@ class PagePermission { /** * FIXME: check valid groups and access */ - function sanify() { + function sanify() + { foreach ($this->perm as $access => $groups) { foreach ($groups as $group => $bool) { - $this->perm[$access][$group] = (boolean) $bool; + $this->perm[$access][$group] = (boolean)$bool; } } } @@ -494,7 +510,8 @@ class PagePermission { /** * do a recursive comparison */ - function equal($otherperm) { + function equal($otherperm) + { // The equal function seems to be unable to detect removed perm. // Use case is when a rule is removed. return (print_r($this->perm, true) === print_r($otherperm, true)); @@ -503,7 +520,8 @@ class PagePermission { /** * returns list of all supported access types. */ - function accessTypes() { + function accessTypes() + { return array_keys(PagePermission::defaultPerms()); } @@ -511,9 +529,10 @@ class PagePermission { * special permissions for dot-files, beginning with '.' * maybe also for '_' files? */ - function dotPerms() { + function dotPerms() + { $def = array(ACL_ADMIN => true, - ACL_OWNER => true); + ACL_OWNER => true); $perm = array(); foreach (PagePermission::accessTypes() as $access) { $perm[$access] = $def; @@ -524,9 +543,10 @@ class PagePermission { /** * dead code. not needed inside the object. see getPagePermissions($page) */ - function retrieve($page) { + function retrieve($page) + { $hash = $page->get('perm'); - if ($hash) // hash => object + if ($hash) // hash => object $perm = new PagePermission(unserialize($hash)); else $perm = new PagePermission(); @@ -534,57 +554,60 @@ class PagePermission { return $perm; } - function store($page) { + function store($page) + { // object => hash $this->sanify(); - return $page->set('perm',serialize($this->perm)); + return $page->set('perm', serialize($this->perm)); } - function groupName ($group) { - if ($group[0] == '_') return constant("GROUP".$group); + function groupName($group) + { + if ($group[0] == '_') return constant("GROUP" . $group); else return $group; } /* type: page, default, inherited */ - function asTable($type) { + function asTable($type) + { $table = HTML::table(); foreach ($this->perm as $access => $perms) { $td = HTML::table(array('class' => 'cal')); foreach ($perms as $group => $bool) { - $td->pushContent(HTML::tr(HTML::td(array('align'=>'right'),$group), - HTML::td($bool ? '[X]' : '[ ]'))); + $td->pushContent(HTML::tr(HTML::td(array('align' => 'right'), $group), + HTML::td($bool ? '[X]' : '[ ]'))); } $table->pushContent(HTML::tr(array('valign' => 'top'), - HTML::td($access),HTML::td($td))); + HTML::td($access), HTML::td($td))); } if ($type == 'default') - $table->setAttr('style','border: dotted thin black; background-color:#eee;'); + $table->setAttr('style', 'border: dotted thin black; background-color:#eee;'); elseif ($type == 'inherited') - $table->setAttr('style','border: dotted thin black; background-color:#ddd;'); - elseif ($type == 'page') - $table->setAttr('style','border: solid thin black; font-weight: bold;'); + $table->setAttr('style', 'border: dotted thin black; background-color:#ddd;'); elseif ($type == 'page') + $table->setAttr('style', 'border: solid thin black; font-weight: bold;'); return $table; } /* type: page, default, inherited */ - function asEditableTable($type) { + function asEditableTable($type) + { global $WikiTheme; if (!isset($this->_group)) { $this->_group =& $GLOBALS['request']->getGroup(); } $table = HTML::table(); $table->pushContent(HTML::tr( - HTML::th(array('align' => 'left'), - _("Access")), - HTML::th(array('align'=>'right'), - _("Group/User")), - HTML::th(_("Grant")), - HTML::th(_("Del/+")), - HTML::th(_("Description")))); + HTML::th(array('align' => 'left'), + _("Access")), + HTML::th(array('align' => 'right'), + _("Group/User")), + HTML::th(_("Grant")), + HTML::th(_("Del/+")), + HTML::th(_("Description")))); $allGroups = $this->_group->_specialGroups(); foreach ($this->_group->getAllGroupsIn() as $group) { - if (!in_array($group,$this->_group->specialGroups())) + if (!in_array($group, $this->_group->specialGroups())) $allGroups[] = $group; } //array_unique(array_merge($this->_group->getAllGroupsIn(), @@ -595,86 +618,85 @@ class PagePermission { //$permlist = HTML::table(array('class' => 'cal')); $first_only = true; $newperm = HTML::input(array('type' => 'checkbox', - 'name' => "acl[_new_perm][$access]", - 'value' => 1)); + 'name' => "acl[_new_perm][$access]", + 'value' => 1)); $addbutton = HTML::input(array('type' => 'checkbox', - 'name' => "acl[_add_group][$access]", - //'src' => $addsrc, - //'alt' => "Add", - 'title' => _("Add this ACL"), - 'value' => 1)); + 'name' => "acl[_add_group][$access]", + //'src' => $addsrc, + //'alt' => "Add", + 'title' => _("Add this ACL"), + 'value' => 1)); $newgroup = HTML::select(array('name' => "acl[_new_group][$access]", - 'style'=> 'text-align: right;', - 'size' => 1)); + 'style' => 'text-align: right;', + 'size' => 1)); foreach ($allGroups as $groupname) { if (!isset($groups[$groupname])) $newgroup->pushContent(HTML::option(array('value' => $groupname), - $this->groupName($groupname))); + $this->groupName($groupname))); } if (empty($groups)) { - $addbutton->setAttr('checked','checked'); - $newperm->setAttr('checked','checked'); + $addbutton->setAttr('checked', 'checked'); + $newperm->setAttr('checked', 'checked'); $table->pushContent( HTML::tr(array('valign' => 'top'), - HTML::td(HTML::strong($access.":")), - HTML::td($newgroup), - HTML::td($nbsp,$newperm), - HTML::td($nbsp,$addbutton), - HTML::td(HTML::em(getAccessDescription($access))))); + HTML::td(HTML::strong($access . ":")), + HTML::td($newgroup), + HTML::td($nbsp, $newperm), + HTML::td($nbsp, $addbutton), + HTML::td(HTML::em(getAccessDescription($access))))); } foreach ($groups as $group => $bool) { $checkbox = HTML::input(array('type' => 'checkbox', - 'name' => "acl[$access][$group]", - 'title' => _("Allow / Deny"), - 'value' => 1)); - if ($bool) $checkbox->setAttr('checked','checked'); + 'name' => "acl[$access][$group]", + 'title' => _("Allow / Deny"), + 'value' => 1)); + if ($bool) $checkbox->setAttr('checked', 'checked'); $checkbox = HTML(HTML::input(array('type' => 'hidden', - 'name' => "acl[$access][$group]", - 'value' => 0)), - $checkbox); + 'name' => "acl[$access][$group]", + 'value' => 0)), + $checkbox); $deletebutton = HTML::input(array('type' => 'checkbox', - 'name' => "acl[_del_group][$access][$group]", - 'style' => 'background: #aaa url('.$deletesrc.')', - //'src' => $deletesrc, - //'alt' => "Del", - 'title' => _("Delete this ACL"), - 'value' => 1)); + 'name' => "acl[_del_group][$access][$group]", + 'style' => 'background: #aaa url(' . $deletesrc . ')', + //'src' => $deletesrc, + //'alt' => "Del", + 'title' => _("Delete this ACL"), + 'value' => 1)); if ($first_only) { $table->pushContent( HTML::tr( - HTML::td(HTML::strong($access.":")), - HTML::td(array('class' => 'cal-today','align'=>'right'), - HTML::strong($this->groupName($group))), - HTML::td(array('align'=>'center'),$nbsp,$checkbox), - HTML::td(array('align'=>'right','style' => 'background: #aaa url('.$deletesrc.') no-repeat'),$deletebutton), - HTML::td(HTML::em(getAccessDescription($access))))); + HTML::td(HTML::strong($access . ":")), + HTML::td(array('class' => 'cal-today', 'align' => 'right'), + HTML::strong($this->groupName($group))), + HTML::td(array('align' => 'center'), $nbsp, $checkbox), + HTML::td(array('align' => 'right', 'style' => 'background: #aaa url(' . $deletesrc . ') no-repeat'), $deletebutton), + HTML::td(HTML::em(getAccessDescription($access))))); $first_only = false; } else { $table->pushContent( HTML::tr( - HTML::td(), - HTML::td(array('class' => 'cal-today','align'=>'right'), - HTML::strong($this->groupName($group))), - HTML::td(array('align'=>'center'),$nbsp,$checkbox), - HTML::td(array('align'=>'right','style' => 'background: #aaa url('.$deletesrc.') no-repeat'),$deletebutton), - HTML::td())); + HTML::td(), + HTML::td(array('class' => 'cal-today', 'align' => 'right'), + HTML::strong($this->groupName($group))), + HTML::td(array('align' => 'center'), $nbsp, $checkbox), + HTML::td(array('align' => 'right', 'style' => 'background: #aaa url(' . $deletesrc . ') no-repeat'), $deletebutton), + HTML::td())); } } if (!empty($groups)) $table->pushContent( HTML::tr(array('valign' => 'top'), - HTML::td(array('align'=>'right'),_("add ")), - HTML::td($newgroup), - HTML::td(array('align'=>'center'),$nbsp,$newperm), - HTML::td(array('align'=>'right','style' => 'background: #ccc url('.$addsrc.') no-repeat'),$addbutton), - HTML::td(HTML::small(_("Check to add this ACL"))))); + HTML::td(array('align' => 'right'), _("add ")), + HTML::td($newgroup), + HTML::td(array('align' => 'center'), $nbsp, $newperm), + HTML::td(array('align' => 'right', 'style' => 'background: #ccc url(' . $addsrc . ') no-repeat'), $addbutton), + HTML::td(HTML::small(_("Check to add this ACL"))))); } if ($type == 'default') - $table->setAttr('style','border: dotted thin black; background-color:#eee;'); + $table->setAttr('style', 'border: dotted thin black; background-color:#eee;'); elseif ($type == 'inherited') - $table->setAttr('style','border: dotted thin black; background-color:#ddd;'); - elseif ($type == 'page') - $table->setAttr('style','border: solid thin black; font-weight: bold;'); + $table->setAttr('style', 'border: dotted thin black; background-color:#ddd;'); elseif ($type == 'page') + $table->setAttr('style', 'border: solid thin black; font-weight: bold;'); return $table; } @@ -682,61 +704,73 @@ class PagePermission { // Seperate acl's by "; " or whitespace // See http://opag.ca/wiki/HelpOnAccessControlLists // As used by WikiAdminSetAclSimple - function asAclLines() { - $s = ''; $line = ''; + function asAclLines() + { + $s = ''; + $line = ''; $this->sanify(); foreach ($this->perm as $access => $groups) { // unify groups for same access+bool // view:CREATOR,-OWNER, - $line = $access.':'; + $line = $access . ':'; foreach ($groups as $group => $bool) { - $line .= ($bool?'':'-').$group.","; + $line .= ($bool ? '' : '-') . $group . ","; } - if (substr($line,-1) == ',') - $s .= substr($line,0,-1)."; "; + if (substr($line, -1) == ',') + $s .= substr($line, 0, -1) . "; "; } - if (substr($s,-2) == '; ') - $s = substr($s,0,-2); + if (substr($s, -2) == '; ') + $s = substr($s, 0, -2); return $s; } // This is just a bad hack for testing. // Simplify the ACL to a unix-like "rwx------+" string // See getfacl(8) - function asRwxString($owner,$group=false) { + function asRwxString($owner, $group = false) + { global $request; // simplify object => rwxrw---x+ string as in cygwin (+ denotes additional ACLs) $perm =& $this->perm; // get effective user and group $s = '---------+'; if (isset($perm['view'][$owner]) or - (isset($perm['view'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated())) + (isset($perm['view'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()) + ) $s[0] = 'r'; if (isset($perm['edit'][$owner]) or - (isset($perm['edit'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated())) + (isset($perm['edit'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()) + ) $s[1] = 'w'; if (isset($perm['change'][$owner]) or - (isset($perm['change'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated())) + (isset($perm['change'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()) + ) $s[2] = 'x'; if (!empty($group)) { if (isset($perm['view'][$group]) or - (isset($perm['view'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated())) + (isset($perm['view'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()) + ) $s[3] = 'r'; if (isset($perm['edit'][$group]) or - (isset($perm['edit'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated())) + (isset($perm['edit'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()) + ) $s[4] = 'w'; if (isset($perm['change'][$group]) or - (isset($perm['change'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated())) + (isset($perm['change'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()) + ) $s[5] = 'x'; } if (isset($perm['view'][ACL_EVERY]) or - (isset($perm['view'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated())) + (isset($perm['view'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()) + ) $s[6] = 'r'; if (isset($perm['edit'][ACL_EVERY]) or - (isset($perm['edit'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated())) + (isset($perm['edit'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()) + ) $s[7] = 'w'; if (isset($perm['change'][ACL_EVERY]) or - (isset($perm['change'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated())) + (isset($perm['change'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()) + ) $s[8] = 'x'; return $s; } diff --git a/lib/PageType.php b/lib/PageType.php index fd97efa45..d94fbd8e6 100644 --- a/lib/PageType.php +++ b/lib/PageType.php @@ -24,7 +24,8 @@ require_once 'lib/CachedMarkup.php'; /** A cacheable formatted wiki page. */ -class TransformedText extends CacheableMarkup { +class TransformedText extends CacheableMarkup +{ /** Constructor. * * @param WikiDB_Page $page @@ -33,19 +34,21 @@ class TransformedText extends CacheableMarkup { * @param string $type_override For markup of page using a different * pagetype than that specified in its version meta-data. */ - function TransformedText($page, $text, $meta, $type_override=false) { + function TransformedText($page, $text, $meta, $type_override = false) + { $pagetype = false; if ($type_override) $pagetype = $type_override; elseif (isset($meta['pagetype'])) $pagetype = $meta['pagetype']; - $this->_type = PageType::GetPageType($pagetype); - $this->CacheableMarkup($this->_type->transform($page, $text, $meta), - $page->getName()); + $this->_type = PageType::GetPageType($pagetype); + $this->CacheableMarkup($this->_type->transform($page, $text, $meta), + $page->getName()); } - function getType() { - return $this->_type; + function getType() + { + return $this->_type; } } @@ -64,7 +67,8 @@ class TransformedText extends CacheableMarkup { * as of the cached marked-up page, it is important that the PageType classes * not have large amounts of class data. (No class data is even better.) */ -class PageType { +class PageType +{ /** * Get a page type descriptor. * @@ -73,14 +77,15 @@ class PageType { * @param string $pagetype Name of the page type. * @return PageType An object which is a subclass of PageType. */ - function GetPageType ($name=false) { + function GetPageType($name = false) + { if (!$name) $name = 'wikitext'; $class = "PageType_" . (string)$name; if (class_exists($class)) return new $class; trigger_error(sprintf("PageType '%s' unknown", (string)$name), - E_USER_WARNING); + E_USER_WARNING); return new PageType_wikitext; } @@ -89,10 +94,11 @@ class PageType { * * @return string Page type name. */ - function getName() { - if (!preg_match('/^PageType_(.+)$/i', get_class($this), $m)) - trigger_error("Bad class name for formatter(?)", E_USER_ERROR); - return $m[1]; + function getName() + { + if (!preg_match('/^PageType_(.+)$/i', get_class($this), $m)) + trigger_error("Bad class name for formatter(?)", E_USER_ERROR); + return $m[1]; } /** @@ -103,25 +109,45 @@ class PageType { * @param hash $meta Version meta-data * @return XmlContent The transformed page text. */ - function transform(&$page, &$text, $meta) { + function transform(&$page, &$text, $meta) + { $fmt_class = 'PageFormatter_' . $this->getName(); $formatter = new $fmt_class($page, $meta); return $formatter->format($text); } } -class PageType_wikitext extends PageType {} -class PageType_html extends PageType {} -class PageType_pdf extends PageType {} +class PageType_wikitext extends PageType +{ +} -class PageType_wikiblog extends PageType {} -class PageType_comment extends PageType {} -class PageType_wikiforum extends PageType {} +class PageType_html extends PageType +{ +} -class PageType_MediaWiki extends PageType {} +class PageType_pdf extends PageType +{ +} + +class PageType_wikiblog extends PageType +{ +} + +class PageType_comment extends PageType +{ +} + +class PageType_wikiforum extends PageType +{ +} + +class PageType_MediaWiki extends PageType +{ +} /* To prevent from PHP5 Fatal error: Using $this when not in object context */ -function getInterwikiMap ($pagetext=false, $force=false) { +function getInterwikiMap($pagetext = false, $force = false) +{ static $map; if (empty($map) or $force) $map = new PageType_interwikimap($pagetext); @@ -130,7 +156,8 @@ function getInterwikiMap ($pagetext=false, $force=false) { class PageType_interwikimap extends PageType { - function PageType_interwikimap($pagetext = false) { + function PageType_interwikimap($pagetext = false) + { if (!$pagetext) { $dbi = $GLOBALS['request']->getDbh(); $page = $dbi->getPage(_("InterWikiMap")); @@ -141,8 +168,7 @@ class PageType_interwikimap extends PageType } elseif ($page->exists()) { trigger_error(_("WARNING: InterWikiMap page is unlocked, so not using those links.")); $intermap = false; - } - else + } else $intermap = false; } else { $intermap = $this->_getMapFromWikiText($pagetext); @@ -154,7 +180,8 @@ class PageType_interwikimap extends PageType $this->_regexp = $this->_getRegexp(); } - function GetMap ($pagetext = false) { + function GetMap($pagetext = false) + { /*PHP5 Fatal error: Using $this when not in object context */ if (empty($this->_map)) { $map = new PageType_interwikimap($pagetext); @@ -164,27 +191,29 @@ class PageType_interwikimap extends PageType } } - function getRegexp() { + function getRegexp() + { return $this->_regexp; } - function link ($link, $linktext = false) { - global $WikiTheme; - list ($moniker, $page) = explode (":", $link, 2); + function link($link, $linktext = false) + { + global $WikiTheme; + list ($moniker, $page) = explode(":", $link, 2); if (!isset($this->_map[$moniker])) { return HTML::span(array('class' => 'bad-interwiki'), - $linktext ? $linktext : $link); + $linktext ? $linktext : $link); } $url = $this->_map[$moniker]; - // localize Upload:links for WIKIDUMP - if (!empty($WikiTheme->DUMP_MODE) and $moniker == 'Upload') { - global $request; - include_once 'lib/config.php'; - $url = getUploadFilePath(); - // calculate to a relative local path to /uploads for pdf images. - $doc_root = $request->get("DOCUMENT_ROOT"); + // localize Upload:links for WIKIDUMP + if (!empty($WikiTheme->DUMP_MODE) and $moniker == 'Upload') { + global $request; + include_once 'lib/config.php'; + $url = getUploadFilePath(); + // calculate to a relative local path to /uploads for pdf images. + $doc_root = $request->get("DOCUMENT_ROOT"); $ldir = NormalizeLocalFileName($url); $wikiroot = NormalizeLocalFileName(''); if (isWindows()) { @@ -193,11 +222,11 @@ class PageType_interwikimap extends PageType $wikiroot = strtolower($wikiroot); } if (string_starts_with($ldir, $doc_root)) { - $link_prefix = substr($url, strlen($doc_root)); + $link_prefix = substr($url, strlen($doc_root)); } elseif (string_starts_with($ldir, $wikiroot)) { - $link_prefix = NormalizeWebFileName(substr($url, strlen($wikiroot))); + $link_prefix = NormalizeWebFileName(substr($url, strlen($wikiroot))); + } } - } // Urlencode page only if it's a query arg. // FIXME: this is a somewhat broken heuristic. @@ -214,12 +243,11 @@ class PageType_interwikimap extends PageType $link = HTML::a(array('href' => $url)); - if (!$linktext) { + if (!$linktext) { $link->pushContent(PossiblyGlueIconToText('interwiki', "$moniker:"), - HTML::span(array('class' => 'wikipage'), $page)); + HTML::span(array('class' => 'wikipage'), $page)); $link->setAttr('class', 'interwiki'); - } - else { + } else { $link->pushContent(PossiblyGlueIconToText('interwiki', $linktext)); $link->setAttr('class', 'named-interwiki'); } @@ -228,9 +256,11 @@ class PageType_interwikimap extends PageType } - function _parseMap ($text) { + function _parseMap($text) + { if (!preg_match_all("/^\s*(\S+)\s+(.+)$/m", - $text, $matches, PREG_SET_ORDER)) + $text, $matches, PREG_SET_ORDER) + ) return false; foreach ($matches as $m) { @@ -256,13 +286,13 @@ class PageType_interwikimap extends PageType if (empty($map["Talk"])) { $pagename = $GLOBALS['request']->getArg('pagename'); // against PageName/Discussion/Discussion - if (string_ends_with($pagename, SUBPAGE_SEPARATOR._("Discussion"))) + if (string_ends_with($pagename, SUBPAGE_SEPARATOR . _("Discussion"))) $map["Talk"] = "%s"; else - $map["Talk"] = "%s".SUBPAGE_SEPARATOR._("Discussion"); + $map["Talk"] = "%s" . SUBPAGE_SEPARATOR . _("Discussion"); } - foreach (array('Upload','User','Talk') as $special) { + foreach (array('Upload', 'User', 'Talk') as $special) { // Expand special variables: // %u => username // %b => wikibaseurl @@ -270,47 +300,50 @@ class PageType_interwikimap extends PageType // %s is expanded later to the pagename if (strstr($map[$special], '%u')) $map[$special] = str_replace($map[$special], - '%u', - $GLOBALS['request']->_user->_userid); + '%u', + $GLOBALS['request']->_user->_userid); if (strstr($map[$special], '%b')) $map[$special] = str_replace($map[$special], - '%b', - PHPWIKI_BASE_URL); + '%b', + PHPWIKI_BASE_URL); if (strstr($map[$special], '%d')) $map[$special] = str_replace($map[$special], - '%d', - // such as 2003-01-11T14:03:02+00:00 - Iso8601DateTime()); + '%d', + // such as 2003-01-11T14:03:02+00:00 + Iso8601DateTime()); } return $map; } - function _getMapFromWikiText ($pagetext) { + function _getMapFromWikiText($pagetext) + { if (preg_match('|^<verbatim>\n(.*)^</verbatim>|ms', $pagetext, $m)) { return $m[1]; } return false; } - function _getMapFromFile ($filename) { + function _getMapFromFile($filename) + { if (defined('WARN_NONPUBLIC_INTERWIKIMAP') and WARN_NONPUBLIC_INTERWIKIMAP) { $error_html = sprintf(_("Loading InterWikiMap from external file %s."), - $filename); - trigger_error( $error_html, E_USER_NOTICE ); + $filename); + trigger_error($error_html, E_USER_NOTICE); } if (!file_exists($filename)) { $finder = new FileFinder(); $filename = $finder->findFile(INTERWIKI_MAP_FILE); } - @$fd = fopen ($filename, "rb"); - @$data = fread ($fd, filesize($filename)); - @fclose ($fd); + @$fd = fopen($filename, "rb"); + @$data = fread($fd, filesize($filename)); + @fclose($fd); return $data; } - function _getRegexp () { + function _getRegexp() + { if (!$this->_map) return '(?:(?!a)a)'; // Never matches. @@ -323,26 +356,29 @@ class PageType_interwikimap extends PageType /** How to transform text. */ -class PageFormatter { +class PageFormatter +{ /** Constructor. * * @param WikiDB_Page $page * @param hash $meta Version meta-data. */ - function PageFormatter(&$page, $meta) { + function PageFormatter(&$page, $meta) + { $this->_page = $page; - $this->_meta = $meta; - if (!empty($meta['markup'])) - $this->_markup = $meta['markup']; - else - $this->_markup = 2; // dump used old-markup as empty. + $this->_meta = $meta; + if (!empty($meta['markup'])) + $this->_markup = $meta['markup']; + else + $this->_markup = 2; // dump used old-markup as empty. // FIXME: To be able to restore old plain-backups we should keep markup 1 as default. // New policy: default = new markup (old crashes quite often) } - function _transform($text) { - include_once 'lib/BlockParser.php'; - return TransformText($text, $this->_markup); + function _transform($text) + { + include_once 'lib/BlockParser.php'; + return TransformText($text, $this->_markup); } /** Transform the page text. @@ -350,68 +386,78 @@ class PageFormatter { * @param string $text The raw page content (e.g. wiki-text). * @return XmlContent Transformed content. */ - function format($text) { + function format($text) + { trigger_error("pure virtual", E_USER_ERROR); } } class PageFormatter_wikitext extends PageFormatter { - function format($text) { + function format($text) + { return HTML::div(array('class' => 'wikitext'), - $this->_transform($text)); + $this->_transform($text)); } } class PageFormatter_interwikimap extends PageFormatter { - function format($text) { - return HTML::div(array('class' => 'wikitext'), - $this->_transform($this->_getHeader($text)), - $this->_formatMap($text), - $this->_transform($this->_getFooter($text))); + function format($text) + { + return HTML::div(array('class' => 'wikitext'), + $this->_transform($this->_getHeader($text)), + $this->_formatMap($text), + $this->_transform($this->_getFooter($text))); } - function _getHeader($text) { - return preg_replace('/<verbatim>.*/s', '', $text); + function _getHeader($text) + { + return preg_replace('/<verbatim>.*/s', '', $text); } - function _getFooter($text) { - return preg_replace('@.*?(</verbatim>|\Z)@s', '', $text, 1); + function _getFooter($text) + { + return preg_replace('@.*?(</verbatim>|\Z)@s', '', $text, 1); } - function _getMap($pagetext) { + function _getMap($pagetext) + { $map = getInterwikiMap($pagetext, 'force'); return $map->_map; } - function _formatMap($pagetext) { - $map = $this->_getMap($pagetext); - if (!$map) - return HTML::p("<No interwiki map found>"); // Shouldn't happen. + function _formatMap($pagetext) + { + $map = $this->_getMap($pagetext); + if (!$map) + return HTML::p("<No interwiki map found>"); // Shouldn't happen. $mon_attr = array('class' => 'interwiki-moniker'); $url_attr = array('class' => 'interwiki-url'); $thead = HTML::thead(HTML::tr(HTML::th($mon_attr, _("Moniker")), - HTML::th($url_attr, _("InterWiki Address")))); - foreach ($map as $moniker => $interurl) { - $rows[] = HTML::tr(HTML::td($mon_attr, new Cached_WikiLinkIfKnown($moniker)), - HTML::td($url_attr, HTML::tt($interurl))); + HTML::th($url_attr, _("InterWiki Address")))); + foreach ($map as $moniker => $interurl) { + $rows[] = HTML::tr(HTML::td($mon_attr, new Cached_WikiLinkIfKnown($moniker)), + HTML::td($url_attr, HTML::tt($interurl))); } - return HTML::table(array('class' => 'interwiki-map'), - $thead, - HTML::tbody(false, $rows)); + return HTML::table(array('class' => 'interwiki-map'), + $thead, + HTML::tbody(false, $rows)); } } -class FakePageRevision { - function FakePageRevision($meta) { +class FakePageRevision +{ + function FakePageRevision($meta) + { $this->_meta = $meta; } - function get($key) { + function get($key) + { if (empty($this->_meta[$key])) return false; return $this->_meta[$key]; @@ -424,7 +470,8 @@ class PageFormatter_attach extends PageFormatter var $type, $prefix; // Display templated contents for wikiblog, comment and wikiforum - function format($text) { + function format($text) + { if (empty($this->type)) trigger_error('PageFormatter_attach->format: $type missing'); include_once 'lib/Template.php'; @@ -434,23 +481,28 @@ class PageFormatter_attach extends PageFormatter $tokens['rev'] = new FakePageRevision($this->_meta); $name = new WikiPageName($this->_page->getName()); - $tokens[$this->prefix."_PARENT"] = $name->getParent(); + $tokens[$this->prefix . "_PARENT"] = $name->getParent(); $meta = $this->_meta[$this->type]; - foreach(array('ctime', 'creator', 'creator_id') as $key) + foreach (array('ctime', 'creator', 'creator_id') as $key) $tokens[$this->prefix . "_" . strtoupper($key)] = $meta[$key]; return new Template($this->type, $request, $tokens); } } -class PageFormatter_wikiblog extends PageFormatter_attach { +class PageFormatter_wikiblog extends PageFormatter_attach +{ var $type = 'wikiblog', $prefix = "BLOG"; } -class PageFormatter_comment extends PageFormatter_attach { + +class PageFormatter_comment extends PageFormatter_attach +{ var $type = 'comment', $prefix = "COMMENT"; } -class PageFormatter_wikiforum extends PageFormatter_attach { + +class PageFormatter_wikiforum extends PageFormatter_attach +{ var $type = 'wikiforum', $prefix = "FORUM"; } @@ -465,10 +517,13 @@ class PageFormatter_wikiforum extends PageFormatter_attach { */ class PageFormatter_html extends PageFormatter { - function _transform($text) { + function _transform($text) + { return $text; } - function format($text) { + + function format($text) + { return $text; } } @@ -479,17 +534,19 @@ class PageFormatter_html extends PageFormatter class PageFormatter_pdf extends PageFormatter { - function _transform($text) { - include_once 'lib/BlockParser.php'; - return TransformText($text, $this->_markup); + function _transform($text) + { + include_once 'lib/BlockParser.php'; + return TransformText($text, $this->_markup); } // one page or set of pages? // here we try to format only a single page - function format($text) { + function format($text) + { include_once 'lib/Template.php'; global $request; - $tokens['page'] = $this->_page; + $tokens['page'] = $this->_page; $tokens['CONTENT'] = $this->_transform($text); $pagename = $this->_page->getName(); @@ -508,11 +565,11 @@ class PageFormatter_pdf extends PageFormatter $pdf = new PDF(); $pdf->SetTitle($pagename); $pdf->SetAuthor($this->_page->get('author')); - $pdf->SetCreator(WikiURL($pagename,false,1)); + $pdf->SetCreator(WikiURL($pagename, false, 1)); $pdf->AliasNbPages(); $pdf->AddPage(); //TODO: define fonts - $pdf->SetFont('Times','',12); + $pdf->SetFont('Times', '', 12); //$pdf->SetFont('Arial','B',16); // PDF pagelayout from a special template @@ -520,7 +577,7 @@ class PageFormatter_pdf extends PageFormatter $pdf->ConvertFromHTML($template); // specify filename, destination - $pdf->Output($pagename.".pdf",'I'); // I for stdin or D for download + $pdf->Output($pagename . ".pdf", 'I'); // I for stdin or D for download // Output([string name [, string dest]]) return $pdf; @@ -529,19 +586,21 @@ class PageFormatter_pdf extends PageFormatter class PageFormatter_MediaWiki extends PageFormatter { - function _transform($text) { - include_once 'lib/BlockParser.php'; - // Expand leading tabs. - $text = expand_tabs($text); + function _transform($text) + { + include_once 'lib/BlockParser.php'; + // Expand leading tabs. + $text = expand_tabs($text); $input = new BlockParser_Input($text); $output = $this->ParsedBlock($input); - return new XmlContent($output->getContent()); + return new XmlContent($output->getContent()); } - function format($text) { - return HTML::div(array('class' => 'wikitext'), - $this->_transform($text)); + function format($text) + { + return HTML::div(array('class' => 'wikitext'), + $this->_transform($text)); } } diff --git a/lib/RSSWriter091.php b/lib/RSSWriter091.php index ce4d09e8b..da8709d26 100644 --- a/lib/RSSWriter091.php +++ b/lib/RSSWriter091.php @@ -29,9 +29,10 @@ class RSSWriter091 extends RSSWriter $this->XmlElement('rss', array('version' => "0.91")); $this->_items = array(); } - /** - * Finish construction of RSS. - */ + + /** + * Finish construction of RSS. + */ function finish() { if (isset($this->_finished)) @@ -40,11 +41,10 @@ class RSSWriter091 extends RSSWriter $channel = &$this->_channel; $items = &$this->_items; - if ($items) - { - foreach ($items as $i) - $channel->pushContent($i); - } + if ($items) { + foreach ($items as $i) + $channel->pushContent($i); + } $this->pushContent($channel); $this->__spew(); $this->_finished = true; @@ -53,15 +53,17 @@ class RSSWriter091 extends RSSWriter /** * Create a new RDF <em>typedNode</em>. */ - function __node($type, $properties, $uri = false) { - return new XmlElement($type, '', - $this->__elementize($properties)); + function __node($type, $properties, $uri = false) + { + return new XmlElement($type, '', + $this->__elementize($properties)); } /** * Write output to HTTP client. */ - function __spew() { + function __spew() + { header("Content-Type: application/xml; charset=" . RSS_ENCODING); printf("<?xml version=\"1.0\" encoding=\"%s\"?>\n", RSS_ENCODING); print("<!DOCTYPE rss PUBLIC \"-//Netscape Communications//DTD RSS 0.91//EN\"\n"); @@ -72,10 +74,10 @@ class RSSWriter091 extends RSSWriter } class _RecentChanges_RssFormatter091 -extends _RecentChanges_RSSFormatter + extends _RecentChanges_RSSFormatter // This class should probably go at then of RecentChanges.php { - function format ($changes) + function format($changes) { // include_once('lib/RssWriter.php'); $rss = new RssWriter091; @@ -89,25 +91,25 @@ extends _RecentChanges_RSSFormatter while ($rev = $changes->next()) { $rss->addItem($this->item_properties($rev), - $this->pageURI($rev)); + $this->pageURI($rev)); } global $request; $request->discardOutput(); $rss->finish(); - $request->finish(); // NORETURN!!!! + $request->finish(); // NORETURN!!!! } - function channel_properties () + function channel_properties() { global $request; $rc_url = WikiURL($request->getArg('pagename'), false, 'absurl'); return array('title' => WIKI_NAME, - 'description' => _("RecentChanges"), - 'link' => $rc_url, - 'language' => 'en-US'); + 'description' => _("RecentChanges"), + 'link' => $rc_url, + 'language' => 'en-US'); /* FIXME: language should come from $LANG (or other config variable). */ @@ -119,15 +121,15 @@ extends _RecentChanges_RSSFormatter */ } - function item_properties ($rev) + function item_properties($rev) { $page = $rev->getPage(); $pagename = $page->getName(); - return array( 'title' => SplitPagename($pagename), - 'description' => $this->summary($rev), - 'link' => $this->pageURL($rev) - ); + return array('title' => SplitPagename($pagename), + 'description' => $this->summary($rev), + 'link' => $this->pageURL($rev) + ); } } diff --git a/lib/Request.php b/lib/Request.php index 905e1cf5f..b5671bfa2 100644 --- a/lib/Request.php +++ b/lib/Request.php @@ -20,23 +20,25 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -class Request { +class Request +{ - function Request() { + function Request() + { $this->_fix_magic_quotes_gpc(); $this->_fix_multipart_form_data(); - switch($this->get('REQUEST_METHOD')) { - case 'GET': - case 'HEAD': - $this->args = &$GLOBALS['HTTP_GET_VARS']; - break; - case 'POST': - $this->args = &$GLOBALS['HTTP_POST_VARS']; - break; - default: - $this->args = array(); - break; + switch ($this->get('REQUEST_METHOD')) { + case 'GET': + case 'HEAD': + $this->args = &$GLOBALS['HTTP_GET_VARS']; + break; + case 'POST': + $this->args = &$GLOBALS['HTTP_POST_VARS']; + break; + default: + $this->args = array(); + break; } $this->session = new Request_SessionVars; @@ -49,43 +51,47 @@ class Request { $GLOBALS['request'] = $this; } - function get($key) { + function get($key) + { if (!empty($GLOBALS['HTTP_SERVER_VARS'])) $vars = &$GLOBALS['HTTP_SERVER_VARS']; elseif (!empty($GLOBALS['HTTP_ENV_VARS'])) $vars = &$GLOBALS['HTTP_ENV_VARS']; // cgi or other servers than Apache else trigger_error("Serious php configuration error!" - ." No HTTP_SERVER_VARS and HTTP_ENV_VARS vars available." - ." These should get defined in lib/prepend.php", - E_USER_WARNING); + . " No HTTP_SERVER_VARS and HTTP_ENV_VARS vars available." + . " These should get defined in lib/prepend.php", + E_USER_WARNING); if (isset($vars[$key])) return $vars[$key]; switch ($key) { - case 'REMOTE_HOST': - $addr = $vars['REMOTE_ADDR']; - if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS) - return $vars[$key] = gethostbyaddr($addr); - else - return $addr; - default: - return false; + case 'REMOTE_HOST': + $addr = $vars['REMOTE_ADDR']; + if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS) + return $vars[$key] = gethostbyaddr($addr); + else + return $addr; + default: + return false; } } - function getArg($key) { + function getArg($key) + { if (isset($this->args[$key])) return $this->args[$key]; return false; } - function getArgs () { + function getArgs() + { return $this->args; } - function setArg($key, $val) { + function setArg($key, $val) + { if ($val === false) unset($this->args[$key]); else @@ -93,7 +99,8 @@ class Request { } // Well oh well. Do we really want to pass POST params back as GET? - function getURLtoSelf($args = false, $exclude = array()) { + function getURLtoSelf($args = false, $exclude = array()) + { $get_args = $this->args; if ($args) $get_args = array_merge($get_args, $args); @@ -106,7 +113,7 @@ class Request { // Err... good point... // sortby buttons if ($this->isPost()) { - $exclude = array_merge($exclude, array('action','auth')); + $exclude = array_merge($exclude, array('action', 'auth')); //$get_args = $args; // or only the provided /* trigger_error("Request::getURLtoSelf() should probably not be from POST", @@ -126,25 +133,29 @@ class Request { return WikiURL($pagename, $get_args); } - function isPost () { + function isPost() + { return $this->get("REQUEST_METHOD") == "POST"; } - function isGetOrHead () { + function isGetOrHead() + { return in_array($this->get('REQUEST_METHOD'), - array('GET', 'HEAD')); + array('GET', 'HEAD')); } - function httpVersion() { + function httpVersion() + { if (!preg_match('@HTTP\s*/\s*(\d+.\d+)@', $this->get('SERVER_PROTOCOL'), $m)) return false; - return (float) $m[1]; + return (float)$m[1]; } /* Redirects after edit may fail if no theme signature image is defined. * Set DISABLE_HTTP_REDIRECT = true then. */ - function redirect($url, $noreturn = true) { + function redirect($url, $noreturn = true) + { $bogus = defined('DISABLE_HTTP_REDIRECT') && DISABLE_HTTP_REDIRECT; if (!$bogus) { @@ -180,8 +191,7 @@ class Request { $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url)); $tmpl->printXML(); $this->finish(); - } - elseif ($bogus) { + } elseif ($bogus) { // Safari needs window.location.href = targeturl return JavaScript(" function redirect(url) { @@ -221,7 +231,8 @@ class Request { * // After all validators have been set: * $request->checkValidators(); */ - function setValidators($validator_set) { + function setValidators($validator_set) + { if (is_array($validator_set)) $validator_set = new HTTP_ValidatorSet($validator_set); $this->_validators = $validator_set; @@ -231,7 +242,8 @@ class Request { * i.e dependencies on other pages mtimes * now it may be called in init also to simplify client code. */ - function appendValidators($validator_set) { + function appendValidators($validator_set) + { if (!isset($this->_validators)) { $this->setValidators($validator_set); return; @@ -249,7 +261,8 @@ class Request { * instead will send "304 Not Modified" or "412 Precondition * Failed" (as appropriate) back to the client. */ - function checkValidators() { + function checkValidators() + { $validators = &$this->_validators; // Set validator headers @@ -264,7 +277,7 @@ class Request { } if (CACHE_CONTROL == 'NO_CACHE') - return; // don't check conditionals... + return; // don't check conditionals... // Check conditional headers in request $status = $validators->checkConditionalRequest($this); @@ -280,15 +293,14 @@ class Request { /** Set the cache control headers in the HTTP response. */ - function cacheControl($strategy=CACHE_CONTROL, $max_age=CACHE_CONTROL_MAX_AGE) { + function cacheControl($strategy = CACHE_CONTROL, $max_age = CACHE_CONTROL_MAX_AGE) + { if ($strategy == 'NO_CACHE') { $cache_control = "no-cache"; // better set private. See Pear HTTP_Header $max_age = -20; - } - elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) { + } elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) { $cache_control = sprintf("max-age=%d", $max_age); - } - else { + } else { $cache_control = "must-revalidate"; $max_age = -20; } @@ -297,22 +309,22 @@ class Request { header("Vary: Cookie"); // FIXME: add more here? } - function setStatus($status) { + function setStatus($status) + { if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) { header($status); $status = $m[1]; - } - else { - $status = (integer) $status; + } else { + $status = (integer)$status; $reason = array('200' => 'OK', - '302' => 'Found', - '303' => 'See Other', - '304' => 'Not Modified', - '400' => 'Bad Request', - '401' => 'Unauthorized', - '403' => 'Forbidden', - '404' => 'Not Found', - '412' => 'Precondition Failed'); + '302' => 'Found', + '303' => 'See Other', + '304' => 'Not Modified', + '400' => 'Bad Request', + '401' => 'Unauthorized', + '403' => 'Forbidden', + '404' => 'Not Found', + '412' => 'Precondition Failed'); // FIXME: is it always okay to send HTTP/1.1 here, even for older clients? header(sprintf("HTTP/1.1 %d %s", $status, $reason[$status])); } @@ -321,7 +333,8 @@ class Request { $this->_log_entry->setStatus($status); } - function buffer_output($compress = true) { + function buffer_output($compress = true) + { // FIXME: disables sessions (some byte before all headers_sent()) /*if (defined('USECACHE') and !USECACHE) { $this->_is_buffering_output = false; @@ -330,8 +343,7 @@ class Request { if (defined('COMPRESS_OUTPUT')) { if (!COMPRESS_OUTPUT) $compress = false; - } - elseif (isCGI()) // necessary? + } elseif (isCGI()) // necessary? $compress = false; if ($this->getArg('start_debug')) $compress = false; @@ -343,7 +355,8 @@ class Request { // This effectively eliminates CGI, but all other servers also. hmm. if ($compress and (!function_exists('ob_gzhandler') - or !function_exists('apache_note'))) + or !function_exists('apache_note')) + ) $compress = false; // "output handler 'ob_gzhandler' cannot be used twice" @@ -355,7 +368,8 @@ class Request { // This should eliminate a lot or reported problems. if ($compress and (!$this->get("HTTP_ACCEPT_ENCODING") - or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip"))) + or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip")) + ) $compress = false; // Most RSS clients are NOT(!) application/xml gzip compatible yet. @@ -365,7 +379,8 @@ class Request { // See also http://phpwiki.sourceforge.net/phpwiki/KnownBugs if ($compress and $this->getArg('format') - and strstr($this->getArg('format'), 'rss')) + and strstr($this->getArg('format'), 'rss') + ) $compress = false; if ($compress) { @@ -383,8 +398,7 @@ class Request { */ if (function_exists('apache_note')) @apache_note('no-gzip', 1); - } - else { + } else { // Now we alway buffer output. // This is so we can set HTTP headers (e.g. for redirect) // at any point. @@ -396,7 +410,8 @@ class Request { $this->_ob_get_length = 0; } - function discardOutput() { + function discardOutput() + { if (!empty($this->_is_buffering_output)) { if (ob_get_length()) ob_clean(); $this->_is_buffering_output = false; @@ -412,21 +427,23 @@ class Request { * Note that this must not be called inside Template expansion or other * sections with ob_buffering. */ - function chunkOutput() { - if (!empty($this->_is_buffering_output) - or - (function_exists('ob_get_level') and @ob_get_level())) + function chunkOutput() { + if (!empty($this->_is_buffering_output) + or + (function_exists('ob_get_level') and @ob_get_level()) + ) { $this->_do_chunked_output = true; if (empty($this->_ob_get_length)) $this->_ob_get_length = 0; $this->_ob_get_length += ob_get_length(); - while (@ob_end_flush()); + while (@ob_end_flush()) ; @ob_end_clean(); ob_start(); } } - function finish() { + function finish() + { $this->_finishing = true; if (!empty($this->_accesslog)) { $this->_accesslog->push($this); @@ -443,7 +460,7 @@ class Request { if (!empty($this->_is_buffering_output)) { // if _is_compressing_output then ob_get_length() returns // the uncompressed length, not the gzip'ed as required. - if (!headers_sent() and !$this->_is_compressing_output) { + if (!headers_sent() and !$this->_is_compressing_output) { // php url-rewriting miscalculates the ob length. fixes bug #1376007 if (ini_get('use_trans_sid') == 'off') { if (empty($this->_do_chunked_output)) { @@ -454,7 +471,7 @@ class Request { } $this->_is_buffering_output = false; ob_end_flush(); - } elseif (function_exists('ob_get_level') and @ob_get_level()) { + } elseif (function_exists('ob_get_level') and @ob_get_level()) { ob_end_flush(); } session_write_close(); @@ -466,10 +483,13 @@ class Request { exit; } - function getSessionVar($key) { + function getSessionVar($key) + { return $this->session->get($key); } - function setSessionVar($key, $val) { + + function setSessionVar($key, $val) + { if ($key == 'wiki_user') { if (empty($val->page)) $val->page = $this->getArg('pagename'); @@ -493,31 +513,40 @@ class Request { } return $this->session->set($key, $val); } - function deleteSessionVar($key) { + + function deleteSessionVar($key) + { return $this->session->delete($key); } - function getCookieVar($key) { + function getCookieVar($key) + { return $this->cookies->get($key); } - function setCookieVar($key, $val, $lifetime_in_days = false, $path = false) { + + function setCookieVar($key, $val, $lifetime_in_days = false, $path = false) + { return $this->cookies->set($key, $val, $lifetime_in_days, $path); } - function deleteCookieVar($key) { + + function deleteCookieVar($key) + { return $this->cookies->delete($key); } - function getUploadedFile($key) { + function getUploadedFile($key) + { return Request_UploadedFile::getUploadedFile($key); } - function _fix_magic_quotes_gpc() { + function _fix_magic_quotes_gpc() + { $needs_fix = array('HTTP_POST_VARS', - 'HTTP_GET_VARS', - 'HTTP_COOKIE_VARS', - 'HTTP_SERVER_VARS', - 'HTTP_POST_FILES'); + 'HTTP_GET_VARS', + 'HTTP_COOKIE_VARS', + 'HTTP_SERVER_VARS', + 'HTTP_POST_FILES'); // Fix magic quotes. if (get_magic_quotes_gpc()) { @@ -526,32 +555,35 @@ class Request { } } - function _stripslashes(&$var) { + function _stripslashes(&$var) + { if (is_array($var)) { foreach ($var as $key => $val) $this->_stripslashes($var[$key]); - } - elseif (is_string($var)) + } elseif (is_string($var)) $var = stripslashes($var); } - function _fix_multipart_form_data () { + function _fix_multipart_form_data() + { if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE'))) $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']); } - function _strip_leading_nl(&$var) { + function _strip_leading_nl(&$var) + { if (is_array($var)) { foreach ($var as $key => $val) $this->_strip_leading_nl($var[$key]); - } - elseif (is_string($var)) + } elseif (is_string($var)) $var = preg_replace('|^\r?\n?|', '', $var); } } -class Request_SessionVars { - function Request_SessionVars() { +class Request_SessionVars +{ + function Request_SessionVars() + { // Prevent cacheing problems with IE 5 session_cache_limiter('none'); @@ -561,7 +593,8 @@ class Request_SessionVars { session_start(); } - function get($key) { + function get($key) + { $vars = &$GLOBALS['HTTP_SESSION_VARS']; if (isset($vars[$key])) return $vars[$key]; @@ -570,7 +603,8 @@ class Request_SessionVars { return false; } - function set($key, $val) { + function set($key, $val) + { $vars = &$GLOBALS['HTTP_SESSION_VARS']; if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) { // This is funky but necessary, at least in some PHP's @@ -579,11 +613,12 @@ class Request_SessionVars { $vars[$key] = $val; if (isset($_SESSION)) // php-5.2 $_SESSION[$key] = $val; - if (!check_php_version(5,3)) + if (!check_php_version(5, 3)) session_register($key); } - function delete($key) { + function delete($key) + { $vars = &$GLOBALS['HTTP_SESSION_VARS']; if (!function_usable('ini_get') or ini_get('register_globals')) unset($GLOBALS[$key]); @@ -591,21 +626,23 @@ class Request_SessionVars { unset($vars[$key]); if (isset($_SESSION)) // php-5.2 unset($_SESSION[$key]); - if (!check_php_version(5,3)) + if (!check_php_version(5, 3)) session_unregister($key); } } -class Request_CookieVars { +class Request_CookieVars +{ - function get($key) { + function get($key) + { $vars = &$GLOBALS['HTTP_COOKIE_VARS']; if (isset($vars[$key])) { @$decode = base64_decode($vars[$key]); - if (strlen($decode) > 3 and substr($decode,1,1) == ':') { - @$val = unserialize($decode); - if (!empty($val)) - return $val; + if (strlen($decode) > 3 and substr($decode, 1, 1) == ':') { + @$val = unserialize($decode); + if (!empty($val)) + return $val; } @$val = urldecode($vars[$key]); if (!empty($val)) @@ -614,14 +651,15 @@ class Request_CookieVars { return false; } - function get_old($key) { + function get_old($key) + { $vars = &$GLOBALS['HTTP_COOKIE_VARS']; if (isset($vars[$key])) { @$decode = base64_decode($vars[$key]); - if (strlen($decode) > 3 and substr($decode,1,1) == ':') { - @$val = unserialize($decode); - if (!empty($val)) - return $val; + if (strlen($decode) > 3 and substr($decode, 1, 1) == ':') { + @$val = unserialize($decode); + if (!empty($val)) + return $val; } @$val = unserialize($vars[$key]); if (!empty($val)) @@ -633,7 +671,8 @@ class Request_CookieVars { return false; } - function set($key, $val, $persist_days = false, $path = false) { + function set($key, $val, $persist_days = false, $path = false) + { // if already defined, ignore if (defined('MAIN_setUser') and $key = getCookieName()) return; if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return; @@ -641,8 +680,7 @@ class Request_CookieVars { $vars = &$GLOBALS['HTTP_COOKIE_VARS']; if (is_numeric($persist_days)) { $expires = time() + (24 * 3600) * $persist_days; - } - else { + } else { $expires = 0; } if (is_array($val) or is_object($val)) @@ -657,7 +695,8 @@ class Request_CookieVars { @setcookie($key, $packedval, $expires); } - function delete($key) { + function delete($key) + { static $deleted = array(); if (isset($deleted[$key])) return; if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return; @@ -680,8 +719,10 @@ class Request_CookieVars { and with ending slash! Otherwise "\\" => "" and the uploaded file will not be found. */ -class Request_UploadedFile { - function getUploadedFile($postname) { +class Request_UploadedFile +{ + function getUploadedFile($postname) + { global $HTTP_POST_FILES; // Against php5 with !ini_get('register-long-arrays'). See Bug #1180115 @@ -693,23 +734,23 @@ class Request_UploadedFile { $fileinfo =& $HTTP_POST_FILES[$postname]; if ($fileinfo['error']) { // See https://sourceforge.net/forum/message.php?msg_id=3093651 - $err = (int) $fileinfo['error']; + $err = (int)$fileinfo['error']; // errmsgs by Shilad Sen switch ($err) { - case 1: - trigger_error(_("Upload error: file too big"), E_USER_WARNING); - break; - case 2: - trigger_error(_("Upload error: file too big"), E_USER_WARNING); - break; - case 3: - trigger_error(_("Upload error: file only partially received"), E_USER_WARNING); - break; - case 4: - trigger_error(_("Upload error: no file selected"), E_USER_WARNING); - break; - default: - trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING); + case 1: + trigger_error(_("Upload error: file too big"), E_USER_WARNING); + break; + case 2: + trigger_error(_("Upload error: file too big"), E_USER_WARNING); + break; + case 3: + trigger_error(_("Upload error: file only partially received"), E_USER_WARNING); + break; + case 4: + trigger_error(_("Upload error: no file selected"), E_USER_WARNING); + break; + default: + trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING); } return false; } @@ -724,12 +765,12 @@ class Request_UploadedFile { $tmp_file .= '/' . basename($fileinfo['tmp_name']); /* ending slash in php.ini upload_tmp_dir is required. */ if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) { - trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.",$tmp_file, $fileinfo['tmp_name']). - "\n". - "Probably illegal TEMP environment or upload_tmp_dir setting. ". - "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and ". - "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.", - E_USER_ERROR); + trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.", $tmp_file, $fileinfo['tmp_name']) . + "\n" . + "Probably illegal TEMP environment or upload_tmp_dir setting. " . + "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and " . + "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.", + E_USER_ERROR); return false; } else { /* @@ -741,36 +782,42 @@ class Request_UploadedFile { ; } } else { - trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name'])."\n". - " Probably illegal TEMP environment or upload_tmp_dir setting.", - E_USER_WARNING); + trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name']) . "\n" . + " Probably illegal TEMP environment or upload_tmp_dir setting.", + E_USER_WARNING); } } return new Request_UploadedFile($fileinfo); } - function Request_UploadedFile($fileinfo) { + function Request_UploadedFile($fileinfo) + { $this->_info = $fileinfo; } - function getSize() { + function getSize() + { return $this->_info['size']; } - function getName() { + function getName() + { return $this->_info['name']; } - function getType() { + function getType() + { return $this->_info['type']; } - function getTmpName() { + function getTmpName() + { return $this->_info['tmp_name']; } - function open() { - if ( ($fd = fopen($this->_info['tmp_name'], "rb")) ) { + function open() + { + if (($fd = fopen($this->_info['tmp_name'], "rb"))) { if ($this->getSize() < filesize($this->_info['tmp_name'])) { // FIXME: Some PHP's (or is it some browsers?) put // HTTP/MIME headers in the file body, some don't. @@ -781,11 +828,10 @@ class Request_UploadedFile { // This code is more-or-less untested currently. // // Dump HTTP headers. - while ( ($header = fgets($fd, 4096)) ) { + while (($header = fgets($fd, 4096))) { if (trim($header) == '') { break; - } - else if (!preg_match('/^content-(length|type):/i', $header)) { + } else if (!preg_match('/^content-(length|type):/i', $header)) { rewind($fd); break; } @@ -795,7 +841,8 @@ class Request_UploadedFile { return $fd; } - function getContents() { + function getContents() + { $fd = $this->open(); $data = fread($fd, $this->getSize()); fclose($fd); @@ -808,22 +855,24 @@ class Request_UploadedFile { * Also needed for advanced spam prevention. * global object holding global state (sql or file, entries, to dump) */ -class Request_AccessLog { +class Request_AccessLog +{ /** * @param $logfile string Log file name. */ - function Request_AccessLog ($logfile, $do_sql = false) { + function Request_AccessLog($logfile, $do_sql = false) + { //global $request; // request not yet initialized! $this->logfile = $logfile; if ($logfile and !is_writeable($logfile)) { trigger_error - (sprintf(_("%s is not writable."), _("The PhpWiki access log file")) - . "\n" - . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."), - sprintf(_("the file '%s'"), ACCESS_LOG), - 'ACCESS_LOG') - , E_USER_NOTICE); + (sprintf(_("%s is not writable."), _("The PhpWiki access log file")) + . "\n" + . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."), + sprintf(_("the file '%s'"), ACCESS_LOG), + 'ACCESS_LOG') + , E_USER_NOTICE); } //$request->_accesslog =& $this; //if (empty($request->_accesslog->entries)) @@ -831,66 +880,85 @@ class Request_AccessLog { if ($do_sql) { global $DBParams; - if (!in_array($DBParams['dbtype'], array('SQL','ADODB'))) { + if (!in_array($DBParams['dbtype'], array('SQL', 'ADODB'))) { trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB"); } else { //$this->_dbi =& $request->_dbi; - $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '')."accesslog"; + $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog"; } } $this->entries = array(); $this->entries[] = new Request_AccessLogEntry($this); } - function _do($cmd, &$arg) { + function _do($cmd, &$arg) + { if ($this->entries) - for ($i=0; $i < count($this->entries);$i++) + for ($i = 0; $i < count($this->entries); $i++) $this->entries[$i]->$cmd($arg); } - function push(&$request) { $this->_do('push',$request); } - function setSize($arg) { $this->_do('setSize',$arg); } - function setStatus($arg) { $this->_do('setStatus',$arg); } - function setDuration($arg) { $this->_do('setDuration',$arg); } + + function push(&$request) + { + $this->_do('push', $request); + } + + function setSize($arg) + { + $this->_do('setSize', $arg); + } + + function setStatus($arg) + { + $this->_do('setStatus', $arg); + } + + function setDuration($arg) + { + $this->_do('setDuration', $arg); + } /** * Read sequentially all previous entries from the beginning. * while ($logentry = Request_AccessLogEntry::read()) ; * For internal log analyzers: RecentReferrers, WikiAccessRestrictions */ - function read() { + function read() + { return $this->logtable ? $this->read_sql() : $this->read_file(); } /** * Return iterator of referer items reverse sorted (latest first). */ - function get_referer($limit=15, $external_only=false) { + function get_referer($limit = 15, $external_only = false) + { if ($external_only) { // see stdlin.php:isExternalReferrer() $base = SERVER_URL; $blen = strlen($base); } if (!empty($this->_dbi)) { // check same hosts in referer and request and remove them - $ext_where = " AND LEFT(referer,$blen) <> ".$this->_dbi->quote($base) - ." AND LEFT(referer,$blen) <> LEFT(CONCAT(".$this->_dbi->quote(SERVER_URL).",request_uri),$blen)"; + $ext_where = " AND LEFT(referer,$blen) <> " . $this->_dbi->quote($base) + . " AND LEFT(referer,$blen) <> LEFT(CONCAT(" . $this->_dbi->quote(SERVER_URL) . ",request_uri),$blen)"; return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))" - .($external_only ? $ext_where : '') - ." ORDER BY time_stamp DESC" - .($limit ? " LIMIT $limit" : "")); + . ($external_only ? $ext_where : '') + . " ORDER BY time_stamp DESC" + . ($limit ? " LIMIT $limit" : "")); } else { $iter = new WikiDB_Array_generic_iter(0); $logs =& $iter->_array; while ($logentry = $this->read_file()) { if (!empty($logentry->referer) - and (!$external_only or (substr($logentry->referer,0,$blen) != $base))) - { + and (!$external_only or (substr($logentry->referer, 0, $blen) != $base)) + ) { $iter->_array[] = $logentry; if ($limit and count($logs) > $limit) array_shift($logs); } } $logs = array_reverse($logs); - $logs = array_slice($logs,0,min($limit,count($logs))); + $logs = array_slice($logs, 0, min($limit, count($logs))); return $iter; } } @@ -898,11 +966,12 @@ class Request_AccessLog { /** * Return iterator of matching host items reverse sorted (latest first). */ - function get_host($host, $since_minutes=20) { + function get_host($host, $since_minutes = 20) + { if ($this->logtable) { // mysql specific only: - return $this->read_sql("request_host=".$this->_dbi->quote($host)." AND time_stamp > ". (time()-$since_minutes*60) - ." ORDER BY time_stamp DESC"); + return $this->read_sql("request_host=" . $this->_dbi->quote($host) . " AND time_stamp > " . (time() - $since_minutes * 60) + . " ORDER BY time_stamp DESC"); } else { $iter = new WikiDB_Array_generic_iter(); $logs =& $iter->_array; @@ -916,7 +985,7 @@ class Request_AccessLog { } } $logs = array_reverse($logs); - $logs = array_slice($logs,0,min($limit,count($logs))); + $logs = array_slice($logs, 0, min($limit, count($logs))); return $iter; } } @@ -924,18 +993,19 @@ class Request_AccessLog { /** * Read sequentially all previous entries from log file. */ - function read_file() { + function read_file() + { global $request; if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read - if (empty($this->reader)) // start at the beginning + if (empty($this->reader)) // start at the beginning $this->reader = fopen($this->logfile, "r"); if ($s = fgets($this->reader)) { $entry = new Request_AccessLogEntry($this); - if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/',$s,$m)) { - list(,$entry->host, $entry->ident, $entry->user, $entry->time, - $entry->request, $entry->status, $entry->size, - $entry->referer, $entry->user_agent) = $m; + if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/', $s, $m)) { + list(, $entry->host, $entry->ident, $entry->user, $entry->time, + $entry->request, $entry->status, $entry->size, + $entry->referer, $entry->user_agent) = $m; } return $entry; } else { // until the end @@ -943,38 +1013,47 @@ class Request_AccessLog { return false; } } - function _read_sql_query($where='') { + + function _read_sql_query($where = '') + { $dbh =& $GLOBALS['request']->_dbi; $log_tbl =& $this->logtable; return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user," - ."remote_host as host,agent as user_agent" - ." FROM $log_tbl" - . ($where ? " WHERE $where" : "")); + . "remote_host as host,agent as user_agent" + . " FROM $log_tbl" + . ($where ? " WHERE $where" : "")); } - function read_sql($where='') { + + function read_sql($where = '') + { if (empty($this->sqliter)) $this->sqliter = $this->_read_sql_query($where); return $this->sqliter->next(); } /* done in request->finish() before the db is closed */ - function write_sql() { + function write_sql() + { $dbh =& $GLOBALS['request']->_dbi; if (isset($this->entries) and $dbh and $dbh->isOpen()) foreach ($this->entries as $entry) { $entry->write_sql(); } } + /* done in the shutdown callback */ - function write_file() { + function write_file() + { if (isset($this->entries) and $this->logfile) foreach ($this->entries as $entry) { $entry->write_file(); } unset($this->entries); } + /* in an ideal world... */ - function write() { + function write() + { if ($this->logfile) $this->write_file(); if ($this->logtable) $this->write_sql(); unset($this->entries); @@ -1002,19 +1081,21 @@ class Request_AccessLogEntry * * */ - function Request_AccessLogEntry (&$accesslog) { + function Request_AccessLogEntry(&$accesslog) + { $this->_accesslog = $accesslog; $this->logfile = $accesslog->logfile; $this->time = time(); - $this->status = 200; // see setStatus() - $this->size = 0; // see setSize() + $this->status = 200; // see setStatus() + $this->size = 0; // see setSize() } /** * @param $request object Request object for current request. */ - function push(&$request) { - $this->host = $request->get('REMOTE_HOST'); + function push(&$request) + { + $this->host = $request->get('REMOTE_HOST'); $this->ident = $request->get('REMOTE_IDENT'); if (!$this->ident) $this->ident = '-'; @@ -1024,10 +1105,10 @@ class Request_AccessLogEntry else $this->user = '-'; $this->request = join(' ', array($request->get('REQUEST_METHOD'), - $request->get('REQUEST_URI'), - $request->get('SERVER_PROTOCOL'))); - $this->referer = (string) $request->get('HTTP_REFERER'); - $this->user_agent = (string) $request->get('HTTP_USER_AGENT'); + $request->get('REQUEST_URI'), + $request->get('SERVER_PROTOCOL'))); + $this->referer = (string)$request->get('HTTP_REFERER'); + $this->user_agent = (string)$request->get('HTTP_USER_AGENT'); } /** @@ -1035,7 +1116,8 @@ class Request_AccessLogEntry * * @param $status integer HTTP status code. */ - function setStatus ($status) { + function setStatus($status) + { $this->status = $status; } @@ -1044,13 +1126,16 @@ class Request_AccessLogEntry * * @param $size integer */ - function setSize ($size=0) { + function setSize($size = 0) + { $this->size = (int)$size; } - function setDuration ($seconds) { + + function setDuration($seconds) + { // Pear DB does not correctly quote , in floats using ?. e.g. in european locales. // Workaround: - $this->duration = strtr(sprintf("%f", $seconds),",","."); + $this->duration = strtr(sprintf("%f", $seconds), ",", "."); } /** @@ -1061,7 +1146,8 @@ class Request_AccessLogEntry * @param $time integer Unix timestamp (defaults to current time). * @return string Zone offset, e.g. "-0800" for PST. */ - function _zone_offset ($time = false) { + function _zone_offset($time = false) + { if (!$time) $time = time(); $offset = date("Z", $time); @@ -1071,7 +1157,7 @@ class Request_AccessLogEntry $offset = -$offset; } $offhours = floor($offset / 3600); - $offmins = $offset / 60 - $offhours * 60; + $offmins = $offset / 60 - $offhours * 60; return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins); } @@ -1083,14 +1169,16 @@ class Request_AccessLogEntry * @param $time integer Unix timestamp (defaults to current time). * @return string Formatted date & time. */ - function _ncsa_time($time = false) { + function _ncsa_time($time = false) + { if (!$time) $time = time(); return date("d/M/Y:H:i:s", $time) . " " . $this->_zone_offset(); } - function write() { + function write() + { if ($this->_accesslog->logfile) $this->write_file(); if ($this->_accesslog->logtable) $this->write_sql(); } @@ -1098,12 +1186,13 @@ class Request_AccessLogEntry /** * Write entry to log file. */ - function write_file() { + function write_file() + { $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"', - $this->host, $this->ident, $this->user, - $this->_ncsa_time($this->time), - $this->request, $this->status, $this->size, - $this->referer, $this->user_agent); + $this->host, $this->ident, $this->user, + $this->_ncsa_time($this->time), + $this->request, $this->status, $this->size, + $this->referer, $this->user_agent); if (!empty($this->_accesslog->reader)) { fclose($this->_accesslog->reader); unset($this->_accesslog->reader); @@ -1120,7 +1209,8 @@ class Request_AccessLogEntry /* This is better been done by apache mod_log_sql */ /* If ACCESS_LOG_SQL & 2 we do write it by our own */ - function write_sql() { + function write_sql() + { global $request; $dbh =& $request->_dbi; @@ -1130,13 +1220,13 @@ class Request_AccessLogEntry // strangely HTTP_POST_VARS doesn't contain all posted vars. $args = $_POST; // copy not ref. clone not needed on hashes // garble passwords - if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>'; + if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>'; if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>'; - if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>'; - if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>'; - $this->request_args = substr(serialize($args),0,254); // if VARCHAR(255) is used. + if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>'; + if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>'; + $this->request_args = substr(serialize($args), 0, 254); // if VARCHAR(255) is used. } else { - $this->request_args = $request->get('QUERY_STRING'); + $this->request_args = $request->get('QUERY_STRING'); } $this->request_method = $request->get('REQUEST_METHOD'); $this->request_uri = $request->get('REQUEST_URI'); @@ -1152,7 +1242,8 @@ class Request_AccessLogEntry * @access private * @see Request_AccessLogEntry */ -function Request_AccessLogEntry_shutdown_function () { +function Request_AccessLogEntry_shutdown_function() +{ global $request; if (isset($request->_accesslog->entries) and $request->_accesslog->logfile) @@ -1163,8 +1254,10 @@ function Request_AccessLogEntry_shutdown_function () { } -class HTTP_ETag { - function HTTP_ETag($val, $is_weak=false) { +class HTTP_ETag +{ + function HTTP_ETag($val, $is_weak = false) + { $this->_val = wikihash($val); $this->_weak = $is_weak; } @@ -1174,7 +1267,8 @@ class HTTP_ETag { * Strong comparison: If either (or both) tag is weak, they * are not equal. */ - function equals($that, $strong_match=false) { + function equals($that, $strong_match = false) + { if ($this->_val != $that->_val) return false; if ($strong_match and ($this->_weak or $that->_weak)) @@ -1183,7 +1277,8 @@ class HTTP_ETag { } - function asString() { + function asString() + { $quoted = '"' . addslashes($this->_val) . '"'; return $this->_weak ? "W/$quoted" : $quoted; } @@ -1192,25 +1287,27 @@ class HTTP_ETag { * * This is a static member function. */ - function parse($strval) { + function parse($strval) + { if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m)) - return false; // parse failed - list(,$weak,$str) = $m; + return false; // parse failed + list(, $weak, $str) = $m; return new HTTP_ETag(stripslashes($str), $weak); } - function matches($taglist, $strong_match=false) { + function matches($taglist, $strong_match = false) + { $taglist = trim($taglist); if ($taglist == '*') { if ($strong_match) - return ! $this->_weak; + return !$this->_weak; else return true; } while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i', - $taglist, $m)) { + $taglist, $m)) { list($match, $weak, $str) = $m; $taglist = substr($taglist, strlen($match)); $tag = new HTTP_ETag(stripslashes($str), $weak); @@ -1224,31 +1321,32 @@ class HTTP_ETag { // Possible results from the HTTP_ValidatorSet::_check*() methods. // (Higher numerical values take precedence.) -define ('_HTTP_VAL_PASS', 0); // Test is irrelevant -define ('_HTTP_VAL_NOT_MODIFIED', 1); // Test passed, content not changed -define ('_HTTP_VAL_MODIFIED', 2); // Test failed, content changed -define ('_HTTP_VAL_FAILED', 3); // Precondition failed. +define ('_HTTP_VAL_PASS', 0); // Test is irrelevant +define ('_HTTP_VAL_NOT_MODIFIED', 1); // Test passed, content not changed +define ('_HTTP_VAL_MODIFIED', 2); // Test failed, content changed +define ('_HTTP_VAL_FAILED', 3); // Precondition failed. -class HTTP_ValidatorSet { - function HTTP_ValidatorSet($validators) { +class HTTP_ValidatorSet +{ + function HTTP_ValidatorSet($validators) + { $this->_mtime = $this->_weak = false; $this->_tag = array(); foreach ($validators as $key => $val) { if ($key == '%mtime') { $this->_mtime = $val; - } - elseif ($key == '%weak') { + } elseif ($key == '%weak') { if ($val) $this->_weak = true; - } - else { + } else { $this->_tag[$key] = $val; } } } - function append($that) { + function append($that) + { if (is_array($that)) $that = new HTTP_ValidatorSet($that); @@ -1266,34 +1364,38 @@ class HTTP_ValidatorSet { $this->_tag = $that->_tag; } - function getETag() { - if (! $this->_tag) + function getETag() + { + if (!$this->_tag) return false; return new HTTP_ETag($this->_tag, $this->_weak); } - function getModificationTime() { + function getModificationTime() + { return $this->_mtime; } - function checkConditionalRequest (&$request) { + function checkConditionalRequest(&$request) + { $result = max($this->_checkIfUnmodifiedSince($request), - $this->_checkIfModifiedSince($request), - $this->_checkIfMatch($request), - $this->_checkIfNoneMatch($request)); + $this->_checkIfModifiedSince($request), + $this->_checkIfMatch($request), + $this->_checkIfNoneMatch($request)); if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED) - return false; // "please proceed with normal processing" + return false; // "please proceed with normal processing" elseif ($result == _HTTP_VAL_FAILED) - return 412; // "412 Precondition Failed" + return 412; // "412 Precondition Failed" elseif ($result == _HTTP_VAL_NOT_MODIFIED) - return 304; // "304 Not Modified" + return 304; // "304 Not Modified" trigger_error("Ack, shouldn't get here", E_USER_ERROR); return false; } - function _checkIfUnmodifiedSince(&$request) { + function _checkIfUnmodifiedSince(&$request) + { if ($this->_mtime !== false) { $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE")); if ($since !== false && $this->_mtime > $since) @@ -1302,7 +1404,8 @@ class HTTP_ValidatorSet { return _HTTP_VAL_PASS; } - function _checkIfModifiedSince(&$request) { + function _checkIfModifiedSince(&$request) + { if ($this->_mtime !== false and $request->isGetOrHead()) { $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE")); if ($since !== false) { @@ -1314,7 +1417,8 @@ class HTTP_ValidatorSet { return _HTTP_VAL_PASS; } - function _checkIfMatch(&$request) { + function _checkIfMatch(&$request) + { if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) { $tag = $this->getETag(); if (!$tag->matches($taglist, 'strong')) @@ -1323,10 +1427,11 @@ class HTTP_ValidatorSet { return _HTTP_VAL_PASS; } - function _checkIfNoneMatch(&$request) { + function _checkIfNoneMatch(&$request) + { if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) { $tag = $this->getETag(); - $strong_compare = ! $request->isGetOrHead(); + $strong_compare = !$request->isGetOrHead(); if ($taglist) { if ($tag->matches($taglist, $strong_compare)) { if ($request->isGetOrHead()) diff --git a/lib/RssParser.php b/lib/RssParser.php index d1051ca9a..37f47bf8c 100644 --- a/lib/RssParser.php +++ b/lib/RssParser.php @@ -42,22 +42,24 @@ require_once 'lib/XmlParser.php'; class RSSParser -extends XmlParser { + extends XmlParser +{ var $title = ""; var $author = ""; var $pubDate = ""; - var $link = ""; + var $link = ""; var $description = ""; var $inside_item = false; var $list_items = false; - var $item = array(); + var $item = array(); var $items; var $channel; var $divers = ""; var $date = ""; - function tag_open($parser, $name, $attrs=''){ + function tag_open($parser, $name, $attrs = '') + { global $current_tag, $current_attrs; $current_tag = $name; @@ -65,12 +67,12 @@ extends XmlParser { if ($name == "ITEM") $this->inside_item = true; elseif ($name == "ITEMS") - $this->list_items = true; - elseif ($name == "IMAGE") + $this->list_items = true; elseif ($name == "IMAGE") $this->inside_item = true; } - function tag_close($parser, $tagName, $attrs=''){ + function tag_close($parser, $tagName, $attrs = '') + { global $current_tag; if ($tagName == "ITEM") { @@ -82,42 +84,43 @@ extends XmlParser { $this->items = array(); $GLOBALS['rss_parser_items'] =& $this->items; } - $this->items[] = array("title" => $this->item['TITLE'], - "author" => $this->item['AUTHOR'], - "pubDate" => $this->item['PUBDATE'], - "description" => @$this->item['DESCRIPTION'], - "link" => $this->item['LINK']); - $this->item = array("TITLE" => "", - "DESCRIPTION" => "", - "LINK" => ""); + $this->items[] = array("title" => $this->item['TITLE'], + "author" => $this->item['AUTHOR'], + "pubDate" => $this->item['PUBDATE'], + "description" => @$this->item['DESCRIPTION'], + "link" => $this->item['LINK']); + $this->item = array("TITLE" => "", + "DESCRIPTION" => "", + "LINK" => ""); $this->inside_item = false; } elseif ($tagName == "IMAGE") { - $this->item = array("TITLE" => "", - "DESCRIPTION" => "", - "LINK" => ""); + $this->item = array("TITLE" => "", + "DESCRIPTION" => "", + "LINK" => ""); $this->inside_item = false; } elseif ($tagName == "CHANNEL") { $this->channel = array("title" => $this->title, - "description" => $this->description, - "link" => $this->link, - "date" => $this->date, - "divers" => $this->divers); + "description" => $this->description, + "link" => $this->link, + "date" => $this->date, + "divers" => $this->divers); $GLOBALS['rss_parser_channel'] =& $this->channel; - $this->title = ""; + $this->title = ""; $this->description = ""; - $this->link = ""; - $this->divers = ""; - $this->date = ""; + $this->link = ""; + $this->divers = ""; + $this->date = ""; } elseif ($tagName == "ITEMS") { $GLOBALS['rss_parser_items'] =& $this->items; - $this->item = array("TITLE" => "", - "DESCRIPTION" => "", - "LINK" => ""); + $this->item = array("TITLE" => "", + "DESCRIPTION" => "", + "LINK" => ""); $this->list_items = false; } } - function cdata($parser, $data){ + function cdata($parser, $data) + { global $current_tag, $current_attrs; if ($this->inside_item) { @@ -132,45 +135,46 @@ extends XmlParser { } elseif ($this->list_items) { if ($current_tag == 'RDF:LI') { // FIXME: avoid duplicates. cdata called back 4x per RDF:LI - if ($this->items[count($this->items)-1]['link'] != @$current_attrs['RDF:RESOURCE']) + if ($this->items[count($this->items) - 1]['link'] != @$current_attrs['RDF:RESOURCE']) $this->items[] = array('link' => @$current_attrs['RDF:RESOURCE'], - 'title' => ''); + 'title' => ''); } } else { switch ($current_tag) { - case "TITLE": - if (trim($data)) - $this->title .= " " . trim($data); - break; - case "DESCRIPTION": - if (trim($data)) - $this->description .= trim($data); - break; - case "LINK": - if (trim($data)) - $this->link = trim($data); - break; - case "DC:DATE": - if (trim($data)) - $this->date .= " " . trim($data); - default: - if (trim($data)) - $this->divers .= " " . $current_tag."/".$data; - break; + case "TITLE": + if (trim($data)) + $this->title .= " " . trim($data); + break; + case "DESCRIPTION": + if (trim($data)) + $this->description .= trim($data); + break; + case "LINK": + if (trim($data)) + $this->link = trim($data); + break; + case "DC:DATE": + if (trim($data)) + $this->date .= " " . trim($data); + default: + if (trim($data)) + $this->divers .= " " . $current_tag . "/" . $data; + break; } } } - function parse($content, $is_final = true) { + function parse($content, $is_final = true) + { xml_parse($this->_parser, $content, $is_final) or trigger_error(sprintf("XML error: %s at line %d", - xml_error_string(xml_get_error_code($this->_parser)), - xml_get_current_line_number($this->_parser)), - E_USER_WARNING); + xml_error_string(xml_get_error_code($this->_parser)), + xml_get_current_line_number($this->_parser)), + E_USER_WARNING); //OO workaround: parser object looses its params. we have to store them in globals if ($is_final) { if (empty($this->items)) { - $this->items = @$GLOBALS['rss_parser_items']; + $this->items = @$GLOBALS['rss_parser_items']; $this->channel = @$GLOBALS['rss_parser_channel']; } unset($GLOBALS['rss_parser_items']); diff --git a/lib/RssWriter.php b/lib/RssWriter.php index 7da264bc0..58aa1c615 100644 --- a/lib/RssWriter.php +++ b/lib/RssWriter.php @@ -5,7 +5,7 @@ // Encoding for RSS output. if (!defined('RSS_ENCODING')) - define('RSS_ENCODING', $GLOBALS['charset']); + define('RSS_ENCODING', $GLOBALS['charset']); /** * A class for writing RSS 1.0. @@ -15,42 +15,45 @@ if (!defined('RSS_ENCODING')) */ class RssWriter extends XmlElement { - function RssWriter () { + function RssWriter() + { $this->XmlElement('rdf:RDF', - array('xmlns' => "http://purl.org/rss/1.0/", - 'xmlns:rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')); + array('xmlns' => "http://purl.org/rss/1.0/", + 'xmlns:rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')); - $this->_modules = array( + $this->_modules = array( //Standards - 'content' => "http://purl.org/rss/1.0/modules/content/", - 'dc' => "http://purl.org/dc/elements/1.1/", - 'sy' => "http://purl.org/rss/1.0/modules/syndication/", + 'content' => "http://purl.org/rss/1.0/modules/content/", + 'dc' => "http://purl.org/dc/elements/1.1/", + 'sy' => "http://purl.org/rss/1.0/modules/syndication/", //Proposed - 'wiki' => "http://purl.org/rss/1.0/modules/wiki/", - 'ag' => "http://purl.org/rss/1.0/modules/aggregation/", - 'annotate' => "http://purl.org/rss/1.0/modules/annotate/", - 'audio' => "http://media.tangent.org/rss/1.0/", - 'cp' => "http://my.theinfo.org/changed/1.0/rss/", - 'rss091' => "http://purl.org/rss/1.0/modules/rss091/", - 'slash' => "http://purl.org/rss/1.0/modules/slash/", - 'taxo' => "http://purl.org/rss/1.0/modules/taxonomy/", - 'thr' => "http://purl.org/rss/1.0/modules/threading/" + 'wiki' => "http://purl.org/rss/1.0/modules/wiki/", + 'ag' => "http://purl.org/rss/1.0/modules/aggregation/", + 'annotate' => "http://purl.org/rss/1.0/modules/annotate/", + 'audio' => "http://media.tangent.org/rss/1.0/", + 'cp' => "http://my.theinfo.org/changed/1.0/rss/", + 'rss091' => "http://purl.org/rss/1.0/modules/rss091/", + 'slash' => "http://purl.org/rss/1.0/modules/slash/", + 'taxo' => "http://purl.org/rss/1.0/modules/taxonomy/", + 'thr' => "http://purl.org/rss/1.0/modules/threading/" ); - $this->_uris_seen = array(); + $this->_uris_seen = array(); $this->_items = array(); } - function registerModule($alias, $uri) { - assert(!isset($this->_modules[$alias])); - $this->_modules[$alias] = $uri; + function registerModule($alias, $uri) + { + assert(!isset($this->_modules[$alias])); + $this->_modules[$alias] = $uri; } // Args should include: // 'title', 'link', 'description' // and can include: // 'URI' - function channel($properties, $uri = false) { + function channel($properties, $uri = false) + { $this->_channel = $this->__node('channel', $properties, $uri); } @@ -58,7 +61,8 @@ class RssWriter extends XmlElement // 'title', 'link' // and can include: // 'description', 'URI' - function addItem($properties, $uri = false) { + function addItem($properties, $uri = false) + { $this->_items[] = $this->__node('item', $properties, $uri); } @@ -66,7 +70,8 @@ class RssWriter extends XmlElement // 'url', 'title', 'link' // and can include: // 'URI' - function image($properties, $uri = false) { + function image($properties, $uri = false) + { $this->_image = $this->__node('image', $properties, $uri); } @@ -74,14 +79,16 @@ class RssWriter extends XmlElement // 'title', 'description', 'name', and 'link' // and can include: // 'URI' - function textinput($properties, $uri = false) { + function textinput($properties, $uri = false) + { $this->_textinput = $this->__node('textinput', $properties, $uri); } /** * Finish construction of RSS. */ - function finish() { + function finish() + { if (isset($this->_finished)) return; @@ -95,18 +102,18 @@ class RssWriter extends XmlElement } $channel->pushContent(new XmlElement('items', false, $seq)); - if (isset($this->_image)) { + if (isset($this->_image)) { $channel->pushContent($this->__ref('image', $this->_image)); - $items[] = $this->_image; - } - if (isset($this->_textinput)) { + $items[] = $this->_image; + } + if (isset($this->_textinput)) { $channel->pushContent($this->__ref('textinput', $this->_textinput)); - $items[] = $this->_textinput; - } + $items[] = $this->_textinput; + } - $this->pushContent($channel); - if ($items) - $this->pushContent($items); + $this->pushContent($channel); + if ($items) + $this->pushContent($items); $this->__spew(); $this->_finished = true; @@ -115,9 +122,10 @@ class RssWriter extends XmlElement /** * Write output to HTTP client. */ - function __spew() { + function __spew() + { header("Content-Type: application/xml; charset=" . RSS_ENCODING); - echo('<'.'?xml version="1.0" encoding="'.RSS_ENCODING.'"?'.">\n"); + echo('<' . '?xml version="1.0" encoding="' . RSS_ENCODING . '"?' . ">\n"); //printf("<!-- generator=\"PhpWiki-%s\" -->\n", PHPWIKI_VERSION); $this->printXML(); } @@ -125,90 +133,99 @@ class RssWriter extends XmlElement /** * Create a new RDF <em>typedNode</em>. */ - function __node($type, $properties, $uri = false) { - if (! $uri) - $uri = $properties['link']; - $attr['rdf:about'] = $this->__uniquify_uri($uri); - return new XmlElement($type, $attr, - $this->__elementize($properties)); + function __node($type, $properties, $uri = false) + { + if (!$uri) + $uri = $properties['link']; + $attr['rdf:about'] = $this->__uniquify_uri($uri); + return new XmlElement($type, $attr, + $this->__elementize($properties)); } /** * Check object URI for uniqueness, create a unique URI if needed. */ - function __uniquify_uri ($uri) { - if (!$uri || isset($this->_uris_seen[$uri])) { - $n = count($this->_uris_seen); - $uri = $this->_channel->getAttr('rdf:about') . "#uri$n"; - assert(!isset($this->_uris_seen[$uri])); - } - $this->_uris_seen[$uri] = true; - return $uri; + function __uniquify_uri($uri) + { + if (!$uri || isset($this->_uris_seen[$uri])) { + $n = count($this->_uris_seen); + $uri = $this->_channel->getAttr('rdf:about') . "#uri$n"; + assert(!isset($this->_uris_seen[$uri])); + } + $this->_uris_seen[$uri] = true; + return $uri; } /** * Convert hash of RDF properties to <em>propertyElt</em>s. */ - function __elementize ($elements) { - $out = array(); + function __elementize($elements) + { + $out = array(); foreach ($elements as $prop => $val) { - $this->__check_predicate($prop); - if (is_array($val)) - $out[] = new XmlElement($prop, $val); - elseif (is_object($val)) - $out[] = $val; - else - $out[] = new XmlElement($prop, false, $val); - } - return $out; + $this->__check_predicate($prop); + if (is_array($val)) + $out[] = new XmlElement($prop, $val); + elseif (is_object($val)) + $out[] = $val; else + $out[] = new XmlElement($prop, false, $val); + } + return $out; } /** * Check property predicates for XMLNS sanity. */ - function __check_predicate ($name) { - if (preg_match('/^([^:]+):[^:]/', $name, $m)) { - $ns = $m[1]; - if (! $this->getAttr("xmlns:$ns")) { - if (!isset($this->_modules[$ns])) - die("$name: unknown namespace ($ns)"); - $this->setAttr("xmlns:$ns", $this->_modules[$ns]); + function __check_predicate($name) + { + if (preg_match('/^([^:]+):[^:]/', $name, $m)) { + $ns = $m[1]; + if (!$this->getAttr("xmlns:$ns")) { + if (!isset($this->_modules[$ns])) + die("$name: unknown namespace ($ns)"); + $this->setAttr("xmlns:$ns", $this->_modules[$ns]); + } } } - } /** * Create a <em>propertyElt</em> which references another node in the RSS. */ - function __ref($predicate, $reference) { + function __ref($predicate, $reference) + { $attr['rdf:resource'] = $reference->getAttr('rdf:about'); return new XmlElement($predicate, $attr); } -}; +} + +; /* Taken from mediawiki. * See http://www.atomenabled.org/developers/syndication/ */ -class AtomFeed extends RssWriter { +class AtomFeed extends RssWriter +{ // Args should include: // 'title', 'link', 'description' // and can include: // 'URI' - function feed($properties, $uri = false) { + function feed($properties, $uri = false) + { global $LANG; $attr = array('xmlns' => 'http://www.w3.org/2005/Atom', - 'version' => '0.3', // or 1.0 - 'lang' => $LANG); + 'version' => '0.3', // or 1.0 + 'lang' => $LANG); $this->_channel = $this->__node('feed', $attr, $properties, $uri); } /** * Write output to HTTP client. */ - function __spew() { + function __spew() + { header("Content-Type: application/atom+xml; charset=" . RSS_ENCODING); - echo('<'.'?xml version="1.0" encoding="'.RSS_ENCODING.'"?'.">\n"); + echo('<' . '?xml version="1.0" encoding="' . RSS_ENCODING . '"?' . ">\n"); //printf("<!-- generator=\"PhpWiki-%s\" -->\n", PHPWIKI_VERSION); $this->printXML(); } @@ -216,34 +233,37 @@ class AtomFeed extends RssWriter { /** * Create a new entry */ - function __node($type, $attr, $properties, $uri = false) { - if (! $uri) - $uri = $properties['link']; - //$attr['rdf:about'] = $this->__uniquify_uri($uri); - return new XmlElement($type, $attr, - $this->__elementize($properties)); + function __node($type, $attr, $properties, $uri = false) + { + if (!$uri) + $uri = $properties['link']; + //$attr['rdf:about'] = $this->__uniquify_uri($uri); + return new XmlElement($type, $attr, + $this->__elementize($properties)); } // Args should include: // 'title', 'link', author, modified, issued, created, summary, // and can include: // comment - function addItem($properties, $attr=false, $uri = false) { + function addItem($properties, $attr = false, $uri = false) + { $this->_items[] = $this->__node('entry', $attr, $properties, $uri); } /** * Print it. */ - function finish() { + function finish() + { if (isset($this->_finished)) return; $channel = &$this->_channel; $items = &$this->_items; - if ($items) - $channel->pushContent($items); - $this->pushContent($channel); + if ($items) + $channel->pushContent($items); + $this->pushContent($channel); $this->__spew(); $this->_finished = true; diff --git a/lib/RssWriter2.php b/lib/RssWriter2.php index 658165cf5..aa99a3eef 100644 --- a/lib/RssWriter2.php +++ b/lib/RssWriter2.php @@ -17,28 +17,29 @@ include_once 'lib/RssWriter.php'; */ class RssWriter2 extends RssWriter { - function RssWriter2 () { + function RssWriter2() + { $this->XmlElement('rss', - array('version' => "2.0")); + array('version' => "2.0")); // not used. no namespaces should be used. - $this->_modules = array( + $this->_modules = array( //Standards - 'content' => "http://purl.org/rss/1.0/modules/content/", - 'dc' => "http://purl.org/dc/elements/1.1/", - 'sy' => "http://purl.org/rss/1.0/modules/syndication/", + 'content' => "http://purl.org/rss/1.0/modules/content/", + 'dc' => "http://purl.org/dc/elements/1.1/", + 'sy' => "http://purl.org/rss/1.0/modules/syndication/", //Proposed - 'wiki' => "http://purl.org/rss/1.0/modules/wiki/", - 'ag' => "http://purl.org/rss/1.0/modules/aggregation/", - 'annotate' => "http://purl.org/rss/1.0/modules/annotate/", - 'audio' => "http://media.tangent.org/rss/1.0/", - 'cp' => "http://my.theinfo.org/changed/1.0/rss/", - 'rss091' => "http://purl.org/rss/1.0/modules/rss091/", - 'slash' => "http://purl.org/rss/1.0/modules/slash/", - 'taxo' => "http://purl.org/rss/1.0/modules/taxonomy/", - 'thr' => "http://purl.org/rss/1.0/modules/threading/" + 'wiki' => "http://purl.org/rss/1.0/modules/wiki/", + 'ag' => "http://purl.org/rss/1.0/modules/aggregation/", + 'annotate' => "http://purl.org/rss/1.0/modules/annotate/", + 'audio' => "http://media.tangent.org/rss/1.0/", + 'cp' => "http://my.theinfo.org/changed/1.0/rss/", + 'rss091' => "http://purl.org/rss/1.0/modules/rss091/", + 'slash' => "http://purl.org/rss/1.0/modules/slash/", + 'taxo' => "http://purl.org/rss/1.0/modules/taxonomy/", + 'thr' => "http://purl.org/rss/1.0/modules/threading/" ); - $this->_uris_seen = array(); + $this->_uris_seen = array(); $this->_items = array(); } @@ -46,12 +47,13 @@ class RssWriter2 extends RssWriter // 'domain', 'port', 'path', 'registerProcedure', 'protocol' // Optional args: // none - function cloud($properties) { + function cloud($properties) + { // xml-rpc or soap or http-post if (!isset($properties['protocol'])) $properties['protocol'] = 'xml-rpc'; if (!isset($properties['registerProcedure'])) $properties['registerProcedure'] = 'rssPleaseNotify'; - if (!isset($properties['path'])) $properties['path'] = DATA_PATH.'/RPC2.php'; + if (!isset($properties['path'])) $properties['path'] = DATA_PATH . '/RPC2.php'; if (!isset($properties['port'])) $properties['port'] = !SERVER_PORT ? '80' @@ -63,17 +65,20 @@ class RssWriter2 extends RssWriter /** * Write output to HTTP client. */ - function __spew() { + function __spew() + { header("Content-Type: application/rss+xml; charset=" . RSS_ENCODING); - echo('<'.'?xml version="1.0" encoding="'.RSS_ENCODING.'"?'.">\n"); + echo('<' . '?xml version="1.0" encoding="' . RSS_ENCODING . '"?' . ">\n"); //printf("<!-- generator=\"PhpWiki-%s\" -->\n", PHPWIKI_VERSION); //RSS2 really is 0.92 - echo '<!DOCTYPE rss SYSTEM "http://my.netscape.com/publish/formats/rss-0.92.dtd">',"\n"; + echo '<!DOCTYPE rss SYSTEM "http://my.netscape.com/publish/formats/rss-0.92.dtd">', "\n"; echo "<!DOCTYPE rss [<!ENTITY % HTMLlat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent\">\n"; echo " %HTMLlat1;]>\n"; $this->printXML(); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/SemanticWeb.php b/lib/SemanticWeb.php index 2185569d1..841fda93f 100644 --- a/lib/SemanticWeb.php +++ b/lib/SemanticWeb.php @@ -57,11 +57,9 @@ * optimization and maintainance of the SemanticWeb KB (Knowledge * Base). Hooks will be tested to KM (an interactive KB playground), * LISA (standard unifier), FaCT, RACER, ... - * Maybe also ZEBU (parser generator) is needed to convert the wiki KB * syntax to the KB reasoner backend (LISA, KM, CLIPS, JESS, FaCT, * ...) and forth. - * pOWL is a simple php backend with some very simple AI logic in PHP, * though I strongly doubt the usefulness of reasoners not written in * Common Lisp. @@ -118,125 +116,132 @@ require_once 'lib/Units.php'; */ class RdfWriter extends RssWriter // in fact it should be rewritten to be other way round. { - function RdfWriter (&$request, &$pagelist) { - $this->_request =& $request; - $this->_pagelist =& $pagelist; + function RdfWriter(&$request, &$pagelist) + { + $this->_request =& $request; + $this->_pagelist =& $pagelist; $this->XmlElement('rdf:RDF', - array('xmlns' => "http://purl.org/rss/1.0/", - 'xmlns:rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')); + array('xmlns' => "http://purl.org/rss/1.0/", + 'xmlns:rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')); - $this->_modules = array( + $this->_modules = array( //Standards - 'content' => "http://purl.org/rss/1.0/modules/content/", - 'dc' => "http://purl.org/dc/elements/1.1/", + 'content' => "http://purl.org/rss/1.0/modules/content/", + 'dc' => "http://purl.org/dc/elements/1.1/", ); - $this->_uris_seen = array(); + $this->_uris_seen = array(); $this->_items = array(); - $this->wiki_xmlns_xml = WikiURL(_("UriResolver")."?",false,true); - $this->wiki_xmlns_url = PHPWIKI_BASE_URL; - - $this->pre_ns_buffer = - "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . - "<!DOCTYPE rdf:RDF[\n" . - "\t"."<!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n" . - "\t"."<!ENTITY rdfs 'http://www.w3.org/2000/01/rdf-schema#'>\n" . - "\t"."<!ENTITY owl 'http://www.w3.org/2002/07/owl#'>\n" . - "\t"."<!ENTITY smw 'http://smw.ontoware.org/2005/smw#'>\n" . - "\t"."<!ENTITY smwdt 'http://smw.ontoware.org/2005/smw-datatype#'>\n" . - // A note on "wiki": this namespace is crucial as a fallback when it would be illegal to start e.g. with a number. In this case, one can always use wiki:... followed by "_" and possibly some namespace, since _ is legal as a first character. - "\t"."<!ENTITY wiki '" . $this->wiki_xmlns_xml . "'>\n" . - "\t"."<!ENTITY relation '" . $this->wiki_xmlns_xml . - $this->makeXMLExportId(urlencode(str_replace(' ', '_', _("Relation") . ':'))) . "'>\n" . - "\t"."<!ENTITY attribute '" . $this->wiki_xmlns_xml . - $this->makeXMLExportId(urlencode(str_replace(' ', '_', _("Attribute") . ':'))) . "'>\n" . - "\t"."<!ENTITY wikiurl '" . $this->wiki_xmlns_url . "'>\n" . - "]>\n\n" . - "<rdf:RDF\n" . - "\t"."xmlns:rdf=\"&rdf;\"\n" . - "\t"."xmlns:rdfs=\"&rdfs;\"\n" . - "\t"."xmlns:owl =\"&owl;\"\n" . - "\t"."xmlns:smw=\"&smw;\"\n" . - "\t"."xmlns:wiki=\"&wiki;\"\n" . - "\t"."xmlns:relation=\"&relation;\"\n" . - "\t"."xmlns:attribute=\"&attribute;\""; - $this->post_ns_buffer = - "\n\t<!-- reference to the Semantic MediaWiki schema -->\n" . - "\t"."<owl:AnnotationProperty rdf:about=\"&smw;hasArticle\">\n" . - "\t\t"."<rdfs:isDefinedBy rdf:resource=\"http://smw.ontoware.org/2005/smw\"/>\n" . - "\t"."</owl:AnnotationProperty>\n" . - "\t"."<owl:AnnotationProperty rdf:about=\"&smw;hasType\">\n" . - "\t\t"."<rdfs:isDefinedBy rdf:resource=\"http://smw.ontoware.org/2005/smw\"/>\n" . - "\t"."</owl:AnnotationProperty>\n" . - "\t"."<owl:Class rdf:about=\"&smw;Thing\">\n" . - "\t\t"."<rdfs:isDefinedBy rdf:resource=\"http://smw.ontoware.org/2005/smw\"/>\n" . - "\t"."</owl:Class>\n" . - "\t<!-- exported page data -->\n"; + $this->wiki_xmlns_xml = WikiURL(_("UriResolver") . "?", false, true); + $this->wiki_xmlns_url = PHPWIKI_BASE_URL; + + $this->pre_ns_buffer = + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . + "<!DOCTYPE rdf:RDF[\n" . + "\t" . "<!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n" . + "\t" . "<!ENTITY rdfs 'http://www.w3.org/2000/01/rdf-schema#'>\n" . + "\t" . "<!ENTITY owl 'http://www.w3.org/2002/07/owl#'>\n" . + "\t" . "<!ENTITY smw 'http://smw.ontoware.org/2005/smw#'>\n" . + "\t" . "<!ENTITY smwdt 'http://smw.ontoware.org/2005/smw-datatype#'>\n" . + // A note on "wiki": this namespace is crucial as a fallback when it would be illegal to start e.g. with a number. In this case, one can always use wiki:... followed by "_" and possibly some namespace, since _ is legal as a first character. + "\t" . "<!ENTITY wiki '" . $this->wiki_xmlns_xml . "'>\n" . + "\t" . "<!ENTITY relation '" . $this->wiki_xmlns_xml . + $this->makeXMLExportId(urlencode(str_replace(' ', '_', _("Relation") . ':'))) . "'>\n" . + "\t" . "<!ENTITY attribute '" . $this->wiki_xmlns_xml . + $this->makeXMLExportId(urlencode(str_replace(' ', '_', _("Attribute") . ':'))) . "'>\n" . + "\t" . "<!ENTITY wikiurl '" . $this->wiki_xmlns_url . "'>\n" . + "]>\n\n" . + "<rdf:RDF\n" . + "\t" . "xmlns:rdf=\"&rdf;\"\n" . + "\t" . "xmlns:rdfs=\"&rdfs;\"\n" . + "\t" . "xmlns:owl =\"&owl;\"\n" . + "\t" . "xmlns:smw=\"&smw;\"\n" . + "\t" . "xmlns:wiki=\"&wiki;\"\n" . + "\t" . "xmlns:relation=\"&relation;\"\n" . + "\t" . "xmlns:attribute=\"&attribute;\""; + $this->post_ns_buffer = + "\n\t<!-- reference to the Semantic MediaWiki schema -->\n" . + "\t" . "<owl:AnnotationProperty rdf:about=\"&smw;hasArticle\">\n" . + "\t\t" . "<rdfs:isDefinedBy rdf:resource=\"http://smw.ontoware.org/2005/smw\"/>\n" . + "\t" . "</owl:AnnotationProperty>\n" . + "\t" . "<owl:AnnotationProperty rdf:about=\"&smw;hasType\">\n" . + "\t\t" . "<rdfs:isDefinedBy rdf:resource=\"http://smw.ontoware.org/2005/smw\"/>\n" . + "\t" . "</owl:AnnotationProperty>\n" . + "\t" . "<owl:Class rdf:about=\"&smw;Thing\">\n" . + "\t\t" . "<rdfs:isDefinedBy rdf:resource=\"http://smw.ontoware.org/2005/smw\"/>\n" . + "\t" . "</owl:Class>\n" . + "\t<!-- exported page data -->\n"; } - function format() { - header( "Content-type: application/rdf+xml; charset=UTF-8" ); - echo $this->pre_ns_buffer; - echo ">\n"; - - $first = true; - $dbi = $this->_request->_dbi; - /* Elements per page: - out-links internal, out-links external - backlinks - relations - attributes - */ - foreach ($this->_pagelist->_pages as $page) { - $relation = new TextSearchQuery("*"); - foreach (array('linkto','linkfrom','relation','attribute') as $linktype) { - $linkiter = $dbi->linkSearch($pages, $search, $linktype, $relation); - } - while ($link = $linkiter->next()) { - if (mayAccessPage('view', $rev->_pagename)) { - $linkto->addItem($this->item_properties($rev), - $this->pageURI($rev)); - if ($first) - $this->setValidators($rev); - $first = false; - } + function format() + { + header("Content-type: application/rdf+xml; charset=UTF-8"); + echo $this->pre_ns_buffer; + echo ">\n"; + + $first = true; + $dbi = $this->_request->_dbi; + /* Elements per page: + out-links internal, out-links external + backlinks + relations + attributes + */ + foreach ($this->_pagelist->_pages as $page) { + $relation = new TextSearchQuery("*"); + foreach (array('linkto', 'linkfrom', 'relation', 'attribute') as $linktype) { + $linkiter = $dbi->linkSearch($pages, $search, $linktype, $relation); + } + while ($link = $linkiter->next()) { + if (mayAccessPage('view', $rev->_pagename)) { + $linkto->addItem($this->item_properties($rev), + $this->pageURI($rev)); + if ($first) + $this->setValidators($rev); + $first = false; + } + } } - } - echo $this->post_ns_buffer; - echo "</rdf:RDF>\n"; + echo $this->post_ns_buffer; + echo "</rdf:RDF>\n"; } /** This function transforms a valid url-encoded URI into a string * that can be used as an XML-ID. The mapping should be injective. */ - function makeXMLExportId($uri) { - $uri = str_replace( '-', '-2D', $uri); - //$uri = str_replace( ':', '-3A', $uri); //already done by PHP - //$uri = str_replace( '_', '-5F', $uri); //not necessary - $uri = str_replace( array('"', '#', '&', "'", '+', '=', '%'), - array('-22','-23','-26','-27','-2B','-3D','-'), - $uri); - return $uri; + function makeXMLExportId($uri) + { + $uri = str_replace('-', '-2D', $uri); + //$uri = str_replace( ':', '-3A', $uri); //already done by PHP + //$uri = str_replace( '_', '-5F', $uri); //not necessary + $uri = str_replace(array('"', '#', '&', "'", '+', '=', '%'), + array('-22', '-23', '-26', '-27', '-2B', '-3D', '-'), + $uri); + return $uri; } /** This function transforms an XML-ID string into a valid * url-encoded URI. This is the inverse to makeXMLExportID. */ - function makeURIfromXMLExportId($id) { - $id = str_replace( array('-22','-23','-26','-27','-2B','-3D','-'), - array('"', '#', '&', "'", '+', '=', '%'), - $id); - $id = str_replace( '-2D', '-', $id); - return $id; + function makeURIfromXMLExportId($id) + { + $id = str_replace(array('-22', '-23', '-26', '-27', '-2B', '-3D', '-'), + array('"', '#', '&', "'", '+', '=', '%'), + $id); + $id = str_replace('-2D', '-', $id); + return $id; } } /** */ -class RdfsWriter extends RdfWriter { -}; +class RdfsWriter extends RdfWriter +{ +} + +; /** * OwlWriter - A class to represent a set of wiki pages (a DL model) as OWL. @@ -246,9 +251,12 @@ class RdfsWriter extends RdfWriter { * OwlWriter * - RdfWriter * - Reasoner -*/ -class OwlWriter extends RdfWriter { -}; + */ +class OwlWriter extends RdfWriter +{ +} + +; /** * ModelWriter - Export a KB as set of wiki pages. @@ -258,9 +266,12 @@ class OwlWriter extends RdfWriter { * ModelWriter * - OwlWriter * - ReasonerBackend -*/ -class ModelWriter extends OwlWriter { -}; + */ +class ModelWriter extends OwlWriter +{ +} + +; /** * NumericSearchQuery can do: @@ -279,7 +290,7 @@ class ModelWriter extends OwlWriter { * Definition: 1.609344e+09 m */ class SemanticAttributeSearchQuery -extends NumericSearchQuery + extends NumericSearchQuery { /* var $base_units = array('m' => explode(',','km,miles,cm,dm,mm,ft,inch,inches,meter'), @@ -292,10 +303,11 @@ extends NumericSearchQuery * We need to detect units from the freetext query: * population > 1 million */ - function SemanticAttributeSearchQuery($search_query, $placeholders, $unit = '') { - $this->NumericSearchQuery($search_query, $placeholders); - $this->_units = new Units(); - $this->unit = $unit; + function SemanticAttributeSearchQuery($search_query, $placeholders, $unit = '') + { + $this->NumericSearchQuery($search_query, $placeholders); + $this->_units = new Units(); + $this->unit = $unit; } /** @@ -309,34 +321,35 @@ extends NumericSearchQuery * @param $x string The variable name to be replaced in the query. * @return string */ - function _bind($value, $x) { + function _bind($value, $x) + { $ori_value = $value; - $value = preg_replace("/,/", "", $value); - $this->_bound[] = array('linkname' => $x, - 'linkvalue' => $value); - // We must ensure that the same baseunits are matched against. - // We cannot compare m^2 to m or '' - $val_base = $this->_units->basevalue($value); + $value = preg_replace("/,/", "", $value); + $this->_bound[] = array('linkname' => $x, + 'linkvalue' => $value); + // We must ensure that the same baseunits are matched against. + // We cannot compare m^2 to m or '' + $val_base = $this->_units->basevalue($value); if (!DISABLE_UNITS and $this->_units->baseunit($value) != $this->unit) { - // Poor user has selected an attribute, but no unit. assume he means the baseunit - if (count($this->getVars() == 1) and $this->unit == '') { - ; - } else { - // non-matching units are silently ignored - $this->_workquery = ''; - return ''; - } + // Poor user has selected an attribute, but no unit. assume he means the baseunit + if (count($this->getVars() == 1) and $this->unit == '') { + ; + } else { + // non-matching units are silently ignored + $this->_workquery = ''; + return ''; + } } $value = $val_base; - if (!is_numeric($value)) { - $this->_workquery = ''; //must return false - trigger_error("Cannot match against non-numeric attribute value $x := $ori_value", - E_USER_NOTICE); - return ''; - } + if (!is_numeric($value)) { + $this->_workquery = ''; //must return false + trigger_error("Cannot match against non-numeric attribute value $x := $ori_value", + E_USER_NOTICE); + return ''; + } - $this->_workquery = preg_replace("/\b".preg_quote($x,"/")."\b/", $value, $this->_workquery); - return $this->_workquery; + $this->_workquery = preg_replace("/\b" . preg_quote($x, "/") . "\b/", $value, $this->_workquery); + return $this->_workquery; } } @@ -349,13 +362,18 @@ extends NumericSearchQuery * @return array A list of found and bound matches */ class SemanticSearchQuery -extends SemanticAttributeSearchQuery + extends SemanticAttributeSearchQuery { - function hasAttributes() { // TODO + function hasAttributes() + { // TODO } - function hasRelations() { // TODO + + function hasRelations() + { // TODO } - function getLinkNames() { // TODO + + function getLinkNames() + { // TODO } } @@ -364,38 +382,57 @@ extends SemanticAttributeSearchQuery * via http as with DIG, * or internally */ -class ReasonerBackend { - function ReasonerBackend () { +class ReasonerBackend +{ + function ReasonerBackend() + { ; } + /** * transform to reasoner syntax */ - function transformTo () { + function transformTo() + { ; } + /** * transform from reasoner syntax */ - function transformFrom () { + function transformFrom() + { ; } + /** * call the reasoner */ - function invoke () { + function invoke() + { ; } -}; +} -class ReasonerBackend_LISA extends ReasonerBackend { -}; +; -class ReasonerBackend_Racer extends ReasonerBackend { -}; +class ReasonerBackend_LISA extends ReasonerBackend +{ +} + +; + +class ReasonerBackend_Racer extends ReasonerBackend +{ +} + +; + +class ReasonerBackend_KM extends ReasonerBackend +{ +} -class ReasonerBackend_KM extends ReasonerBackend { -}; +; // Local Variables: // mode: php diff --git a/lib/SpamBlocklist.php b/lib/SpamBlocklist.php index 25fefa6b2..47f068387 100644 --- a/lib/SpamBlocklist.php +++ b/lib/SpamBlocklist.php @@ -33,37 +33,39 @@ * Strip domain prefixes so that either the last two name parts are returned, * or if it's a known tld (like "co.uk") the last three. */ -function stripDomainPrefixes($host) { +function stripDomainPrefixes($host) +{ static $twoleveltlds = array(); $host_elements = explode('.', $host); while (count($host_elements) > 3) { - array_shift($host_elements); + array_shift($host_elements); } $host_3_elements = implode('.', $host_elements); if (count($host_elements) > 2) { - array_shift($host_elements); + array_shift($host_elements); } $host_2_elements = implode('.', $host_elements); if (empty($twoleveltlds)) { - $data = @file(dirname(__FILE__)."/../config/two-level-tlds"); - $twoleveltlds = $data ? array_flip($data) : array(); + $data = @file(dirname(__FILE__) . "/../config/two-level-tlds"); + $twoleveltlds = $data ? array_flip($data) : array(); } if (array_key_exists($host_2_elements, $twoleveltlds)) - //IS_IN_2LEVEL: we want the last three names - $host = $host_3_elements; + //IS_IN_2LEVEL: we want the last three names + $host = $host_3_elements; else - // IS_NOT_2LEVEL: we want the last two names - $host = $host_2_elements; + // IS_NOT_2LEVEL: we want the last two names + $host = $host_2_elements; return $host; } -function IsBlackListed($uri) { +function IsBlackListed($uri) +{ static $blacklists = array("multi.surbl.org", "bl.spamcop.net"); - /* "sbl-xbl.spamhaus.net" */ + /* "sbl-xbl.spamhaus.net" */ static $whitelist = array(); if (empty($whitelist)) { // list of domains - $data = @file(dirname(__FILE__)."/../config/whitelist"); - $whitelist = $data ? array_flip($data) : array(); + $data = @file(dirname(__FILE__) . "/../config/whitelist"); + $whitelist = $data ? array_flip($data) : array(); } $parsed_uri = parse_url($uri); @@ -72,26 +74,26 @@ function IsBlackListed($uri) { else $host = $parsed_uri['path']; if (array_key_exists($host, $whitelist)) - return 0; + return 0; if (preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $host)) { - $host = implode('.', array_reverse(explode('.', $host))); - $revip = 1; + $host = implode('.', array_reverse(explode('.', $host))); + $revip = 1; } else { - $revip = 0; + $revip = 0; } foreach ($blacklists as $bl) { - if (!$revip and $bl == "multi.surbl.org") { - $host = stripDomainPrefixes($host); // strip domain prefixes - if (array_key_exists($host, $whitelist)) - return 0; - } elseif (!$revip) { - // convert to IP addr and revert it. - $host = implode('.', array_reverse(explode('.', gethostbyname($host)))); - } - //echo "($host.$bl)"; - $res = gethostbyname($host . "." . $bl); - if (preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $res)) - return array($bl, $res, $host); + if (!$revip and $bl == "multi.surbl.org") { + $host = stripDomainPrefixes($host); // strip domain prefixes + if (array_key_exists($host, $whitelist)) + return 0; + } elseif (!$revip) { + // convert to IP addr and revert it. + $host = implode('.', array_reverse(explode('.', gethostbyname($host)))); + } + //echo "($host.$bl)"; + $res = gethostbyname($host . "." . $bl); + if (preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $res)) + return array($bl, $res, $host); } return 0; } diff --git a/lib/Template.php b/lib/Template.php index 407933e46..fa3797395 100644 --- a/lib/Template.php +++ b/lib/Template.php @@ -9,7 +9,8 @@ class Template /** * name optionally of form "theme/template" to include parent templates in children */ - function Template ($name, &$request, $args = false) { + function Template($name, &$request, $args = false) + { global $WikiTheme; $this->_request =& $request; @@ -44,12 +45,12 @@ class Template if (is_array($args)) $this->_locals = $args; elseif ($args) - $this->_locals = array('CONTENT' => $args); - else + $this->_locals = array('CONTENT' => $args); else $this->_locals = array(); } - function _munge_input($template) { + function _munge_input($template) + { // Convert < ?plugin expr ? > to < ?php $this->_printPluginPI("expr"); ? > $orig[] = '/<\?plugin.*?\?>/se'; @@ -66,19 +67,21 @@ class Template return preg_replace($orig, $repl, $template); } - function _mungePlugin($pi) { + function _mungePlugin($pi) + { // HACK ALERT: PHP's preg_replace, with the /e option seems to // escape both single and double quotes with backslashes. // So we need to unescape the double quotes here... $pi = preg_replace('/(?!<\\\\)\\\\"/x', '"', $pi); return sprintf('<?php $this->_printPlugin(%s); ?>', - "'" . str_replace("'", "\'", $pi) . "'"); + "'" . str_replace("'", "\'", $pi) . "'"); } - function _printPlugin ($pi) { - include_once 'lib/WikiPlugin.php'; - static $loader; + function _printPlugin($pi) + { + include_once 'lib/WikiPlugin.php'; + static $loader; if (empty($loader)) $loader = new WikiPluginLoader; @@ -86,7 +89,8 @@ class Template $this->_print($loader->expandPI($pi, $this->_request, $this, $this->_basepage)); } - function _print ($val) { + function _print($val) + { if (isa($val, 'Template')) { $this->_expandSubtemplate($val); } else { @@ -94,7 +98,8 @@ class Template } } - function _expandSubtemplate (&$template) { + function _expandSubtemplate(&$template) + { // FIXME: big hack! //if (!$template->_request) // $template->_request = &$this->_request; @@ -119,12 +124,14 @@ class Template * * @param $replacement string Replacement HTML text. */ - function replace($varname, $value) { + function replace($varname, $value) + { $this->_locals[$varname] = $value; } - function printExpansion ($defaults = false) { + function printExpansion($defaults = false) + { if (!is_array($defaults)) // HTML object or template object $defaults = array('CONTENT' => $defaults); $this->_vars = array_merge($defaults, $this->_locals); @@ -135,9 +142,9 @@ class Template $user = $request->getUser(); if (!isset($page)) $page = $request->getPage(); - // Speedup. I checked all templates + // Speedup. I checked all templates if (!isset($revision)) - $revision = false; + $revision = false; global $WikiTheme, $charset; //$this->_dump_template(); @@ -155,25 +162,29 @@ class Template // Find a way to do template expansion less memory intensive and faster. // 1.3.4 needed no memory at all for dumphtml, now it needs +15MB. // Smarty? As before? - function getExpansion ($defaults = false) { + function getExpansion($defaults = false) + { ob_start(); $this->printExpansion($defaults); $xml = ob_get_contents(); - ob_end_clean(); // PHP problem: Doesn't release its memory? + ob_end_clean(); // PHP problem: Doesn't release its memory? return $xml; } - function printXML () { + function printXML() + { $this->printExpansion(); } - function asXML () { + function asXML() + { return $this->getExpansion(); } // Debugging: - function _dump_template () { + function _dump_template() + { $lines = explode("\n", $this->_munge_input($this->_tmpl)); $pre = HTML::pre(); $n = 1; @@ -182,9 +193,10 @@ class Template $pre->printXML(); } - function _errorHandler($error) { + function _errorHandler($error) + { //if (!preg_match('/: eval\(\)\'d code$/', $error->errfile)) - // return false; + // return false; if (preg_match('/: eval\(\)\'d code$/', $error->errfile)) { $error->errfile = "In template '$this->_name'"; @@ -192,17 +204,14 @@ class Template // whose names are ALL_CAPS. if (preg_match('/Undefined variable:\s*[_A-Z]+\s*$/', $error->errstr)) return true; - } - // ignore recursively nested htmldump loop: browse -> body -> htmldump -> browse -> body ... + } // ignore recursively nested htmldump loop: browse -> body -> htmldump -> browse -> body ... // FIXME for other possible loops also elseif (strstr($error->errfile, "In template 'htmldump'")) { ; //return $error; - } - elseif (strstr($error->errfile, "In template '")) { // merge + } elseif (strstr($error->errfile, "In template '")) { // merge $error->errfile = preg_replace("/'(\w+)'\)$/", "'\\1' < '$this->_name')", - $error->errfile); - } - else { + $error->errfile); + } else { $error->errfile .= " (In template '$this->_name')"; } @@ -211,9 +220,11 @@ class Template if (isset($lines[$error->errline - 1])) $error->errstr .= ":\n\t" . $lines[$error->errline - 1]; } - return $error; + return $error; } -}; +} + +; /** * Get a templates @@ -223,15 +234,18 @@ class Template * new Template(...) * </pre> */ -function Template($name, $args = false) { +function Template($name, $args = false) +{ global $request; return new Template($name, $request, $args); } -function alreadyTemplateProcessed($name) { +function alreadyTemplateProcessed($name) +{ global $request; return !empty($request->_TemplatesProcessed[$name]) ? true : false; } + /** * Make and expand the top-level template. * @@ -243,7 +257,8 @@ function alreadyTemplateProcessed($name) { * * @return string HTML expansion of template. */ -function GeneratePage($content, $title, $page_revision = false, $args = false) { +function GeneratePage($content, $title, $page_revision = false, $args = false) +{ global $request; if (!is_array($args)) @@ -264,7 +279,8 @@ function GeneratePage($content, $title, $page_revision = false, $args = false) { * For dumping pages as html to a file. * Used for action=dumphtml,action=ziphtml,format=pdf,format=xml */ -function GeneratePageasXML($content, $title, $page_revision = false, $args = false) { +function GeneratePageasXML($content, $title, $page_revision = false, $args = false) +{ global $request; if (!is_array($args)) @@ -281,7 +297,7 @@ function GeneratePageasXML($content, $title, $page_revision = false, $args = fal global $HIDE_TOOLBARS, $NO_BASEHREF, $WikiTheme; $HIDE_TOOLBARS = true; if (!$WikiTheme->DUMP_MODE) - $WikiTheme->DUMP_MODE = 'HTML'; + $WikiTheme->DUMP_MODE = 'HTML'; // FIXME: unfatal errors and login requirements $html = asXML(new Template('htmldump', $request, $args)); diff --git a/lib/TextSearchQuery.php b/lib/TextSearchQuery.php index 11d4af39e..1a2647f54 100644 --- a/lib/TextSearchQuery.php +++ b/lib/TextSearchQuery.php @@ -58,27 +58,27 @@ // regex-style: 'auto', 'none', 'glob', 'posix', 'pcre', 'sql' define ('TSQ_REGEX_NONE', 0); define ('TSQ_REGEX_AUTO', 1); -define ('TSQ_REGEX_POSIX',2); +define ('TSQ_REGEX_POSIX', 2); define ('TSQ_REGEX_GLOB', 4); define ('TSQ_REGEX_PCRE', 8); define ('TSQ_REGEX_SQL', 16); -define ('TSQ_TOK_VOID', 0); -define ('TSQ_TOK_BINOP', 1); -define ('TSQ_TOK_NOT', 2); +define ('TSQ_TOK_VOID', 0); +define ('TSQ_TOK_BINOP', 1); +define ('TSQ_TOK_NOT', 2); define ('TSQ_TOK_LPAREN', 4); define ('TSQ_TOK_RPAREN', 8); -define ('TSQ_TOK_WORD', 16); +define ('TSQ_TOK_WORD', 16); define ('TSQ_TOK_STARTS_WITH', 32); -define ('TSQ_TOK_ENDS_WITH', 64); -define ('TSQ_TOK_EXACT', 128); -define ('TSQ_TOK_REGEX', 256); +define ('TSQ_TOK_ENDS_WITH', 64); +define ('TSQ_TOK_EXACT', 128); +define ('TSQ_TOK_REGEX', 256); define ('TSQ_TOK_REGEX_GLOB', 512); define ('TSQ_TOK_REGEX_PCRE', 1024); -define ('TSQ_TOK_REGEX_SQL', 2048); -define ('TSQ_TOK_ALL', 4096); +define ('TSQ_TOK_REGEX_SQL', 2048); +define ('TSQ_TOK_ALL', 4096); // all bits from word to the last. -define ('TSQ_ALLWORDS', (4096*2)-1 - (16-1)); +define ('TSQ_ALLWORDS', (4096 * 2) - 1 - (16 - 1)); /* define ('TSQ_NODE_ALL', 0); @@ -96,7 +96,8 @@ define ('TSQ_NODE_OR', 11); */ -class TextSearchQuery { +class TextSearchQuery +{ /** * Create a new query. * @@ -106,52 +107,56 @@ class TextSearchQuery { * @param $regex string one of 'auto', 'none', 'glob', 'posix', 'pcre', 'sql' * @see TextSearchQuery */ - function TextSearchQuery($search_query, $case_exact=false, $regex='auto') { + function TextSearchQuery($search_query, $case_exact = false, $regex = 'auto') + { if ($regex == 'none' or !$regex) $this->_regex = 0; - elseif (defined("TSQ_REGEX_".strtoupper($regex))) - $this->_regex = constant("TSQ_REGEX_".strtoupper($regex)); - else { + elseif (defined("TSQ_REGEX_" . strtoupper($regex))) + $this->_regex = constant("TSQ_REGEX_" . strtoupper($regex)); else { trigger_error(fmt("Unsupported argument: %s=%s", 'regex', $regex)); $this->_regex = 0; } - $this->_regex_modifier = ($case_exact?'':'i').'sS'; + $this->_regex_modifier = ($case_exact ? '' : 'i') . 'sS'; $this->_case_exact = $case_exact; if ($regex != 'pcre') { - $parser = new TextSearchQuery_Parser; - $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex); - $this->_optimize(); // broken under certain circumstances: "word -word -word" - if (defined("FULLTEXTSEARCH_STOPLIST")) - $this->_stoplist = FULLTEXTSEARCH_STOPLIST; - else // default stoplist, localizable. - $this->_stoplist = _("(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)"); - } - else { - $this->_tree = new TextSearchQuery_node_regex_pcre($search_query); - if (preg_match("/^\/(.*)\/(\w*)$/", $search_query, $m)) { - $this->_tree->word = $m[1]; - $this->_regex_modifier = $m[2]; // overrides case_exact + $parser = new TextSearchQuery_Parser; + $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex); + $this->_optimize(); // broken under certain circumstances: "word -word -word" + if (defined("FULLTEXTSEARCH_STOPLIST")) + $this->_stoplist = FULLTEXTSEARCH_STOPLIST; + else // default stoplist, localizable. + $this->_stoplist = _("(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)"); + } else { + $this->_tree = new TextSearchQuery_node_regex_pcre($search_query); + if (preg_match("/^\/(.*)\/(\w*)$/", $search_query, $m)) { + $this->_tree->word = $m[1]; + $this->_regex_modifier = $m[2]; // overrides case_exact + } } } - } - function getType() { return 'text'; } + function getType() + { + return 'text'; + } - function _optimize() { + function _optimize() + { $this->_tree = $this->_tree->optimize(); } /** * Get a PCRE regexp which matches the query. */ - function asRegexp() { + function asRegexp() + { if (!isset($this->_regexp)) { if (!isset($this->_regex_modifier)) - $this->_regex_modifier = ($this->_case_exact?'':'i').'sS'; + $this->_regex_modifier = ($this->_case_exact ? '' : 'i') . 'sS'; if ($this->_regex) - $this->_regexp = '/' . $this->_tree->regexp() . '/'.$this->_regex_modifier; + $this->_regexp = '/' . $this->_tree->regexp() . '/' . $this->_regex_modifier; else - $this->_regexp = '/^' . $this->_tree->regexp() . '/'.$this->_regex_modifier; + $this->_regexp = '/^' . $this->_tree->regexp() . '/' . $this->_regex_modifier; } return $this->_regexp; } @@ -163,23 +168,26 @@ class TextSearchQuery { * @param $string string The string to match. * @return boolean True if the string matches the query. */ - function match($string) { - if ($this->_tree->_op == TSQ_TOK_ALL) return true; + function match($string) + { + if ($this->_tree->_op == TSQ_TOK_ALL) return true; if ($this->_tree->_op == TSQ_TOK_EXACT) return $this->_tree->word == $string; return preg_match($this->asRegexp(), $string); } /* How good does it match? Returns a number */ - function score($string) { - $score = 0.0; - $i = 10; - foreach (array_unique($this->_tree->highlight_words()) as $word) { - if ($nummatch = preg_match_all("/".preg_quote($word, '/')."/". - $this->_regex_modifier, - $string, $out)) - $score += ($i-- * $nummatch); - } - return min(1.0, $score / 10.0); + function score($string) + { + $score = 0.0; + $i = 10; + foreach (array_unique($this->_tree->highlight_words()) as $word) { + if ($nummatch = preg_match_all("/" . preg_quote($word, '/') . "/" . + $this->_regex_modifier, + $string, $out) + ) + $score += ($i-- * $nummatch); + } + return min(1.0, $score / 10.0); } @@ -191,7 +199,8 @@ class TextSearchQuery { * * @return string The PCRE regexp. */ - function getHighlightRegexp() { + function getHighlightRegexp() + { if (!isset($this->_hilight_regexp)) { $words = array_unique($this->_tree->highlight_words()); if (!$words) { @@ -199,8 +208,8 @@ class TextSearchQuery { } else { foreach ($words as $key => $word) $words[$key] = preg_quote($word, '/'); - $this->_hilight_regexp = '(?'.($this->_case_exact?'':'i').':' - . join('|', $words) . ')'; + $this->_hilight_regexp = '(?' . ($this->_case_exact ? '' : 'i') . ':' + . join('|', $words) . ')'; } } return $this->_hilight_regexp; @@ -238,82 +247,92 @@ class TextSearchQuery { * * @return string The SQL clause. */ - function makeSqlClause($sql_clause_cb) { + function makeSqlClause($sql_clause_cb) + { $this->_sql_clause_cb = $sql_clause_cb; return $this->_sql_clause($this->_tree); } + // deprecated: use _sql_clause_obj now. - function _sql_clause($node) { + function _sql_clause($node) + { switch ($node->_op) { - case TSQ_TOK_WORD: // word => %word% - return $this->_sql_clause_cb->call($node->word); - case TSQ_TOK_NOT: - return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")"; - case TSQ_TOK_BINOP: - $subclauses = array(); - foreach ($node->leaves as $leaf) - $subclauses[] = "(" . $this->_sql_clause($leaf) . ")"; - return join(" $node->op ", $subclauses); - default: - assert($node->_op == TSQ_TOK_VOID); - return '1=1'; + case TSQ_TOK_WORD: // word => %word% + return $this->_sql_clause_cb->call($node->word); + case TSQ_TOK_NOT: + return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")"; + case TSQ_TOK_BINOP: + $subclauses = array(); + foreach ($node->leaves as $leaf) + $subclauses[] = "(" . $this->_sql_clause($leaf) . ")"; + return join(" $node->op ", $subclauses); + default: + assert($node->_op == TSQ_TOK_VOID); + return '1=1'; } } /** Get away with the callback and use a db-specific search class instead. * @see WikiDB_backend_PearDB_search */ - function makeSqlClauseObj(&$sql_search_cb) { + function makeSqlClauseObj(&$sql_search_cb) + { $this->_sql_clause_cb = $sql_search_cb; return $this->_sql_clause_obj($this->_tree); } - function _sql_clause_obj($node) { + function _sql_clause_obj($node) + { switch ($node->_op) { - case TSQ_TOK_NOT: - return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")"; - case TSQ_TOK_BINOP: - $subclauses = array(); - foreach ($node->leaves as $leaf) - $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")"; - return join(" $node->op ", $subclauses); - case TSQ_TOK_VOID: - return '0=1'; - case TSQ_TOK_ALL: - return '1=1'; - default: - return $this->_sql_clause_cb->call($node); + case TSQ_TOK_NOT: + return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")"; + case TSQ_TOK_BINOP: + $subclauses = array(); + foreach ($node->leaves as $leaf) + $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")"; + return join(" $node->op ", $subclauses); + case TSQ_TOK_VOID: + return '0=1'; + case TSQ_TOK_ALL: + return '1=1'; + default: + return $this->_sql_clause_cb->call($node); } } /* postgresql tsearch2 uses no WHERE operators, just & | and ! in the searchstring */ - function makeTsearch2SqlClauseObj(&$sql_search_cb) { + function makeTsearch2SqlClauseObj(&$sql_search_cb) + { $this->_sql_clause_cb = $sql_search_cb; return $this->_Tsearch2Sql_clause_obj($this->_tree); } - function _Tsearch2Sql_clause_obj($node) { + function _Tsearch2Sql_clause_obj($node) + { // TODO: "such a phrase" switch ($node->_op) { - case TSQ_TOK_NOT: - return "!" . $node->leaves[0]; - case TSQ_TOK_BINOP: - $subclauses = array(); - foreach ($node->leaves as $leaf) - $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf); - return join($node->_op == 'AND' ? "&" : "|", $subclauses); - case TSQ_TOK_VOID: - return ''; - case TSQ_TOK_ALL: - return '1'; - default: - return $this->_sql_clause_cb->call($node); + case TSQ_TOK_NOT: + return "!" . $node->leaves[0]; + case TSQ_TOK_BINOP: + $subclauses = array(); + foreach ($node->leaves as $leaf) + $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf); + return join($node->_op == 'AND' ? "&" : "|", $subclauses); + case TSQ_TOK_VOID: + return ''; + case TSQ_TOK_ALL: + return '1'; + default: + return $this->_sql_clause_cb->call($node); } } - function sql() { return '%'.$this->_sql_quote($this->word).'%'; } + function sql() + { + return '%' . $this->_sql_quote($this->word) . '%'; + } /** * Get printable representation of the parse tree. @@ -321,24 +340,26 @@ class TextSearchQuery { * This is for debugging only. * @return string Printable parse tree. */ - function asString() { + function asString() + { return $this->_as_string($this->_tree); } - function _as_string($node, $indent = '') { + function _as_string($node, $indent = '') + { switch ($node->_op) { - case TSQ_TOK_WORD: - return $indent . "WORD: $node->word"; - case TSQ_TOK_VOID: - return $indent . "VOID"; - case TSQ_TOK_ALL: - return $indent . "ALL"; - default: - $lines = array($indent . $node->op . ":"); - $indent .= " "; - foreach ($node->leaves as $leaf) - $lines[] = $this->_as_string($leaf, $indent); - return join("\n", $lines); + case TSQ_TOK_WORD: + return $indent . "WORD: $node->word"; + case TSQ_TOK_VOID: + return $indent . "VOID"; + case TSQ_TOK_ALL: + return $indent . "ALL"; + default: + $lines = array($indent . $node->op . ":"); + $indent .= " "; + foreach ($node->leaves as $leaf) + $lines[] = $this->_as_string($leaf, $indent); + return join("\n", $lines); } } } @@ -346,19 +367,44 @@ class TextSearchQuery { /** * This is a TextSearchQuery which matches nothing. */ -class NullTextSearchQuery extends TextSearchQuery { +class NullTextSearchQuery extends TextSearchQuery +{ /** * Create a new query. * * @see TextSearchQuery */ - function NullTextSearchQuery() {} - function asRegexp() { return '/^(?!a)a/x'; } - function match($string) { return false; } - function getHighlightRegexp() { return ""; } - function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; } - function asString() { return "NullTextSearchQuery"; } -}; + function NullTextSearchQuery() + { + } + + function asRegexp() + { + return '/^(?!a)a/x'; + } + + function match($string) + { + return false; + } + + function getHighlightRegexp() + { + return ""; + } + + function makeSqlClause($make_sql_clause_cb) + { + return "(1 = 0)"; + } + + function asString() + { + return "NullTextSearchQuery"; + } +} + +; /** * A simple algebraic matcher for numeric attributes. @@ -396,33 +442,37 @@ class NumericSearchQuery * @param $placeholders array or string All placeholders in the query must be defined * here, and will be replaced by the matcher. */ - function NumericSearchQuery($search_query, $placeholders) { - // added some basic security checks against user input + function NumericSearchQuery($search_query, $placeholders) + { + // added some basic security checks against user input $this->_query = $search_query; - $this->_placeholders = $placeholders; - - // we should also allow the M_ constants - $this->_allowed_functions = explode(':','abs:acos:acosh:asin:asinh:atan2:atan:atanh:base_convert:bindec:ceil:cos:cosh:decbin:dechex:decoct:deg2rad:exp:expm1:floor:fmod:getrandmax:hexdec:hypot:is_finite:is_infinite:is_nan:lcg_value:log10:log1p:log:max:min:mt_getrandmax:mt_rand:mt_srand:octdec:pi:pow:rad2deg:rand:round:sin:sinh:sqrt:srand:tan:tanh'); - $this->_allowed_operators = explode(',', '-,<,<=,>,>=,==,!=,*,+,/,(,),%,and,or,xor,<<,>>,===,!==,&,^,|,&&,||'); - $this->_parser_check = array(); - // check should be fast, so make a hash - foreach ($this->_allowed_functions as $f) - $this->_parser_check[$f] = 1; - foreach ($this->_allowed_operators as $f) - $this->_parser_check[$f] = 1; - if (is_array($placeholders)) - foreach ($placeholders as $f) - $this->_parser_check[$f] = 1; - else $this->_parser_check[$placeholders] = 1; - - // This is a speciality: := looks like the attribute definition and is - // therefore a dummy check for this definition. - // php-4.2.2 has a problem with /\b:=\b/ matching "population := 1223400" - $this->_query = preg_replace("/:=/", "==", $this->_query); - $this->_query = $this->check_query($this->_query); - } - - function getType() { return 'numeric'; } + $this->_placeholders = $placeholders; + + // we should also allow the M_ constants + $this->_allowed_functions = explode(':', 'abs:acos:acosh:asin:asinh:atan2:atan:atanh:base_convert:bindec:ceil:cos:cosh:decbin:dechex:decoct:deg2rad:exp:expm1:floor:fmod:getrandmax:hexdec:hypot:is_finite:is_infinite:is_nan:lcg_value:log10:log1p:log:max:min:mt_getrandmax:mt_rand:mt_srand:octdec:pi:pow:rad2deg:rand:round:sin:sinh:sqrt:srand:tan:tanh'); + $this->_allowed_operators = explode(',', '-,<,<=,>,>=,==,!=,*,+,/,(,),%,and,or,xor,<<,>>,===,!==,&,^,|,&&,||'); + $this->_parser_check = array(); + // check should be fast, so make a hash + foreach ($this->_allowed_functions as $f) + $this->_parser_check[$f] = 1; + foreach ($this->_allowed_operators as $f) + $this->_parser_check[$f] = 1; + if (is_array($placeholders)) + foreach ($placeholders as $f) + $this->_parser_check[$f] = 1; + else $this->_parser_check[$placeholders] = 1; + + // This is a speciality: := looks like the attribute definition and is + // therefore a dummy check for this definition. + // php-4.2.2 has a problem with /\b:=\b/ matching "population := 1223400" + $this->_query = preg_replace("/:=/", "==", $this->_query); + $this->_query = $this->check_query($this->_query); + } + + function getType() + { + return 'numeric'; + } /** * Check the symbolic definition query against unwanted functions and characters. @@ -430,73 +480,75 @@ class NumericSearchQuery * "area > 1000000 and mail($me,file("/etc/passwd"),...)" * http://localhost/wikicvs/SemanticSearch?attribute=*&attr_op=<0 and find(1)>&s=-0.01&start_debug=1 */ - function check_query ($query) { - $tmp = $query; // check for all function calls, in case the tokenizer is not available. + function check_query($query) + { + $tmp = $query; // check for all function calls, in case the tokenizer is not available. while (preg_match("/([a-z][a-z0-9]+)\s*\((.*)$/i", $tmp, $m)) { - if (!in_array($m[1], $this->_allowed_functions) - and !in_array($m[1], $this->_allowed_operators)) - { - trigger_error("Illegal function in query: ".$m[1], E_USER_WARNING); - return ''; + if (!in_array($m[1], $this->_allowed_functions) + and !in_array($m[1], $this->_allowed_operators) + ) { + trigger_error("Illegal function in query: " . $m[1], E_USER_WARNING); + return ''; + } + $tmp = $m[2]; } - $tmp = $m[2]; - } - // Strictly check for illegal functions and operators, which are no placeholders. - if (function_exists('token_get_all')) { - $parsed = token_get_all("<?$query?>"); - foreach ($parsed as $x) { // flat, non-recursive array - if (is_string($x) and !isset($this->_parser_check[$x])) { - // single char op or name - trigger_error("Illegal string or operator in query: \"$x\"", E_USER_WARNING); - $query = ''; - } - elseif (is_array($x)) { - $n = token_name($x[0]); - if ($n == 'T_OPEN_TAG' or $n == 'T_WHITESPACE' - or $n == 'T_CLOSE_TAG' or $n == 'T_LNUMBER' - or $n == 'T_CONST' or $n == 'T_DNUMBER' ) continue; - if ($n == 'T_VARIABLE') { // but we do allow consts - trigger_error("Illegal variable in query: \"$x[1]\"", E_USER_WARNING); - $query = ''; + // Strictly check for illegal functions and operators, which are no placeholders. + if (function_exists('token_get_all')) { + $parsed = token_get_all("<?$query?>"); + foreach ($parsed as $x) { // flat, non-recursive array + if (is_string($x) and !isset($this->_parser_check[$x])) { + // single char op or name + trigger_error("Illegal string or operator in query: \"$x\"", E_USER_WARNING); + $query = ''; + } elseif (is_array($x)) { + $n = token_name($x[0]); + if ($n == 'T_OPEN_TAG' or $n == 'T_WHITESPACE' + or $n == 'T_CLOSE_TAG' or $n == 'T_LNUMBER' + or $n == 'T_CONST' or $n == 'T_DNUMBER' + ) continue; + if ($n == 'T_VARIABLE') { // but we do allow consts + trigger_error("Illegal variable in query: \"$x[1]\"", E_USER_WARNING); + $query = ''; + } + if (is_string($x[1]) and !isset($this->_parser_check[$x[1]])) { + // multi-char char op or name + trigger_error("Illegal $n in query: \"$x[1]\"", E_USER_WARNING); + $query = ''; + } + } } - if (is_string($x[1]) and !isset($this->_parser_check[$x[1]])) { - // multi-char char op or name - trigger_error("Illegal $n in query: \"$x[1]\"", E_USER_WARNING); - $query = ''; + //echo "$query <br>"; + //$this->_parse_token($parsed); + //echo "<br>\n"; + //var_dump($parsed); + /* + "_x > 0" => + { T_OPEN_TAG "<?"} { T_STRING "_x"} { T_WHITESPACE " "} ">" { T_WHITESPACE " "} { T_LNUMBER "0"} { T_CLOSE_TAG "?>"} + Interesting: on-char ops, as ">" are not tokenized. + "_x <= 0" + { T_OPEN_TAG "< ?" } { T_STRING "_x" } { T_WHITESPACE " " } { T_IS_SMALLER_OR_EQUAL "<=" } { T_WHITESPACE " " } { T_LNUMBER "0" } { T_CLOSE_TAG "?>" } + */ + } else { + // Detect illegal characters besides nums, words and ops. + // So attribute names can not be utf-8 + $c = "/([^\d\w.,\s" . preg_quote(join("", $this->_allowed_operators), "/") . "])/"; + if (preg_match($c, $query, $m)) { + trigger_error("Illegal character in query: " . $m[1], E_USER_WARNING); + return ''; } } - } - //echo "$query <br>"; - //$this->_parse_token($parsed); - //echo "<br>\n"; - //var_dump($parsed); - /* -"_x > 0" => -{ T_OPEN_TAG "<?"} { T_STRING "_x"} { T_WHITESPACE " "} ">" { T_WHITESPACE " "} { T_LNUMBER "0"} { T_CLOSE_TAG "?>"} - Interesting: on-char ops, as ">" are not tokenized. -"_x <= 0" -{ T_OPEN_TAG "< ?" } { T_STRING "_x" } { T_WHITESPACE " " } { T_IS_SMALLER_OR_EQUAL "<=" } { T_WHITESPACE " " } { T_LNUMBER "0" } { T_CLOSE_TAG "?>" } - */ - } else { - // Detect illegal characters besides nums, words and ops. - // So attribute names can not be utf-8 - $c = "/([^\d\w.,\s".preg_quote(join("",$this->_allowed_operators),"/")."])/"; - if (preg_match($c, $query, $m)) { - trigger_error("Illegal character in query: ".$m[1], E_USER_WARNING); - return ''; - } - } - return $query; + return $query; } /** * Check the bound, numeric-only query against unwanted functions and sideeffects. * "4560000 < 20000 and 1456022 > 1000000" */ - function _live_check () { - // TODO: check $this->_workquery again? - return !empty($this->_workquery); + function _live_check() + { + // TODO: check $this->_workquery again? + return !empty($this->_workquery); } /** @@ -504,9 +556,10 @@ class NumericSearchQuery * * @return array The names as array of strings. => ('x', 'y') the placeholders. */ - function getVars() { - if(is_array($this->_placeholders)) return $this->_placeholders; - else return array($this->_placeholders); + function getVars() + { + if (is_array($this->_placeholders)) return $this->_placeholders; + else return array($this->_placeholders); } /** @@ -518,47 +571,50 @@ class NumericSearchQuery * @param $x string The variable name to be replaced in the query. * @return string */ - function _bind($value, $x) { - // TODO: check is_number, is_float, is_integer and do casting - $this->_bound[] = array('linkname' => $x, - 'linkvalue' => $value); - $value = preg_replace("/[^-+0123456789.,]/", "", $value); - //$c = "/\b".preg_quote($x,"/")."\b/"; - $this->_workquery = preg_replace("/\b".preg_quote($x,"/")."\b/", $value, $this->_workquery); - // FIXME: do again a final check. now only numbers and some operators are allowed. - return $this->_workquery; + function _bind($value, $x) + { + // TODO: check is_number, is_float, is_integer and do casting + $this->_bound[] = array('linkname' => $x, + 'linkvalue' => $value); + $value = preg_replace("/[^-+0123456789.,]/", "", $value); + //$c = "/\b".preg_quote($x,"/")."\b/"; + $this->_workquery = preg_replace("/\b" . preg_quote($x, "/") . "\b/", $value, $this->_workquery); + // FIXME: do again a final check. now only numbers and some operators are allowed. + return $this->_workquery; } /* array of successfully bound vars, and in case of success, the resulting vars */ - function _bound() { + function _bound() + { return $this->_bound; } /** * With an array of placeholders we need a hash to check against, if all required names are given. * Purpose: Be silent about missing vars, just return false. - `* + `* * @access public * @param $variable string or hash of name => value The keys must satisfy all placeholders in the definition. * We want the full hash and not just the keys because a hash check is faster than the array of keys check. * @return boolean */ - function can_match(&$variables) { + function can_match(&$variables) + { if (empty($this->_query)) return false; - $p =& $this->_placeholders; - if (!is_array($variables) and !is_array($p)) - return $variables == $p; // This was easy. - // Check if all placeholders have definitions. can be overdefined but not underdefined. - if (!is_array($p)) { - if (!isset($variables[$p])) return false; - } else { - foreach ($p as $x) { - if (!isset($variables[$x])) return false; + $p =& $this->_placeholders; + if (!is_array($variables) and !is_array($p)) + return $variables == $p; // This was easy. + // Check if all placeholders have definitions. can be overdefined but not underdefined. + if (!is_array($p)) { + if (!isset($variables[$p])) return false; + } else { + foreach ($p as $x) { + if (!isset($variables[$x])) return false; + } } - } - return true; + return true; } /** @@ -570,37 +626,38 @@ class NumericSearchQuery * @param $variable number or array of name => value The keys must satisfy all placeholders in the definition. * @return boolean */ - function match(&$variable) { - $p =& $this->_placeholders; - $this->_workquery = $this->_query; - if (!is_array($p)) { - if (is_array($variable)) { // which var to match? we cannot decide this here - if (!isset($variable[$p])) - trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR); - $this->_bind($variable[$p], $p); + function match(&$variable) + { + $p =& $this->_placeholders; + $this->_workquery = $this->_query; + if (!is_array($p)) { + if (is_array($variable)) { // which var to match? we cannot decide this here + if (!isset($variable[$p])) + trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR); + $this->_bind($variable[$p], $p); + } else { + $this->_bind($variable, $p); + } } else { - $this->_bind($variable, $p); - } - } else { - foreach ($p as $x) { - if (!isset($variable[$x])) - trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR); - $this->_bind($variable[$x], $x); + foreach ($p as $x) { + if (!isset($variable[$x])) + trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR); + $this->_bind($variable[$x], $x); + } } - } if (!$this->_live_check()) // check returned an error return false; $search = $this->_workquery; - $result = false; - //if (DEBUG & _DEBUG_VERBOSE) - // trigger_error("\$result = (boolean)($search);", E_USER_NOTICE); - // We might have a numerical problem: - // php-4.2.2 eval'ed as module: "9.636e+08 > 1000" false; - // php-5.1.2 cgi true, 4.2.2 cgi true - eval("\$result = (boolean)($search);"); - if ($result and is_array($p)) { - return $this->_bound(); - } + $result = false; + //if (DEBUG & _DEBUG_VERBOSE) + // trigger_error("\$result = (boolean)($search);", E_USER_NOTICE); + // We might have a numerical problem: + // php-4.2.2 eval'ed as module: "9.636e+08 > 1000" false; + // php-5.1.2 cgi true, 4.2.2 cgi true + eval("\$result = (boolean)($search);"); + if ($result and is_array($p)) { + return $this->_bound(); + } return $result; } } @@ -624,14 +681,16 @@ class TextSearchQuery_node * Optimize this node. * @return object Optimized node. */ - function optimize() { + function optimize() + { return $this; } /** * @return regexp matching this node. */ - function regexp() { + function regexp() + { return ''; } @@ -639,14 +698,19 @@ class TextSearchQuery_node * @param bool True if this node has been negated (higher in the parse tree.) * @return array A list of all non-negated words contained by this node. */ - function highlight_words($negated = false) { + function highlight_words($negated = false) + { return array(); } - function sql() { return $this->word; } + function sql() + { + return $this->word; + } - function _sql_quote() { - global $request; + function _sql_quote() + { + global $request; $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word); return $request->_dbi->_backend->qstr($word); } @@ -656,111 +720,194 @@ class TextSearchQuery_node * A word. Exact or substring? */ class TextSearchQuery_node_word -extends TextSearchQuery_node + extends TextSearchQuery_node { var $op = "WORD"; var $_op = TSQ_TOK_WORD; - function TextSearchQuery_node_word($word) { + function TextSearchQuery_node_word($word) + { $this->word = $word; } - function regexp() { + + function regexp() + { return '(?=.*\b' . preg_quote($this->word, '/') . '\b)'; } - function highlight_words ($negated = false) { + + function highlight_words($negated = false) + { return $negated ? array() : array($this->word); } - function sql() { return '%'.$this->_sql_quote($this->word).'%'; } + + function sql() + { + return '%' . $this->_sql_quote($this->word) . '%'; + } } class TextSearchQuery_node_all -extends TextSearchQuery_node { + extends TextSearchQuery_node +{ var $op = "ALL"; var $_op = TSQ_TOK_ALL; - function regexp() { return '(?=.*)'; } - function sql() { return '%'; } + + function regexp() + { + return '(?=.*)'; + } + + function sql() + { + return '%'; + } } class TextSearchQuery_node_starts_with -extends TextSearchQuery_node_word { + extends TextSearchQuery_node_word +{ var $op = "STARTS_WITH"; var $_op = TSQ_TOK_STARTS_WITH; - function regexp() { return '(?=.*\b' . preg_quote($this->word, '/') . ')'; } - function sql () { return $this->_sql_quote($this->word).'%'; } + + function regexp() + { + return '(?=.*\b' . preg_quote($this->word, '/') . ')'; + } + + function sql() + { + return $this->_sql_quote($this->word) . '%'; + } } // ^word: full phrase starts with class TextSearchQuery_phrase_starts_with -extends TextSearchQuery_node_starts_with { - function regexp() { return '(?=^' . preg_quote($this->word, '/') . ')'; } + extends TextSearchQuery_node_starts_with +{ + function regexp() + { + return '(?=^' . preg_quote($this->word, '/') . ')'; + } } class TextSearchQuery_node_ends_with -extends TextSearchQuery_node_word { + extends TextSearchQuery_node_word +{ var $op = "ENDS_WITH"; var $_op = TSQ_TOK_ENDS_WITH; - function regexp() { return '(?=.*' . preg_quote($this->word, '/') . '\b)'; } - function sql () { return '%'.$this->_sql_quote($this->word); } + + function regexp() + { + return '(?=.*' . preg_quote($this->word, '/') . '\b)'; + } + + function sql() + { + return '%' . $this->_sql_quote($this->word); + } } // word$: full phrase ends with class TextSearchQuery_phrase_ends_with -extends TextSearchQuery_node_ends_with { - function regexp() { return '(?=' . preg_quote($this->word, '/') . '$)'; } + extends TextSearchQuery_node_ends_with +{ + function regexp() + { + return '(?=' . preg_quote($this->word, '/') . '$)'; + } } class TextSearchQuery_node_exact -extends TextSearchQuery_node_word { + extends TextSearchQuery_node_word +{ var $op = "EXACT"; var $_op = TSQ_TOK_EXACT; - function regexp() { return '(?=\b' . preg_quote($this->word, '/') . '\b)'; } - function sql () { return $this->_sql_squote($this->word); } + + function regexp() + { + return '(?=\b' . preg_quote($this->word, '/') . '\b)'; + } + + function sql() + { + return $this->_sql_squote($this->word); + } } class TextSearchQuery_node_regex // posix regex. FIXME! -extends TextSearchQuery_node_word { + extends TextSearchQuery_node_word +{ var $op = "REGEX"; // using REGEXP or ~ extension var $_op = TSQ_TOK_REGEX; - function regexp() { return '(?=.*\b' . $this->word . '\b)'; } - function sql () { return $this->_sql_quote($this->word); } + + function regexp() + { + return '(?=.*\b' . $this->word . '\b)'; + } + + function sql() + { + return $this->_sql_quote($this->word); + } } class TextSearchQuery_node_regex_glob -extends TextSearchQuery_node_regex { + extends TextSearchQuery_node_regex +{ var $op = "REGEX_GLOB"; var $_op = TSQ_TOK_REGEX_GLOB; - function regexp() { return '(?=.*\b' . glob_to_pcre($this->word) . '\b)'; } + + function regexp() + { + return '(?=.*\b' . glob_to_pcre($this->word) . '\b)'; + } } class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i -extends TextSearchQuery_node_regex { + extends TextSearchQuery_node_regex +{ var $op = "REGEX_PCRE"; var $_op = TSQ_TOK_REGEX_PCRE; - function regexp() { return $this->word; } + + function regexp() + { + return $this->word; + } } class TextSearchQuery_node_regex_sql -extends TextSearchQuery_node_regex { + extends TextSearchQuery_node_regex +{ var $op = "REGEX_SQL"; // using LIKE var $_op = TSQ_TOK_REGEX_SQL; - function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); } - function sql() { return $this->word; } + + function regexp() + { + return str_replace(array("/%/", "/_/"), array(".*", "."), $this->word); + } + + function sql() + { + return $this->word; + } } /** * A negated clause. */ class TextSearchQuery_node_not -extends TextSearchQuery_node + extends TextSearchQuery_node { var $op = "NOT"; var $_op = TSQ_TOK_NOT; - function TextSearchQuery_node_not($leaf) { + function TextSearchQuery_node_not($leaf) + { $this->leaves = array($leaf); } - function optimize() { + function optimize() + { $leaf = &$this->leaves[0]; $leaf = $leaf->optimize(); if ($leaf->_op == TSQ_TOK_NOT) @@ -768,12 +915,14 @@ extends TextSearchQuery_node return $this; } - function regexp() { + function regexp() + { $leaf = &$this->leaves[0]; return '(?!' . $leaf->regexp() . ')'; } - function highlight_words ($negated = false) { + function highlight_words($negated = false) + { return $this->leaves[0]->highlight_words(!$negated); } } @@ -782,14 +931,17 @@ extends TextSearchQuery_node * Virtual base class for 'AND' and 'OR conjoins. */ class TextSearchQuery_node_binop -extends TextSearchQuery_node + extends TextSearchQuery_node { var $_op = TSQ_TOK_BINOP; - function TextSearchQuery_node_binop($leaves) { + + function TextSearchQuery_node_binop($leaves) + { $this->leaves = $leaves; } - function _flatten() { + function _flatten() + { // This flattens e.g. (AND (AND a b) (OR c d) e) // to (AND a b e (OR c d)) $flat = array(); @@ -803,7 +955,8 @@ extends TextSearchQuery_node $this->leaves = $flat; } - function optimize() { + function optimize() + { $this->_flatten(); assert(!empty($this->leaves)); if (count($this->leaves) == 1) @@ -811,11 +964,12 @@ extends TextSearchQuery_node return $this; } - function highlight_words($negated = false) { + function highlight_words($negated = false) + { $words = array(); foreach ($this->leaves as $leaf) - array_splice($words,0,0, - $leaf->highlight_words($negated)); + array_splice($words, 0, 0, + $leaf->highlight_words($negated)); return $words; } } @@ -824,11 +978,12 @@ extends TextSearchQuery_node * A (possibly multi-argument) 'AND' conjoin. */ class TextSearchQuery_node_and -extends TextSearchQuery_node_binop + extends TextSearchQuery_node_binop { var $op = "AND"; - function optimize() { + function optimize() + { $this->_flatten(); // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d). @@ -846,14 +1001,14 @@ extends TextSearchQuery_node_binop // Combine the negated leaves into a single negated or. if ($nots) { - $node = ( new TextSearchQuery_node_not - (new TextSearchQuery_node_or($nots)) ); + $node = (new TextSearchQuery_node_not + (new TextSearchQuery_node_or($nots))); array_unshift($this->leaves, $node->optimize()); } assert(!empty($this->leaves)); if (count($this->leaves) == 1) - return $this->leaves[0]; // (AND x) -> x + return $this->leaves[0]; // (AND x) -> x return $this; } @@ -862,7 +1017,8 @@ extends TextSearchQuery_node_binop * or we have to use multiple match calls for each AND * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/ */ - function regexp() { + function regexp() + { $regexp = ''; foreach ($this->leaves as $leaf) $regexp .= $leaf->regexp(); @@ -874,11 +1030,12 @@ extends TextSearchQuery_node_binop * A (possibly multi-argument) 'OR' conjoin. */ class TextSearchQuery_node_or -extends TextSearchQuery_node_binop + extends TextSearchQuery_node_binop { var $op = "OR"; - function regexp() { + function regexp() + { // We will combine any of our direct descendents which are WORDs // into a single (?=.*(?:word1|word2|...)) regexp. @@ -894,12 +1051,13 @@ extends TextSearchQuery_node_binop if ($words) array_unshift($regexps, - '(?=.*' . $this->_join($words) . ')'); + '(?=.*' . $this->_join($words) . ')'); return $this->_join($regexps); } - function _join($regexps) { + function _join($regexps) + { assert(count($regexps) > 0); if (count($regexps) > 1) @@ -956,7 +1114,8 @@ class TextSearchQuery_Parser * * ALL */ - function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) { + function parse($search_expr, $case_exact = false, $regex = TSQ_REGEX_AUTO) + { $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex); $this->_regex = $regex; $tree = $this->get_list('toplevel'); @@ -967,7 +1126,8 @@ class TextSearchQuery_Parser return $tree; } - function get_list ($is_toplevel = false) { + function get_list($is_toplevel = false) + { $list = array(); // token types we'll accept as words (and thus expr's) for the @@ -976,9 +1136,8 @@ class TextSearchQuery_Parser if ($is_toplevel) $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN; - while ( ($expr = $this->get_expr()) - || ($expr = $this->get_word($accept_as_words)) ) - { + while (($expr = $this->get_expr()) + || ($expr = $this->get_word($accept_as_words))) { $list[] = $expr; } @@ -997,14 +1156,15 @@ class TextSearchQuery_Parser return new TextSearchQuery_node_and($list); } - function get_expr () { - if ( ($expr = $this->get_atom()) === false ) // protect against '0' + function get_expr() + { + if (($expr = $this->get_atom()) === false) // protect against '0' return false; $savedpos = $this->lexer->tell(); // Bug#1791564: allow string '0' - while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) !== false) { - if ( ! ($right = $this->get_atom()) ) { + while (($op = $this->lexer->get(TSQ_TOK_BINOP)) !== false) { + if (!($right = $this->get_atom())) { break; } @@ -1023,51 +1183,52 @@ class TextSearchQuery_Parser } - function get_atom() { + function get_atom() + { if ($atom = $this->get_word(TSQ_ALLWORDS)) // Bug#1791564 not involved: '*' return $atom; $savedpos = $this->lexer->tell(); - if ( $this->lexer->get(TSQ_TOK_LPAREN) ) { - if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) ) { + if ($this->lexer->get(TSQ_TOK_LPAREN)) { + if (($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN)) { return $list; } else { // Fix Bug#1792170 // Handle " ( " or "(test" without closing ")" as plain word - $this->lexer->seek($savedpos); + $this->lexer->seek($savedpos); return new TextSearchQuery_node_word($this->lexer->get(-1)); } - } - elseif ( $this->lexer->get(TSQ_TOK_NOT) ) { - if ( ($atom = $this->get_atom()) ) + } elseif ($this->lexer->get(TSQ_TOK_NOT)) { + if (($atom = $this->get_atom())) return new TextSearchQuery_node_not($atom); } $this->lexer->seek($savedpos); return false; } - function get_word($accept = TSQ_ALLWORDS) { + function get_word($accept = TSQ_ALLWORDS) + { // Performance shortcut for ( and ). This is always false - if (!empty($this->lexer->tokens[$this->lexer->pos])) { - list ($type, $val) = $this->lexer->tokens[$this->lexer->pos]; - if ($type == TSQ_TOK_LPAREN or $type == TSQ_TOK_RPAREN) - return false; - } - foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT", - "REGEX","REGEX_GLOB","REGEX_PCRE","ALL") as $tok) { - $const = constant("TSQ_TOK_".$tok); + if (!empty($this->lexer->tokens[$this->lexer->pos])) { + list ($type, $val) = $this->lexer->tokens[$this->lexer->pos]; + if ($type == TSQ_TOK_LPAREN or $type == TSQ_TOK_RPAREN) + return false; + } + foreach (array("WORD", "STARTS_WITH", "ENDS_WITH", "EXACT", + "REGEX", "REGEX_GLOB", "REGEX_PCRE", "ALL") as $tok) { + $const = constant("TSQ_TOK_" . $tok); // Bug#1791564: allow word '0' - if ( $accept & $const and - (($word = $this->lexer->get($const)) !== false)) - { + if ($accept & $const and + (($word = $this->lexer->get($const)) !== false) + ) { // phrase or word level? if ($tok == 'STARTS_WITH' and $this->lexer->query_str[0] == '^') - $classname = "TextSearchQuery_phrase_".strtolower($tok); + $classname = "TextSearchQuery_phrase_" . strtolower($tok); elseif ($tok == 'ENDS_WITH' and - string_ends_with($this->lexer->query_str,'$')) - $classname = "TextSearchQuery_phrase_".strtolower($tok); - else - $classname = "TextSearchQuery_node_".strtolower($tok); + string_ends_with($this->lexer->query_str, '$') + ) + $classname = "TextSearchQuery_phrase_" . strtolower($tok); else + $classname = "TextSearchQuery_node_" . strtolower($tok); return new $classname($word); } } @@ -1075,24 +1236,28 @@ class TextSearchQuery_Parser } } -class TextSearchQuery_Lexer { - function TextSearchQuery_Lexer ($query_str, $case_exact=false, - $regex=TSQ_REGEX_AUTO) +class TextSearchQuery_Lexer +{ + function TextSearchQuery_Lexer($query_str, $case_exact = false, + $regex = TSQ_REGEX_AUTO) { $this->tokens = $this->tokenize($query_str, $case_exact, $regex); $this->query_str = $query_str; $this->pos = 0; } - function tell() { + function tell() + { return $this->pos; } - function seek($pos) { + function seek($pos) + { $this->pos = $pos; } - function eof() { + function eof() + { return $this->pos == count($this->tokens); } @@ -1100,88 +1265,81 @@ class TextSearchQuery_Lexer { * TODO: support more regex styles, esp. prefer the forced ones over auto * re: and // stuff */ - function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) { + function tokenize($string, $case_exact = false, $regex = TSQ_REGEX_AUTO) + { $tokens = array(); $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string)); while (!empty($buf)) { if (preg_match('/^([()])\s*/', $buf, $m)) { $val = $m[1]; $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN; - } - // * => ALL - elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB) - and preg_match('/^\*\s*/', $buf, $m)) { + } // * => ALL + elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_GLOB) + and preg_match('/^\*\s*/', $buf, $m) + ) { $val = "*"; $type = TSQ_TOK_ALL; - } - // .* => ALL + } // .* => ALL elseif ($regex & (TSQ_REGEX_PCRE) - and preg_match('/^\.\*\s*/', $buf, $m)) { + and preg_match('/^\.\*\s*/', $buf, $m) + ) { $val = ".*"; $type = TSQ_TOK_ALL; - } - // % => ALL + } // % => ALL elseif ($regex & (TSQ_REGEX_SQL) - and preg_match('/^%\s*/', $buf, $m)) { + and preg_match('/^%\s*/', $buf, $m) + ) { $val = "%"; $type = TSQ_TOK_ALL; - } - - // ^word - elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE) - and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) { + } // ^word + elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_PCRE) + and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m) + ) { $val = $m[1]; $type = TSQ_TOK_STARTS_WITH; - } - // word* - elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB) - and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) { + } // word* + elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_GLOB) + and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m) + ) { $val = $m[1]; $type = TSQ_TOK_STARTS_WITH; - } - // *word - elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB) - and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) { + } // *word + elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_GLOB) + and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m) + ) { $val = $m[1]; $type = TSQ_TOK_ENDS_WITH; - } - // word$ - elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE) - and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)) { + } // word$ + elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_PCRE) + and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m) + ) { $val = $m[1]; $type = TSQ_TOK_ENDS_WITH; - } - // ^word$ - elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE) - and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) { + } // ^word$ + elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_PCRE) + and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m) + ) { $val = $m[1]; $type = TSQ_TOK_EXACT; - } - elseif (preg_match('/^(and|or)\b\s*/i', $buf, $m)) { + } elseif (preg_match('/^(and|or)\b\s*/i', $buf, $m)) { $val = strtolower($m[1]); $type = TSQ_TOK_BINOP; - } - elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) { + } elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) { $val = strtolower($m[1]); $type = TSQ_TOK_NOT; - } - - // "words " + } // "words " elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) { $val = str_replace('""', '"', $m[1]); $type = TSQ_TOK_WORD; - } - // 'words ' + } // 'words ' elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) { $val = str_replace("''", "'", $m[1]); $type = TSQ_TOK_WORD; - } - // word + } // word elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) { $val = $m[1]; $type = TSQ_TOK_WORD; - } - else { + } else { assert(empty($buf)); break; } @@ -1202,7 +1360,8 @@ class TextSearchQuery_Lexer { return $tokens; } - function get($accept) { + function get($accept) + { if ($this->pos >= count($this->tokens)) return false; diff --git a/lib/Units.php b/lib/Units.php index d90129d87..e6e6694d9 100644 --- a/lib/Units.php +++ b/lib/Units.php @@ -21,41 +21,43 @@ * YYYY-MM-DD, "CW"ww/yy (CalendarWeek) */ -class Units { - function Units ($UNITSFILE = false) { +class Units +{ + function Units($UNITSFILE = false) + { if (DISABLE_UNITS) $this->errcode = 1; elseif (defined("UNITS_EXE")) // ignore dynamic check - $this->errcode = 0; - else + $this->errcode = 0; else exec("units m2", $o, $this->errcode); } /** * $this->_attribute_base = $units->Definition($this->_attribute); */ - function Definition ($query) { + function Definition($query) + { static $Definitions = array(); if (isset($Definitions[$query])) return $Definitions[$query]; if ($this->errcode) return $query; - $query = preg_replace("/,/","", $query); + $query = preg_replace("/,/", "", $query); if ($query == '' or $query == '*') return ($Definitions[$query] = ''); // detect date values, currently only ISO: YYYY-MM-DD or YY-MM-DD - if (preg_match("/^(\d{2,4})-(\d{1,2})-(\d{1,2})$/",$query, $m)) { - $date = mktime(0,0,0,$m[2],$m[3],$m[1]); + if (preg_match("/^(\d{2,4})-(\d{1,2})-(\d{1,2})$/", $query, $m)) { + $date = mktime(0, 0, 0, $m[2], $m[3], $m[1]); return ($Definitions[$query] = "$date date"); } - if (preg_match("/^(\d{2,4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{2}):?(\d{2})?$/",$query, $m)) { - $date = mktime($m[4],$m[5],@$m[6],$m[2],$m[3],$m[1]); + if (preg_match("/^(\d{2,4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{2}):?(\d{2})?$/", $query, $m)) { + $date = mktime($m[4], $m[5], @$m[6], $m[2], $m[3], $m[1]); return ($Definitions[$query] = "$date date"); } $def = $this->_cmd("\"$query\""); - if (preg_match("/Definition: (.+)$/",$def,$m)) + if (preg_match("/Definition: (.+)$/", $def, $m)) return ($Definitions[$query] = $m[1]); else { - trigger_error("units: ". $def, E_USER_WARNING); + trigger_error("units: " . $def, E_USER_WARNING); return ''; } } @@ -65,12 +67,13 @@ class Units { * We cannot compare m^2 to m or '' * $val_base = $this->_units->basevalue($value); // SemanticAttributeSearchQuery */ - function basevalue($query, $def = false) { + function basevalue($query, $def = false) + { if (!$def) $def = $this->Definition($query); if ($def) { if (is_numeric($def)) // e.g. "1 million" return $def; - if (preg_match("/^([-0-9].*) \w.*$/",$def,$m)) + if (preg_match("/^([-0-9].*) \w.*$/", $def, $m)) return $m[1]; } return ''; @@ -80,19 +83,21 @@ class Units { * $this->_unit = $units->baseunit($this->_attribute); // SemanticAttributeSearchQuery * and Cached_SemanticLink::_expandurl() */ - function baseunit($query, $def = false) { + function baseunit($query, $def = false) + { if (!$def) $def = $this->Definition($query); if ($def) { - if (preg_match("/ (.+)$/",$def,$m)) - return $m[1]; + if (preg_match("/ (.+)$/", $def, $m)) + return $m[1]; } return ''; } - function _cmd($args) { + function _cmd($args) + { if ($this->errcode) return $args; if (defined("UNITS_EXE")) { - $s = UNITS_EXE ." $args"; + $s = UNITS_EXE . " $args"; $result = `$s`; } else $result = `units $args`; diff --git a/lib/WikiCallback.php b/lib/WikiCallback.php index 7d5851e28..dba06c56f 100644 --- a/lib/WikiCallback.php +++ b/lib/WikiCallback.php @@ -26,7 +26,8 @@ class WikiCallback * @return object Returns the appropriate subclass of WikiCallback. * @access public */ - function callback ($pearCb) { + function callback($pearCb) + { if (is_string($pearCb)) return new WikiFunctionCb($pearCb); else if (is_array($pearCb)) { @@ -44,7 +45,8 @@ class WikiCallback * @return mixed The return value of the callback. * @access public */ - function call () { + function call() + { return $this->call_array(func_get_args()); } @@ -56,7 +58,8 @@ class WikiCallback * @see call_user_func_array. * @access public */ - function call_array ($args) { + function call_array($args) + { trigger_error('pure virtual', E_USER_ERROR); } @@ -68,7 +71,8 @@ class WikiCallback * to a number of different Pear functions and methods.) * @access public */ - function toPearCb() { + function toPearCb() + { trigger_error('pure virtual', E_USER_ERROR); } } @@ -85,15 +89,18 @@ class WikiFunctionCb * @param $functionName string Name of global function to call. * @access public */ - function WikiFunctionCb ($functionName) { + function WikiFunctionCb($functionName) + { $this->functionName = $functionName; } - function call_array ($args) { + function call_array($args) + { return call_user_func_array($this->functionName, $args); } - function toPearCb() { + function toPearCb() + { return $this->functionName; } } @@ -111,17 +118,20 @@ class WikiMethodCb * @param $methodName string Name of method to call. * @access public */ - function WikiMethodCb(&$object, $methodName) { + function WikiMethodCb(&$object, $methodName) + { $this->object = &$object; $this->methodName = $methodName; } - function call_array ($args) { + function call_array($args) + { $method = &$this->methodName; return call_user_func_array(array(&$this->object, $method), $args); } - function toPearCb() { + function toPearCb() + { return array($this->object, $this->methodName); } } @@ -140,17 +150,20 @@ class WikiAnonymousCb * @see create_function(). * @access public */ - function WikiAnonymousCb ($args, $code) { + function WikiAnonymousCb($args, $code) + { $this->function = create_function($args, $code); } - function call_array ($args) { + function call_array($args) + { return call_user_func_array($this->function, $args); } - function toPearCb() { + function toPearCb() + { trigger_error("Can't convert WikiAnonymousCb to Pear callback", - E_USER_ERROR); + E_USER_ERROR); } } diff --git a/lib/WikiDB.php b/lib/WikiDB.php index 201baec81..76adbcb74 100644 --- a/lib/WikiDB.php +++ b/lib/WikiDB.php @@ -38,7 +38,8 @@ if (!defined('WIKIDB_FORCE_CREATE')) * only create new revisions or delete old ones --- one can not modify * an existing revision. */ -class WikiDB { +class WikiDB +{ /** * Open a WikiDB database. * @@ -97,7 +98,8 @@ class WikiDB { * * @return WikiDB A WikiDB object. **/ - function open ($dbparams) { + function open($dbparams) + { $dbtype = $dbparams{'dbtype'}; include_once("lib/WikiDB/$dbtype.php"); @@ -111,7 +113,8 @@ class WikiDB { * @access private * @see open() */ - function WikiDB (&$backend, $dbparams) { + function WikiDB(&$backend, $dbparams) + { $this->_backend =& $backend; // don't do the following with the auth_dsn! if (isset($dbparams['auth_dsn'])) return; @@ -142,7 +145,8 @@ class WikiDB { * * @access public */ - function close () { + function close() + { $this->_backend->close(); $this->_cache->close(); } @@ -157,9 +161,10 @@ class WikiDB { * @param string $pagename Which page to get. * @return WikiDB_Page The requested WikiDB_Page. */ - function getPage($pagename) { + function getPage($pagename) + { static $error_displayed = false; - $pagename = (string) $pagename; + $pagename = (string)$pagename; if ((int)DEBUG) { if ($pagename === '') { if ($error_displayed) return false; @@ -195,7 +200,8 @@ class WikiDB { * @return boolean True if the page actually exists with * non-default contents in the WikiDataBase. */ - function isWikiPage ($pagename) { + function isWikiPage($pagename) + { $page = $this->getPage($pagename); return ($page and $page->exists()); } @@ -212,8 +218,12 @@ class WikiDB { * @param string $pagename Name of page to delete. * @see purgePage */ - function deletePage($pagename) { - if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } + function deletePage($pagename) + { + if (!empty($this->readonly)) { + trigger_error("readonly database", E_USER_WARNING); + return; + } // don't create empty revisions of already purged pages. if ($this->_backend->get_latest_version($pagename)) $result = $this->_cache->delete_page($pagename); @@ -224,7 +234,7 @@ class WikiDB { if (ENABLE_MAILNOTIFY) { include_once 'lib/MailNotify.php'; $MailNotify = new MailNotify($pagename); - $MailNotify->onDeletePage ($this, $pagename); + $MailNotify->onDeletePage($this, $pagename); } //How to create a RecentChanges entry with explaining summary? Dynamically @@ -245,8 +255,12 @@ class WikiDB { * @param string $pagename Name of page to delete. * @see deletePage */ - function purgePage($pagename) { - if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } + function purgePage($pagename) + { + if (!empty($this->readonly)) { + trigger_error("readonly database", E_USER_WARNING); + return; + } $result = $this->_cache->purge_page($pagename); $this->deletePage($pagename); // just for the notification return $result; @@ -272,15 +286,15 @@ class WikiDB { * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages * in the WikiDB which have non-default contents. */ - function getAllPages($include_empty=false, $sortby='', $limit='', $exclude='') + function getAllPages($include_empty = false, $sortby = '', $limit = '', $exclude = '') { $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit, - $exclude); + $exclude); return new WikiDB_PageIterator($this, $result, - array('include_empty' => $include_empty, - 'exclude' => $exclude, - 'limit_by_db' => $result->_options['limit_by_db'], - 'limit' => $result->limit())); + array('include_empty' => $include_empty, + 'exclude' => $exclude, + 'limit_by_db' => $result->_options['limit_by_db'], + 'limit' => $result->limit())); } /** @@ -292,7 +306,8 @@ class WikiDB { * @return integer * */ - function numPages($include_empty=false, $exclude='') { + function numPages($include_empty = false, $exclude = '') + { if (method_exists($this->_backend, 'numPages')) // FIXME: currently are all args ignored. $count = $this->_backend->numPages($include_empty, $exclude); @@ -325,10 +340,11 @@ class WikiDB { * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages. * @see TextSearchQuery */ - function titleSearch($search, $sortby='pagename', $limit='', $exclude='') { + function titleSearch($search, $sortby = 'pagename', $limit = '', $exclude = '') + { $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude); $options = array('exclude' => $exclude, - 'limit' => $limit); + 'limit' => $limit); //if (isset($result->_count)) $options['count'] = $result->_count; return new WikiDB_PageIterator($this, $result, $options); } @@ -355,13 +371,14 @@ class WikiDB { * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages. * @see TextSearchQuery */ - function fullSearch($search, $sortby='pagename', $limit='', $exclude='') { + function fullSearch($search, $sortby = 'pagename', $limit = '', $exclude = '') + { $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude); return new WikiDB_PageIterator($this, $result, - array('exclude' => $exclude, - 'limit' => $limit, - 'stoplisted' => $result->stoplisted - )); + array('exclude' => $exclude, + 'limit' => $limit, + 'stoplisted' => $result->stoplisted + )); } /** @@ -380,7 +397,8 @@ class WikiDB { * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching * pages. */ - function mostPopular($limit = 20, $sortby = '-hits') { + function mostPopular($limit = 20, $sortby = '-hits') + { $result = $this->_backend->most_popular($limit, $sortby); return new WikiDB_PageIterator($this, $result); } @@ -414,7 +432,8 @@ class WikiDB { * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator * containing the matching revisions. */ - function mostRecent($params = false) { + function mostRecent($params = false) + { $result = $this->_backend->most_recent($params); return new WikiDB_PageRevisionIterator($this, $result); } @@ -429,7 +448,8 @@ class WikiDB { * @return Iterator A generic iterator containing rows of * (duplicate) pagename, wantedfrom. */ - function wantedPages($exclude_from='', $exclude='', $sortby='', $limit='') { + function wantedPages($exclude_from = '', $exclude = '', $sortby = '', $limit = '') + { return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit); //return new WikiDB_PageIterator($this, $result); } @@ -460,7 +480,8 @@ class WikiDB { * @return Iterator A generic iterator containing links to pages or values. * hash of "pagename", "linkname", "linkvalue. */ - function linkSearch($pages, $search, $linktype, $relation=false) { + function linkSearch($pages, $search, $linktype, $relation = false) + { return $this->_backend->link_search($pages, $search, $linktype, $relation); } @@ -472,7 +493,8 @@ class WikiDB { * * @return array of strings */ - function listRelations($also_attributes=false, $only_attributes=false, $sorted=true) { + function listRelations($also_attributes = false, $only_attributes = false, $sorted = true) + { if (method_exists($this->_backend, "list_relations")) return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted); // dumb, slow fallback. no iter, so simply define it here. @@ -482,7 +504,7 @@ class WikiDB { $reliter = $page->getRelations(); $names = array(); while ($rel = $reliter->next()) { - // if there's no pagename it's an attribute + // if there's no pagename it's an attribute $names[] = $rel->getName(); } $relations = array_merge($relations, $names); @@ -505,8 +527,12 @@ class WikiDB { * @param boolean $updateWikiLinks If the text in all pages should be replaced. * @return boolean true or false */ - function renamePage($from, $to, $updateWikiLinks = false) { - if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } + function renamePage($from, $to, $updateWikiLinks = false) + { + if (!empty($this->readonly)) { + trigger_error("readonly database", E_USER_WARNING); + return; + } assert(is_string($from) && $from != ''); assert(is_string($to) && $to != ''); $result = false; @@ -522,25 +548,25 @@ class WikiDB { $links = $oldpage->getBackLinks(); while ($linked_page = $links->next()) { WikiPlugin_WikiAdminSearchReplace::replaceHelper - ($this, - $linked_page->getName(), - $lookbehind.$from.$lookahead, $to, - true, true); + ($this, + $linked_page->getName(), + $lookbehind . $from . $lookahead, $to, + true, true); } // FIXME: Disabled to avoid recursive modification when renaming // a page like 'PageFoo to 'PageFooTwo' if (0) { - $links = $newpage->getBackLinks(); - while ($linked_page = $links->next()) { - WikiPlugin_WikiAdminSearchReplace::replaceHelper - ($this, - $linked_page->getName(), - $lookbehind.$from.$lookahead, $to, - true, true); - } + $links = $newpage->getBackLinks(); + while ($linked_page = $links->next()) { + WikiPlugin_WikiAdminSearchReplace::replaceHelper + ($this, + $linked_page->getName(), + $lookbehind . $from . $lookahead, $to, + true, true); + } } } - if ($oldpage->exists() and ! $newpage->exists()) { + if ($oldpage->exists() and !$newpage->exists()) { if ($result = $this->_backend->rename_page($from, $to)) { // create a RecentChanges entry with explaining summary $page = $this->getPage($to); @@ -557,7 +583,7 @@ class WikiDB { } } else { trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"), - E_USER_WARNING); + E_USER_WARNING); } /* Generate notification emails? */ if ($result and ENABLE_MAILNOTIFY and !isa($GLOBALS['request'], 'MockRequest')) { @@ -565,7 +591,7 @@ class WikiDB { if (!empty($notify) and is_array($notify)) { include_once 'lib/MailNotify.php'; $MailNotify = new MailNotify($from); - $MailNotify->onRenamePage ($this, $from, $to); + $MailNotify->onRenamePage($this, $from, $to); } } return $result; @@ -582,7 +608,8 @@ class WikiDB { * int to get a timestamp, or you can use the string value * as a good hash for the entire database. */ - function getTimestamp() { + function getTimestamp() + { $ts = $this->get('_timestamp'); return sprintf("%d %d", $ts[0], $ts[1]); } @@ -591,7 +618,8 @@ class WikiDB { * Update the database timestamp. * */ - function touch() { + function touch() + { $ts = $this->get('_timestamp'); $this->set('_timestamp', array(time(), $ts[1] + 1)); } @@ -599,10 +627,13 @@ class WikiDB { /** * Roughly similar to the float in phpwiki_version(). Set by action=upgrade. */ - function get_db_version() { - return (float) $this->get('_db_version'); + function get_db_version() + { + return (float)$this->get('_db_version'); } - function set_db_version($ver) { + + function set_db_version($ver) + { return $this->set('_db_version', (float)$ver); } @@ -623,7 +654,8 @@ class WikiDB { * @return scalar The requested value, or false if the requested data * is not set. */ - function get($key) { + function get($key) + { if (!$key || $key[0] == '%') return false; /* @@ -651,8 +683,12 @@ class WikiDB { * @param string $key Meta-data key to set. * @param string $newval New value. */ - function set($key, $newval) { - if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } + function set($key, $newval) + { + if (!empty($this->readonly)) { + trigger_error("readonly database", E_USER_WARNING); + return; + } if (!$key || $key[0] == '%') return; @@ -673,7 +709,8 @@ class WikiDB { // SQL result: for simple select or create/update queries // returns the database specific resource type - function genericSqlQuery($sql, $args=false) { + function genericSqlQuery($sql, $args = false) + { echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n"; trigger_error("no SQL database", E_USER_ERROR); return false; @@ -681,7 +718,8 @@ class WikiDB { // SQL iter: for simple select or create/update queries // returns the generic iterator object (count,next) - function genericSqlIter($sql, $field_list = NULL) { + function genericSqlIter($sql, $field_list = NULL) + { echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n"; trigger_error("no SQL database", E_USER_ERROR); return false; @@ -689,32 +727,35 @@ class WikiDB { // see backend upstream methods // ADODB adds surrounding quotes, SQL not yet! - function quote ($s) { + function quote($s) + { return $s; } - function isOpen () { + function isOpen() + { global $request; if (!$request->_dbi) return false; else return false; /* so far only needed for sql so false it. later we have to check dba also */ } - function getParam($param) { + function getParam($param) + { global $DBParams; if (isset($DBParams[$param])) return $DBParams[$param]; - elseif ($param == 'prefix') return ''; - else return false; + elseif ($param == 'prefix') return ''; else return false; } - function getAuthParam($param) { + function getAuthParam($param) + { global $DBAuthParams; if (isset($DBAuthParams[$param])) return $DBAuthParams[$param]; - elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER']; - elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY']; - else return false; + elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER']; elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY']; else return false; } -}; +} + +; /** @@ -726,13 +767,15 @@ class WikiDB { */ class WikiDB_Page { - function WikiDB_Page(&$wikidb, $pagename) { + function WikiDB_Page(&$wikidb, $pagename) + { $this->_wikidb = &$wikidb; $this->_pagename = $pagename; if ((int)DEBUG) { if (!(is_string($pagename) and $pagename != '')) { if (function_exists("xdebug_get_function_stack")) { - echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack()); + echo "xdebug_get_function_stack(): "; + var_dump(xdebug_get_function_stack()); } else { printSimpleTrace(debug_backtrace()); } @@ -751,18 +794,20 @@ class WikiDB_Page * * @return string The page name. */ - function getName() { + function getName() + { return $this->_pagename; } // To reduce the memory footprint for larger sets of pagelists, // we don't cache the content (only true or false) and // we purge the pagedata (_cached_html) also - function exists() { + function exists() + { if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true; $current = $this->getCurrentRevision(false); if (!$current) return false; - return ! $current->hasDefaultContents(); + return !$current->hasDefaultContents(); } /** @@ -776,8 +821,12 @@ class WikiDB_Page * @param integer $version Which revision to delete. (You can also * use a WikiDB_PageRevision object here.) */ - function deleteRevision($version) { - if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; } + function deleteRevision($version) + { + if ($this->_wikidb->readonly) { + trigger_error("readonly database", E_USER_WARNING); + return; + } $backend = &$this->_wikidb->_backend; $cache = &$this->_wikidb->_cache; $pagename = &$this->_pagename; @@ -786,17 +835,17 @@ class WikiDB_Page if ($version == 0) return; - $backend->lock(array('page','version')); + $backend->lock(array('page', 'version')); $latestversion = $cache->get_latest_version($pagename); if ($latestversion && ($version == $latestversion)) { - $backend->unlock(array('page','version')); + $backend->unlock(array('page', 'version')); trigger_error(sprintf("Attempt to delete most recent revision of '%s'", - $pagename), E_USER_ERROR); + $pagename), E_USER_ERROR); return; } $cache->delete_versiondata($pagename, $version); - $backend->unlock(array('page','version')); + $backend->unlock(array('page', 'version')); } /* @@ -826,8 +875,12 @@ class WikiDB_Page * <li>It has the same author as the immediately preceding revision. * </ul> */ - function mergeRevision($version) { - if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; } + function mergeRevision($version) + { + if ($this->_wikidb->readonly) { + trigger_error("readonly database", E_USER_WARNING); + return; + } $backend = &$this->_wikidb->_backend; $cache = &$this->_wikidb->_cache; $pagename = &$this->_pagename; @@ -841,7 +894,7 @@ class WikiDB_Page if ($latestversion && $version == $latestversion) { $backend->unlock(array('version')); trigger_error(sprintf("Attempt to merge most recent revision of '%s'", - $pagename), E_USER_ERROR); + $pagename), E_USER_ERROR); return; } @@ -861,8 +914,8 @@ class WikiDB_Page // by the same author. We will merge the // revisions. $cache->update_versiondata($pagename, $previous, - array('%content' => $versiondata['%content'], - '_supplanted' => $versiondata['_supplanted'])); + array('%content' => $versiondata['%content'], + '_supplanted' => $versiondata['_supplanted'])); } } } @@ -893,21 +946,25 @@ class WikiDB_Page * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If * $version was incorrect, returns false */ - function createRevision($version, &$content, $metadata, $links) { - if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; } + function createRevision($version, &$content, $metadata, $links) + { + if ($this->_wikidb->readonly) { + trigger_error("readonly database", E_USER_WARNING); + return; + } $backend = &$this->_wikidb->_backend; $cache = &$this->_wikidb->_cache; $pagename = &$this->_pagename; $cache->invalidate_cache($pagename); - $backend->lock(array('version','page','recent','link','nonempty')); + $backend->lock(array('version', 'page', 'recent', 'link', 'nonempty')); $latestversion = $backend->get_latest_version($pagename); $newversion = ($latestversion ? $latestversion : 0) + 1; assert($newversion >= 1); if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) { - $backend->unlock(array('version','page','recent','link','nonempty')); + $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty')); return false; } @@ -930,8 +987,8 @@ class WikiDB_Page $pdata = $cache->get_versiondata($pagename, $latestversion); if ($data['mtime'] < $pdata['mtime']) { trigger_error(sprintf(_("%s: Date of new revision is %s"), - $pagename,"'non-monotonic'"), - E_USER_NOTICE); + $pagename, "'non-monotonic'"), + E_USER_NOTICE); $data['orig_mtime'] = $data['mtime']; $data['mtime'] = $pdata['mtime']; } @@ -939,7 +996,7 @@ class WikiDB_Page // FIXME: use (possibly user specified) 'mtime' time or // time()? $cache->update_versiondata($pagename, $latestversion, - array('_supplanted' => $data['mtime'])); + array('_supplanted' => $data['mtime'])); } $data['%content'] = &$content; @@ -951,10 +1008,10 @@ class WikiDB_Page $backend->set_links($pagename, $links); - $backend->unlock(array('version','page','recent','link','nonempty')); + $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty')); return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion, - $data); + $data); } /** A higher-level interface to createRevision. @@ -972,8 +1029,12 @@ class WikiDB_Page * * @param hash $meta Meta-data for new revision. */ - function save($wikitext, $version, $meta, $formatted = null) { - if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; } + function save($wikitext, $version, $meta, $formatted = null) + { + if ($this->_wikidb->readonly) { + trigger_error("readonly database", E_USER_WARNING); + return; + } if (is_null($formatted)) $formatted = new TransformedText($this, $wikitext, $meta); $type = $formatted->getType(); @@ -998,8 +1059,9 @@ class WikiDB_Page // We're doing this here rather than in createRevision because // postgresql can't optimize while locked. if (((int)DEBUG & _DEBUG_SQL) - or (DATABASE_OPTIMISE_FREQUENCY > 0 and - (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) { + or (DATABASE_OPTIMISE_FREQUENCY > 0 and + (time() % DATABASE_OPTIMISE_FREQUENCY == 0)) + ) { if ($backend->optimize()) { if ((int)DEBUG) trigger_error(_("Optimizing database"), E_USER_NOTICE); @@ -1012,20 +1074,20 @@ class WikiDB_Page $notify = $this->_wikidb->get('notify'); if (!empty($notify) and is_array($notify) - and !isa($GLOBALS['request'],'MockRequest')) - { + and !isa($GLOBALS['request'], 'MockRequest') + ) { include_once 'lib/MailNotify.php'; $MailNotify = new MailNotify($newrevision->getName()); - $MailNotify->onChangePage ($this->_wikidb, $wikitext, $version, $meta); + $MailNotify->onChangePage($this->_wikidb, $wikitext, $version, $meta); } $newrevision->_transformedContent = $formatted; } // more pagechange callbacks: (in a hackish manner for now) if (ENABLE_RECENTCHANGESBOX and empty($meta['is_minor_edit']) - and !in_array($GLOBALS['request']->getArg('action'), - array('loadfile','upgrade'))) - { + and !in_array($GLOBALS['request']->getArg('action'), + array('loadfile', 'upgrade')) + ) { require_once 'lib/WikiPlugin.php'; $w = new WikiPluginLoader; $p = $w->getPlugin("RecentChangesCached", false); @@ -1041,7 +1103,8 @@ class WikiDB_Page * * @return WikiDB_PageRevision The current WikiDB_PageRevision object. */ - function getCurrentRevision ($need_content=true) { + function getCurrentRevision($need_content = true) + { $backend = &$this->_wikidb->_backend; $cache = &$this->_wikidb->_cache; $pagename = &$this->_pagename; @@ -1072,7 +1135,8 @@ class WikiDB_Page * false if the requested revision does not exist in the {@link WikiDB}. * Note that version zero of any page always exists. */ - function getRevision ($version, $need_content=true) { + function getRevision($version, $need_content = true) + { $cache = &$this->_wikidb->_cache; $pagename = &$this->_pagename; @@ -1086,7 +1150,7 @@ class WikiDB_Page return new WikiDB_PageRevision($this->_wikidb, $pagename, 0); } return new WikiDB_PageRevision($this->_wikidb, $pagename, $version, - $vdata); + $vdata); } /** @@ -1105,7 +1169,8 @@ class WikiDB_Page * unless $version is greater than zero, a revision (perhaps version zero, * the default revision) will always be found. */ - function getRevisionBefore ($version=false, $need_content=true) { + function getRevisionBefore($version = false, $need_content = true) + { $backend = &$this->_wikidb->_backend; $pagename = &$this->_pagename; if ($version === false) @@ -1133,7 +1198,8 @@ class WikiDB_Page * WikiDB_PageRevisionIterator containing all revisions of this * WikiDB_Page in reverse order by version number. */ - function getAllRevisions() { + function getAllRevisions() + { $backend = &$this->_wikidb->_backend; $revs = $backend->get_all_revisions($this->_pagename); return new WikiDB_PageRevisionIterator($this->_wikidb, $revs); @@ -1152,61 +1218,65 @@ class WikiDB_Page * @return WikiDB_PageIterator A WikiDB_PageIterator containing * all matching pages. */ - function getLinks ($reversed=true, $include_empty=false, $sortby='', - $limit='', $exclude='', $want_relations=false) + function getLinks($reversed = true, $include_empty = false, $sortby = '', + $limit = '', $exclude = '', $want_relations = false) { $backend = &$this->_wikidb->_backend; - $result = $backend->get_links($this->_pagename, $reversed, - $include_empty, $sortby, $limit, $exclude, - $want_relations); + $result = $backend->get_links($this->_pagename, $reversed, + $include_empty, $sortby, $limit, $exclude, + $want_relations); return new WikiDB_PageIterator($this->_wikidb, $result, - array('include_empty' => $include_empty, - 'sortby' => $sortby, - 'limit' => $limit, - 'exclude' => $exclude, - 'want_relations'=> $want_relations)); + array('include_empty' => $include_empty, + 'sortby' => $sortby, + 'limit' => $limit, + 'exclude' => $exclude, + 'want_relations' => $want_relations)); } /** * All Links from other pages to this page. */ - function getBackLinks($include_empty=false, $sortby='', $limit='', $exclude='', - $want_relations=false) + function getBackLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '', + $want_relations = false) { return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude); } + /** * Forward Links: All Links from this page to other pages. */ - function getPageLinks($include_empty=false, $sortby='', $limit='', $exclude='', - $want_relations=false) + function getPageLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '', + $want_relations = false) { return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude); } + /** * Relations: All links from this page to other pages with relation <> 0. * is_a:=page or population:=number */ - function getRelations($sortby='', $limit='', $exclude='') { + function getRelations($sortby = '', $limit = '', $exclude = '') + { $backend = &$this->_wikidb->_backend; - $result = $backend->get_links($this->_pagename, false, true, - $sortby, $limit, $exclude, - true); + $result = $backend->get_links($this->_pagename, false, true, + $sortby, $limit, $exclude, + true); // we do not care for the linked page versiondata, just the pagename and linkrelation return new WikiDB_PageIterator($this->_wikidb, $result, - array('include_empty' => true, - 'sortby' => $sortby, - 'limit' => $limit, - 'exclude' => $exclude, - 'want_relations'=> true)); + array('include_empty' => true, + 'sortby' => $sortby, + 'limit' => $limit, + 'exclude' => $exclude, + 'want_relations' => true)); } /** * possibly faster link existance check. not yet accelerated. */ - function existLink($link, $reversed=false) { + function existLink($link, $reversed = false) + { $backend = &$this->_wikidb->_backend; - if (method_exists($backend,'exists_link')) + if (method_exists($backend, 'exists_link')) return $backend->exists_link($this->_pagename, $link, $reversed); //$cache = &$this->_wikidb->_cache; // TODO: check cache if it is possible @@ -1249,14 +1319,15 @@ class WikiDB_Page * E.g. "owner.users" * <dt>'perm' <dd> Permission flag to authorize read/write/execution of * page-headers and content. - + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage + + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt * </dl> * * @return scalar The requested value, or false if the requested data * is not set. */ - function get($key) { + function get($key) + { $cache = &$this->_wikidb->_cache; $backend = &$this->_wikidb->_backend; if (!$key || $key[0] == '%') @@ -1264,8 +1335,8 @@ class WikiDB_Page // several new SQL backends optimize this. if (!WIKIDB_NOCACHE_MARKUP and $key == '_cached_html' - and method_exists($backend, 'get_cached_html')) - { + and method_exists($backend, 'get_cached_html') + ) { return $backend->get_cached_html($this->_pagename); } $data = $cache->get_pagedata($this->_pagename); @@ -1277,12 +1348,15 @@ class WikiDB_Page * * @return hash The page meta-data. */ - function getMetaData() { + function getMetaData() + { $cache = &$this->_wikidb->_cache; $data = $cache->get_pagedata($this->_pagename); $meta = array(); foreach ($data as $key => $val) { - if (/*!empty($val) &&*/ $key[0] != '%') + if ( /*!empty($val) &&*/ + $key[0] != '%' + ) $meta[$key] = $val; } return $meta; @@ -1297,7 +1371,8 @@ class WikiDB_Page * @param string $key Meta-data key to set. * @param string $newval New value. */ - function set($key, $newval) { + function set($key, $newval) + { $cache = &$this->_wikidb->_cache; $backend = &$this->_wikidb->_backend; $pagename = &$this->_pagename; @@ -1307,9 +1382,12 @@ class WikiDB_Page // several new SQL backends optimize this. if (!WIKIDB_NOCACHE_MARKUP and $key == '_cached_html' - and method_exists($backend, 'set_cached_html')) - { - if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; } + and method_exists($backend, 'set_cached_html') + ) { + if ($this->_wikidb->readonly) { + trigger_error("readonly database", E_USER_WARNING); + return; + } return $backend->set_cached_html($pagename, $newval); } @@ -1317,11 +1395,10 @@ class WikiDB_Page if (!empty($newval)) { if (!empty($data[$key]) && $data[$key] == $newval) - return; // values identical, skip update. - } - else { + return; // values identical, skip update. + } else { if (empty($data[$key])) - return; // values identical, skip update. + return; // values identical, skip update. } if (isset($this->_wikidb->readonly) and ($this->_wikidb->readonly)) { @@ -1347,8 +1424,12 @@ class WikiDB_Page * * @access public */ - function increaseHitCount() { - if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_NOTICE); return; } + function increaseHitCount() + { + if ($this->_wikidb->readonly) { + trigger_error("readonly database", E_USER_NOTICE); + return; + } if (method_exists($this->_wikidb->_backend, 'increaseHitCount')) $this->_wikidb->_backend->increaseHitCount($this->_pagename); else { @@ -1366,7 +1447,8 @@ class WikiDB_Page * * @return string Printable representation of the WikiDB_Page. */ - function asString () { + function asString() + { ob_start(); printf("[%s:%s\n", get_class($this), $this->getName()); print_r($this->getMetaData()); @@ -1384,31 +1466,34 @@ class WikiDB_Page * object. * @return integer The version number. */ - function _coerce_to_version($version_or_pagerevision) { + function _coerce_to_version($version_or_pagerevision) + { if (method_exists($version_or_pagerevision, "getContent")) $version = $version_or_pagerevision->getVersion(); else - $version = (int) $version_or_pagerevision; + $version = (int)$version_or_pagerevision; assert($version >= 0); return $version; } - function isUserPage ($include_empty = true) { + function isUserPage($include_empty = true) + { if (!$include_empty and !$this->exists()) return false; return $this->get('pref') ? true : false; } // May be empty. Either the stored owner (/Chown), or the first authorized author - function getOwner() { + function getOwner() + { if ($owner = $this->get('owner')) return $owner; // check all revisions forwards for the first author_id $backend = &$this->_wikidb->_backend; $pagename = &$this->_pagename; $latestversion = $backend->get_latest_version($pagename); - for ($v=1; $v <= $latestversion; $v++) { - $rev = $this->getRevision($v,false); + for ($v = 1; $v <= $latestversion; $v++) { + $rev = $this->getRevision($v, false); if ($rev and $owner = $rev->get('author_id')) { return $owner; } @@ -1417,13 +1502,15 @@ class WikiDB_Page } // The authenticated author of the first revision or empty if not authenticated then. - function getCreator() { - if ($current = $this->getRevision(1,false)) return $current->get('author_id'); + function getCreator() + { + if ($current = $this->getRevision(1, false)) return $current->get('author_id'); else return ''; } // The authenticated author of the current revision. - function getAuthor() { + function getAuthor() + { if ($current = $this->getCurrentRevision(false)) return $current->get('author_id'); else return ''; } @@ -1431,7 +1518,8 @@ class WikiDB_Page /* Semantic Web value, not stored in the links. * todo: unify with some unit knowledge */ - function setAttribute($relation, $value) { + function setAttribute($relation, $value) + { $attr = $this->get('attributes'); if (empty($attr)) $attr = array($relation => $value); @@ -1440,7 +1528,8 @@ class WikiDB_Page $this->set('attributes', $attr); } - function getAttribute($relation) { + function getAttribute($relation) + { $meta = $this->get('attributes'); if (empty($meta)) return ''; @@ -1448,7 +1537,9 @@ class WikiDB_Page return $meta[$relation]; } -}; +} + +; /** * This class represents a specific revision of a WikiDB_Page within @@ -1479,7 +1570,8 @@ class WikiDB_PageRevision * * @return WikiDB_Page The WikiDB_Page which this revision belongs to. */ - function getPage() { + function getPage() + { return new WikiDB_Page($this->_wikidb, $this->_pagename); } @@ -1490,7 +1582,8 @@ class WikiDB_PageRevision * * @return integer The version number of this revision. */ - function getVersion() { + function getVersion() + { return $this->_version; } @@ -1508,7 +1601,8 @@ class WikiDB_PageRevision * * @return boolean Returns true if the page has default content. */ - function hasDefaultContents() { + function hasDefaultContents() + { $data = &$this->_data; if (!isset($data['%content'])) return true; if ($data['%content'] === true) return false; @@ -1523,21 +1617,25 @@ class WikiDB_PageRevision * @return array An array of lines. * The lines should contain no trailing white space. */ - function getContent() { + function getContent() + { return explode("\n", $this->getPackedContent()); } - /** + /** * Get the pagename of the revision. * * @access public * * @return string pagename. */ - function getPageName() { + function getPageName() + { return $this->_pagename; } - function getName() { + + function getName() + { return $this->_pagename; } @@ -1548,7 +1646,8 @@ class WikiDB_PageRevision * * @return boolean True iff the revision is the latest (most recent) one. */ - function isCurrent() { + function isCurrent() + { if (!isset($this->_iscurrent)) { $page = $this->getPage(); $current = $page->getCurrentRevision(false); @@ -1565,7 +1664,8 @@ class WikiDB_PageRevision * @return object An XmlContent-like object containing the page transformed * contents. */ - function getTransformedContent($pagetype_override=false) { + function getTransformedContent($pagetype_override = false) + { $backend = &$this->_wikidb->_backend; if ($pagetype_override) { @@ -1578,9 +1678,9 @@ class WikiDB_PageRevision if ($pagetype_override) { // Overriden page type, don't cache (or check cache). return new TransformedText($this->getPage(), - $this->getPackedContent(), - $this->getMetaData(), - $pagetype_override); + $this->getPackedContent(), + $this->getMetaData(), + $pagetype_override); } $possibly_cache_results = true; @@ -1592,14 +1692,12 @@ class WikiDB_PageRevision $page->set('_cached_html', ''); // ignored with !USECACHE } $possibly_cache_results = false; - } - elseif (USECACHE and !$this->_transformedContent) { + } elseif (USECACHE and !$this->_transformedContent) { //$backend->lock(); if ($this->isCurrent()) { $page = $this->getPage(); $this->_transformedContent = TransformedText::unpack($page->get('_cached_html')); - } - else { + } else { $possibly_cache_results = false; } //$backend->unlock(); @@ -1608,8 +1706,8 @@ class WikiDB_PageRevision if (!$this->_transformedContent) { $this->_transformedContent = new TransformedText($this->getPage(), - $this->getPackedContent(), - $this->getMetaData()); + $this->getPackedContent(), + $this->getMetaData()); if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) { // If we're still the current version, cache the transfomed page. @@ -1632,37 +1730,39 @@ class WikiDB_PageRevision * @return string The page content. * Lines are separated by new-lines. */ - function getPackedContent() { + function getPackedContent() + { $data = &$this->_data; if (empty($data['%content']) || (!$this->_wikidb->isWikiPage($this->_pagename) - && $this->isCurrent())) { + && $this->isCurrent()) + ) { include_once 'lib/InlineParser.php'; // A feature similar to taglines at http://www.wlug.org.nz/ // Lib from http://www.aasted.org/quote/ if (defined('FORTUNE_DIR') and is_dir(FORTUNE_DIR) - and in_array($GLOBALS['request']->getArg('action'), - array('create','edit'))) - { + and in_array($GLOBALS['request']->getArg('action'), + array('create', 'edit')) + ) { include_once 'lib/fortune.php'; $fortune = new Fortune(); $quote = $fortune->quoteFromDir(FORTUNE_DIR); if ($quote != -1) $quote = "<verbatim>\n" - . str_replace("\n<br>","\n", $quote) - . "</verbatim>\n\n"; + . str_replace("\n<br>", "\n", $quote) + . "</verbatim>\n\n"; else $quote = ""; return $quote . sprintf(_("Describe %s here."), - "[" . WikiEscape($this->_pagename) . "]"); + "[" . WikiEscape($this->_pagename) . "]"); } // Replace empty content with default value. return sprintf(_("Describe %s here."), - "[" . WikiEscape($this->_pagename) . "]"); + "[" . WikiEscape($this->_pagename) . "]"); } // There is (non-default) content. @@ -1682,7 +1782,8 @@ class WikiDB_PageRevision return $data['%content']; } - function _get_content() { + function _get_content() + { $cache = &$this->_wikidb->_cache; $pagename = $this->_pagename; $version = $this->_version; @@ -1693,11 +1794,10 @@ class WikiDB_PageRevision if ($newdata) { assert(is_string($newdata['%content'])); return $newdata['%content']; - } - else { + } else { // else revision has been deleted... What to do? return __sprintf("Oops! Revision %s of %s seems to have been deleted!", - $version, $pagename); + $version, $pagename); } } @@ -1743,7 +1843,8 @@ class WikiDB_PageRevision * @return string The requested value, or false if the requested value * is not defined. */ - function get($key) { + function get($key) + { if (!$key || $key[0] == '%') return false; $data = &$this->_data; @@ -1755,7 +1856,8 @@ class WikiDB_PageRevision * * @return hash The revision meta-data. */ - function getMetaData() { + function getMetaData() + { $meta = array(); foreach ($this->_data as $key => $val) { if (!empty($val) && $key[0] != '%') @@ -1774,7 +1876,8 @@ class WikiDB_PageRevision * * @return string Printable representation of the WikiDB_Page. */ - function asString () { + function asString() + { ob_start(); printf("[%s:%d\n", get_class($this), $this->get('version')); print_r($this->_data); @@ -1783,7 +1886,9 @@ class WikiDB_PageRevision ob_end_clean(); return $strval; } -}; +} + +; /** @@ -1795,16 +1900,20 @@ class WikiDB_PageRevision */ class WikiDB_PageIterator { - function WikiDB_PageIterator(&$wikidb, &$iter, $options=false) { + function WikiDB_PageIterator(&$wikidb, &$iter, $options = false) + { $this->_iter = $iter; // a WikiDB_backend_iterator $this->_wikidb = &$wikidb; $this->_options = $options; - } + } - function count () { + function count() + { return $this->_iter->count(); } - function limit () { + + function limit() + { return empty($this->_options['limit']) ? 0 : $this->_options['limit']; } @@ -1815,8 +1924,9 @@ class WikiDB_PageIterator * * @return WikiDB_Page The next WikiDB_Page in the sequence. */ - function next () { - if ( ! ($next = $this->_iter->next()) ) { + function next() + { + if (!($next = $this->_iter->next())) { return false; } @@ -1827,7 +1937,8 @@ class WikiDB_PageIterator if (!$pagename) { if (isset($next['linkrelation']) - or isset($next['pagedata']['linkrelation'])) { + or isset($next['pagedata']['linkrelation']) + ) { return false; } } @@ -1836,10 +1947,11 @@ class WikiDB_PageIterator // (well not with file, cvs and dba) if (isset($next['pagedata']) and count($next['pagedata']) > 1) { $this->_wikidb->_cache->cache_data($next); - // cache existing page id's since we iterate over all links in GleanDescription - // and need them later for LinkExistingWord + // cache existing page id's since we iterate over all links in GleanDescription + // and need them later for LinkExistingWord } elseif ($this->_options and array_key_exists('include_empty', $this->_options) - and !$this->_options['include_empty'] and isset($next['id'])) { + and !$this->_options['include_empty'] and isset($next['id']) + ) { $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id']; } $page = new WikiDB_Page($this->_wikidb, $pagename); @@ -1862,13 +1974,18 @@ class WikiDB_PageIterator * * @access public */ - function free() { + function free() + { $this->_iter->free(); } - function reset() { + + function reset() + { $this->_iter->reset(); } - function asArray() { + + function asArray() + { $result = array(); while ($page = $this->next()) $result[] = $page; @@ -1882,7 +1999,8 @@ class WikiDB_PageIterator * Since iteration is usually destructive for SQL results, * we have to generate a copy. */ - function applyFilters($options = false) { + function applyFilters($options = false) + { if (!$options) $options = $this->_options; if (isset($options['sortby'])) { $array = array(); @@ -1894,7 +2012,8 @@ class WikiDB_PageIterator /* the rest is not destructive. * reconstruct a new iterator */ - $pagenames = array(); $i = 0; + $pagenames = array(); + $i = 0; if (isset($options['limit'])) $limit = $options['limit']; else @@ -1903,7 +2022,7 @@ class WikiDB_PageIterator $exclude = $options['exclude']; if (is_string($exclude) and !is_array($exclude)) $exclude = PageList::explodePageList($exclude, false, false, $limit); - foreach($array as $pagename) { + foreach ($array as $pagename) { if ($limit and $i++ > $limit) return new WikiDB_Array_PageIterator($pagenames); if (!empty($exclude) and !in_array($pagename, $exclude)) @@ -1915,7 +2034,8 @@ class WikiDB_PageIterator } /* pagename only */ - function _doSort(&$array, $sortby) { + function _doSort(&$array, $sortby) + { $sortby = PageList::sortby($sortby, 'init'); if ($sortby == '+pagename') sort($array, SORT_STRING); @@ -1924,7 +2044,9 @@ class WikiDB_PageIterator reset($array); } -}; +} + +; /** * A class which represents a sequence of WikiDB_PageRevisions. @@ -1932,13 +2054,15 @@ class WikiDB_PageIterator */ class WikiDB_PageRevisionIterator { - function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options=false) { + function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options = false) + { $this->_revisions = $revisions; $this->_wikidb = &$wikidb; $this->_options = $options; } - function count () { + function count() + { return $this->_revisions->count(); } @@ -1950,8 +2074,9 @@ class WikiDB_PageRevisionIterator * @return WikiDB_PageRevision * The next WikiDB_PageRevision in the sequence. */ - function next () { - if ( ! ($next = $this->_revisions->next()) ) + function next() + { + if (!($next = $this->_revisions->next())) return false; //$this->_wikidb->_cache->cache_data($next); @@ -1961,25 +2086,25 @@ class WikiDB_PageRevisionIterator $versiondata = $next['versiondata']; if ((int)DEBUG) { if (!(is_string($pagename) and $pagename != '')) { - trigger_error("empty pagename",E_USER_WARNING); + trigger_error("empty pagename", E_USER_WARNING); return false; } } else assert(is_string($pagename) and $pagename != ''); if ((int)DEBUG) { if (!is_array($versiondata)) { - trigger_error("empty versiondata",E_USER_WARNING); + trigger_error("empty versiondata", E_USER_WARNING); return false; } } else assert(is_array($versiondata)); if ((int)DEBUG) { if (!($version > 0)) { - trigger_error("invalid version",E_USER_WARNING); + trigger_error("invalid version", E_USER_WARNING); return false; } } else assert($version > 0); return new WikiDB_PageRevision($this->_wikidb, $pagename, $version, - $versiondata); + $versiondata); } /** @@ -1994,42 +2119,58 @@ class WikiDB_PageRevisionIterator * * @access public */ - function free() { + function free() + { $this->_revisions->free(); } - function asArray() { + function asArray() + { $result = array(); while ($rev = $this->next()) $result[] = $rev; $this->free(); return $result; } -}; +} + +; /** pseudo iterator */ class WikiDB_Array_PageIterator { - function WikiDB_Array_PageIterator($pagenames) { + function WikiDB_Array_PageIterator($pagenames) + { global $request; $this->_dbi = $request->getDbh(); $this->_pages = $pagenames; reset($this->_pages); } - function next() { + + function next() + { $c = current($this->_pages); next($this->_pages); return $c !== false ? $this->_dbi->getPage($c) : false; } - function count() { + + function count() + { return count($this->_pages); } - function reset() { + + function reset() + { reset($this->_pages); } - function free() {} - function asArray() { + + function free() + { + } + + function asArray() + { reset($this->_pages); return $this->_pages; } @@ -2037,7 +2178,8 @@ class WikiDB_Array_PageIterator class WikiDB_Array_generic_iter { - function WikiDB_Array_generic_iter($result) { + function WikiDB_Array_generic_iter($result) + { // $result may be either an array or a query result if (is_array($result)) { $this->_array = $result; @@ -2049,19 +2191,30 @@ class WikiDB_Array_generic_iter if (!empty($this->_array)) reset($this->_array); } - function next() { + + function next() + { $c = current($this->_array); next($this->_array); return $c !== false ? $c : false; } - function count() { + + function count() + { return count($this->_array); } - function reset() { + + function reset() + { reset($this->_array); } - function free() {} - function asArray() { + + function free() + { + } + + function asArray() + { if (!empty($this->_array)) reset($this->_array); return $this->_array; @@ -2079,12 +2232,13 @@ class WikiDB_cache { // FIXME: beautify versiondata cache. Cache only limited data? - function WikiDB_cache (&$backend) { + function WikiDB_cache(&$backend) + { $this->_backend = &$backend; $this->_pagedata_cache = array(); $this->_versiondata_cache = array(); - array_push ($this->_versiondata_cache, array()); + array_push($this->_versiondata_cache, array()); $this->_glv_cache = array(); $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id) @@ -2092,14 +2246,16 @@ class WikiDB_cache $this->readonly = $GLOBALS['request']->_dbi->readonly; } - function close() { + function close() + { $this->_pagedata_cache = array(); $this->_versiondata_cache = array(); $this->_glv_cache = array(); $this->_id_cache = array(); } - function get_pagedata($pagename) { + function get_pagedata($pagename) + { assert(is_string($pagename) && $pagename != ''); if (USECACHE) { $cache = &$this->_pagedata_cache; @@ -2114,25 +2270,30 @@ class WikiDB_cache } } - function update_pagedata($pagename, $newdata) { + function update_pagedata($pagename, $newdata) + { assert(is_string($pagename) && $pagename != ''); - if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } + if (!empty($this->readonly)) { + trigger_error("readonly database", E_USER_WARNING); + return; + } $this->_backend->update_pagedata($pagename, $newdata); if (USECACHE) { if (!empty($this->_pagedata_cache[$pagename]) - and is_array($this->_pagedata_cache[$pagename])) - { + and is_array($this->_pagedata_cache[$pagename]) + ) { $cachedata = &$this->_pagedata_cache[$pagename]; - foreach($newdata as $key => $val) + foreach ($newdata as $key => $val) $cachedata[$key] = $val; } else $this->_pagedata_cache[$pagename] = $newdata; } } - function invalidate_cache($pagename) { + function invalidate_cache($pagename) + { unset ($this->_pagedata_cache[$pagename]); unset ($this->_versiondata_cache[$pagename]); unset ($this->_glv_cache[$pagename]); @@ -2140,47 +2301,57 @@ class WikiDB_cache //unset ($this->_backend->_page_data); } - function delete_page($pagename) { - if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } + function delete_page($pagename) + { + if (!empty($this->readonly)) { + trigger_error("readonly database", E_USER_WARNING); + return; + } $result = $this->_backend->delete_page($pagename); $this->invalidate_cache($pagename); return $result; } - function purge_page($pagename) { - if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } + function purge_page($pagename) + { + if (!empty($this->readonly)) { + trigger_error("readonly database", E_USER_WARNING); + return; + } $result = $this->_backend->purge_page($pagename); $this->invalidate_cache($pagename); return $result; } // FIXME: ugly and wrong. may overwrite full cache with partial cache - function cache_data($data) { + function cache_data($data) + { ; //if (isset($data['pagedata'])) // $this->_pagedata_cache[$data['pagename']] = $data['pagedata']; } - function get_versiondata($pagename, $version, $need_content = false) { + function get_versiondata($pagename, $version, $need_content = false) + { // FIXME: Seriously ugly hackage $readdata = false; - if (USECACHE) { //temporary - for debugging + if (USECACHE) { //temporary - for debugging assert(is_string($pagename) && $pagename != ''); // There is a bug here somewhere which results in an assertion failure at line 105 // of ArchiveCleaner.php It goes away if we use the next line. //$need_content = true; - $nc = $need_content ? '1':'0'; + $nc = $need_content ? '1' : '0'; $cache = &$this->_versiondata_cache; if (!isset($cache[$pagename][$version][$nc]) - || !(is_array ($cache[$pagename])) - || !(is_array ($cache[$pagename][$version]))) - { + || !(is_array($cache[$pagename])) + || !(is_array($cache[$pagename][$version])) + ) { $cache[$pagename][$version][$nc] = $this->_backend->get_versiondata($pagename, $version, $need_content); $readdata = true; // If we have retrieved all data, we may as well set the cache for // $need_content = false - if ($need_content){ + if ($need_content) { $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1']; } } @@ -2198,10 +2369,14 @@ class WikiDB_cache return $vdata; } - function set_versiondata($pagename, $version, $data) { + function set_versiondata($pagename, $version, $data) + { //unset($this->_versiondata_cache[$pagename][$version]); - if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } + if (!empty($this->readonly)) { + trigger_error("readonly database", E_USER_WARNING); + return; + } $new = $this->_backend->set_versiondata($pagename, $version, $data); // Update the cache $this->_versiondata_cache[$pagename][$version]['1'] = $data; @@ -2210,8 +2385,12 @@ class WikiDB_cache unset($this->_glv_cache[$pagename]); } - function update_versiondata($pagename, $version, $data) { - if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } + function update_versiondata($pagename, $version, $data) + { + if (!empty($this->readonly)) { + trigger_error("readonly database", E_USER_WARNING); + return; + } $new = $this->_backend->update_versiondata($pagename, $version, $data); // Update the cache $this->_versiondata_cache[$pagename][$version]['1'] = $data; @@ -2221,8 +2400,12 @@ class WikiDB_cache unset($this->_glv_cache[$pagename]); } - function delete_versiondata($pagename, $version) { - if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } + function delete_versiondata($pagename, $version) + { + if (!empty($this->readonly)) { + trigger_error("readonly database", E_USER_WARNING); + return; + } $new = $this->_backend->delete_versiondata($pagename, $version); if (isset($this->_versiondata_cache[$pagename][$version])) unset ($this->_versiondata_cache[$pagename][$version]); @@ -2231,9 +2414,10 @@ class WikiDB_cache unset ($this->_glv_cache[$pagename]); } - function get_latest_version($pagename) { + function get_latest_version($pagename) + { if (USECACHE) { - assert (is_string($pagename) && $pagename != ''); + assert(is_string($pagename) && $pagename != ''); $cache = &$this->_glv_cache; if (!isset($cache[$pagename])) { $cache[$pagename] = $this->_backend->get_latest_version($pagename); @@ -2245,14 +2429,17 @@ class WikiDB_cache return $this->_backend->get_latest_version($pagename); } } -}; +} -function _sql_debuglog($msg, $newline=true, $shutdown=false) { +; + +function _sql_debuglog($msg, $newline = true, $shutdown = false) +{ static $fp = false; static $i = 0; if (!$fp) { $stamp = strftime("%y%m%d-%H%M%S"); - $fp = fopen(TEMP_DIR."/sql-$stamp.log", "a"); + $fp = fopen(TEMP_DIR . "/sql-$stamp.log", "a"); register_shutdown_function("_sql_debuglog_shutdown_function"); } elseif ($shutdown) { fclose($fp); @@ -2262,8 +2449,9 @@ function _sql_debuglog($msg, $newline=true, $shutdown=false) { else fwrite($fp, $msg); } -function _sql_debuglog_shutdown_function() { - _sql_debuglog('',false,true); +function _sql_debuglog_shutdown_function() +{ + _sql_debuglog('', false, true); } // Local Variables: diff --git a/lib/WikiDB/ADODB.php b/lib/WikiDB/ADODB.php index 415748691..190865dbb 100644 --- a/lib/WikiDB/ADODB.php +++ b/lib/WikiDB/ADODB.php @@ -12,7 +12,8 @@ require_once 'lib/WikiDB.php'; */ class WikiDB_ADODB extends WikiDB { - function WikiDB_ADODB ($dbparams) { + function WikiDB_ADODB($dbparams) + { $backend = 'ADODB'; if (is_array($dbparams['dsn'])) $backend = $dbparams['dsn']['phptype']; @@ -20,20 +21,20 @@ class WikiDB_ADODB extends WikiDB $backend = $m[1]; // Do we have a override? (currently: mysql, sqlite, oracle, mssql, oci8po, postgres7) // TODO: mysqlt (innodb or bdb) - if ($backend == 'pgsql') { // PearDB DSN cross-compatiblity hack (for unit testing) - $backend = 'postgres7'; - if (is_string($dbparams['dsn'])) - $dbparams['dsn'] = $backend . ':' . substr($dbparams['dsn'], 6); - } - if (FindFile("lib/WikiDB/backend/ADODB_".$backend.".php",true)) { + if ($backend == 'pgsql') { // PearDB DSN cross-compatiblity hack (for unit testing) + $backend = 'postgres7'; + if (is_string($dbparams['dsn'])) + $dbparams['dsn'] = $backend . ':' . substr($dbparams['dsn'], 6); + } + if (FindFile("lib/WikiDB/backend/ADODB_" . $backend . ".php", true)) { $backend = 'ADODB_' . $backend; } else { $backend = 'ADODB'; } - include_once 'lib/WikiDB/backend/'.$backend.'.php'; - $backend_class = "WikiDB_backend_".$backend; + include_once 'lib/WikiDB/backend/' . $backend . '.php'; + $backend_class = "WikiDB_backend_" . $backend; $backend = new $backend_class($dbparams); - if (!$backend->_dbh->_connectionID) return false; + if (!$backend->_dbh->_connectionID) return false; $this->WikiDB($backend, $dbparams); } @@ -41,8 +42,9 @@ class WikiDB_ADODB extends WikiDB * Determine whether page exists (in non-default form). * @see WikiDB::isWikiPage */ - function isWikiPage ($pagename) { - $pagename = (string) $pagename; + function isWikiPage($pagename) + { + $pagename = (string)$pagename; if ($pagename === '') return false; if (!array_key_exists($pagename, $this->_cache->_id_cache)) { $this->_cache->_id_cache[$pagename] = $this->_backend->is_wiki_page($pagename); @@ -51,7 +53,8 @@ class WikiDB_ADODB extends WikiDB } // add surrounding quotes '' if string - function quote ($in) { + function quote($in) + { if (is_int($in) || is_double($in)) { return $in; } elseif (is_bool($in)) { @@ -62,13 +65,16 @@ class WikiDB_ADODB extends WikiDB return $this->_backend->_dbh->qstr($in); } } + // ADODB handles everything as string // Don't add surrounding quotes '', same as in PearDB - function qstr ($in) { + function qstr($in) + { return $this->_backend->_dbh->addq($in); } - function isOpen () { + function isOpen() + { global $request; if (!$request->_dbi) return false; return is_resource($this->_backend->connection()); @@ -76,13 +82,14 @@ class WikiDB_ADODB extends WikiDB // SQL result: for simple select or create/update queries // returns the database specific resource type - function genericSqlQuery($sql, $args=false) { + function genericSqlQuery($sql, $args = false) + { if ($args) $result = $this->_backend->_dbh->Execute($sql, $args); else $result = $this->_backend->_dbh->Execute($sql); if (!$result) { - trigger_error("SQL Error: ".$this->_backend->_dbh->ErrorMsg(), E_USER_WARNING); + trigger_error("SQL Error: " . $this->_backend->_dbh->ErrorMsg(), E_USER_WARNING); return false; } else { return $result; @@ -91,12 +98,15 @@ class WikiDB_ADODB extends WikiDB // SQL iter: for simple select or create/update queries // returns the generic iterator object (count,next) - function genericSqlIter($sql, $field_list = NULL) { + function genericSqlIter($sql, $field_list = NULL) + { $result = $this->genericSqlQuery($sql); return new WikiDB_backend_ADODB_generic_iter($this->_backend, $result, $field_list); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/PDO.php b/lib/WikiDB/PDO.php index 3ff8491c4..445bf6a0a 100644 --- a/lib/WikiDB/PDO.php +++ b/lib/WikiDB/PDO.php @@ -18,13 +18,14 @@ require_once 'lib/WikiDB.php'; */ class WikiDB_PDO extends WikiDB { - function WikiDB_PDO ($dbparams) { + function WikiDB_PDO($dbparams) + { if (is_array($dbparams['dsn'])) $backend = $dbparams['dsn']['phptype']; elseif (preg_match('/^(\w+):/', $dbparams['dsn'], $m)) $backend = $m[1]; // Do we have a override? Currently none: mysql, sqlite, oci, mssql - if (FindFile("lib/WikiDB/backend/PDO_$backend.php",true)) { + if (FindFile("lib/WikiDB/backend/PDO_$backend.php", true)) { $backend = 'PDO_' . $backend; } else { $backend = 'PDO'; @@ -39,8 +40,9 @@ class WikiDB_PDO extends WikiDB * Determine whether page exists (in non-default form). * @see WikiDB::isWikiPage */ - function isWikiPage ($pagename) { - $pagename = (string) $pagename; + function isWikiPage($pagename) + { + $pagename = (string)$pagename; if ($pagename === '') return false; if (!array_key_exists($pagename, $this->_cache->_id_cache)) { $this->_cache->_id_cache[$pagename] = $this->_backend->is_wiki_page($pagename); @@ -51,7 +53,8 @@ class WikiDB_PDO extends WikiDB // With PDO we should really use native quoting using prepared statements with ? // Supported since PDO-0.3 (?) // Add surrounding quotes '' if string - function quote ($in) { + function quote($in) + { if (is_int($in) || is_double($in)) { return $in; } elseif (is_bool($in)) { @@ -62,14 +65,17 @@ class WikiDB_PDO extends WikiDB return $this->qstr($in); } } + // Don't add surrounding quotes '', same as in PearDB // PDO-0.2.1 added now ::quote() - function qstr ($in) { - $in = str_replace(array('\\',"\0"),array('\\\\',"\\\0"), $in); + function qstr($in) + { + $in = str_replace(array('\\', "\0"), array('\\\\', "\\\0"), $in); return str_replace("'", "\'", $in); } - function isOpen () { + function isOpen() + { global $request; if (!$request->_dbi) return false; return is_object($this->_backend->_dbh); @@ -77,11 +83,12 @@ class WikiDB_PDO extends WikiDB // SQL result: for simple select or create/update queries // returns the database specific resource type - function genericSqlQuery($sql, $args=false) { + function genericSqlQuery($sql, $args = false) + { try { $sth = $this->_backend->_dbh->prepare($sql); if ($args) { - foreach ($args as $key => $val ) { + foreach ($args as $key => $val) { $sth->bindParam($key, $val); } } @@ -89,9 +96,8 @@ class WikiDB_PDO extends WikiDB $result = $sth->fetch(PDO_FETCH_BOTH); else return false; - } - catch (PDOException $e) { - trigger_error("SQL Error: ".$e->getMessage(), E_USER_WARNING); + } catch (PDOException $e) { + trigger_error("SQL Error: " . $e->getMessage(), E_USER_WARNING); return false; } return $result; @@ -99,12 +105,15 @@ class WikiDB_PDO extends WikiDB // SQL iter: for simple select or create/update queries // returns the generic iterator object (count, next) - function genericSqlIter($sql, $field_list = NULL) { + function genericSqlIter($sql, $field_list = NULL) + { $result = $this->genericSqlQuery($sql); return new WikiDB_backend_PDO_generic_iter($this->_backend, $result, $field_list); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/SQL.php b/lib/WikiDB/SQL.php index 41633ae36..9b9a85edf 100644 --- a/lib/WikiDB/SQL.php +++ b/lib/WikiDB/SQL.php @@ -9,43 +9,46 @@ require_once 'lib/WikiDB.php'; */ class WikiDB_SQL extends WikiDB { - function WikiDB_SQL ($dbparams) { + function WikiDB_SQL($dbparams) + { $backend = 'PearDB'; if (is_array($dbparams['dsn'])) $backend = $dbparams['dsn']['phptype']; elseif (preg_match('/^(\w+):/', $dbparams['dsn'], $m)) $backend = $m[1]; - if ($backend == 'postgres7') { // ADODB cross-compatiblity hack (for unit testing) - $backend = 'pgsql'; - if (is_string($dbparams['dsn'])) - $dbparams['dsn'] = $backend . ':' . substr($dbparams['dsn'], 10); - } - include_once 'lib/WikiDB/backend/PearDB_'.$backend.'.php'; - $backend_class = "WikiDB_backend_PearDB_".$backend; + if ($backend == 'postgres7') { // ADODB cross-compatiblity hack (for unit testing) + $backend = 'pgsql'; + if (is_string($dbparams['dsn'])) + $dbparams['dsn'] = $backend . ':' . substr($dbparams['dsn'], 10); + } + include_once 'lib/WikiDB/backend/PearDB_' . $backend . '.php'; + $backend_class = "WikiDB_backend_PearDB_" . $backend; $backend = new $backend_class($dbparams); if (DB::isError($backend->_dbh)) return; $this->WikiDB($backend, $dbparams); } - function view_dsn ($dsn = false) { + function view_dsn($dsn = false) + { if (!$dsn) $dsninfo = DB::parseDSN($GLOBALS['DBParams']['dsn']); else $dsninfo = DB::parseDSN($dsn); return sprintf("%s://%s:<not displayed>@%s/%s", - $dsninfo['phptype'], - $dsninfo['username'], - $dsninfo['hostspec'], - $dsninfo['database'] - ); + $dsninfo['phptype'], + $dsninfo['username'], + $dsninfo['hostspec'], + $dsninfo['database'] + ); } /** * Determine whether page exists (in non-default form). * @see WikiDB::isWikiPage for the slow generic version */ - function isWikiPage ($pagename) { - $pagename = (string) $pagename; + function isWikiPage($pagename) + { + $pagename = (string)$pagename; if ($pagename === '') return false; //if (empty($this->_iwpcache)) { $this->_iwpcache = array(); } if (empty($this->_cache->id_cache[$pagename])) { @@ -55,11 +58,19 @@ class WikiDB_SQL extends WikiDB } // adds surrounding quotes - function quote ($s) { return $this->_backend->_dbh->quoteSmart($s); } + function quote($s) + { + return $this->_backend->_dbh->quoteSmart($s); + } + // no surrounding quotes because we know it's a string - function qstr ($s) { return $this->_backend->_dbh->escapeSimple($s); } + function qstr($s) + { + return $this->_backend->_dbh->escapeSimple($s); + } - function isOpen () { + function isOpen() + { global $request; if (!$request->_dbi) return false; return is_resource($this->_backend->connection()); @@ -67,14 +78,15 @@ class WikiDB_SQL extends WikiDB // SQL result: for simple select or create/update queries // returns the database specific resource type - function genericSqlQuery($sql, $args=false) { + function genericSqlQuery($sql, $args = false) + { if ($args) $result = $this->_backend->_dbh->query($sql, $args); else $result = $this->_backend->_dbh->query($sql); if (DB::isError($result)) { $msg = $result->getMessage(); - trigger_error("SQL Error: ".DB::errorMessage($result), E_USER_WARNING); + trigger_error("SQL Error: " . DB::errorMessage($result), E_USER_WARNING); return false; } else { return $result; @@ -83,12 +95,15 @@ class WikiDB_SQL extends WikiDB // SQL iter: for simple select or create/update queries // returns the generic iterator object (count,next) - function genericSqlIter($sql, $field_list = NULL) { + function genericSqlIter($sql, $field_list = NULL) + { $result = $this->genericSqlQuery($sql); return new WikiDB_backend_PearDB_generic_iter($this->_backend, $result); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/adodb/adodb-csvlib.inc.php b/lib/WikiDB/adodb/adodb-csvlib.inc.php index 3e2615e89..112dd5797 100644 --- a/lib/WikiDB/adodb/adodb-csvlib.inc.php +++ b/lib/WikiDB/adodb/adodb-csvlib.inc.php @@ -19,113 +19,113 @@ $ADODB_INCLUDED_CSV = 1; ============== */ - /** - * 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; +/** + * 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(); } + } - $rs =& new ADORecordSet_array(); - $rs->InitArrayFields($rows,$flds); - return $line.serialize($rs); + for ($i = 0; $i < $max; $i++) { + $o =& $rs->FetchField($i); + $flds[] = $o; } + $rs =& new ADORecordSet_array(); + $rs->InitArrayFields($rows, $flds); + return $line . serialize($rs); +} + /** -* 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) - { - $err = false; - $fp = @fopen($url,'r'); - if (!$fp) { - $err = $url.' file/URL not found'; + * 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) +{ + $err = false; + $fp = @fopen($url, 'r'); + 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; } - 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 + // 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 (strncmp($meta[0], '====', 4) === 0) { - if ($meta[0] == "====-1") { - if (sizeof($meta) < 5) { - $err = "Corrupt first line for format -1"; - fclose($fp); - return false; - } + 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->fields = array(); - $rs->timeCreated = $meta[1]; - $rs =& new ADORecordSet($val=true); - $rs->EOF = true; - $rs->_numOfFields=0; - $rs->sql = urldecode($meta[2]); - $rs->affectedrows = (integer)$meta[3]; - $rs->insertid = $meta[4]; - return $rs; + if ($timeout > 0) { + $err = " Illegal Timeout $timeout "; + return false; } + $rs->fields = array(); + $rs->timeCreated = $meta[1]; + $rs =& new ADORecordSet($val = true); + $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. @@ -134,11 +134,11 @@ $ADODB_INCLUDED_CSV = 1; # -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) { + 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) { @@ -165,78 +165,79 @@ $ADODB_INCLUDED_CSV = 1; fclose($fp); $err = "Timeout 0"; return false; - } // switch + } // switch - } // if check flush cache - }// (timeout>0) - $ttl = $meta[1]; + } // if check flush cache } - //================================================ - // new cache format - use serialize extensively... - if ($meta[0] === '====1') { - // slurp in the data - $MAXSIZE = 128000; - - $text = fread($fp,$MAXSIZE); - if (strlen($text) === $MAXSIZE) { - while ($txt = fread($fp,$MAXSIZE)) { - $text .= $txt; - } + // (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) === $MAXSIZE) { + while ($txt = fread($fp, $MAXSIZE)) { + $text .= $txt; } - fclose($fp); - @$rs = unserialize($text); - if (is_object($rs)) $rs->timeCreated = $ttl; - return $rs; } + fclose($fp); + @$rs = unserialize($text); + if (is_object($rs)) $rs->timeCreated = $ttl; + return $rs; + } - $meta = false; - $meta = fgetcsv($fp, 32000, ","); - if (!$meta) { - fclose($fp); - $err = "Unexpected EOF 1"; - return false; - } + $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; + // Get Column definitions + $flds = array(); + foreach ($meta as $o) { + $o2 = explode(':', $o); + if (sizeof($o2) != 3) { + $arr[] = $meta; + $flds = false; + break; } - } else { - fclose($fp); - $err = "Recordset had unexpected EOF 2"; - return false; + $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; + // slurp in the data + $MAXSIZE = 128000; - $text = ''; - while ($txt = fread($fp,$MAXSIZE)) { - $text .= $txt; - } + $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 ADORecordSet_array(); - $rs->timeCreated = $ttl; - $rs->InitArrayFields($arr,$flds); - return $rs; + 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 ADORecordSet_array(); + $rs->timeCreated = $ttl; + $rs->InitArrayFields($arr, $flds); + return $rs; +} diff --git a/lib/WikiDB/adodb/adodb-error.inc.php b/lib/WikiDB/adodb/adodb-error.inc.php index b49673dd3..0572275b1 100644 --- a/lib/WikiDB/adodb/adodb-error.inc.php +++ b/lib/WikiDB/adodb/adodb-error.inc.php @@ -11,73 +11,89 @@ * Portions (c)1997-2002 The PHP Group. */ -if (!defined("DB_ERROR")) define("DB_ERROR",-1); +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_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); + 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; + 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"); + 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) +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; + switch ($provider) { + case 'mysql': + $map = adodb_error_mysql(); + break; - case 'oracle': - case 'oci8': $map = adodb_error_oci8(); break; + case 'oracle': + case 'oci8': + $map = adodb_error_oci8(); + break; - case 'ibase': $map = adodb_error_ibase(); break; + case 'ibase': + $map = adodb_error_ibase(); + break; - case 'odbc': $map = adodb_error_odbc(); break; + case 'odbc': + $map = adodb_error_odbc(); + break; - case 'mssql': - case 'sybase': $map = adodb_error_mssql(); break; + case 'mssql': + case 'sybase': + $map = adodb_error_mssql(); + break; - case 'informix': $map = adodb_error_ifx(); break; + case 'informix': + $map = adodb_error_ifx(); + break; - case 'postgres': return adodb_error_pg($errno); break; + case 'postgres': + return adodb_error_pg($errno); + break; - case 'sqlite': return $map = adodb_error_sqlite(); break; - default: - return DB_ERROR; + case 'sqlite': + return $map = adodb_error_sqlite(); + break; + default: + return DB_ERROR; } //print_r($map); //var_dump($errno); @@ -90,16 +106,16 @@ function adodb_error($provider,$dbType,$errno) function adodb_error_pg($errormsg) { static $error_regexps = array( - '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => DB_ERROR_NOSUCHTABLE, - '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/' => DB_ERROR_ALREADY_EXISTS, - '/divide by zero$/' => DB_ERROR_DIVZERO, - '/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER, - '/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD, - '/parser: parse error at or near \"/' => DB_ERROR_SYNTAX, - '/referential integrity violation/' => DB_ERROR_CONSTRAINT - ); + '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => DB_ERROR_NOSUCHTABLE, + '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/' => DB_ERROR_ALREADY_EXISTS, + '/divide by zero$/' => DB_ERROR_DIVZERO, + '/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER, + '/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD, + '/parser: parse error at or near \"/' => DB_ERROR_SYNTAX, + '/referential integrity violation/' => DB_ERROR_CONSTRAINT + ); reset($error_regexps); - while (list($regexp,$code) = each($error_regexps)) { + while (list($regexp, $code) = each($error_regexps)) { if (preg_match($regexp, $errormsg)) { return $code; } @@ -110,143 +126,143 @@ function adodb_error_pg($errormsg) 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; + 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; + 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; + 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 - ); + 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 - ); + 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 - ); + 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 - ); + 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 + ); return $MAP; } diff --git a/lib/WikiDB/adodb/adodb-errorhandler.inc.php b/lib/WikiDB/adodb/adodb-errorhandler.inc.php index d54b7c02b..3cfc0fb0b 100644 --- a/lib/WikiDB/adodb/adodb-errorhandler.inc.php +++ b/lib/WikiDB/adodb/adodb-errorhandler.inc.php @@ -9,45 +9,45 @@ * * Latest version is available at http://php.weblogs.com * -*/ + */ // added Claudio Bustos clbustos#entelchile.net -if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); +if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE', E_USER_ERROR); -define('ADODB_ERROR_HANDLER','ADODB_Error_Handler'); +define('ADODB_ERROR_HANDLER', 'ADODB_Error_Handler'); /** -* 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 -* @param $thisConn $current connection object - can be false if no connection object created -*/ + * 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 + * @param $thisConn $current connection object - can be false if no connection object created + */ function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) { if (error_reporting() == 0) return; // obey @ protocol - switch($fn) { - case 'EXECUTE': - $sql = $p1; - $inputparams = $p2; + switch ($fn) { + case 'EXECUTE': + $sql = $p1; + $inputparams = $p2; - $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n"; - break; + $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n"; + break; - case 'PCONNECT': - case 'CONNECT': - $host = $p1; - $database = $p2; + case 'PCONNECT': + case 'CONNECT': + $host = $p1; + $database = $p2; - $s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)\n"; - break; - default: - $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n"; - break; + $s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)\n"; + break; + default: + $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n"; + break; } /* * Log connection error somewhere @@ -72,5 +72,5 @@ function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnec } //print "<p>$s</p>"; - trigger_error($s,ADODB_ERROR_HANDLER_TYPE); + trigger_error($s, ADODB_ERROR_HANDLER_TYPE); } diff --git a/lib/WikiDB/adodb/adodb-errorpear.inc.php b/lib/WikiDB/adodb/adodb-errorpear.inc.php index f4ad641d8..8905b6151 100644 --- a/lib/WikiDB/adodb/adodb-errorpear.inc.php +++ b/lib/WikiDB/adodb/adodb-errorpear.inc.php @@ -2,17 +2,17 @@ /** * @version V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). 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. +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 * -*/ + */ include_once 'PEAR.php'; -define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR'); +define('ADODB_ERROR_HANDLER', 'ADODB_Error_PEAR'); /* * Enabled the following if you want to terminate scripts when an error occurs @@ -22,47 +22,48 @@ define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR'); /* * Name of the PEAR_Error derived class to call. */ -if (!defined('ADODB_PEAR_ERROR_CLASS')) define('ADODB_PEAR_ERROR_CLASS','PEAR_Error'); +if (!defined('ADODB_PEAR_ERROR_CLASS')) define('ADODB_PEAR_ERROR_CLASS', 'PEAR_Error'); /* * Store the last PEAR_Error object here */ -global $ADODB_Last_PEAR_Error; $ADODB_Last_PEAR_Error = false; +global $ADODB_Last_PEAR_Error; +$ADODB_Last_PEAR_Error = false; - /** -* Error Handler with PEAR support. 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_Error_PEAR($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false) +/** + * Error Handler with PEAR support. 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_Error_PEAR($dbms, $fn, $errno, $errmsg, $p1 = false, $p2 = false) { -global $ADODB_Last_PEAR_Error; + global $ADODB_Last_PEAR_Error; if (error_reporting() == 0) return; // obey @ protocol - switch($fn) { - case 'EXECUTE': - $sql = $p1; - $inputparams = $p2; + switch ($fn) { + case 'EXECUTE': + $sql = $p1; + $inputparams = $p2; - $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")"; - break; + $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")"; + break; - case 'PCONNECT': - case 'CONNECT': - $host = $p1; - $database = $p2; + case 'PCONNECT': + case 'CONNECT': + $host = $p1; + $database = $p2; - $s = "$dbms error: [$errno: $errmsg] in $fn('$host', ?, ?, '$database')"; - break; + $s = "$dbms error: [$errno: $errmsg] in $fn('$host', ?, ?, '$database')"; + break; - default: - $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)"; - break; + default: + $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)"; + break; } $class = ADODB_PEAR_ERROR_CLASS; @@ -75,12 +76,12 @@ global $ADODB_Last_PEAR_Error; } /** -* Returns last PEAR_Error object. This error might be for an error that -* occured several sql statements ago. -*/ + * Returns last PEAR_Error object. This error might be for an error that + * occured several sql statements ago. + */ function &ADODB_PEAR_Error() { -global $ADODB_Last_PEAR_Error; + global $ADODB_Last_PEAR_Error; return $ADODB_Last_PEAR_Error; } diff --git a/lib/WikiDB/adodb/adodb-exceptions.inc.php b/lib/WikiDB/adodb/adodb-exceptions.inc.php index a71b7ce23..0f2f6d319 100644 --- a/lib/WikiDB/adodb/adodb-exceptions.inc.php +++ b/lib/WikiDB/adodb/adodb-exceptions.inc.php @@ -13,34 +13,35 @@ * 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'); +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 = ''; +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; + 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; + 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; @@ -50,24 +51,24 @@ var $database = ''; $this->msg = $errmsg; if (!is_numeric($errno)) $errno = -1; - parent::__construct($s,$errno); + 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 -*/ + * 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; + global $ADODB_EXCEPTION; if (is_string($ADODB_EXCEPTION)) $errfn = $ADODB_EXCEPTION; else $errfn = 'ADODB_EXCEPTION'; diff --git a/lib/WikiDB/adodb/adodb-iterator.inc.php b/lib/WikiDB/adodb/adodb-iterator.inc.php index 6875b379b..e31753626 100644 --- a/lib/WikiDB/adodb/adodb-iterator.inc.php +++ b/lib/WikiDB/adodb/adodb-iterator.inc.php @@ -18,7 +18,8 @@ Iterator code based on http://cvs.php.net/cvs.php/php-src/ext/spl/examples/cachingiterator.inc?login=2 */ - class ADODB_Iterator implements Iterator { +class ADODB_Iterator implements Iterator +{ private $rs; @@ -26,6 +27,7 @@ { $this->rs = $rs; } + function rewind() { $this->rs->MoveFirst(); @@ -63,8 +65,10 @@ } -class ADODB_BASE_RS implements IteratorAggregate { - function getIterator() { +class ADODB_BASE_RS implements IteratorAggregate +{ + function getIterator() + { return new ADODB_Iterator($this); } } diff --git a/lib/WikiDB/adodb/adodb-lib.inc.php b/lib/WikiDB/adodb/adodb-lib.inc.php index e4a147edd..cf45fc438 100644 --- a/lib/WikiDB/adodb/adodb-lib.inc.php +++ b/lib/WikiDB/adodb/adodb-lib.inc.php @@ -18,110 +18,109 @@ $ADODB_INCLUDED_LIB = 1; function _array_change_key_case($an_array) { if (is_array($an_array)) { - foreach($an_array as $key=>$value) + foreach ($an_array as $key => $value) $new_array[strtoupper($key)] = $value; - return $new_array; - } + return $new_array; + } return $an_array; } function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc) { - if (count($fieldArray) == 0) return 0; - $first = true; - $uSet = ''; + if (count($fieldArray) == 0) return 0; + $first = true; + $uSet = ''; - if (!is_array($keyCol)) { - $keyCol = array($keyCol); + if (!is_array($keyCol)) { + $keyCol = array($keyCol); + } + foreach ($fieldArray as $k => $v) { + if ($autoQuote && !is_numeric($v) and strncmp($v, "'", 1) !== 0 and strcasecmp($v, 'null') != 0) { + $v = $zthis->qstr($v); + $fieldArray[$k] = $v; } - foreach($fieldArray as $k => $v) { - if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,'null')!=0) { - $v = $zthis->qstr($v); - $fieldArray[$k] = $v; - } - if (in_array($k,$keyCol)) continue; // skip UPDATE if is key + if (in_array($k, $keyCol)) continue; // skip UPDATE if is key - if ($first) { - $first = false; - $uSet = "$k=$v"; - } else - $uSet .= ",$k=$v"; - } + if ($first) { + $first = false; + $uSet = "$k=$v"; + } else + $uSet .= ",$k=$v"; + } - $where = false; - foreach ($keyCol as $v) { - if ($where) $where .= " and $v=$fieldArray[$v]"; - else $where = "$v=$fieldArray[$v]"; - } + $where = false; + foreach ($keyCol as $v) { + if ($where) $where .= " and $v=$fieldArray[$v]"; + else $where = "$v=$fieldArray[$v]"; + } - if ($uSet && $where) { - $update = "UPDATE $table SET $uSet WHERE $where"; + if ($uSet && $where) { + $update = "UPDATE $table SET $uSet WHERE $where"; - $rs = $zthis->Execute($update); - if ($rs) { - if ($zthis->poorAffectedRows) { + $rs = $zthis->Execute($update); + if ($rs) { + if ($zthis->poorAffectedRows) { /* The Select count(*) wipes out any errors that the update would have returned. http://phplens.com/lens/lensforum/msgs.php?id=5696 */ - if ($zthis->ErrorNo()<>0) return 0; + if ($zthis->ErrorNo() <> 0) return 0; # affected_rows == 0 if update field values identical to old values # for mysql - which is silly. - $cnt = $zthis->GetOne("select count(*) from $table where $where"); - if ($cnt > 0) return 1; // record already exists - } else - if (($zthis->Affected_Rows()>0)) return 1; - } + $cnt = $zthis->GetOne("select count(*) from $table where $where"); + if ($cnt > 0) return 1; // record already exists + } else + if (($zthis->Affected_Rows() > 0)) return 1; } + } // print "<p>Error=".$this->ErrorNo().'<p>'; - $first = true; - foreach($fieldArray as $k => $v) { - if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col - - if ($first) { - $first = false; - $iCols = "$k"; - $iVals = "$v"; - } else { - $iCols .= ",$k"; - $iVals .= ",$v"; - } + $first = true; + foreach ($fieldArray as $k => $v) { + if ($has_autoinc && in_array($k, $keyCol)) continue; // skip autoinc col + + if ($first) { + $first = false; + $iCols = "$k"; + $iVals = "$v"; + } else { + $iCols .= ",$k"; + $iVals .= ",$v"; } - $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; - $rs = $zthis->Execute($insert); - return ($rs) ? 2 : 0; + } + $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; + $rs = $zthis->Execute($insert); + return ($rs) ? 2 : 0; } // Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM -function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false, - $size=0, $selectAttr='',$compareFields0=true) +function _adodb_getmenu(&$zthis, $name, $defstr = '', $blank1stItem = true, $multiple = false, + $size = 0, $selectAttr = '', $compareFields0 = true) { $hasvalue = false; if ($multiple or is_array($defstr)) { - if ($size==0) $size=5; + if ($size == 0) $size = 5; $attr = " multiple size=$size"; - if (!strpos($name,'[]')) $name .= '[]'; - } elseif ($size) $attr = " size=$size"; - else $attr =''; + if (!strpos($name, '[]')) $name .= '[]'; + } elseif ($size) $attr = " size=$size"; else $attr = ''; $s = "<select name=\"$name\"$attr $selectAttr>"; if ($blank1stItem) - if (is_string($blank1stItem)) { - $barr = explode(':',$blank1stItem); + if (is_string($blank1stItem)) { + $barr = explode(':', $blank1stItem); if (sizeof($barr) == 1) $barr[] = ''; - $s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>"; + $s .= "\n<option value=\"" . $barr[0] . "\">" . $barr[1] . "</option>"; } else $s .= "\n<option></option>"; - if ($zthis->FieldCount() > 1) $hasvalue=true; + if ($zthis->FieldCount() > 1) $hasvalue = true; else $compareFields0 = true; $value = ''; - while(!$zthis->EOF) { + while (!$zthis->EOF) { $zval = rtrim(reset($zthis->fields)); if (sizeof($zthis->fields) > 1) { if (isset($zthis->fields[1])) @@ -131,30 +130,29 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f } $selected = ($compareFields0) ? $zval : $zval2; - if ($blank1stItem && $zval=="") { + if ($blank1stItem && $zval == "") { $zthis->MoveNext(); continue; } if ($hasvalue) - $value = ' value="'.htmlspecialchars($zval2).'"'; + $value = ' value="' . htmlspecialchars($zval2) . '"'; - if (is_array($defstr)) { + if (is_array($defstr)) { - if (in_array($selected,$defstr)) - $s .= "<option selected$value>".htmlspecialchars($zval).'</option>'; + if (in_array($selected, $defstr)) + $s .= "<option selected$value>" . htmlspecialchars($zval) . '</option>'; else - $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>'; - } - else { - if (strcasecmp($selected,$defstr)==0) - $s .= "<option selected$value>".htmlspecialchars($zval).'</option>'; + $s .= "\n<option" . $value . '>' . htmlspecialchars($zval) . '</option>'; + } else { + if (strcasecmp($selected, $defstr) == 0) + $s .= "<option selected$value>" . htmlspecialchars($zval) . '</option>'; else - $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>'; + $s .= "\n<option" . $value . '>' . htmlspecialchars($zval) . '</option>'; } $zthis->MoveNext(); } // while - return $s ."\n</select>\n"; + return $s . "\n</select>\n"; } /* @@ -163,23 +161,23 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f Does not work with UNIONs. */ -function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) +function _adodb_getcount(&$zthis, $sql, $inputarr = false, $secs2cache = 0) { $qryRecs = 0; - if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) { + if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is', $sql)) { // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias // but this is only supported by oracle and postgresql... if ($zthis->dataProvider == 'oci8') { - $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); + $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is', '', $sql); $rewritesql = "SELECT COUNT(*) FROM ($rewritesql)"; - } elseif ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7') { + } elseif ($zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7') { $info = $zthis->ServerInfo(); - if (substr($info['version'],0,3) >= 7.1) { // good till version 999 - $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); + if (substr($info['version'], 0, 3) >= 7.1) { // good till version 999 + $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is', '', $sql); $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_"; } } @@ -187,22 +185,22 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) // now replace SELECT ... FROM with SELECT COUNT(*) FROM $rewritesql = preg_replace( - '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql); + '/^\s*SELECT\s.*\s+FROM\s/Uis', 'SELECT COUNT(*) FROM ', $sql); // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails // with mssql, access and postgresql. Also a good speedup optimization - skips sorting! - $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql); + $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is', '', $rewritesql); } if (isset($rewritesql) && $rewritesql != $sql) { if ($secs2cache) { // we only use half the time of secs2cache because the count can quickly // become inaccurate if new records are added - $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr); + $qryRecs = $zthis->CacheGetOne($secs2cache / 2, $rewritesql, $inputarr); } else { - $qryRecs = $zthis->GetOne($rewritesql,$inputarr); - } + $qryRecs = $zthis->GetOne($rewritesql, $inputarr); + } if ($qryRecs !== false) return $qryRecs; } @@ -210,19 +208,19 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) // query rewrite failed - so try slower way... // strip off unneeded ORDER BY - $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); - $rstest = &$zthis->Execute($rewritesql,$inputarr); + $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is', '', $sql); + $rstest = &$zthis->Execute($rewritesql, $inputarr); if ($rstest) { - $qryRecs = $rstest->RecordCount(); + $qryRecs = $rstest->RecordCount(); if ($qryRecs == -1) { - global $ADODB_EXTENSION; - // some databases will return -1 on MoveLast() - change to MoveNext() + global $ADODB_EXTENSION; + // some databases will return -1 on MoveLast() - change to MoveNext() if ($ADODB_EXTENSION) { - while(!$rstest->EOF) { + while (!$rstest->EOF) { adodb_movenext($rstest); } } else { - while(!$rstest->EOF) { + while (!$rstest->EOF) { $rstest->MoveNext(); } } @@ -245,11 +243,11 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) rarely change. */ function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, - $inputarr=false, $secs2cache=0) + $inputarr = false, $secs2cache = 0) { $atfirstpage = false; $atlastpage = false; - $lastpageno=1; + $lastpageno = 1; // If an invalid nrows is supplied, // we assume a default value of 10 rows per page @@ -257,8 +255,8 @@ function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, $qryRecs = false; //count records for no offset - $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache); - $lastpageno = (int) ceil($qryRecs / $nrows); + $qryRecs = _adodb_getcount($zthis, $sql, $inputarr, $secs2cache); + $lastpageno = (int)ceil($qryRecs / $nrows); $zthis->_maxRecordCount = $qryRecs; // If page number <= 1, then we are at the first page @@ -276,7 +274,7 @@ function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, } // We get the data we want - $offset = $nrows * ($page-1); + $offset = $nrows * ($page - 1); if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr); else @@ -295,43 +293,43 @@ function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, } // Iván Oliva version -function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0) +function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr = false, $secs2cache = 0) { $atfirstpage = false; $atlastpage = false; - if (!isset($page) || $page <= 1) { // If page number <= 1, then we are at the first page + if (!isset($page) || $page <= 1) { // If page number <= 1, then we are at the first page $page = 1; $atfirstpage = true; } - if ($nrows <= 0) $nrows = 10; // If an invalid nrows is supplied, we assume a default value of 10 rows per page + if ($nrows <= 0) $nrows = 10; // If an invalid nrows is supplied, we assume a default value of 10 rows per page // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than // the last page number. $pagecounter = $page + 1; $pagecounteroffset = ($pagecounter * $nrows) - $nrows; - if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr); + if ($secs2cache > 0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr); else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache); if ($rstest) { - while ($rstest && $rstest->EOF && $pagecounter>0) { + while ($rstest && $rstest->EOF && $pagecounter > 0) { $atlastpage = true; $pagecounter--; $pagecounteroffset = $nrows * ($pagecounter - 1); $rstest->Close(); - if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr); + if ($secs2cache > 0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr); else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache); } if ($rstest) $rstest->Close(); } - if ($atlastpage) { // If we are at the last page or beyond it, we are going to retrieve it + if ($atlastpage) { // If we are at the last page or beyond it, we are going to retrieve it $page = $pagecounter; - if ($page == 1) $atfirstpage = true; // We have to do this again in case the last page is the same as the first - //... page, that is, the recordset has only 1 page. + if ($page == 1) $atfirstpage = true; // We have to do this again in case the last page is the same as the first + //... page, that is, the recordset has only 1 page. } // We get the data we want - $offset = $nrows * ($page-1); + $offset = $nrows * ($page - 1); if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr); else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); @@ -345,51 +343,52 @@ function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputar return $rsreturn; } -function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false) +function _adodb_getupdatesql(&$zthis, &$rs, $arrFields, $forceUpdate = false, $magicq = false) { - if (!$rs) { - printf(ADODB_BAD_RS,'GetUpdateSQL'); - return false; - } + if (!$rs) { + printf(ADODB_BAD_RS, 'GetUpdateSQL'); + return false; + } - $fieldUpdatedCount = 0; - $arrFields = _array_change_key_case($arrFields); + $fieldUpdatedCount = 0; + $arrFields = _array_change_key_case($arrFields); - $hasnumeric = isset($rs->fields[0]); - $setFields = ''; + $hasnumeric = isset($rs->fields[0]); + $setFields = ''; - // Loop through all of the fields in the recordset - for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { - // Get the field from the recordset - $field = $rs->FetchField($i); + // Loop through all of the fields in the recordset + for ($i = 0, $max = $rs->FieldCount(); $i < $max; $i++) { + // Get the field from the recordset + $field = $rs->FetchField($i); - // If the recordset field is one - // of the fields passed in then process. - $upperfname = strtoupper($field->name); - if (adodb_key_exists($upperfname,$arrFields)) { + // If the recordset field is one + // of the fields passed in then process. + $upperfname = strtoupper($field->name); + if (adodb_key_exists($upperfname, $arrFields)) { - // If the existing field value in the recordset - // is different from the value passed in then - // go ahead and append the field name and new value to - // the update query. + // If the existing field value in the recordset + // is different from the value passed in then + // go ahead and append the field name and new value to + // the update query. - if ($hasnumeric) $val = $rs->fields[$i]; - else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname]; - else if (isset($rs->fields[$field->name])) $val = $rs->fields[$field->name]; - else if (isset($rs->fields[strtolower($upperfname)])) $val = $rs->fields[strtolower($upperfname)]; - else $val = ''; + if ($hasnumeric) $val = $rs->fields[$i]; + else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname]; + else if (isset($rs->fields[$field->name])) $val = $rs->fields[$field->name]; + else if (isset($rs->fields[strtolower($upperfname)])) $val = $rs->fields[strtolower($upperfname)]; + else $val = ''; - if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) { - // Set the counter for the number of fields that will be updated. - $fieldUpdatedCount++; + if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) { + // Set the counter for the number of fields that will be updated. + $fieldUpdatedCount++; - // Based on the datatype of the field - // Format the value properly for the database + // Based on the datatype of the field + // Format the value properly for the database $type = $rs->MetaType($field->type); - // is_null requires php 4.0.4 + // is_null requires php 4.0.4 if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) || - $arrFields[$upperfname] === 'null') { + $arrFields[$upperfname] === 'null' + ) { $setFields .= $field->name . " = null, "; } else { if ($type == 'null') { @@ -400,39 +399,39 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq //Oracle needs BLOB types to be handled with a returning clause //postgres has special needs as well $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, - $arrFields, $magicq); + $arrFields, $magicq); } } } } - // If there were any modified fields then build the rest of the update query. - if ($fieldUpdatedCount > 0 || $forceUpdate) { - // Get the table name from the existing query. - preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName); + // If there were any modified fields then build the rest of the update query. + if ($fieldUpdatedCount > 0 || $forceUpdate) { + // Get the table name from the existing query. + preg_match("/FROM\s+" . ADODB_TABLE_REGEX . "/is", $rs->sql, $tableName); - // Get the full where clause excluding the word "WHERE" from - // the existing query. - preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause); + // Get the full where clause excluding the word "WHERE" from + // the existing query. + preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause); - $discard = false; - // not a good hack, improvements? - if ($whereClause) - preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard); - else - $whereClause = array(false,false); + $discard = false; + // not a good hack, improvements? + if ($whereClause) + preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard); + else + $whereClause = array(false, false); - if ($discard) - $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1])); + if ($discard) + $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1])); - $sql = 'UPDATE '.$tableName[1].' SET '.substr($setFields, 0, -2); + $sql = 'UPDATE ' . $tableName[1] . ' SET ' . substr($setFields, 0, -2); if (strlen($whereClause[1]) > 0) - $sql .= ' WHERE '.$whereClause[1]; + $sql .= ' WHERE ' . $whereClause[1]; return $sql; - } else { - return false; + } else { + return false; } } @@ -440,12 +439,12 @@ function adodb_key_exists($key, &$arr) { if (!defined('ADODB_FORCE_NULLS')) { // the following is the old behaviour where null or empty fields are ignored - return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0); + return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key]) > 0); } if (isset($arr[$key])) return true; ## null check below - if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr); + if (ADODB_PHPVER >= 0x4010) return array_key_exists($key, $arr); return false; } @@ -456,7 +455,7 @@ function adodb_key_exists($key, &$arr) * * */ -function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false) +function _adodb_getinsertsql(&$zthis, &$rs, $arrFields, $magicq = false) { $tableName = ''; $values = ''; @@ -473,25 +472,25 @@ function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false) //we need an object for the recordSet //because we have to call MetaType. //php can't do a $rsclass::MetaType() - $rsclass = $zthis->rsPrefix.$zthis->databaseType; - $recordSet =& new $rsclass(-1,$zthis->fetchMode); + $rsclass = $zthis->rsPrefix . $zthis->databaseType; + $recordSet =& new $rsclass(-1, $zthis->fetchMode); $recordSet->connection = &$zthis; - $columns = $zthis->MetaColumns( $tableName ); + $columns = $zthis->MetaColumns($tableName); } elseif (is_subclass_of($rs, 'adorecordset')) { - for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) + for ($i = 0, $max = $rs->FieldCount(); $i < $max; $i++) $columns[] = $rs->FetchField($i); $recordSet =& $rs; } else { - printf(ADODB_BAD_RS,'GetInsertSQL'); + printf(ADODB_BAD_RS, 'GetInsertSQL'); return false; } // Loop through all of the fields in the recordset - foreach( $columns as $field ) { + foreach ($columns as $field) { $upperfname = strtoupper($field->name); - if (adodb_key_exists($upperfname,$arrFields)) { + if (adodb_key_exists($upperfname, $arrFields)) { // Set the counter for the number of fields that will be inserted. $fieldInsertedCount++; @@ -502,27 +501,28 @@ function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false) $type = $recordSet->MetaType($field->type); if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) || - $arrFields[$upperfname] === 'null') { - $values .= "null, "; + $arrFields[$upperfname] === 'null' + ) { + $values .= "null, "; } else { //we do this so each driver can customize the sql for //DB specific column types. //Oracle needs BLOB types to be handled with a returning clause //postgres has special needs as well $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, - $arrFields, $magicq); + $arrFields, $magicq); } } } // If there were any inserted fields then build the rest of the insert query. - if ($fieldInsertedCount <= 0) return false; + if ($fieldInsertedCount <= 0) return false; // Get the table name from the existing query. if (!$tableName) { - preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName); - $tableName = $tableName[1]; + preg_match("/FROM\s+" . ADODB_TABLE_REGEX . "/is", $rs->sql, $tableName); + $tableName = $tableName[1]; } // Strip off the comma and space on the end of both the fields @@ -531,7 +531,7 @@ function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false) $values = substr($values, 0, -2); // Append the fields and their values to the insert query. - return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )'; + return 'INSERT INTO ' . $tableName . ' ( ' . $fields . ' ) VALUES ( ' . $values . ' )'; } @@ -550,93 +550,93 @@ function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false) * @return string * */ -function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $arrFields, $magicq) +function _adodb_column_sql_oci8(&$zthis, $action, $type, $fname, $arrFields, $magicq) { $sql = ''; // Based on the datatype of the field // Format the value properly for the database - switch($type) { - case 'B': - //in order to handle Blobs correctly, we need - //to do some magic for Oracle - - //we need to create a new descriptor to handle - //this properly - if (!empty($zthis->hasReturningInto)) { - if ($action == 'I') { - $sql = 'empty_blob(), '; + switch ($type) { + case 'B': + //in order to handle Blobs correctly, we need + //to do some magic for Oracle + + //we need to create a new descriptor to handle + //this properly + if (!empty($zthis->hasReturningInto)) { + if ($action == 'I') { + $sql = 'empty_blob(), '; + } else { + $sql = $fname . '=empty_blob(), '; + } + //add the variable to the returning clause array + //so the user can build this later in + //case they want to add more to it + $zthis->_returningArray[$fname] = ':xx' . $fname . 'xx'; } else { - $sql = $fname. '=empty_blob(), '; + //this is to maintain compatibility + //with older adodb versions. + $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq, false); } - //add the variable to the returning clause array - //so the user can build this later in - //case they want to add more to it - $zthis->_returningArray[$fname] = ':xx'.$fname.'xx'; - } else { - //this is to maintain compatibility - //with older adodb versions. - $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq,false); - } - break; - - case "X": - //we need to do some more magic here for long variables - //to handle these correctly in oracle. + break; - //create a safe bind var name - //to avoid conflicts w/ dupes. - if (!empty($zthis->hasReturningInto)) { - if ($action == 'I') { - $sql = ':xx'.$fname.'xx, '; + case "X": + //we need to do some more magic here for long variables + //to handle these correctly in oracle. + + //create a safe bind var name + //to avoid conflicts w/ dupes. + if (!empty($zthis->hasReturningInto)) { + if ($action == 'I') { + $sql = ':xx' . $fname . 'xx, '; + } else { + $sql = $fname . '=:xx' . $fname . 'xx, '; + } + //add the variable to the returning clause array + //so the user can build this later in + //case they want to add more to it + $zthis->_returningArray[$fname] = ':xx' . $fname . 'xx'; } else { - $sql = $fname.'=:xx'.$fname.'xx, '; + //this is to maintain compatibility + //with older adodb versions. + $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq, false); } - //add the variable to the returning clause array - //so the user can build this later in - //case they want to add more to it - $zthis->_returningArray[$fname] = ':xx'.$fname.'xx'; - } else { - //this is to maintain compatibility - //with older adodb versions. - $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq,false); - } - break; + break; - default: - $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq,false); - break; + default: + $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq, false); + break; } return $sql; } -function _adodb_column_sql(&$zthis, $action, $type, $fname, $arrFields, $magicq, $recurse=true) +function _adodb_column_sql(&$zthis, $action, $type, $fname, $arrFields, $magicq, $recurse = true) { if ($recurse) { - switch($zthis->dataProvider) { - case 'postgres': - if ($type == 'L') $type = 'C'; - break; - case 'oci8': - return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $arrFields, $magicq); + switch ($zthis->dataProvider) { + case 'postgres': + if ($type == 'L') $type = 'C'; + break; + case 'oci8': + return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $arrFields, $magicq); } } $sql = ''; - switch($type) { + switch ($type) { case "C": case "X": case 'B': if ($action == 'I') { - $sql = $zthis->qstr($arrFields[$fname],$magicq) . ", "; + $sql = $zthis->qstr($arrFields[$fname], $magicq) . ", "; } else { - $sql .= $fname . "=" . $zthis->qstr($arrFields[$fname],$magicq) . ", "; + $sql .= $fname . "=" . $zthis->qstr($arrFields[$fname], $magicq) . ", "; } - break; + break; case "D": if ($action == 'I') { @@ -662,7 +662,7 @@ function _adodb_column_sql(&$zthis, $action, $type, $fname, $arrFields, $magicq, if ($action == 'I') { $sql .= $val . ", "; } else { - $sql .= $fname . "=" . $val . ", "; + $sql .= $fname . "=" . $val . ", "; } break; } diff --git a/lib/WikiDB/adodb/adodb-pear.inc.php b/lib/WikiDB/adodb/adodb-pear.inc.php index b16b2d2ac..debea0d56 100644 --- a/lib/WikiDB/adodb/adodb-pear.inc.php +++ b/lib/WikiDB/adodb/adodb-pear.inc.php @@ -9,75 +9,75 @@ * * PEAR DB Emulation Layer for ADODB. * - * The following code is modelled on PEAR DB code by Stig Bakken <ssb@fast.no> | - * and Tomas V.V.Cox <cox@idecnet.com>. Portions (c)1997-2002 The PHP Group. + * The following code is modelled on PEAR DB code by Stig Bakken <ssb@fast.no> | + * and Tomas V.V.Cox <cox@idecnet.com>. Portions (c)1997-2002 The PHP Group. */ - /* - We support: - - DB_Common - --------- - query - returns PEAR_Error on error - limitQuery - return PEAR_Error on error - prepare - does not return PEAR_Error on error - execute - does not return PEAR_Error on error - setFetchMode - supports ASSOC and ORDERED - errorNative - quote - nextID - disconnect - - DB_Result - --------- - numRows - returns -1 if not supported - numCols - fetchInto - does not support passing of fetchmode - fetchRows - does not support passing of fetchmode - free - */ - -define('ADODB_PEAR',dirname(__FILE__)); +/* +We support: + +DB_Common +--------- + query - returns PEAR_Error on error + limitQuery - return PEAR_Error on error + prepare - does not return PEAR_Error on error + execute - does not return PEAR_Error on error + setFetchMode - supports ASSOC and ORDERED + errorNative + quote + nextID + disconnect + +DB_Result +--------- + numRows - returns -1 if not supported + numCols + fetchInto - does not support passing of fetchmode + fetchRows - does not support passing of fetchmode + free +*/ + +define('ADODB_PEAR', dirname(__FILE__)); include_once 'PEAR.php'; -include_once ADODB_PEAR."/adodb-errorpear.inc.php"; -include_once ADODB_PEAR."/adodb.inc.php"; +include_once ADODB_PEAR . "/adodb-errorpear.inc.php"; +include_once ADODB_PEAR . "/adodb.inc.php"; if (!defined('DB_OK')) { -define("DB_OK", 1); -define("DB_ERROR",-1); -/** - * This is a special constant that tells DB the user hasn't specified - * any particular get mode, so the default should be used. - */ + define("DB_OK", 1); + define("DB_ERROR", -1); + /** + * This is a special constant that tells DB the user hasn't specified + * any particular get mode, so the default should be used. + */ -define('DB_FETCHMODE_DEFAULT', 0); + define('DB_FETCHMODE_DEFAULT', 0); -/** - * Column data indexed by numbers, ordered from 0 and up - */ + /** + * Column data indexed by numbers, ordered from 0 and up + */ -define('DB_FETCHMODE_ORDERED', 1); + define('DB_FETCHMODE_ORDERED', 1); -/** - * Column data indexed by column names - */ + /** + * Column data indexed by column names + */ -define('DB_FETCHMODE_ASSOC', 2); + define('DB_FETCHMODE_ASSOC', 2); -/* for compatibility */ + /* for compatibility */ -define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED); -define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC); + define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED); + define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC); -/** - * these are constants for the tableInfo-function - * they are bitwised or'ed. so if there are more constants to be defined - * in the future, adjust DB_TABLEINFO_FULL accordingly - */ + /** + * these are constants for the tableInfo-function + * they are bitwised or'ed. so if there are more constants to be defined + * in the future, adjust DB_TABLEINFO_FULL accordingly + */ -define('DB_TABLEINFO_ORDER', 1); -define('DB_TABLEINFO_ORDERTABLE', 2); -define('DB_TABLEINFO_FULL', 3); + define('DB_TABLEINFO_ORDER', 1); + define('DB_TABLEINFO_ORDERTABLE', 2); + define('DB_TABLEINFO_FULL', 3); } /** @@ -100,9 +100,9 @@ class DB function &factory($type) { - include_once(ADODB_DIR."/drivers/adodb-$type.inc.php"); + include_once(ADODB_DIR . "/drivers/adodb-$type.inc.php"); $obj = &NewADOConnection($type); - if (!is_object($obj)) $obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1); + if (!is_object($obj)) $obj =& new PEAR_Error('Unknown Database Driver: ' . $dsninfo['phptype'], -1); return $obj; } @@ -133,47 +133,66 @@ class DB $dsninfo = DB::parseDSN($dsn); } switch ($dsninfo["phptype"]) { - case 'pgsql': $type = 'postgres7'; break; - case 'ifx': $type = 'informix9'; break; - default: $type = $dsninfo["phptype"]; break; + case 'pgsql': + $type = 'postgres7'; + break; + case 'ifx': + $type = 'informix9'; + break; + default: + $type = $dsninfo["phptype"]; + break; } if (is_array($options) && isset($options["debug"]) && - $options["debug"] >= 2) { + $options["debug"] >= 2 + ) { // expose php errors with sufficient debug level - @include_once("adodb-$type.inc.php"); + @include_once("adodb-$type.inc.php"); } else { - @include_once("adodb-$type.inc.php"); + @include_once("adodb-$type.inc.php"); } @$obj =& NewADOConnection($type); if (!is_object($obj)) { - $obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1); + $obj =& new PEAR_Error('Unknown Database Driver: ' . $dsninfo['phptype'], -1); return $obj; } if (is_array($options)) { - foreach($options as $k => $v) { - switch(strtolower($k)) { - case 'persistent': $persist = $v; break; - #ibase - case 'dialect': $obj->dialect = $v; break; - case 'charset': $obj->charset = $v; break; - case 'buffers': $obj->buffers = $v; break; - #ado - case 'charpage': $obj->charPage = $v; break; - #mysql - case 'clientflags': $obj->clientFlags = $v; break; + foreach ($options as $k => $v) { + switch (strtolower($k)) { + case 'persistent': + $persist = $v; + break; + #ibase + case 'dialect': + $obj->dialect = $v; + break; + case 'charset': + $obj->charset = $v; + break; + case 'buffers': + $obj->buffers = $v; + break; + #ado + case 'charpage': + $obj->charPage = $v; + break; + #mysql + case 'clientflags': + $obj->clientFlags = $v; + break; } } } else { - $persist = false; + $persist = false; } - if (isset($dsninfo['socket'])) $dsninfo['hostspec'] .= ':'.$dsninfo['socket']; - else if (isset($dsninfo['port'])) $dsninfo['hostspec'] .= ':'.$dsninfo['port']; + if (isset($dsninfo['socket'])) $dsninfo['hostspec'] .= ':' . $dsninfo['socket']; + else if (isset($dsninfo['port'])) $dsninfo['hostspec'] .= ':' . $dsninfo['port']; - if($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']); - else $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']); + if ($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'], $dsninfo['password'], $dsninfo['database']); + else $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'], $dsninfo['password'], $dsninfo['database']); if (!$ok) $obj = ADODB_PEAR_Error(); return $obj; @@ -199,8 +218,8 @@ class DB function isError($value) { return (is_object($value) && - (strtolower(get_class($value)) == 'db_error' || - is_subclass_of($value, 'db_error'))); + (strtolower(get_class($value)) == 'db_error' || + is_subclass_of($value, 'db_error'))); } /** @@ -215,8 +234,8 @@ class DB function isWarning($value) { return is_object($value) && - (strtolower(get_class( $value )) == "db_warning" || - is_subclass_of($value, "db_warning")); + (strtolower(get_class($value)) == "db_warning" || + is_subclass_of($value, "db_warning")); } /** @@ -258,7 +277,7 @@ class DB } $parsed = array( - 'phptype' => false, + 'phptype' => false, 'dbsyntax' => false, 'protocol' => false, 'hostspec' => false, @@ -292,7 +311,7 @@ class DB // Get (if found): username and password // $dsn => username:password@protocol+hostspec/database - if (($at = strpos($dsn,'@')) !== false) { + if (($at = strpos($dsn, '@')) !== false) { $str = substr($dsn, 0, $at); $dsn = substr($dsn, $at + 1); if (($pos = strpos($str, ':')) !== false) { @@ -305,7 +324,7 @@ class DB // Find protocol and hostspec // $dsn => protocol+hostspec/database - if (($pos=strpos($dsn, '/')) !== false) { + if (($pos = strpos($dsn, '/')) !== false) { $str = substr($dsn, 0, $pos); $dsn = substr($dsn, $pos + 1); } else { @@ -315,7 +334,7 @@ class DB // Get protocol + hostspec // $str => protocol+hostspec - if (($pos=strpos($str, '+')) !== false) { + if (($pos = strpos($str, '+')) !== false) { $parsed['protocol'] = substr($str, 0, $pos); $parsed['hostspec'] = urldecode(substr($str, $pos + 1)); } else { @@ -345,7 +364,7 @@ class DB function assertExtension($name) { if (!extension_loaded($name)) { - $dlext = (strncmp(PHP_OS,'WIN',3) === 0) ? '.dll' : '.so'; + $dlext = (strncmp(PHP_OS, 'WIN', 3) === 0) ? '.dll' : '.so'; @dl($name . $dlext); } if (!extension_loaded($name)) { diff --git a/lib/WikiDB/adodb/adodb-php4.inc.php b/lib/WikiDB/adodb/adodb-php4.inc.php index 65d67fc97..7bf5ef095 100644 --- a/lib/WikiDB/adodb/adodb-php4.inc.php +++ b/lib/WikiDB/adodb/adodb-php4.inc.php @@ -9,5 +9,6 @@ Set tabs to 4. */ -class ADODB_BASE_RS { +class ADODB_BASE_RS +{ } diff --git a/lib/WikiDB/adodb/adodb-time.inc.php b/lib/WikiDB/adodb/adodb-time.inc.php index 1f22d77c8..05094de0c 100644 --- a/lib/WikiDB/adodb/adodb-time.inc.php +++ b/lib/WikiDB/adodb/adodb-time.inc.php @@ -19,11 +19,11 @@ would take too long with the current implementation of adodb_mktime(). This library replaces native functions as follows: <pre> - getdate() with adodb_getdate() - date() with adodb_date() - gmdate() with adodb_gmdate() - mktime() with adodb_mktime() - gmmktime() with adodb_gmmktime() +getdate() with adodb_getdate() +date() with adodb_date() +gmdate() with adodb_gmdate() +mktime() with adodb_mktime() +gmmktime() with adodb_gmmktime() </pre> The parameters are identical, except that adodb_date() accepts a subset @@ -49,7 +49,7 @@ October 4, 1582 (Julian) was followed immediately by Friday, October 15, Since 0.06, we handle this correctly, so: adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582) - == 24 * 3600 (1 day) +== 24 * 3600 (1 day) ============================================================================= @@ -65,7 +65,7 @@ BUG REPORTS These should be posted to the ADOdb forums at - http://phplens.com/lens/lensforum/topics.php?id=4 +http://phplens.com/lens/lensforum/topics.php?id=4 ============================================================================= @@ -106,7 +106,7 @@ Q - Quarter, as in 1, 2, 3, 4 r - RFC 822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200" s - seconds; i.e. "00" to "59" S - English ordinal suffix for the day of the month, 2 characters; - i.e. "st", "nd", "rd" or "th" +i.e. "st", "nd", "rd" or "th" t - number of days in the given month; i.e. "28" to "31" T - Timezone setting of this machine; e.g. "EST" or "MDT" U - seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) @@ -115,8 +115,8 @@ Y - year, 4 digits; e.g. "1999" y - year, 2 digits; e.g. "99" z - day of the year; i.e. "0" to "365" Z - timezone offset in seconds (i.e. "-43200" to "43200"). - The offset for timezones west of UTC is always negative, - and for those east of UTC is always positive. +The offset for timezones west of UTC is always negative, +and for those east of UTC is always positive. </pre> Unsupported: @@ -130,7 +130,7 @@ W - ISO-8601 week number of year, weeks starting on Monday FUNCTION adodb_date2($fmt, $isoDateString = false) Same as adodb_date, but 2nd parameter accepts iso date, eg. - adodb_date2('d-M-Y H:i','2003-12-25 13:01:34'); +adodb_date2('d-M-Y H:i','2003-12-25 13:01:34'); FUNCTION adodb_gmdate($fmt, $timestamp = false) @@ -155,7 +155,7 @@ are currently compulsory. NOTES Useful url for generating test timestamps: - http://www.4webhelp.net/us/timestamp.php +http://www.4webhelp.net/us/timestamp.php Possible future optimizations include @@ -167,7 +167,7 @@ b. Iterate over a block of years (say 12) when searching for the correct year. c. Implement daylight savings, which looks awfully complicated, see - http://webexhibits.org/daylightsaving/ +http://webexhibits.org/daylightsaving/ CHANGELOG - 20 Mar 2004 0.12 @@ -225,7 +225,7 @@ Fixed problem with time-zones west of GMT +0000. - 24 Jan 2003 0.01 First implementation. -*/ + */ /* Initialization */ @@ -233,7 +233,7 @@ First implementation. /* Version Number */ -define('ADODB_DATE_VERSION',0.12); +define('ADODB_DATE_VERSION', 0.12); /* We check for Windows as only +ve ints are accepted as dates on Windows. @@ -249,72 +249,73 @@ define('ADODB_DATE_VERSION',0.12); http://lists.debian.org/debian-glibc/2002/debian-glibc-200205/msg00010.html */ -if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1); +if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS', 1); -function adodb_date_test_date($y1,$m) +function adodb_date_test_date($y1, $m) { //print " $y1/$m "; - $t = adodb_mktime(0,0,0,$m,13,$y1); - if ("$y1-$m-13 00:00:00" != adodb_date('Y-n-d H:i:s',$t)) { + $t = adodb_mktime(0, 0, 0, $m, 13, $y1); + if ("$y1-$m-13 00:00:00" != adodb_date('Y-n-d H:i:s', $t)) { print "<b>$y1 error</b><br>"; return false; } return true; } + /** - Test Suite -*/ +Test Suite + */ function adodb_date_test() { error_reporting(E_ALL); - print "<h4>Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION. "</h4>"; + print "<h4>Testing adodb_date and adodb_mktime. version=" . ADODB_DATE_VERSION . "</h4>"; set_time_limit(0); $fail = false; // This flag disables calling of PHP native functions, so we can properly test the code - if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES',1); + if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES', 1); - $t = adodb_mktime(0,0,0,6,1,2102); - if (!(adodb_date('Y-m-d',$t) == '2102-06-01')) print 'Error in '.adodb_date('Y-m-d',$t).'<br>'; + $t = adodb_mktime(0, 0, 0, 6, 1, 2102); + if (!(adodb_date('Y-m-d', $t) == '2102-06-01')) print 'Error in ' . adodb_date('Y-m-d', $t) . '<br>'; - $t = adodb_mktime(0,0,0,2,1,2102); - if (!(adodb_date('Y-m-d',$t) == '2102-02-01')) print 'Error in '.adodb_date('Y-m-d',$t).'<br>'; + $t = adodb_mktime(0, 0, 0, 2, 1, 2102); + if (!(adodb_date('Y-m-d', $t) == '2102-02-01')) print 'Error in ' . adodb_date('Y-m-d', $t) . '<br>'; print "<p>Testing gregorian <=> julian conversion<p>"; - $t = adodb_mktime(0,0,0,10,11,1492); + $t = adodb_mktime(0, 0, 0, 10, 11, 1492); //http://www.holidayorigins.com/html/columbus_day.html - Friday check - if (!(adodb_date('D Y-m-d',$t) == 'Fri 1492-10-11')) print 'Error in Columbus landing<br>'; + if (!(adodb_date('D Y-m-d', $t) == 'Fri 1492-10-11')) print 'Error in Columbus landing<br>'; - $t = adodb_mktime(0,0,0,2,29,1500); - if (!(adodb_date('Y-m-d',$t) == '1500-02-29')) print 'Error in julian leap years<br>'; + $t = adodb_mktime(0, 0, 0, 2, 29, 1500); + if (!(adodb_date('Y-m-d', $t) == '1500-02-29')) print 'Error in julian leap years<br>'; - $t = adodb_mktime(0,0,0,2,29,1700); - if (!(adodb_date('Y-m-d',$t) == '1700-03-01')) print 'Error in gregorian leap years<br>'; + $t = adodb_mktime(0, 0, 0, 2, 29, 1700); + if (!(adodb_date('Y-m-d', $t) == '1700-03-01')) print 'Error in gregorian leap years<br>'; - print adodb_mktime(0,0,0,10,4,1582).' '; - print adodb_mktime(0,0,0,10,15,1582); - $diff = (adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582)); - if ($diff != 3600*24) print " <b>Error in gregorian correction = ".($diff/3600/24)." days </b><br>"; + print adodb_mktime(0, 0, 0, 10, 4, 1582) . ' '; + print adodb_mktime(0, 0, 0, 10, 15, 1582); + $diff = (adodb_mktime(0, 0, 0, 10, 15, 1582) - adodb_mktime(0, 0, 0, 10, 4, 1582)); + if ($diff != 3600 * 24) print " <b>Error in gregorian correction = " . ($diff / 3600 / 24) . " days </b><br>"; - print " 15 Oct 1582, Fri=".(adodb_dow(1582,10,15) == 5 ? 'Fri' : '<b>Error</b>')."<br>"; - print " 4 Oct 1582, Thu=".(adodb_dow(1582,10,4) == 4 ? 'Thu' : '<b>Error</b>')."<br>"; + print " 15 Oct 1582, Fri=" . (adodb_dow(1582, 10, 15) == 5 ? 'Fri' : '<b>Error</b>') . "<br>"; + print " 4 Oct 1582, Thu=" . (adodb_dow(1582, 10, 4) == 4 ? 'Thu' : '<b>Error</b>') . "<br>"; print "<p>Testing overflow<p>"; - $t = adodb_mktime(0,0,0,3,33,1965); - if (!(adodb_date('Y-m-d',$t) == '1965-04-02')) print 'Error in day overflow 1 <br>'; - $t = adodb_mktime(0,0,0,4,33,1971); - if (!(adodb_date('Y-m-d',$t) == '1971-05-03')) print 'Error in day overflow 2 <br>'; - $t = adodb_mktime(0,0,0,1,60,1965); - if (!(adodb_date('Y-m-d',$t) == '1965-03-01')) print 'Error in day overflow 3 '.adodb_date('Y-m-d',$t).' <br>'; - $t = adodb_mktime(0,0,0,12,32,1965); - if (!(adodb_date('Y-m-d',$t) == '1966-01-01')) print 'Error in day overflow 4 '.adodb_date('Y-m-d',$t).' <br>'; - $t = adodb_mktime(0,0,0,12,63,1965); - if (!(adodb_date('Y-m-d',$t) == '1966-02-01')) print 'Error in day overflow 5 '.adodb_date('Y-m-d',$t).' <br>'; - $t = adodb_mktime(0,0,0,13,3,1965); - if (!(adodb_date('Y-m-d',$t) == '1966-01-03')) print 'Error in mth overflow 1 <br>'; + $t = adodb_mktime(0, 0, 0, 3, 33, 1965); + if (!(adodb_date('Y-m-d', $t) == '1965-04-02')) print 'Error in day overflow 1 <br>'; + $t = adodb_mktime(0, 0, 0, 4, 33, 1971); + if (!(adodb_date('Y-m-d', $t) == '1971-05-03')) print 'Error in day overflow 2 <br>'; + $t = adodb_mktime(0, 0, 0, 1, 60, 1965); + if (!(adodb_date('Y-m-d', $t) == '1965-03-01')) print 'Error in day overflow 3 ' . adodb_date('Y-m-d', $t) . ' <br>'; + $t = adodb_mktime(0, 0, 0, 12, 32, 1965); + if (!(adodb_date('Y-m-d', $t) == '1966-01-01')) print 'Error in day overflow 4 ' . adodb_date('Y-m-d', $t) . ' <br>'; + $t = adodb_mktime(0, 0, 0, 12, 63, 1965); + if (!(adodb_date('Y-m-d', $t) == '1966-02-01')) print 'Error in day overflow 5 ' . adodb_date('Y-m-d', $t) . ' <br>'; + $t = adodb_mktime(0, 0, 0, 13, 3, 1965); + if (!(adodb_date('Y-m-d', $t) == '1966-01-03')) print 'Error in mth overflow 1 <br>'; print "Testing 2-digit => 4-digit year conversion<p>"; if (adodb_year_digit_check(00) != 2000) print "Err 2-digit 2000<br>"; @@ -328,41 +329,41 @@ function adodb_date_test() // Test string formating print "<p>Testing date formating</p>"; $fmt = '\d\a\t\e T Y-m-d H:i:s a A d D F g G h H i j l L m M n O \R\F\C822 r s t U w y Y z Z 2003'; - $s1 = date($fmt,0); - $s2 = adodb_date($fmt,0); + $s1 = date($fmt, 0); + $s2 = adodb_date($fmt, 0); if ($s1 != $s2) { print " date() 0 failed<br>$s1<br>$s2<br>"; } flush(); - for ($i=100; --$i > 0; ) { + for ($i = 100; --$i > 0;) { - $ts = 3600.0*((rand()%60000)+(rand()%60000))+(rand()%60000); - $s1 = date($fmt,$ts); - $s2 = adodb_date($fmt,$ts); + $ts = 3600.0 * ((rand() % 60000) + (rand() % 60000)) + (rand() % 60000); + $s1 = date($fmt, $ts); + $s2 = adodb_date($fmt, $ts); //print "$s1 <br>$s2 <p>"; - $pos = strcmp($s1,$s2); + $pos = strcmp($s1, $s2); if (($s1) != ($s2)) { - for ($j=0,$k=strlen($s1); $j < $k; $j++) { + for ($j = 0, $k = strlen($s1); $j < $k; $j++) { if ($s1[$j] != $s2[$j]) { - print substr($s1,$j).' '; + print substr($s1, $j) . ' '; break; } } print "<b>Error date(): $ts<br><pre> -  \"$s1\" (date len=".strlen($s1).") -  \"$s2\" (adodb_date len=".strlen($s2).")</b></pre><br>"; +  \"$s1\" (date len=" . strlen($s1) . ") +  \"$s2\" (adodb_date len=" . strlen($s2) . ")</b></pre><br>"; $fail = true; } $a1 = getdate($ts); $a2 = adodb_getdate($ts); - $rez = array_diff($a1,$a2); - if (sizeof($rez)>0) { + $rez = array_diff($a1, $a2); + if (sizeof($rez) > 0) { print "<b>Error getdate() $ts</b><br>"; - print_r($a1); + print_r($a1); print "<br>"; - print_r($a2); + print_r($a2); print "<p>"; $fail = true; } @@ -370,36 +371,36 @@ function adodb_date_test() // Test generation of dates outside 1901-2038 print "<p>Testing random dates between 100 and 4000</p>"; - adodb_date_test_date(100,1); - for ($i=100; --$i >= 0;) { - $y1 = 100+rand(0,1970-100); - $m = rand(1,12); - adodb_date_test_date($y1,$m); - - $y1 = 3000-rand(0,3000-1970); - adodb_date_test_date($y1,$m); + adodb_date_test_date(100, 1); + for ($i = 100; --$i >= 0;) { + $y1 = 100 + rand(0, 1970 - 100); + $m = rand(1, 12); + adodb_date_test_date($y1, $m); + + $y1 = 3000 - rand(0, 3000 - 1970); + adodb_date_test_date($y1, $m); } print '<p>'; - $start = 1960+rand(0,10); + $start = 1960 + rand(0, 10); $yrs = 12; - $i = 365.25*86400*($start-1970); - $offset = 36000+rand(10000,60000); - $max = 365*$yrs*86400; + $i = 365.25 * 86400 * ($start - 1970); + $offset = 36000 + rand(10000, 60000); + $max = 365 * $yrs * 86400; $lastyear = 0; // we generate a timestamp, convert it to a date, and convert it back to a timestamp // and check if the roundtrip broke the original timestamp value. - print "Testing $start to ".($start+$yrs).", or $max seconds, offset=$offset: "; + print "Testing $start to " . ($start + $yrs) . ", or $max seconds, offset=$offset: "; for ($max += $i; $i < $max; $i += $offset) { - $ret = adodb_date('m,d,Y,H,i,s',$i); - $arr = explode(',',$ret); + $ret = adodb_date('m,d,Y,H,i,s', $i); + $arr = explode(',', $ret); if ($lastyear != $arr[2]) { $lastyear = $arr[2]; print " $lastyear "; flush(); } - $newi = adodb_mktime($arr[3],$arr[4],$arr[5],$arr[0],$arr[1],$arr[2]); + $newi = adodb_mktime($arr[3], $arr[4], $arr[5], $arr[0], $arr[1], $arr[2]); if ($i != $newi) { print "Error at $i, adodb_mktime returned $newi ($ret)"; $fail = true; @@ -412,55 +413,56 @@ function adodb_date_test() } /** - Returns day of week, 0 = Sunday,... 6=Saturday. - Algorithm from PEAR::Date_Calc -*/ +Returns day of week, 0 = Sunday,... 6=Saturday. +Algorithm from PEAR::Date_Calc + */ function adodb_dow($year, $month, $day) { -/* -Pope Gregory removed 10 days - October 5 to October 14 - from the year 1582 and -proclaimed that from that time onwards 3 days would be dropped from the calendar -every 400 years. + /* + Pope Gregory removed 10 days - October 5 to October 14 - from the year 1582 and + proclaimed that from that time onwards 3 days would be dropped from the calendar + every 400 years. -Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 15, 1582 (Gregorian). -*/ + Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 15, 1582 (Gregorian). + */ if ($year <= 1582) { if ($year < 1582 || - ($year == 1582 && ($month < 10 || ($month == 10 && $day < 15)))) $greg_correction = 3; - else + ($year == 1582 && ($month < 10 || ($month == 10 && $day < 15))) + ) $greg_correction = 3; + else $greg_correction = 0; } else $greg_correction = 0; - if($month > 2) + if ($month > 2) $month -= 2; else { $month += 10; $year--; } - $day = ( floor((13 * $month - 1) / 5) + - $day + ($year % 100) + - floor(($year % 100) / 4) + - floor(($year / 100) / 4) - 2 * - floor($year / 100) + 77); + $day = (floor((13 * $month - 1) / 5) + + $day + ($year % 100) + + floor(($year % 100) / 4) + + floor(($year / 100) / 4) - 2 * + floor($year / 100) + 77); return (($day - 7 * floor($day / 7))) + $greg_correction; } /** - Checks for leap year, returns true if it is. No 2-digit year check. Also - handles julian calendar correctly. -*/ +Checks for leap year, returns true if it is. No 2-digit year check. Also +handles julian calendar correctly. + */ function _adodb_is_leap_year($year) { if ($year % 4 != 0) return false; if ($year % 400 == 0) { return true; - // if gregorian calendar (>1582), century not-divisible by 400 is not leap - } elseif ($year > 1582 && $year % 100 == 0 ) { + // if gregorian calendar (>1582), century not-divisible by 400 is not leap + } elseif ($year > 1582 && $year % 100 == 0) { return false; } @@ -468,25 +470,25 @@ function _adodb_is_leap_year($year) } /** - checks for leap year, returns true if it is. Has 2-digit year check -*/ +checks for leap year, returns true if it is. Has 2-digit year check + */ function adodb_is_leap_year($year) { - return _adodb_is_leap_year(adodb_year_digit_check($year)); + return _adodb_is_leap_year(adodb_year_digit_check($year)); } /** - Fix 2-digit years. Works for any century. - Assumes that if 2-digit is more than 30 years in future, then previous century. -*/ +Fix 2-digit years. Works for any century. +Assumes that if 2-digit is more than 30 years in future, then previous century. + */ function adodb_year_digit_check($y) { if ($y < 100) { - $yr = (integer) date("Y"); - $century = (integer) ($yr /100); + $yr = (integer)date("Y"); + $century = (integer)($yr / 100); - if ($yr%100 > 50) { + if ($yr % 100 > 50) { $c1 = $century + 1; $c0 = $century; } else { @@ -496,28 +498,28 @@ function adodb_year_digit_check($y) $c1 *= 100; // if 2-digit year is less than 30 years in future, set it to this century // otherwise if more than 30 years in future, then we set 2-digit year to the prev century. - if (($y + $c1) < $yr+30) $y = $y + $c1; - else $y = $y + $c0*100; + if (($y + $c1) < $yr + 30) $y = $y + $c1; + else $y = $y + $c0 * 100; } return $y; } /** - get local time zone offset from GMT -*/ +get local time zone offset from GMT + */ function adodb_get_gmt_diff() { -static $TZ; + static $TZ; if (isset($TZ)) return $TZ; - $TZ = mktime(0,0,0,1,2,1970,0) - gmmktime(0,0,0,1,2,1970,0); + $TZ = mktime(0, 0, 0, 1, 2, 1970, 0) - gmmktime(0, 0, 0, 1, 2, 1970, 0); return $TZ; } /** - Returns an array with date info. -*/ -function adodb_getdate($d=false,$fast=false) +Returns an array with date info. + */ +function adodb_getdate($d = false, $fast = false) { if ($d === false) return getdate(); if (!defined('ADODB_TEST_DATES')) { @@ -530,28 +532,28 @@ function adodb_getdate($d=false,$fast=false) } /** - Low-level function that returns the getdate() array. We have a special - $fast flag, which if set to true, will return fewer array values, - and is much faster as it does not calculate dow, etc. -*/ -function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) +Low-level function that returns the getdate() array. We have a special +$fast flag, which if set to true, will return fewer array values, +and is much faster as it does not calculate dow, etc. + */ +function _adodb_getdate($origd = false, $fast = false, $is_gmt = false) { - $d = $origd - ($is_gmt ? 0 : adodb_get_gmt_diff()); + $d = $origd - ($is_gmt ? 0 : adodb_get_gmt_diff()); $_day_power = 86400; $_hour_power = 3600; $_min_power = 60; - if ($d < -12219321600) $d -= 86400*10; // if 15 Oct 1582 or earlier, gregorian correction + if ($d < -12219321600) $d -= 86400 * 10; // if 15 Oct 1582 or earlier, gregorian correction - $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); - $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); + $_month_table_normal = array("", 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); + $_month_table_leaf = array("", 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); if ($d < 0) { $origd = $d; // The valid range of a 32bit signed timestamp is typically from // Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT - for ($a = 1970 ; --$a >= 0;) { + for ($a = 1970; --$a >= 0;) { $lastd = $d; if ($leaf = _adodb_is_leap_year($a)) { @@ -568,7 +570,7 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) $d = $lastd; $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; - for ($a = 13 ; --$a > 0;) { + for ($a = 13; --$a > 0;) { $lastd = $d; $d += $mtab[$a] * $_day_power; if ($d >= 0) { @@ -579,14 +581,14 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) } $d = $lastd; - $day = $ndays + ceil(($d+1) / ($_day_power)); + $day = $ndays + ceil(($d + 1) / ($_day_power)); - $d += ($ndays - $day+1)* $_day_power; - $hour = floor($d/$_hour_power); + $d += ($ndays - $day + 1) * $_day_power; + $hour = floor($d / $_hour_power); } else { - for ($a = 1970 ;; $a++) { + for ($a = 1970; ; $a++) { $lastd = $d; if ($leaf = _adodb_is_leap_year($a)) { @@ -601,7 +603,7 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) $secsInYear = $lastd; $d = $lastd; $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; - for ($a = 1 ; $a <= 12; $a++) { + for ($a = 1; $a <= 12; $a++) { $lastd = $d; $d -= $mtab[$a] * $_day_power; if ($d < 0) { @@ -611,30 +613,30 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) } } $d = $lastd; - $day = ceil(($d+1) / $_day_power); - $d = $d - ($day-1) * $_day_power; - $hour = floor($d /$_hour_power); + $day = ceil(($d + 1) / $_day_power); + $d = $d - ($day - 1) * $_day_power; + $hour = floor($d / $_hour_power); } $d -= $hour * $_hour_power; - $min = floor($d/$_min_power); + $min = floor($d / $_min_power); $secs = $d - $min * $_min_power; if ($fast) { return array( - 'seconds' => $secs, - 'minutes' => $min, - 'hours' => $hour, - 'mday' => $day, - 'mon' => $month, - 'year' => $year, - 'yday' => floor($secsInYear/$_day_power), - 'leap' => $leaf, - 'ndays' => $ndays + 'seconds' => $secs, + 'minutes' => $min, + 'hours' => $hour, + 'mday' => $day, + 'mon' => $month, + 'year' => $year, + 'yday' => floor($secsInYear / $_day_power), + 'leap' => $leaf, + 'ndays' => $ndays ); } - $dow = adodb_dow($year,$month,$day); + $dow = adodb_dow($year, $month, $day); return array( 'seconds' => $secs, @@ -644,50 +646,51 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) 'wday' => $dow, 'mon' => $month, 'year' => $year, - 'yday' => floor($secsInYear/$_day_power), - 'weekday' => gmdate('l',$_day_power*(3+$dow)), - 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)), + 'yday' => floor($secsInYear / $_day_power), + 'weekday' => gmdate('l', $_day_power * (3 + $dow)), + 'month' => gmdate('F', mktime(0, 0, 0, $month, 2, 1971)), 0 => $origd ); } -function adodb_gmdate($fmt,$d=false) +function adodb_gmdate($fmt, $d = false) { - return adodb_date($fmt,$d,true); + return adodb_date($fmt, $d, true); } -function adodb_date2($fmt, $d=false, $is_gmt=false) +function adodb_date2($fmt, $d = false, $is_gmt = false) { if ($d !== false) { if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", - ($d), $rr)) return adodb_date($fmt,false,$is_gmt); + ($d), $rr) + ) return adodb_date($fmt, false, $is_gmt); - if ($rr[1] <= 100 && $rr[2]<= 1) return adodb_date($fmt,false,$is_gmt); + if ($rr[1] <= 100 && $rr[2] <= 1) return adodb_date($fmt, false, $is_gmt); // h-m-s-MM-DD-YY - if (!isset($rr[5])) $d = adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); - else $d = @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); + if (!isset($rr[5])) $d = adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]); + else $d = @adodb_mktime($rr[5], $rr[6], $rr[7], $rr[2], $rr[3], $rr[1]); } - return adodb_date($fmt,$d,$is_gmt); + return adodb_date($fmt, $d, $is_gmt); } /** - Return formatted date based on timestamp $d -*/ -function adodb_date($fmt,$d=false,$is_gmt=false) +Return formatted date based on timestamp $d + */ +function adodb_date($fmt, $d = false, $is_gmt = false) { if ($d === false) return date($fmt); if (!defined('ADODB_TEST_DATES')) { if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer - return @date($fmt,$d); + return @date($fmt, $d); } } $_day_power = 86400; - $arr = _adodb_getdate($d,true,$is_gmt); + $arr = _adodb_getdate($d, true, $is_gmt); $year = $arr['year']; $month = $arr['mon']; $day = $arr['mday']; @@ -702,131 +705,173 @@ function adodb_date($fmt,$d=false,$is_gmt=false) at this point, we have the following integer vars to manipulate: $year, $month, $day, $hour, $min, $secs */ - for ($i=0; $i < $max; $i++) { - switch($fmt[$i]) { - case 'T': $dates .= date('T');break; - // YEAR - case 'L': $dates .= $arr['leap'] ? '1' : '0'; break; - case 'r': // Thu, 21 Dec 2000 16:01:07 +0200 - - $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))).', ' - . ($day<10?' '.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' '; - - if ($hour < 10) $dates .= '0'.$hour; else $dates .= $hour; - - if ($min < 10) $dates .= ':0'.$min; else $dates .= ':'.$min; - - if ($secs < 10) $dates .= ':0'.$secs; else $dates .= ':'.$secs; - - $gmt = adodb_get_gmt_diff(); - $dates .= sprintf(' %s%04d',($gmt<0)?'+':'-',abs($gmt)/36); break; - - case 'Y': $dates .= $year; break; - case 'y': $dates .= substr($year,strlen($year)-2,2); break; - // MONTH - case 'm': if ($month<10) $dates .= '0'.$month; else $dates .= $month; break; - case 'Q': $dates .= ($month+3)>>2; break; - case 'n': $dates .= $month; break; - case 'M': $dates .= date('M',mktime(0,0,0,$month,2,1971)); break; - case 'F': $dates .= date('F',mktime(0,0,0,$month,2,1971)); break; - // DAY - case 't': $dates .= $arr['ndays']; break; - case 'z': $dates .= $arr['yday']; break; - case 'w': $dates .= adodb_dow($year,$month,$day); break; - case 'l': $dates .= gmdate('l',$_day_power*(3+adodb_dow($year,$month,$day))); break; - case 'D': $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))); break; - case 'j': $dates .= $day; break; - case 'd': if ($day<10) $dates .= '0'.$day; else $dates .= $day; break; - case 'S': - $d10 = $day % 10; - if ($d10 == 1) $dates .= 'st'; - else if ($d10 == 2) $dates .= 'nd'; - else if ($d10 == 3) $dates .= 'rd'; - else $dates .= 'th'; - break; + for ($i = 0; $i < $max; $i++) { + switch ($fmt[$i]) { + case 'T': + $dates .= date('T'); + break; + // YEAR + case 'L': + $dates .= $arr['leap'] ? '1' : '0'; + break; + case 'r': // Thu, 21 Dec 2000 16:01:07 +0200 - // HOUR - case 'Z': - $dates .= ($is_gmt) ? 0 : -adodb_get_gmt_diff(); break; - case 'O': - $gmt = ($is_gmt) ? 0 : adodb_get_gmt_diff(); - $dates .= sprintf('%s%04d',($gmt<0)?'+':'-',abs($gmt)/36); break; + $dates .= gmdate('D', $_day_power * (3 + adodb_dow($year, $month, $day))) . ', ' + . ($day < 10 ? ' ' . $day : $day) . ' ' . date('M', mktime(0, 0, 0, $month, 2, 1971)) . ' ' . $year . ' '; - case 'H': - if ($hour < 10) $dates .= '0'.$hour; - else $dates .= $hour; - break; - case 'h': - if ($hour > 12) $hh = $hour - 12; - else { - if ($hour == 0) $hh = '12'; - else $hh = $hour; - } + if ($hour < 10) $dates .= '0' . $hour; else $dates .= $hour; - if ($hh < 10) $dates .= '0'.$hh; - else $dates .= $hh; - break; + if ($min < 10) $dates .= ':0' . $min; else $dates .= ':' . $min; - case 'G': - $dates .= $hour; - break; + if ($secs < 10) $dates .= ':0' . $secs; else $dates .= ':' . $secs; - case 'g': - if ($hour > 12) $hh = $hour - 12; - else { - if ($hour == 0) $hh = '12'; - else $hh = $hour; - } - $dates .= $hh; - break; - // MINUTES - case 'i': if ($min < 10) $dates .= '0'.$min; else $dates .= $min; break; - // SECONDS - case 'U': $dates .= $d; break; - case 's': if ($secs < 10) $dates .= '0'.$secs; else $dates .= $secs; break; - // AM/PM - // Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM - case 'a': - if ($hour>=12) $dates .= 'pm'; - else $dates .= 'am'; - break; - case 'A': - if ($hour>=12) $dates .= 'PM'; - else $dates .= 'AM'; - break; - default: - $dates .= $fmt[$i]; break; - // ESCAPE - case "\\": - $i++; - if ($i < $max) $dates .= $fmt[$i]; - break; + $gmt = adodb_get_gmt_diff(); + $dates .= sprintf(' %s%04d', ($gmt < 0) ? '+' : '-', abs($gmt) / 36); + break; + + case 'Y': + $dates .= $year; + break; + case 'y': + $dates .= substr($year, strlen($year) - 2, 2); + break; + // MONTH + case 'm': + if ($month < 10) $dates .= '0' . $month; else $dates .= $month; + break; + case 'Q': + $dates .= ($month + 3) >> 2; + break; + case 'n': + $dates .= $month; + break; + case 'M': + $dates .= date('M', mktime(0, 0, 0, $month, 2, 1971)); + break; + case 'F': + $dates .= date('F', mktime(0, 0, 0, $month, 2, 1971)); + break; + // DAY + case 't': + $dates .= $arr['ndays']; + break; + case 'z': + $dates .= $arr['yday']; + break; + case 'w': + $dates .= adodb_dow($year, $month, $day); + break; + case 'l': + $dates .= gmdate('l', $_day_power * (3 + adodb_dow($year, $month, $day))); + break; + case 'D': + $dates .= gmdate('D', $_day_power * (3 + adodb_dow($year, $month, $day))); + break; + case 'j': + $dates .= $day; + break; + case 'd': + if ($day < 10) $dates .= '0' . $day; else $dates .= $day; + break; + case 'S': + $d10 = $day % 10; + if ($d10 == 1) $dates .= 'st'; + else if ($d10 == 2) $dates .= 'nd'; + else if ($d10 == 3) $dates .= 'rd'; + else $dates .= 'th'; + break; + + // HOUR + case 'Z': + $dates .= ($is_gmt) ? 0 : -adodb_get_gmt_diff(); + break; + case 'O': + $gmt = ($is_gmt) ? 0 : adodb_get_gmt_diff(); + $dates .= sprintf('%s%04d', ($gmt < 0) ? '+' : '-', abs($gmt) / 36); + break; + + case 'H': + if ($hour < 10) $dates .= '0' . $hour; + else $dates .= $hour; + break; + case 'h': + if ($hour > 12) $hh = $hour - 12; + else { + if ($hour == 0) $hh = '12'; + else $hh = $hour; + } + + if ($hh < 10) $dates .= '0' . $hh; + else $dates .= $hh; + break; + + case 'G': + $dates .= $hour; + break; + + case 'g': + if ($hour > 12) $hh = $hour - 12; + else { + if ($hour == 0) $hh = '12'; + else $hh = $hour; + } + $dates .= $hh; + break; + // MINUTES + case 'i': + if ($min < 10) $dates .= '0' . $min; else $dates .= $min; + break; + // SECONDS + case 'U': + $dates .= $d; + break; + case 's': + if ($secs < 10) $dates .= '0' . $secs; else $dates .= $secs; + break; + // AM/PM + // Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM + case 'a': + if ($hour >= 12) $dates .= 'pm'; + else $dates .= 'am'; + break; + case 'A': + if ($hour >= 12) $dates .= 'PM'; + else $dates .= 'AM'; + break; + default: + $dates .= $fmt[$i]; + break; + // ESCAPE + case "\\": + $i++; + if ($i < $max) $dates .= $fmt[$i]; + break; } } return $dates; } /** - Returns a timestamp given a GMT/UTC time. - Note that $is_dst is not implemented and is ignored. -*/ -function adodb_gmmktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false) +Returns a timestamp given a GMT/UTC time. +Note that $is_dst is not implemented and is ignored. + */ +function adodb_gmmktime($hr, $min, $sec, $mon, $day, $year, $is_dst = false) { - return adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst,true); + return adodb_mktime($hr, $min, $sec, $mon, $day, $year, $is_dst, true); } /** - Return a timestamp given a local time. Originally by jackbbs. - Note that $is_dst is not implemented and is ignored. -*/ -function adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false,$is_gmt=false) +Return a timestamp given a local time. Originally by jackbbs. +Note that $is_dst is not implemented and is ignored. + */ +function adodb_mktime($hr, $min, $sec, $mon, $day, $year, $is_dst = false, $is_gmt = false) { if (!defined('ADODB_TEST_DATES')) { // for windows, we don't check 1970 because with timezone differences, // 1 Jan 1970 could generate negative timestamp, which is illegal if (!defined('ADODB_NO_NEGATIVE_TS') || ($year >= 1971)) if (1901 < $year && $year < 2038) - return @mktime($hr,$min,$sec,$mon,$day,$year); + return @mktime($hr, $min, $sec, $mon, $day, $year); } $gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_diff(); @@ -843,19 +888,19 @@ function adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false,$is_gmt=false) if ($mon > 12) { $y = floor($mon / 12); $year += $y; - $mon -= $y*12; + $mon -= $y * 12; } $_day_power = 86400; $_hour_power = 3600; $_min_power = 60; - $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); - $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); + $_month_table_normal = array("", 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); + $_month_table_leaf = array("", 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); $_total_date = 0; if ($year >= 1970) { - for ($a = 1970 ; $a <= $year; $a++) { + for ($a = 1970; $a <= $year; $a++) { $leaf = _adodb_is_leap_year($a); if ($leaf == true) { $loop_table = $_month_table_leaf; @@ -867,16 +912,16 @@ function adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false,$is_gmt=false) if ($a < $year) { $_total_date += $_add_date; } else { - for($b=1;$b<$mon;$b++) { + for ($b = 1; $b < $mon; $b++) { $_total_date += $loop_table[$b]; } } } - $_total_date +=$day-1; + $_total_date += $day - 1; $ret = $_total_date * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different; } else { - for ($a = 1969 ; $a >= $year; $a--) { + for ($a = 1969; $a >= $year; $a--) { $leaf = _adodb_is_leap_year($a); if ($leaf == true) { $loop_table = $_month_table_leaf; @@ -885,9 +930,10 @@ function adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false,$is_gmt=false) $loop_table = $_month_table_normal; $_add_date = 365; } - if ($a > $year) { $_total_date += $_add_date; + if ($a > $year) { + $_total_date += $_add_date; } else { - for($b=12;$b>$mon;$b--) { + for ($b = 12; $b > $mon; $b--) { $_total_date += $loop_table[$b]; } } @@ -896,8 +942,8 @@ function adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false,$is_gmt=false) $_day_time = $hr * $_hour_power + $min * $_min_power + $sec; $_day_time = $_day_power - $_day_time; - $ret = -( $_total_date * $_day_power + $_day_time - $gmt_different); - if ($ret < -12220185600) $ret += 10*86400; // if earlier than 5 Oct 1582 - gregorian correction + $ret = -($_total_date * $_day_power + $_day_time - $gmt_different); + if ($ret < -12220185600) $ret += 10 * 86400; // if earlier than 5 Oct 1582 - gregorian correction else if ($ret < -12219321600) $ret = -12219321600; // if in limbo, reset to 15 Oct 1582. } //print " dmy=$day/$mon/$year $hr:$min:$sec => " .$ret; diff --git a/lib/WikiDB/adodb/adodb.inc.php b/lib/WikiDB/adodb/adodb.inc.php index fdb6f91d9..2e55626df 100644 --- a/lib/WikiDB/adodb/adodb.inc.php +++ b/lib/WikiDB/adodb/adodb.inc.php @@ -12,29 +12,29 @@ */ /** - \mainpage +\mainpage - @version V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). All rights reserved. +@version V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). All rights reserved. - Released under both BSD license and Lesser GPL library license. You can choose which license - you prefer. +Released under both BSD license and Lesser GPL library license. You can choose which license +you prefer. - PHP's database access functions are not standardised. This creates a need for a database - class library to hide the differences between the different database API's (encapsulate - the differences) so we can easily switch databases. +PHP's database access functions are not standardised. This creates a need for a database +class library to hide the differences between the different database API's (encapsulate +the differences) so we can easily switch databases. - We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2, - Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access, - ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and - other databases via ODBC. +We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2, +Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access, +ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and +other databases via ODBC. - Latest Download at http://php.weblogs.com/adodb<br> - Manual is at http://php.weblogs.com/adodb_manual +Latest Download at http://php.weblogs.com/adodb<br> +Manual is at http://php.weblogs.com/adodb_manual */ - if (!defined('_ADODB_LAYER')) { - define('_ADODB_LAYER',1); +if (!defined('_ADODB_LAYER')) { + define('_ADODB_LAYER', 1); //========================================================================== // CONSTANT DEFINITIONS @@ -44,19 +44,19 @@ * Set ADODB_DIR to the directory where this file resides... * This constant was formerly called $ADODB_RootPath */ - if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__)); + if (!defined('ADODB_DIR')) define('ADODB_DIR', dirname(__FILE__)); //========================================================================== // GLOBAL VARIABLES //========================================================================== GLOBAL - $ADODB_vers, // database version - $ADODB_COUNTRECS, // count number of records returned - slows down query - $ADODB_CACHE_DIR, // directory to cache recordsets - $ADODB_EXTENSION, // ADODB extension installed - $ADODB_COMPAT_PATCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF - $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default... + $ADODB_vers, // database version + $ADODB_COUNTRECS, // count number of records returned - slows down query + $ADODB_CACHE_DIR, // directory to cache recordsets + $ADODB_EXTENSION, // ADODB extension installed + $ADODB_COMPAT_PATCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF + $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default... //========================================================================== // GLOBAL SETUP @@ -65,16 +65,16 @@ $ADODB_EXTENSION = defined('ADODB_EXTENSION'); if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) { - define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>'); + define('ADODB_BAD_RS', '<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>'); - // allow [ ] @ ` " and . in table names - define('ADODB_TABLE_REGEX','([]0-9a-z_\"\`\.\@\[-]*)'); + // allow [ ] @ ` " and . in table names + define('ADODB_TABLE_REGEX', '([]0-9a-z_\"\`\.\@\[-]*)'); - // prefetching used by oracle - if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10); + // prefetching used by oracle + if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS', 10); - /* + /* Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names. This currently works only with mssql, odbc, oci8po and ibase derived drivers. @@ -83,21 +83,21 @@ 2 = use native-case field names. $rs->fields['OrderID'] */ - define('ADODB_FETCH_DEFAULT',0); - define('ADODB_FETCH_NUM',1); - define('ADODB_FETCH_ASSOC',2); - define('ADODB_FETCH_BOTH',3); + define('ADODB_FETCH_DEFAULT', 0); + define('ADODB_FETCH_NUM', 1); + define('ADODB_FETCH_ASSOC', 2); + define('ADODB_FETCH_BOTH', 3); - if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100); + if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR', 100); - if (strnatcmp(PHP_VERSION,'4.3.0')>=0) { - define('ADODB_PHPVER',0x4300); - } elseif (strnatcmp(PHP_VERSION,'4.2.0')>=0) { - define('ADODB_PHPVER',0x4200); - } elseif (strnatcmp(PHP_VERSION,'4.0.5')>=0) { - define('ADODB_PHPVER',0x4050); + if (strnatcmp(PHP_VERSION, '4.3.0') >= 0) { + define('ADODB_PHPVER', 0x4300); + } elseif (strnatcmp(PHP_VERSION, '4.2.0') >= 0) { + define('ADODB_PHPVER', 0x4200); + } elseif (strnatcmp(PHP_VERSION, '4.0.5') >= 0) { + define('ADODB_PHPVER', 0x4050); } else { - define('ADODB_PHPVER',0x4000); + define('ADODB_PHPVER', 0x4000); } } @@ -105,16 +105,16 @@ /** - Accepts $src and $dest arrays, replacing string $data - */ + Accepts $src and $dest arrays, replacing string $data + */ function ADODB_str_replace($src, $dest, $data) { - if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data); + if (ADODB_PHPVER >= 0x4050) return str_replace($src, $dest, $data); $s = reset($src); $d = reset($dest); while ($s !== false) { - $data = str_replace($s,$d,$data); + $data = str_replace($s, $d, $data); $s = next($src); $d = next($dest); } @@ -123,11 +123,11 @@ function ADODB_Setup() { - GLOBAL - $ADODB_vers, // database version - $ADODB_COUNTRECS, // count number of records returned - slows down query - $ADODB_CACHE_DIR, // directory to cache recordsets - $ADODB_FETCH_MODE; + GLOBAL + $ADODB_vers, // database version + $ADODB_COUNTRECS, // count number of records returned - slows down query + $ADODB_CACHE_DIR, // directory to cache recordsets + $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT; @@ -135,13 +135,13 @@ $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp'; } else { // do not accept url based paths, eg. http:/ or ftp:/ - if (strpos($ADODB_CACHE_DIR,'://') !== false) + if (strpos($ADODB_CACHE_DIR, '://') !== false) die("Illegal path http:// or ftp://"); } // Initialize random number generator for randomizing cache flushes - srand(((double)microtime())*1000000); + srand(((double)microtime()) * 1000000); /** * ADODB version as a string. @@ -169,10 +169,11 @@ /** * Helper class for FetchFields -- holds info on a column */ - class ADOFieldObject { + class ADOFieldObject + { var $name = ''; - var $max_length=0; - var $type=""; + var $max_length = 0; + var $type = ""; // additional fields by dannym... (danny_milo@yahoo.com) var $not_null = false; @@ -180,19 +181,18 @@ // so we can as well make not_null standard (leaving it at "false" does not harm anyways) var $has_default = false; // this one I have done only in mysql and postgres for now ... - // others to come (dannym) + // others to come (dannym) var $default_value; // default, if any, and supported. Check has_default first. } - function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) { //print "Errorno ($fn errno=$errno m=$errmsg) "; $thisConnection->_transOK = false; if ($thisConnection->_oldRaiseFn) { $fn = $thisConnection->_oldRaiseFn; - $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection); + $fn($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection); } } @@ -203,406 +203,406 @@ /** * Connection object. For connecting to databases, and executing queries. */ - class ADOConnection { - // - // PUBLIC VARS - // - var $dataProvider = 'native'; - var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql - var $database = ''; /// Name of database to be used. - var $host = ''; /// The hostname of the database server - var $user = ''; /// The username which is used to connect to the database server. - var $password = ''; /// Password for the username. For security, we no longer store it. - var $debug = false; /// if set to true will output sql statements - var $maxblobsize = 256000; /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro - var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase - var $substr = 'substr'; /// substring operator - var $length = 'length'; /// string length operator - var $random = 'rand()'; /// random function - var $upperCase = false; /// uppercase function - var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database - var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt. - var $true = '1'; /// string that represents TRUE for a database - var $false = '0'; /// string that represents FALSE for a database - var $replaceQuote = "\\'"; /// string to use to replace quotes - var $nameQuote = '"'; /// string to use to quote identifiers and names - var $charSet=false; /// character set to use - only for interbase - var $metaDatabasesSQL = ''; - var $metaTablesSQL = ''; - var $uniqueOrderBy = false; /// All order by columns have to be unique - var $emptyDate = ' '; - var $emptyTimeStamp = ' '; - var $lastInsID = false; - //-- - var $hasInsertID = false; /// supports autoincrement ID? - var $hasAffectedRows = false; /// supports affected rows for update/delete? - var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE - var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10 - var $readOnly = false; /// this is a readonly database - used by phpLens - var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards - var $hasGenID = false; /// can generate sequences using GenID(); - var $hasTransactions = true; /// has transactions - //-- - var $genID = 0; /// sequence id used by GenID(); - var $raiseErrorFn = false; /// error function to call - var $isoDates = false; /// accepts dates in ISO format - var $cacheSecs = 3600; /// cache for 1 hour - var $sysDate = false; /// name of function that returns the current date - var $sysTimeStamp = false; /// name of function that returns the current timestamp - var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets - - var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' ' - var $numCacheHits = 0; - var $numCacheMisses = 0; - var $pageExecuteCountRows = true; - var $uniqueSort = false; /// indicates that all fields in order by must be unique - var $leftOuter = false; /// operator to use for left outer join in WHERE clause - var $rightOuter = false; /// operator to use for right outer join in WHERE clause - var $ansiOuter = false; /// whether ansi outer join syntax supported - var $autoRollback = false; // autoRollback on PConnect(). - var $poorAffectedRows = false; // affectedRows not working or unreliable - - var $fnExecute = false; - var $fnCacheExecute = false; - var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char - var $rsPrefix = "ADORecordSet_"; - - var $autoCommit = true; /// do not modify this yourself - actually private - var $transOff = 0; /// temporarily disable transactions - var $transCnt = 0; /// count of nested transactions - - var $fetchMode=false; - // - // PRIVATE VARS - // - var $_oldRaiseFn = false; - var $_transOK = null; - var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made. - var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will - /// then returned by the errorMsg() function - var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8 - var $_queryID = false; /// This variable keeps the last created result link identifier - - var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */ - var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters. - var $_evalAll = false; - var $_affected = false; - var $_logsql = false; + class ADOConnection + { + // + // PUBLIC VARS + // + var $dataProvider = 'native'; + var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql + var $database = ''; /// Name of database to be used. + var $host = ''; /// The hostname of the database server + var $user = ''; /// The username which is used to connect to the database server. + var $password = ''; /// Password for the username. For security, we no longer store it. + var $debug = false; /// if set to true will output sql statements + var $maxblobsize = 256000; /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro + var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase + var $substr = 'substr'; /// substring operator + var $length = 'length'; /// string length operator + var $random = 'rand()'; /// random function + var $upperCase = false; /// uppercase function + var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database + var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt. + var $true = '1'; /// string that represents TRUE for a database + var $false = '0'; /// string that represents FALSE for a database + var $replaceQuote = "\\'"; /// string to use to replace quotes + var $nameQuote = '"'; /// string to use to quote identifiers and names + var $charSet = false; /// character set to use - only for interbase + var $metaDatabasesSQL = ''; + var $metaTablesSQL = ''; + var $uniqueOrderBy = false; /// All order by columns have to be unique + var $emptyDate = ' '; + var $emptyTimeStamp = ' '; + var $lastInsID = false; + //-- + var $hasInsertID = false; /// supports autoincrement ID? + var $hasAffectedRows = false; /// supports affected rows for update/delete? + var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE + var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10 + var $readOnly = false; /// this is a readonly database - used by phpLens + var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards + var $hasGenID = false; /// can generate sequences using GenID(); + var $hasTransactions = true; /// has transactions + //-- + var $genID = 0; /// sequence id used by GenID(); + var $raiseErrorFn = false; /// error function to call + var $isoDates = false; /// accepts dates in ISO format + var $cacheSecs = 3600; /// cache for 1 hour + var $sysDate = false; /// name of function that returns the current date + var $sysTimeStamp = false; /// name of function that returns the current timestamp + var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets + + var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' ' + var $numCacheHits = 0; + var $numCacheMisses = 0; + var $pageExecuteCountRows = true; + var $uniqueSort = false; /// indicates that all fields in order by must be unique + var $leftOuter = false; /// operator to use for left outer join in WHERE clause + var $rightOuter = false; /// operator to use for right outer join in WHERE clause + var $ansiOuter = false; /// whether ansi outer join syntax supported + var $autoRollback = false; // autoRollback on PConnect(). + var $poorAffectedRows = false; // affectedRows not working or unreliable + + var $fnExecute = false; + var $fnCacheExecute = false; + var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char + var $rsPrefix = "ADORecordSet_"; + + var $autoCommit = true; /// do not modify this yourself - actually private + var $transOff = 0; /// temporarily disable transactions + var $transCnt = 0; /// count of nested transactions + + var $fetchMode = false; + // + // PRIVATE VARS + // + var $_oldRaiseFn = false; + var $_transOK = null; + var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made. + var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will + /// then returned by the errorMsg() function + var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8 + var $_queryID = false; /// This variable keeps the last created result link identifier + + var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */ + var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters. + var $_evalAll = false; + var $_affected = false; + var $_logsql = false; + /** + * Constructor + */ + function ADOConnection() + { + die('Virtual Class -- cannot instantiate'); + } - /** - * Constructor - */ - function ADOConnection() - { - die('Virtual Class -- cannot instantiate'); - } - - /** + /** Get server version info... @returns An array with 2 elements: $arr['string'] is the description string, - and $arr[version] is the version (also a string). - */ - function ServerInfo() - { - return array('description' => '', 'version' => ''); - } - - function _findvers($str) - { - if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1]; - else return ''; - } - - /** - * All error messages go through this bottleneck function. - * You can define your own handler by defining the function name in ADODB_OUTP. - */ - function outp($msg,$newline=true) - { - global $HTTP_SERVER_VARS,$ADODB_FLUSH,$ADODB_OUTP; + and $arr[version] is the version (also a string). + */ + function ServerInfo() + { + return array('description' => '', 'version' => ''); + } - if (defined('ADODB_OUTP')) { - $fn = ADODB_OUTP; - $fn($msg,$newline); - return; - } elseif (isset($ADODB_OUTP)) { - $fn = $ADODB_OUTP; - $fn($msg,$newline); - return; + function _findvers($str) + { + if (preg_match('/([0-9]+\.([0-9\.])+)/', $str, $arr)) return $arr[1]; + else return ''; } - if ($newline) $msg .= "<br>\n"; + /** + * All error messages go through this bottleneck function. + * You can define your own handler by defining the function name in ADODB_OUTP. + */ + function outp($msg, $newline = true) + { + global $HTTP_SERVER_VARS, $ADODB_FLUSH, $ADODB_OUTP; + + if (defined('ADODB_OUTP')) { + $fn = ADODB_OUTP; + $fn($msg, $newline); + return; + } elseif (isset($ADODB_OUTP)) { + $fn = $ADODB_OUTP; + $fn($msg, $newline); + return; + } - if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) echo $msg; - else echo strip_tags($msg); - if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // dp not flush if output buffering enabled - useless - thx to Jesse Mullan + if ($newline) $msg .= "<br>\n"; - } + if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) echo $msg; + else echo strip_tags($msg); + if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // dp not flush if output buffering enabled - useless - thx to Jesse Mullan - function Time() - { - $rs =& $this->Execute("select $this->sysTimeStamp"); - if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields)); + } - return false; - } + function Time() + { + $rs =& $this->Execute("select $this->sysTimeStamp"); + if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields)); - /** - * Connect to database - * - * @param [argHostname] Host to connect to - * @param [argUsername] Userid to login - * @param [argPassword] Associated password - * @param [argDatabaseName] database - * @param [forceNew] force new connection - * - * @return true or false - */ - function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) - { - if ($argHostname != "") $this->host = $argHostname; - if ($argUsername != "") $this->user = $argUsername; - if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons - if ($argDatabaseName != "") $this->database = $argDatabaseName; - - $this->_isPersistentConnection = false; - if ($fn = $this->raiseErrorFn) { - if ($forceNew) { - if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true; - } else { - if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true; - } - $err = $this->ErrorMsg(); - if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; - $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); - } else { - if ($forceNew) { - if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true; + return false; + } + + /** + * Connect to database + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * @param [forceNew] force new connection + * + * @return true or false + */ + function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) + { + if ($argHostname != "") $this->host = $argHostname; + if ($argUsername != "") $this->user = $argUsername; + if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons + if ($argDatabaseName != "") $this->database = $argDatabaseName; + + $this->_isPersistentConnection = false; + if ($fn = $this->raiseErrorFn) { + if ($forceNew) { + if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true; + } else { + if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true; + } + $err = $this->ErrorMsg(); + if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; + $fn($this->databaseType, 'CONNECT', $this->ErrorNo(), $err, $this->host, $this->database, $this); } else { - if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true; + if ($forceNew) { + if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true; + } else { + if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true; + } } + if ($this->debug) ADOConnection::outp($this->host . ': ' . $this->ErrorMsg()); + return false; } - if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg()); - return false; - } - function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) - { - return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName); - } + function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) + { + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName); + } - /** - * Always force a new connection to database - currently only works with oracle - * - * @param [argHostname] Host to connect to - * @param [argUsername] Userid to login - * @param [argPassword] Associated password - * @param [argDatabaseName] database - * - * @return true or false - */ - function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") - { - return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true); - } + /** + * Always force a new connection to database - currently only works with oracle + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * + * @return true or false + */ + function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") + { + return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true); + } - /** - * Establish persistent connect to database - * - * @param [argHostname] Host to connect to - * @param [argUsername] Userid to login - * @param [argPassword] Associated password - * @param [argDatabaseName] database - * - * @return return true or false - */ - function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") - { - if (defined('ADODB_NEVER_PERSIST')) - return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName); + /** + * Establish persistent connect to database + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * + * @return return true or false + */ + function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") + { + if (defined('ADODB_NEVER_PERSIST')) + return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName); - if ($argHostname != "") $this->host = $argHostname; - if ($argUsername != "") $this->user = $argUsername; - if ($argPassword != "") $this->password = $argPassword; - if ($argDatabaseName != "") $this->database = $argDatabaseName; + if ($argHostname != "") $this->host = $argHostname; + if ($argUsername != "") $this->user = $argUsername; + if ($argPassword != "") $this->password = $argPassword; + if ($argDatabaseName != "") $this->database = $argDatabaseName; - $this->_isPersistentConnection = true; + $this->_isPersistentConnection = true; - if ($fn = $this->raiseErrorFn) { - if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true; - $err = $this->ErrorMsg(); - if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; - $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); - } else - if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true; + if ($fn = $this->raiseErrorFn) { + if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true; + $err = $this->ErrorMsg(); + if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; + $fn($this->databaseType, 'PCONNECT', $this->ErrorNo(), $err, $this->host, $this->database, $this); + } else + if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true; - if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg()); - return false; - } + if ($this->debug) ADOConnection::outp($this->host . ': ' . $this->ErrorMsg()); + return false; + } - // Format date column in sql string given an input format that understands Y M D - function SQLDate($fmt, $col=false) - { - if (!$col) $col = $this->sysDate; - return $col; // child class implement - } + // Format date column in sql string given an input format that understands Y M D + function SQLDate($fmt, $col = false) + { + if (!$col) $col = $this->sysDate; + return $col; // child class implement + } - /** - * Should prepare the sql statement and return the stmt resource. - * For databases that do not support this, we return the $sql. To ensure - * compatibility with databases that do not support prepare: - * - * $stmt = $db->Prepare("insert into table (id, name) values (?,?)"); - * $db->Execute($stmt,array(1,'Jill')) or die('insert failed'); - * $db->Execute($stmt,array(2,'Joe')) or die('insert failed'); - * - * @param sql SQL to send to database - * - * @return return FALSE, or the prepared statement, or the original sql if - * if the database does not support prepare. - * - */ - function Prepare($sql) - { - return $sql; - } + /** + * Should prepare the sql statement and return the stmt resource. + * For databases that do not support this, we return the $sql. To ensure + * compatibility with databases that do not support prepare: + * + * $stmt = $db->Prepare("insert into table (id, name) values (?,?)"); + * $db->Execute($stmt,array(1,'Jill')) or die('insert failed'); + * $db->Execute($stmt,array(2,'Joe')) or die('insert failed'); + * + * @param sql SQL to send to database + * + * @return return FALSE, or the prepared statement, or the original sql if + * if the database does not support prepare. + * + */ + function Prepare($sql) + { + return $sql; + } - /** - * Some databases, eg. mssql require a different function for preparing - * stored procedures. So we cannot use Prepare(). - * - * Should prepare the stored procedure and return the stmt resource. - * For databases that do not support this, we return the $sql. To ensure - * compatibility with databases that do not support prepare: - * - * @param sql SQL to send to database - * - * @return return FALSE, or the prepared statement, or the original sql if - * if the database does not support prepare. - * - */ - function PrepareSP($sql,$param=true) - { - return $this->Prepare($sql,$param); - } + /** + * Some databases, eg. mssql require a different function for preparing + * stored procedures. So we cannot use Prepare(). + * + * Should prepare the stored procedure and return the stmt resource. + * For databases that do not support this, we return the $sql. To ensure + * compatibility with databases that do not support prepare: + * + * @param sql SQL to send to database + * + * @return return FALSE, or the prepared statement, or the original sql if + * if the database does not support prepare. + * + */ + function PrepareSP($sql, $param = true) + { + return $this->Prepare($sql, $param); + } - /** - * PEAR DB Compat - */ - function Quote($s) - { - return $this->qstr($s,false); - } + /** + * PEAR DB Compat + */ + function Quote($s) + { + return $this->qstr($s, false); + } - /** - Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de> - */ - function QMagic($s) - { - return $this->qstr($s,get_magic_quotes_gpc()); - } + /** + Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de> + */ + function QMagic($s) + { + return $this->qstr($s, get_magic_quotes_gpc()); + } - function q(&$s) - { - $s = $this->qstr($s,false); - } + function q(&$s) + { + $s = $this->qstr($s, false); + } - /** - * PEAR DB Compat - do not use internally. - */ - function ErrorNative() - { - return $this->ErrorNo(); - } + /** + * PEAR DB Compat - do not use internally. + */ + function ErrorNative() + { + return $this->ErrorNo(); + } - /** - * PEAR DB Compat - do not use internally. - */ - function nextId($seq_name) - { - return $this->GenID($seq_name); - } + /** + * PEAR DB Compat - do not use internally. + */ + function nextId($seq_name) + { + return $this->GenID($seq_name); + } - /** - * Lock a row, will escalate and lock the table if row locking not supported - * will normally free the lock at the end of the transaction - * - * @param $table name of table to lock - * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock - */ - function RowLock($table,$where) - { - return false; - } + /** + * Lock a row, will escalate and lock the table if row locking not supported + * will normally free the lock at the end of the transaction + * + * @param $table name of table to lock + * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock + */ + function RowLock($table, $where) + { + return false; + } - function CommitLock($table) - { - return $this->CommitTrans(); - } + function CommitLock($table) + { + return $this->CommitTrans(); + } - function RollbackLock($table) - { - return $this->RollbackTrans(); - } + function RollbackLock($table) + { + return $this->RollbackTrans(); + } - /** - * PEAR DB Compat - do not use internally. - * - * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical - * for easy porting :-) - * - * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM - * @returns The previous fetch mode - */ - function SetFetchMode($mode) - { - $old = $this->fetchMode; - $this->fetchMode = $mode; + /** + * PEAR DB Compat - do not use internally. + * + * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical + * for easy porting :-) + * + * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM + * @returns The previous fetch mode + */ + function SetFetchMode($mode) + { + $old = $this->fetchMode; + $this->fetchMode = $mode; - if ($old === false) { - global $ADODB_FETCH_MODE; - return $ADODB_FETCH_MODE; + if ($old === false) { + global $ADODB_FETCH_MODE; + return $ADODB_FETCH_MODE; + } + return $old; } - return $old; - } - /** - * PEAR DB Compat - do not use internally. - */ - function &Query($sql, $inputarr=false) - { - $rs = &$this->Execute($sql, $inputarr); - if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - return $rs; - } + /** + * PEAR DB Compat - do not use internally. + */ + function &Query($sql, $inputarr = false) + { + $rs = &$this->Execute($sql, $inputarr); + if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + return $rs; + } - /** - * PEAR DB Compat - do not use internally - */ - function &LimitQuery($sql, $offset, $count, $params=false) - { - $rs = &$this->SelectLimit($sql, $count, $offset, $params); - if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - return $rs; - } + /** + * PEAR DB Compat - do not use internally + */ + function &LimitQuery($sql, $offset, $count, $params = false) + { + $rs = &$this->SelectLimit($sql, $count, $offset, $params); + if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + return $rs; + } - /** - * PEAR DB Compat - do not use internally - */ - function Disconnect() - { - return $this->Close(); - } + /** + * PEAR DB Compat - do not use internally + */ + function Disconnect() + { + return $this->Close(); + } - /* + /* Returns placeholder for parameter, eg. $DB->Param('a') @@ -611,28 +611,28 @@ For databases that require positioned params, eg $1, $2, $3 for postgresql, pass in Param(false) before setting the first parameter. */ - function Param($name) - { - return '?'; - } + function Param($name) + { + return '?'; + } - /* + /* InParameter and OutParameter are self-documenting versions of Parameter(). */ - function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) - { - return $this->Parameter($stmt,$var,$name,false,$maxLen,$type); - } + function InParameter(&$stmt, &$var, $name, $maxLen = 4000, $type = false) + { + return $this->Parameter($stmt, $var, $name, false, $maxLen, $type); + } - /* + /* */ - function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) - { - return $this->Parameter($stmt,$var,$name,true,$maxLen,$type); + function OutParameter(&$stmt, &$var, $name, $maxLen = 4000, $type = false) + { + return $this->Parameter($stmt, $var, $name, true, $maxLen, $type); - } + } - /* + /* Usage in oracle $stmt = $db->Prepare('select * from table where id =:myid and group=:group'); $db->Parameter($stmt,$id,'myid'); @@ -647,1192 +647,1201 @@ @param [$type] The data type of $var. Legal values depend on driver. */ - function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false) - { - return false; - } + function Parameter(&$stmt, &$var, $name, $isOutput = false, $maxLen = 4000, $type = false) + { + return false; + } - /** + /** Improved method of initiating a transaction. Used together with CompleteTrans(). Advantages include: a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans. - Only the outermost block is treated as a transaction.<br> + Only the outermost block is treated as a transaction.<br> b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br> c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block - are disabled, making it backward compatible. - */ - function StartTrans($errfn = 'ADODB_TransMonitor') - { - if ($this->transOff > 0) { - $this->transOff += 1; - return; - } + are disabled, making it backward compatible. + */ + function StartTrans($errfn = 'ADODB_TransMonitor') + { + if ($this->transOff > 0) { + $this->transOff += 1; + return; + } - $this->_oldRaiseFn = $this->raiseErrorFn; - $this->raiseErrorFn = $errfn; - $this->_transOK = true; + $this->_oldRaiseFn = $this->raiseErrorFn; + $this->raiseErrorFn = $errfn; + $this->_transOK = true; - if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans"); - $this->BeginTrans(); - $this->transOff = 1; - } + if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans"); + $this->BeginTrans(); + $this->transOff = 1; + } - /** + /** Used together with StartTrans() to end a transaction. Monitors connection for sql errors, and will commit or rollback as appropriate. @autoComplete if true, monitor sql errors and commit and rollback as appropriate, and if set to false force rollback even if no SQL error detected. @returns true on commit, false on rollback. - */ - function CompleteTrans($autoComplete = true) - { - if ($this->transOff > 1) { - $this->transOff -= 1; - return true; - } - $this->raiseErrorFn = $this->_oldRaiseFn; + */ + function CompleteTrans($autoComplete = true) + { + if ($this->transOff > 1) { + $this->transOff -= 1; + return true; + } + $this->raiseErrorFn = $this->_oldRaiseFn; - $this->transOff = 0; - if ($this->_transOK && $autoComplete) { - if (!$this->CommitTrans()) { - $this->_transOK = false; - if ($this->debug) ADOConnection::outp("Smart Commit failed"); - } else - if ($this->debug) ADOConnection::outp("Smart Commit occurred"); - } else { - $this->RollbackTrans(); - if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred"); - } + $this->transOff = 0; + if ($this->_transOK && $autoComplete) { + if (!$this->CommitTrans()) { + $this->_transOK = false; + if ($this->debug) ADOConnection::outp("Smart Commit failed"); + } else + if ($this->debug) ADOConnection::outp("Smart Commit occurred"); + } else { + $this->RollbackTrans(); + if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred"); + } - return $this->_transOK; - } + return $this->_transOK; + } - /* + /* At the end of a StartTrans/CompleteTrans block, perform a rollback. */ - function FailTrans() - { - if ($this->debug) - if ($this->transOff == 0) { - ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans"); - } else { - ADOConnection::outp("FailTrans was called"); - adodb_backtrace(); - } - $this->_transOK = false; - } + function FailTrans() + { + if ($this->debug) + if ($this->transOff == 0) { + ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans"); + } else { + ADOConnection::outp("FailTrans was called"); + adodb_backtrace(); + } + $this->_transOK = false; + } - /** + /** Check if transaction has failed, only for Smart Transactions. - */ - function HasFailedTrans() - { - if ($this->transOff > 0) return $this->_transOK == false; - return false; - } + */ + function HasFailedTrans() + { + if ($this->transOff > 0) return $this->_transOK == false; + return false; + } - /** - * Execute SQL - * - * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text) - * @param [inputarr] holds the input data to bind to. Null elements will be set to null. - * @return RecordSet or false - */ - function &Execute($sql,$inputarr=false) - { - if ($this->fnExecute) { - $fn = $this->fnExecute; - $ret =& $fn($this,$sql,$inputarr); - if (isset($ret)) return $ret; - } - if ($inputarr && is_array($inputarr)) { - $element0 = reset($inputarr); - # is_object check is because oci8 descriptors can be passed in - $array_2d = is_array($element0) && !is_object(reset($element0)); - - if (!is_array($sql) && !$this->_bindInputArray) { - $sqlarr = explode('?',$sql); - - if (!$array_2d) $inputarr = array($inputarr); - foreach($inputarr as $arr) { - $sql = ''; $i = 0; - foreach($arr as $v) { + /** + * Execute SQL + * + * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text) + * @param [inputarr] holds the input data to bind to. Null elements will be set to null. + * @return RecordSet or false + */ + function &Execute($sql, $inputarr = false) + { + if ($this->fnExecute) { + $fn = $this->fnExecute; + $ret =& $fn($this, $sql, $inputarr); + if (isset($ret)) return $ret; + } + if ($inputarr && is_array($inputarr)) { + $element0 = reset($inputarr); + # is_object check is because oci8 descriptors can be passed in + $array_2d = is_array($element0) && !is_object(reset($element0)); + + if (!is_array($sql) && !$this->_bindInputArray) { + $sqlarr = explode('?', $sql); + + if (!$array_2d) $inputarr = array($inputarr); + foreach ($inputarr as $arr) { + $sql = ''; + $i = 0; + foreach ($arr as $v) { + $sql .= $sqlarr[$i]; + // from Ron Baldwin <ron.baldwin@sourceprose.com> + // Only quote string types + if (gettype($v) == 'string') + $sql .= $this->qstr($v); + else if ($v === null) + $sql .= 'NULL'; + else + $sql .= $v; + $i += 1; + } $sql .= $sqlarr[$i]; - // from Ron Baldwin <ron.baldwin@sourceprose.com> - // Only quote string types - if (gettype($v) == 'string') - $sql .= $this->qstr($v); - else if ($v === null) - $sql .= 'NULL'; - else - $sql .= $v; - $i += 1; - } - $sql .= $sqlarr[$i]; - if ($i+1 != sizeof($sqlarr)) - ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql)); + if ($i + 1 != sizeof($sqlarr)) + ADOConnection::outp("Input Array does not match ?: " . htmlspecialchars($sql)); - $ret =& $this->_Execute($sql,false); - if (!$ret) return $ret; - } - } else { - if ($array_2d) { - $stmt = $this->Prepare($sql); - foreach($inputarr as $arr) { - $ret =& $this->_Execute($stmt,$arr); + $ret =& $this->_Execute($sql, false); if (!$ret) return $ret; } - } else - $ret =& $this->_Execute($sql,$inputarr); + } else { + if ($array_2d) { + $stmt = $this->Prepare($sql); + foreach ($inputarr as $arr) { + $ret =& $this->_Execute($stmt, $arr); + if (!$ret) return $ret; + } + } else + $ret =& $this->_Execute($sql, $inputarr); + } + } else { + $ret =& $this->_Execute($sql, false); } - } else { - $ret =& $this->_Execute($sql,false); - } - return $ret; - } + return $ret; + } - function& _Execute($sql,$inputarr=false) - { + function& _Execute($sql, $inputarr = false) + { - if ($this->debug) { - global $HTTP_SERVER_VARS; + if ($this->debug) { + global $HTTP_SERVER_VARS; - $ss = ''; - if ($inputarr) { - foreach($inputarr as $kk=>$vv) { - if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...'; - $ss .= "($kk=>'$vv') "; + $ss = ''; + if ($inputarr) { + foreach ($inputarr as $kk => $vv) { + if (is_string($vv) && strlen($vv) > 64) $vv = substr($vv, 0, 64) . '...'; + $ss .= "($kk=>'$vv') "; + } + $ss = "[ $ss ]"; } - $ss = "[ $ss ]"; - } - $sqlTxt = str_replace(',',', ',is_array($sql) ?$sql[0] : $sql); + $sqlTxt = str_replace(',', ', ', is_array($sql) ? $sql[0] : $sql); - // check if running from browser or command-line - $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']); + // check if running from browser or command-line + $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']); - if ($inBrowser) { - if ($this->debug === -1) - ADOConnection::outp( "<br>\n($this->databaseType): ".htmlspecialchars($sqlTxt)."   <code>$ss</code>\n<br>\n",false); - else - ADOConnection::outp( "<hr>\n($this->databaseType): ".htmlspecialchars($sqlTxt)."   <code>$ss</code>\n<hr>\n",false); - } else { - ADOConnection::outp("-----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false); - } - $this->_queryID = $this->_query($sql,$inputarr); - /* + if ($inBrowser) { + if ($this->debug === -1) + ADOConnection::outp("<br>\n($this->databaseType): " . htmlspecialchars($sqlTxt) . "   <code>$ss</code>\n<br>\n", false); + else + ADOConnection::outp("<hr>\n($this->databaseType): " . htmlspecialchars($sqlTxt) . "   <code>$ss</code>\n<hr>\n", false); + } else { + ADOConnection::outp("-----\n($this->databaseType): " . ($sqlTxt) . " \n-----\n", false); + } + $this->_queryID = $this->_query($sql, $inputarr); + /* Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion */ - if ($this->databaseType == 'mssql') { - // ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6 - if($emsg = $this->ErrorMsg()) { - if ($err = $this->ErrorNo()) ADOConnection::outp($err.': '.$emsg); + if ($this->databaseType == 'mssql') { + // ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6 + if ($emsg = $this->ErrorMsg()) { + if ($err = $this->ErrorNo()) ADOConnection::outp($err . ': ' . $emsg); + } + } elseif (!$this->_queryID) { + ADOConnection::outp($this->ErrorNo() . ': ' . $this->ErrorMsg()); } - } elseif (!$this->_queryID) { - ADOConnection::outp($this->ErrorNo() .': '. $this->ErrorMsg()); + } else { + //**************************** + // non-debug version of query + //**************************** + + $this->_queryID = @$this->_query($sql, $inputarr); } - } else { - //**************************** - // non-debug version of query - //**************************** - $this->_queryID =@$this->_query($sql,$inputarr); - } + /************************ + // OK, query executed + *************************/ - /************************ - // OK, query executed - *************************/ + if ($this->_queryID === false) { + // error handling if query fails + if ($this->debug == 99) adodb_backtrace(true, 5); + $fn = $this->raiseErrorFn; + if ($fn) { + $fn($this->databaseType, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $sql, $inputarr, $this); + } - if ($this->_queryID === false) { - // error handling if query fails - if ($this->debug == 99) adodb_backtrace(true,5); - $fn = $this->raiseErrorFn; - if ($fn) { - $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this); + return false; } - return false; - } + if ($this->_queryID === true) { + // return simplified empty recordset for inserts/updates/deletes with lower overhead + $rs =& new ADORecordSet_empty(); + return $rs; + } - if ($this->_queryID === true) { - // return simplified empty recordset for inserts/updates/deletes with lower overhead - $rs =& new ADORecordSet_empty(); + // return real recordset from select statement + $rsclass = $this->rsPrefix . $this->databaseType; + $rs =& new $rsclass($this->_queryID, $this->fetchMode); + $rs->connection = &$this; // Pablo suggestion + $rs->Init(); + if (is_array($sql)) $rs->sql = $sql[0]; + else $rs->sql = $sql; + if ($rs->_numOfRows <= 0) { + global $ADODB_COUNTRECS; + + if ($ADODB_COUNTRECS) { + if (!$rs->EOF) { + $rs = &$this->_rs2rs($rs, -1, -1, !is_array($sql)); + $rs->_queryID = $this->_queryID; + } else + $rs->_numOfRows = 0; + } + } return $rs; } - // return real recordset from select statement - $rsclass = $this->rsPrefix.$this->databaseType; - $rs =& new $rsclass($this->_queryID,$this->fetchMode); - $rs->connection = &$this; // Pablo suggestion - $rs->Init(); - if (is_array($sql)) $rs->sql = $sql[0]; - else $rs->sql = $sql; - if ($rs->_numOfRows <= 0) { - global $ADODB_COUNTRECS; - - if ($ADODB_COUNTRECS) { - if (!$rs->EOF){ - $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql)); - $rs->_queryID = $this->_queryID; - } else - $rs->_numOfRows = 0; - } + function CreateSequence($seqname = 'adodbseq', $startID = 1) + { + if (empty($this->_genSeqSQL)) return false; + return $this->Execute(sprintf($this->_genSeqSQL, $seqname, $startID)); } - return $rs; - } - - function CreateSequence($seqname='adodbseq',$startID=1) - { - if (empty($this->_genSeqSQL)) return false; - return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); - } - - function DropSequence($seqname) - { - if (empty($this->_dropSeqSQL)) return false; - return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); - } - /** - * Generates a sequence id and stores it in $this->genID; - * GenID is only available if $this->hasGenID = true; - * - * @param seqname name of sequence to use - * @param startID if sequence does not exist, start at this ID - * @return 0 if not supported, otherwise a sequence id - */ - function GenID($seqname='adodbseq',$startID=1) - { - if (!$this->hasGenID) { - return 0; // formerly returns false pre 1.60 + function DropSequence($seqname) + { + if (empty($this->_dropSeqSQL)) return false; + return $this->Execute(sprintf($this->_dropSeqSQL, $seqname)); } - $getnext = sprintf($this->_genIDSQL,$seqname); + /** + * Generates a sequence id and stores it in $this->genID; + * GenID is only available if $this->hasGenID = true; + * + * @param seqname name of sequence to use + * @param startID if sequence does not exist, start at this ID + * @return 0 if not supported, otherwise a sequence id + */ + function GenID($seqname = 'adodbseq', $startID = 1) + { + if (!$this->hasGenID) { + return 0; // formerly returns false pre 1.60 + } - $holdtransOK = $this->_transOK; - $rs = @$this->Execute($getnext); - if (!$rs) { - $this->_transOK = $holdtransOK; //if the status was ok before reset - $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); - $rs = $this->Execute($getnext); - } - if ($rs && !$rs->EOF) $this->genID = reset($rs->fields); - else $this->genID = 0; // false + $getnext = sprintf($this->_genIDSQL, $seqname); - if ($rs) $rs->Close(); + $holdtransOK = $this->_transOK; + $rs = @$this->Execute($getnext); + if (!$rs) { + $this->_transOK = $holdtransOK; //if the status was ok before reset + $createseq = $this->Execute(sprintf($this->_genSeqSQL, $seqname, $startID)); + $rs = $this->Execute($getnext); + } + if ($rs && !$rs->EOF) $this->genID = reset($rs->fields); + else $this->genID = 0; // false - return $this->genID; - } + if ($rs) $rs->Close(); - /** - * @return the last inserted ID. Not all databases support this. - */ - function Insert_ID() - { - if ($this->_logsql && $this->lastInsID) return $this->lastInsID; - if ($this->hasInsertID) return $this->_insertid(); - if ($this->debug) { - ADOConnection::outp( '<p>Insert_ID error</p>'); - adodb_backtrace(); + return $this->genID; } - return false; - } + /** + * @return the last inserted ID. Not all databases support this. + */ + function Insert_ID() + { + if ($this->_logsql && $this->lastInsID) return $this->lastInsID; + if ($this->hasInsertID) return $this->_insertid(); + if ($this->debug) { + ADOConnection::outp('<p>Insert_ID error</p>'); + adodb_backtrace(); + } + return false; + } - /** - * Portable Insert ID. Pablo Roca <pabloroca@mvps.org> - * - * @return the last inserted ID. All databases support this. But aware possible - * problems in multiuser environments. Heavy test this before deploying. - */ - function PO_Insert_ID($table="", $id="") - { - if ($this->hasInsertID){ - return $this->Insert_ID(); - } else { - return $this->GetOne("SELECT MAX($id) FROM $table"); - } - } - /** - * @return # rows affected by UPDATE/DELETE - */ - function Affected_Rows() - { - if ($this->hasAffectedRows) { - if ($this->fnExecute === 'adodb_log_sql') { - if ($this->_logsql && $this->_affected !== false) return $this->_affected; + /** + * Portable Insert ID. Pablo Roca <pabloroca@mvps.org> + * + * @return the last inserted ID. All databases support this. But aware possible + * problems in multiuser environments. Heavy test this before deploying. + */ + function PO_Insert_ID($table = "", $id = "") + { + if ($this->hasInsertID) { + return $this->Insert_ID(); + } else { + return $this->GetOne("SELECT MAX($id) FROM $table"); } - $val = $this->_affectedrows(); - return ($val < 0) ? false : $val; } - if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false); - return false; - } + /** + * @return # rows affected by UPDATE/DELETE + */ + function Affected_Rows() + { + if ($this->hasAffectedRows) { + if ($this->fnExecute === 'adodb_log_sql') { + if ($this->_logsql && $this->_affected !== false) return $this->_affected; + } + $val = $this->_affectedrows(); + return ($val < 0) ? false : $val; + } + if ($this->debug) ADOConnection::outp('<p>Affected_Rows error</p>', false); + return false; + } - /** - * @return the last error message - */ - function ErrorMsg() - { - return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg; - } + /** + * @return the last error message + */ + function ErrorMsg() + { + return '!! ' . strtoupper($this->dataProvider . ' ' . $this->databaseType) . ': ' . $this->_errorMsg; + } - /** - * @return the last error number. Normally 0 means no error. - */ - function ErrorNo() - { - return ($this->_errorMsg) ? -1 : 0; - } - function MetaError($err=false) - { - include_once(ADODB_DIR."/adodb-error.inc.php"); - if ($err === false) $err = $this->ErrorNo(); - return adodb_error($this->dataProvider,$this->databaseType,$err); - } + /** + * @return the last error number. Normally 0 means no error. + */ + function ErrorNo() + { + return ($this->_errorMsg) ? -1 : 0; + } - function MetaErrorMsg($errno) - { - include_once(ADODB_DIR."/adodb-error.inc.php"); - return adodb_errormsg($errno); - } + function MetaError($err = false) + { + include_once(ADODB_DIR . "/adodb-error.inc.php"); + if ($err === false) $err = $this->ErrorNo(); + return adodb_error($this->dataProvider, $this->databaseType, $err); + } - /** - * @returns an array with the primary key columns in it. - */ - function MetaPrimaryKeys($table, $owner=false) - { - // owner not used in base class - see oci8 - $p = array(); - $objs =& $this->MetaColumns($table); - if ($objs) { - foreach($objs as $v) { - if (!empty($v->primary_key)) - $p[] = $v->name; - } - } - if (sizeof($p)) return $p; - if (function_exists('ADODB_VIEW_PRIMARYKEYS')) - return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner); - return false; - } + function MetaErrorMsg($errno) + { + include_once(ADODB_DIR . "/adodb-error.inc.php"); + return adodb_errormsg($errno); + } - /** - * @returns assoc array where keys are tables, and values are foreign keys - */ - function MetaForeignKeys($table, $owner=false, $upper=false) - { - return false; - } - /** - * Choose a database to connect to. Many databases do not support this. - * - * @param dbName is the name of the database to select - * @return true or false - */ - function SelectDB($dbName) - {return false;} + /** + * @returns an array with the primary key columns in it. + */ + function MetaPrimaryKeys($table, $owner = false) + { + // owner not used in base class - see oci8 + $p = array(); + $objs =& $this->MetaColumns($table); + if ($objs) { + foreach ($objs as $v) { + if (!empty($v->primary_key)) + $p[] = $v->name; + } + } + if (sizeof($p)) return $p; + if (function_exists('ADODB_VIEW_PRIMARYKEYS')) + return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner); + return false; + } + /** + * @returns assoc array where keys are tables, and values are foreign keys + */ + function MetaForeignKeys($table, $owner = false, $upper = false) + { + return false; + } - /** - * Will select, getting rows from $offset (1-based), for $nrows. - * This simulates the MySQL "select * from table limit $offset,$nrows" , and - * the PostgreSQL "select * from table limit $nrows offset $offset". Note that - * MySQL and PostgreSQL parameter ordering is the opposite of the other. - * eg. - * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based) - * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based) - * - * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set) - * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set - * - * @param sql - * @param [offset] is the row to start calculations from (1-based) - * @param [nrows] is the number of rows to get - * @param [inputarr] array of bind variables - * @param [secs2cache] is a private parameter only used by jlim - * @return the recordset ($rs->databaseType == 'array') - */ - function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) - { - if ($this->hasTop && $nrows > 0) { - // suggested by Reinhard Balling. Access requires top after distinct - // Informix requires first before distinct - F Riosa - $ismssql = (strpos($this->databaseType,'mssql') !== false); - if ($ismssql) $isaccess = false; - else $isaccess = (strpos($this->databaseType,'access') !== false); + /** + * Choose a database to connect to. Many databases do not support this. + * + * @param dbName is the name of the database to select + * @return true or false + */ + function SelectDB($dbName) + { + return false; + } - if ($offset <= 0) { + + /** + * Will select, getting rows from $offset (1-based), for $nrows. + * This simulates the MySQL "select * from table limit $offset,$nrows" , and + * the PostgreSQL "select * from table limit $nrows offset $offset". Note that + * MySQL and PostgreSQL parameter ordering is the opposite of the other. + * eg. + * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based) + * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based) + * + * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set) + * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set + * + * @param sql + * @param [offset] is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to get + * @param [inputarr] array of bind variables + * @param [secs2cache] is a private parameter only used by jlim + * @return the recordset ($rs->databaseType == 'array') + */ + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) + { + if ($this->hasTop && $nrows > 0) { + // suggested by Reinhard Balling. Access requires top after distinct + // Informix requires first before distinct - F Riosa + $ismssql = (strpos($this->databaseType, 'mssql') !== false); + if ($ismssql) $isaccess = false; + else $isaccess = (strpos($this->databaseType, 'access') !== false); + + if ($offset <= 0) { // access includes ties in result if ($isaccess) { $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); + '/(^\s*select\s+(distinctrow|distinct)?)/i', '\\1 ' . $this->hasTop . ' ' . $nrows . ' ', $sql); - if ($secs2cache>0) { - $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr); + if ($secs2cache > 0) { + $ret =& $this->CacheExecute($secs2cache, $sql, $inputarr); } else { - $ret =& $this->Execute($sql,$inputarr); + $ret =& $this->Execute($sql, $inputarr); } return $ret; // PHP5 fix - } elseif ($ismssql){ + } elseif ($ismssql) { $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); + '/(^\s*select\s+(distinctrow|distinct)?)/i', '\\1 ' . $this->hasTop . ' ' . $nrows . ' ', $sql); } else { $sql = preg_replace( - '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); + '/(^\s*select\s)/i', '\\1 ' . $this->hasTop . ' ' . $nrows . ' ', $sql); } - } else { - $nn = $nrows + $offset; - if ($isaccess || $ismssql) { - $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); } else { - $sql = preg_replace( - '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); + $nn = $nrows + $offset; + if ($isaccess || $ismssql) { + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i', '\\1 ' . $this->hasTop . ' ' . $nn . ' ', $sql); + } else { + $sql = preg_replace( + '/(^\s*select\s)/i', '\\1 ' . $this->hasTop . ' ' . $nn . ' ', $sql); + } } } - } - // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows - // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS. - global $ADODB_COUNTRECS; + // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows + // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS. + global $ADODB_COUNTRECS; - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; - if ($offset>0){ - if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); - else $rs = &$this->Execute($sql,$inputarr); - } else { - if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); - else $rs = &$this->Execute($sql,$inputarr); - } - $ADODB_COUNTRECS = $savec; - if ($rs && !$rs->EOF) { - $rs =& $this->_rs2rs($rs,$nrows,$offset); + if ($offset > 0) { + if ($secs2cache > 0) $rs = &$this->CacheExecute($secs2cache, $sql, $inputarr); + else $rs = &$this->Execute($sql, $inputarr); + } else { + if ($secs2cache > 0) $rs = &$this->CacheExecute($secs2cache, $sql, $inputarr); + else $rs = &$this->Execute($sql, $inputarr); + } + $ADODB_COUNTRECS = $savec; + if ($rs && !$rs->EOF) { + $rs =& $this->_rs2rs($rs, $nrows, $offset); + } + //print_r($rs); + return $rs; } - //print_r($rs); - return $rs; - } - /** - * Create serializable recordset. Breaks rs link to connection. - * - * @param rs the recordset to serialize - */ - function &SerializableRS(&$rs) - { - $rs2 =& $this->_rs2rs($rs); - $ignore = false; - $rs2->connection =& $ignore; + /** + * Create serializable recordset. Breaks rs link to connection. + * + * @param rs the recordset to serialize + */ + function &SerializableRS(&$rs) + { + $rs2 =& $this->_rs2rs($rs); + $ignore = false; + $rs2->connection =& $ignore; - return $rs2; - } + return $rs2; + } - /** - * Convert database recordset to an array recordset - * input recordset's cursor should be at beginning, and - * old $rs will be closed. - * - * @param rs the recordset to copy - * @param [nrows] number of rows to retrieve (optional) - * @param [offset] offset by number of rows (optional) - * @return the new recordset - */ - function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true) - { - if (! $rs) return false; + /** + * Convert database recordset to an array recordset + * input recordset's cursor should be at beginning, and + * old $rs will be closed. + * + * @param rs the recordset to copy + * @param [nrows] number of rows to retrieve (optional) + * @param [offset] offset by number of rows (optional) + * @return the new recordset + */ + function &_rs2rs(&$rs, $nrows = -1, $offset = -1, $close = true) + { + if (!$rs) return false; - $dbtype = $rs->databaseType; - if (!$dbtype) { - $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ? - return $rs; - } - if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) { - $rs->MoveFirst(); - $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ? - return $rs; - } - $flds = array(); - for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { - $flds[] = $rs->FetchField($i); - } - $arr =& $rs->GetArrayLimit($nrows,$offset); - //print_r($arr); - if ($close) $rs->Close(); + $dbtype = $rs->databaseType; + if (!$dbtype) { + $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ? + return $rs; + } + if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) { + $rs->MoveFirst(); + $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ? + return $rs; + } + $flds = array(); + for ($i = 0, $max = $rs->FieldCount(); $i < $max; $i++) { + $flds[] = $rs->FetchField($i); + } + $arr =& $rs->GetArrayLimit($nrows, $offset); + //print_r($arr); + if ($close) $rs->Close(); - $arrayClass = $this->arrayClass; + $arrayClass = $this->arrayClass; - $rs2 =& new $arrayClass(); - $rs2->connection = &$this; - $rs2->sql = $rs->sql; - $rs2->dataProvider = $this->dataProvider; - $rs2->InitArrayFields($arr,$flds); - return $rs2; - } + $rs2 =& new $arrayClass(); + $rs2->connection = &$this; + $rs2->sql = $rs->sql; + $rs2->dataProvider = $this->dataProvider; + $rs2->InitArrayFields($arr, $flds); + return $rs2; + } - /* + /* * Return all rows. Compat with PEAR DB */ - function &GetAll($sql, $inputarr=false) - { - $arr =& $this->GetArray($sql,$inputarr); - return $arr; - } - - function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false) - { - $rs =& $this->Execute($sql, $inputarr); - if (!$rs) return false; + function &GetAll($sql, $inputarr = false) + { + $arr =& $this->GetArray($sql, $inputarr); + return $arr; + } - $arr =& $rs->GetAssoc($force_array,$first2cols); - return $arr; - } + function &GetAssoc($sql, $inputarr = false, $force_array = false, $first2cols = false) + { + $rs =& $this->Execute($sql, $inputarr); + if (!$rs) return false; - function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false) - { - if (!is_numeric($secs2cache)) { - $first2cols = $force_array; - $force_array = $inputarr; + $arr =& $rs->GetAssoc($force_array, $first2cols); + return $arr; } - $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr); - if (!$rs) return false; - $arr =& $rs->GetAssoc($force_array,$first2cols); - return $arr; - } + function &CacheGetAssoc($secs2cache, $sql = false, $inputarr = false, $force_array = false, $first2cols = false) + { + if (!is_numeric($secs2cache)) { + $first2cols = $force_array; + $force_array = $inputarr; + } + $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr); + if (!$rs) return false; - /** - * Return first element of first row of sql statement. Recordset is disposed - * for you. - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - function GetOne($sql,$inputarr=false) - { - global $ADODB_COUNTRECS; - $crecs = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - - $ret = false; - $rs = &$this->Execute($sql,$inputarr); - if ($rs) { - if (!$rs->EOF) $ret = reset($rs->fields); - $rs->Close(); + $arr =& $rs->GetAssoc($force_array, $first2cols); + return $arr; } - $ADODB_COUNTRECS = $crecs; - return $ret; - } - function CacheGetOne($secs2cache,$sql=false,$inputarr=false) - { - $ret = false; - $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); - if ($rs) { - if (!$rs->EOF) $ret = reset($rs->fields); - $rs->Close(); + /** + * Return first element of first row of sql statement. Recordset is disposed + * for you. + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function GetOne($sql, $inputarr = false) + { + global $ADODB_COUNTRECS; + $crecs = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + $ret = false; + $rs = &$this->Execute($sql, $inputarr); + if ($rs) { + if (!$rs->EOF) $ret = reset($rs->fields); + $rs->Close(); + } + $ADODB_COUNTRECS = $crecs; + return $ret; } - return $ret; - } + function CacheGetOne($secs2cache, $sql = false, $inputarr = false) + { + $ret = false; + $rs = &$this->CacheExecute($secs2cache, $sql, $inputarr); + if ($rs) { + if (!$rs->EOF) $ret = reset($rs->fields); + $rs->Close(); + } - function GetCol($sql, $inputarr = false, $trim = false) - { - $rv = false; - $rs = &$this->Execute($sql, $inputarr); - if ($rs) { - $rv = array(); - if ($trim) { - while (!$rs->EOF) { - $rv[] = trim(reset($rs->fields)); - $rs->MoveNext(); - } - } else { - while (!$rs->EOF) { - $rv[] = reset($rs->fields); - $rs->MoveNext(); - } + return $ret; + } + + function GetCol($sql, $inputarr = false, $trim = false) + { + $rv = false; + $rs = &$this->Execute($sql, $inputarr); + if ($rs) { + $rv = array(); + if ($trim) { + while (!$rs->EOF) { + $rv[] = trim(reset($rs->fields)); + $rs->MoveNext(); + } + } else { + while (!$rs->EOF) { + $rv[] = reset($rs->fields); + $rs->MoveNext(); + } + } + $rs->Close(); } - $rs->Close(); - } - return $rv; - } + return $rv; + } - function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false) - { - $rv = false; - $rs = &$this->CacheExecute($secs, $sql, $inputarr); - if ($rs) { - if ($trim) { - while (!$rs->EOF) { - $rv[] = trim(reset($rs->fields)); - $rs->MoveNext(); - } - } else { - while (!$rs->EOF) { - $rv[] = reset($rs->fields); - $rs->MoveNext(); - } + function CacheGetCol($secs, $sql = false, $inputarr = false, $trim = false) + { + $rv = false; + $rs = &$this->CacheExecute($secs, $sql, $inputarr); + if ($rs) { + if ($trim) { + while (!$rs->EOF) { + $rv[] = trim(reset($rs->fields)); + $rs->MoveNext(); + } + } else { + while (!$rs->EOF) { + $rv[] = reset($rs->fields); + $rs->MoveNext(); + } + } + $rs->Close(); } - $rs->Close(); - } - return $rv; - } + return $rv; + } - /* + /* Calculate the offset of a date for a particular database and generate appropriate SQL. Useful for calculating future/past dates and storing in a database. If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour. */ - function OffsetDate($dayFraction,$date=false) - { - if (!$date) $date = $this->sysDate; - return '('.$date.'+'.$dayFraction.')'; - } + function OffsetDate($dayFraction, $date = false) + { + if (!$date) $date = $this->sysDate; + return '(' . $date . '+' . $dayFraction . ')'; + } - /** - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - function &GetArray($sql,$inputarr=false) - { - global $ADODB_COUNTRECS; - - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - $rs =& $this->Execute($sql,$inputarr); - $ADODB_COUNTRECS = $savec; - if (!$rs) - if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - else return false; - $arr =& $rs->GetArray(); - $rs->Close(); - return $arr; - } + /** + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function &GetArray($sql, $inputarr = false) + { + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + $rs =& $this->Execute($sql, $inputarr); + $ADODB_COUNTRECS = $savec; + if (!$rs) + if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + else return false; + $arr =& $rs->GetArray(); + $rs->Close(); + return $arr; + } - function &CacheGetAll($secs2cache,$sql=false,$inputarr=false) - { - global $ADODB_COUNTRECS; + function &CacheGetAll($secs2cache, $sql = false, $inputarr = false) + { + global $ADODB_COUNTRECS; - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr); - $ADODB_COUNTRECS = $savec; + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr); + $ADODB_COUNTRECS = $savec; - if (!$rs) - if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - else return false; + if (!$rs) + if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + else return false; - $arr =& $rs->GetArray(); - $rs->Close(); - return $arr; - } + $arr =& $rs->GetArray(); + $rs->Close(); + return $arr; + } + /** + * Return one row of sql statement. Recordset is disposed for you. + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function &GetRow($sql, $inputarr = false) + { + global $ADODB_COUNTRECS; + $crecs = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; - /** - * Return one row of sql statement. Recordset is disposed for you. - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - function &GetRow($sql,$inputarr=false) - { - global $ADODB_COUNTRECS; - $crecs = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; + $rs =& $this->Execute($sql, $inputarr); - $rs =& $this->Execute($sql,$inputarr); + $ADODB_COUNTRECS = $crecs; + if ($rs) { + if (!$rs->EOF) $arr = $rs->fields; + else $arr = array(); + $rs->Close(); + return $arr; + } - $ADODB_COUNTRECS = $crecs; - if ($rs) { - if (!$rs->EOF) $arr = $rs->fields; - else $arr = array(); - $rs->Close(); - return $arr; + return false; } - return false; - } - - function &CacheGetRow($secs2cache,$sql=false,$inputarr=false) - { - $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr); - if ($rs) { - $arr = false; - if (!$rs->EOF) $arr = $rs->fields; - $rs->Close(); - return $arr; + function &CacheGetRow($secs2cache, $sql = false, $inputarr = false) + { + $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr); + if ($rs) { + $arr = false; + if (!$rs->EOF) $arr = $rs->fields; + $rs->Close(); + return $arr; + } + return false; } - return false; - } - /** - * Insert or replace a single record. Note: this is not the same as MySQL's replace. - * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL. - * Also note that no table locking is done currently, so it is possible that the - * record be inserted twice by two programs... - * - * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname'); - * - * $table table name - * $fieldArray associative array of data (you must quote strings yourself). - * $keyCol the primary key field name or if compound key, array of field names - * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers - * but does not work with dates nor SQL functions. - * has_autoinc the primary key is an auto-inc field, so skip in insert. - * - * Currently blob replace not supported - * - * returns 0 = fail, 1 = update, 2 = insert - */ + /** + * Insert or replace a single record. Note: this is not the same as MySQL's replace. + * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL. + * Also note that no table locking is done currently, so it is possible that the + * record be inserted twice by two programs... + * + * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname'); + * + * $table table name + * $fieldArray associative array of data (you must quote strings yourself). + * $keyCol the primary key field name or if compound key, array of field names + * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers + * but does not work with dates nor SQL functions. + * has_autoinc the primary key is an auto-inc field, so skip in insert. + * + * Currently blob replace not supported + * + * returns 0 = fail, 1 = update, 2 = insert + */ - function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false) - { - global $ADODB_INCLUDED_LIB; - if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); + function Replace($table, $fieldArray, $keyCol, $autoQuote = false, $has_autoinc = false) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR . '/adodb-lib.inc.php'); - return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc); - } + return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc); + } - /** - * Will select, getting rows from $offset (1-based), for $nrows. - * This simulates the MySQL "select * from table limit $offset,$nrows" , and - * the PostgreSQL "select * from table limit $nrows offset $offset". Note that - * MySQL and PostgreSQL parameter ordering is the opposite of the other. - * eg. - * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based) - * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based) - * - * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set - * - * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional - * @param sql - * @param [offset] is the row to start calculations from (1-based) - * @param [nrows] is the number of rows to get - * @param [inputarr] array of bind variables - * @return the recordset ($rs->databaseType == 'array') - */ - function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false) - { - if (!is_numeric($secs2cache)) { - if ($sql === false) $sql = -1; - if ($offset == -1) $offset = false; - // sql, nrows, offset,inputarr - $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs); - } else { - if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()"); - $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + /** + * Will select, getting rows from $offset (1-based), for $nrows. + * This simulates the MySQL "select * from table limit $offset,$nrows" , and + * the PostgreSQL "select * from table limit $nrows offset $offset". Note that + * MySQL and PostgreSQL parameter ordering is the opposite of the other. + * eg. + * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based) + * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based) + * + * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set + * + * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional + * @param sql + * @param [offset] is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to get + * @param [inputarr] array of bind variables + * @return the recordset ($rs->databaseType == 'array') + */ + function &CacheSelectLimit($secs2cache, $sql, $nrows = -1, $offset = -1, $inputarr = false) + { + if (!is_numeric($secs2cache)) { + if ($sql === false) $sql = -1; + if ($offset == -1) $offset = false; + // sql, nrows, offset,inputarr + $rs =& $this->SelectLimit($secs2cache, $sql, $nrows, $offset, $this->cacheSecs); + } else { + if ($sql === false) ADOConnection::outp("Warning: \$sql missing from CacheSelectLimit()"); + $rs =& $this->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); + } + return $rs; } - return $rs; - } - /** - * Flush cached recordsets that match a particular $sql statement. - * If $sql == false, then we purge all files in the cache. - */ - function CacheFlush($sql=false,$inputarr=false) - { - global $ADODB_CACHE_DIR; + /** + * Flush cached recordsets that match a particular $sql statement. + * If $sql == false, then we purge all files in the cache. + */ + function CacheFlush($sql = false, $inputarr = false) + { + global $ADODB_CACHE_DIR; - if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) { - if (strncmp(PHP_OS,'WIN',3) === 0) { - $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache'; - } else { - $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache'; - // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`'; + if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) { + if (strncmp(PHP_OS, 'WIN', 3) === 0) { + $cmd = 'del /s ' . str_replace('/', '\\', $ADODB_CACHE_DIR) . '\adodb_*.cache'; + } else { + $cmd = 'rm -rf ' . $ADODB_CACHE_DIR . '/??/adodb_*.cache'; + // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`'; + } + if ($this->debug) { + ADOConnection::outp("CacheFlush: $cmd<br><pre>\n", system($cmd), "</pre>"); + } else { + exec($cmd); + } + return; } - if ($this->debug) { - ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>"); - } else { - exec($cmd); + $f = $this->_gencachename($sql . serialize($inputarr), false); + adodb_write_file($f, ''); // is adodb_write_file needed? + if (!@unlink($f)) { + if ($this->debug) ADOConnection::outp("CacheFlush: failed for $f"); } - return; } - $f = $this->_gencachename($sql.serialize($inputarr),false); - adodb_write_file($f,''); // is adodb_write_file needed? - if (!@unlink($f)) { - if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f"); - } - } - - /** - * Private function to generate filename for caching. - * Filename is generated based on: - * - * - sql statement - * - database type (oci8, ibase, ifx, etc) - * - database name - * - userid - * - * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). - * Assuming that we can have 50,000 files per directory with good performance, - * then we can scale to 12.8 million unique cached recordsets. Wow! - */ - function _gencachename($sql,$createdir) - { - global $ADODB_CACHE_DIR; - $m = md5($sql.$this->databaseType.$this->database.$this->user); - $dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2); - if ($createdir && !file_exists($dir)) { - $oldu = umask(0); - if (!mkdir($dir,0771)) - if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql"); - umask($oldu); + /** + * Private function to generate filename for caching. + * Filename is generated based on: + * + * - sql statement + * - database type (oci8, ibase, ifx, etc) + * - database name + * - userid + * + * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). + * Assuming that we can have 50,000 files per directory with good performance, + * then we can scale to 12.8 million unique cached recordsets. Wow! + */ + function _gencachename($sql, $createdir) + { + global $ADODB_CACHE_DIR; + + $m = md5($sql . $this->databaseType . $this->database . $this->user); + $dir = $ADODB_CACHE_DIR . '/' . substr($m, 0, 2); + if ($createdir && !file_exists($dir)) { + $oldu = umask(0); + if (!mkdir($dir, 0771)) + if ($this->debug) ADOConnection::outp("Unable to mkdir $dir for $sql"); + umask($oldu); + } + return $dir . '/adodb_' . $m . '.cache'; } - return $dir.'/adodb_'.$m.'.cache'; - } - /** - * Execute SQL, caching recordsets. - * - * @param [secs2cache] seconds to cache data, set to 0 to force query. - * This is an optional parameter. - * @param sql SQL statement to execute - * @param [inputarr] holds the input data to bind to - * @return RecordSet or false - */ - function &CacheExecute($secs2cache,$sql=false,$inputarr=false) - { - if (!is_numeric($secs2cache)) { - $inputarr = $sql; - $sql = $secs2cache; - $secs2cache = $this->cacheSecs; - } - global $ADODB_INCLUDED_CSV; - if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php'); + /** + * Execute SQL, caching recordsets. + * + * @param [secs2cache] seconds to cache data, set to 0 to force query. + * This is an optional parameter. + * @param sql SQL statement to execute + * @param [inputarr] holds the input data to bind to + * @return RecordSet or false + */ + function &CacheExecute($secs2cache, $sql = false, $inputarr = false) + { + if (!is_numeric($secs2cache)) { + $inputarr = $sql; + $sql = $secs2cache; + $secs2cache = $this->cacheSecs; + } + global $ADODB_INCLUDED_CSV; + if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR . '/adodb-csvlib.inc.php'); - if (is_array($sql)) $sql = $sql[0]; + if (is_array($sql)) $sql = $sql[0]; - $md5file = $this->_gencachename($sql.serialize($inputarr),true); - $err = ''; + $md5file = $this->_gencachename($sql . serialize($inputarr), true); + $err = ''; - if ($secs2cache > 0){ - $rs = &csv2rs($md5file,$err,$secs2cache); - $this->numCacheHits += 1; - } else { - $err='Timeout 1'; - $rs = false; - $this->numCacheMisses += 1; - } - if (!$rs) { - // no cached rs found - if ($this->debug) { - if (get_magic_quotes_runtime()) { - ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :("); - } - if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)"); + if ($secs2cache > 0) { + $rs = &csv2rs($md5file, $err, $secs2cache); + $this->numCacheHits += 1; + } else { + $err = 'Timeout 1'; + $rs = false; + $this->numCacheMisses += 1; } - $rs = &$this->Execute($sql,$inputarr); - if ($rs) { - $eof = $rs->EOF; - $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately - $txt = _rs2serialize($rs,false,$sql); // serialize - - if (!adodb_write_file($md5file,$txt,$this->debug)) { - if ($fn = $this->raiseErrorFn) { - $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this); + if (!$rs) { + // no cached rs found + if ($this->debug) { + if (get_magic_quotes_runtime()) { + ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :("); } - if ($this->debug) ADOConnection::outp( " Cache write error"); - } - if ($rs->EOF && !$eof) { - $rs->MoveFirst(); - //$rs = &csv2rs($md5file,$err); - $rs->connection = &$this; // Pablo suggestion + if ($this->debug !== -1) ADOConnection::outp(" $md5file cache failure: $err (see sql below)"); } + $rs = &$this->Execute($sql, $inputarr); + if ($rs) { + $eof = $rs->EOF; + $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately + $txt = _rs2serialize($rs, false, $sql); // serialize + + if (!adodb_write_file($md5file, $txt, $this->debug)) { + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType, 'CacheExecute', -32000, "Cache write error", $md5file, $sql, $this); + } + if ($this->debug) ADOConnection::outp(" Cache write error"); + } + if ($rs->EOF && !$eof) { + $rs->MoveFirst(); + //$rs = &csv2rs($md5file,$err); + $rs->connection = &$this; // Pablo suggestion + } - } else - @unlink($md5file); - } else { - $this->_errorMsg = ''; - $this->_errorCode = 0; + } else + @unlink($md5file); + } else { + $this->_errorMsg = ''; + $this->_errorCode = 0; - if ($this->fnCacheExecute) { - $fn = $this->fnCacheExecute; - $fn($this, $secs2cache, $sql, $inputarr); - } - // ok, set cached object found - $rs->connection = &$this; // Pablo suggestion - if ($this->debug){ - global $HTTP_SERVER_VARS; + if ($this->fnCacheExecute) { + $fn = $this->fnCacheExecute; + $fn($this, $secs2cache, $sql, $inputarr); + } + // ok, set cached object found + $rs->connection = &$this; // Pablo suggestion + if ($this->debug) { + global $HTTP_SERVER_VARS; - $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']); - $ttl = $rs->timeCreated + $secs2cache - time(); - $s = is_array($sql) ? $sql[0] : $sql; - if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>'; + $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']); + $ttl = $rs->timeCreated + $secs2cache - time(); + $s = is_array($sql) ? $sql[0] : $sql; + if ($inBrowser) $s = '<i>' . htmlspecialchars($s) . '</i>'; - ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]"); + ADOConnection::outp(" $md5file reloaded, ttl=$ttl [ $s ]"); + } } + return $rs; } - return $rs; - } - /** - * Generates an Update Query based on an existing recordset. - * $arrFields is an associative array of fields with the value - * that should be assigned. - * - * Note: This function should only be used on a recordset - * that is run against a single table and sql should only - * be a simple select stmt with no groupby/orderby/limit - * - * "Jonathan Younger" <jyounger@unilab.com> - */ - function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false) - { - global $ADODB_INCLUDED_LIB; - if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq); - } + /** + * Generates an Update Query based on an existing recordset. + * $arrFields is an associative array of fields with the value + * that should be assigned. + * + * Note: This function should only be used on a recordset + * that is run against a single table and sql should only + * be a simple select stmt with no groupby/orderby/limit + * + * "Jonathan Younger" <jyounger@unilab.com> + */ + function GetUpdateSQL(&$rs, $arrFields, $forceUpdate = false, $magicq = false) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR . '/adodb-lib.inc.php'); + return _adodb_getupdatesql($this, $rs, $arrFields, $forceUpdate, $magicq); + } - /** - * Generates an Insert Query based on an existing recordset. - * $arrFields is an associative array of fields with the value - * that should be assigned. - * - * Note: This function should only be used on a recordset - * that is run against a single table. - */ - function GetInsertSQL(&$rs, $arrFields,$magicq=false) - { - global $ADODB_INCLUDED_LIB; - if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_getinsertsql($this,$rs,$arrFields,$magicq); - } + /** + * Generates an Insert Query based on an existing recordset. + * $arrFields is an associative array of fields with the value + * that should be assigned. + * + * Note: This function should only be used on a recordset + * that is run against a single table. + */ + function GetInsertSQL(&$rs, $arrFields, $magicq = false) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR . '/adodb-lib.inc.php'); + return _adodb_getinsertsql($this, $rs, $arrFields, $magicq); + } - /** - * Update a blob column, given a where clause. There are more sophisticated - * blob handling functions that we could have implemented, but all require - * a very complex API. Instead we have chosen something that is extremely - * simple to understand and use. - * - * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course. - * - * Usage to update a $blobvalue which has a primary key blob_id=1 into a - * field blobtable.blobcolumn: - * - * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1'); - * - * Insert example: - * - * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); - * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); - */ + /** + * Update a blob column, given a where clause. There are more sophisticated + * blob handling functions that we could have implemented, but all require + * a very complex API. Instead we have chosen something that is extremely + * simple to understand and use. + * + * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course. + * + * Usage to update a $blobvalue which has a primary key blob_id=1 into a + * field blobtable.blobcolumn: + * + * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1'); + * + * Insert example: + * + * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); + * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); + */ - function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') - { - return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false; - } + function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB') + { + return $this->Execute("UPDATE $table SET $column=? WHERE $where", array($val)) != false; + } - /** - * Usage: - * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1'); - * - * $blobtype supports 'BLOB' and 'CLOB' - * - * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); - * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1'); - */ - function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') - { - $fd = fopen($path,'rb'); - if ($fd === false) return false; - $val = fread($fd,filesize($path)); - fclose($fd); - return $this->UpdateBlob($table,$column,$val,$where,$blobtype); - } + /** + * Usage: + * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1'); + * + * $blobtype supports 'BLOB' and 'CLOB' + * + * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); + * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1'); + */ + function UpdateBlobFile($table, $column, $path, $where, $blobtype = 'BLOB') + { + $fd = fopen($path, 'rb'); + if ($fd === false) return false; + $val = fread($fd, filesize($path)); + fclose($fd); + return $this->UpdateBlob($table, $column, $val, $where, $blobtype); + } - function BlobDecode($blob) - { - return $blob; - } + function BlobDecode($blob) + { + return $blob; + } - function BlobEncode($blob) - { - return $blob; - } + function BlobEncode($blob) + { + return $blob; + } - function SetCharSet($charset) - { - return false; - } + function SetCharSet($charset) + { + return false; + } - function IfNull( $field, $ifNull ) - { - return " CASE WHEN $field is null THEN $ifNull ELSE $field END "; - } + function IfNull($field, $ifNull) + { + return " CASE WHEN $field is null THEN $ifNull ELSE $field END "; + } - function LogSQL($enable=true) - { - include_once(ADODB_DIR.'/adodb-perf.inc.php'); + function LogSQL($enable = true) + { + include_once(ADODB_DIR . '/adodb-perf.inc.php'); - if ($enable) $this->fnExecute = 'adodb_log_sql'; - else $this->fnExecute = false; + if ($enable) $this->fnExecute = 'adodb_log_sql'; + else $this->fnExecute = false; - $old = $this->_logsql; - $this->_logsql = $enable; - if ($enable && !$old) $this->_affected = false; - return $old; - } + $old = $this->_logsql; + $this->_logsql = $enable; + if ($enable && !$old) $this->_affected = false; + return $old; + } - function GetCharSet() - { - return false; - } + function GetCharSet() + { + return false; + } - /** - * Usage: - * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB'); - * - * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)'); - * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1'); - */ - function UpdateClob($table,$column,$val,$where) - { - return $this->UpdateBlob($table,$column,$val,$where,'CLOB'); - } - - - /** - * Change the SQL connection locale to a specified locale. - * This is used to get the date formats written depending on the client locale. - */ - function SetDateLocale($locale = 'En') - { - $this->locale = $locale; - switch ($locale) + /** + * Usage: + * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB'); + * + * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)'); + * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1'); + */ + function UpdateClob($table, $column, $val, $where) { - default: - case 'En': - $this->fmtDate="Y-m-d"; - $this->fmtTimeStamp = "Y-m-d H:i:s"; - break; + return $this->UpdateBlob($table, $column, $val, $where, 'CLOB'); + } - case 'Fr': - case 'Ro': - case 'It': - $this->fmtDate="d-m-Y"; - $this->fmtTimeStamp = "d-m-Y H:i:s"; - break; - case 'Ge': - $this->fmtDate="d.m.Y"; - $this->fmtTimeStamp = "d.m.Y H:i:s"; - break; + /** + * Change the SQL connection locale to a specified locale. + * This is used to get the date formats written depending on the client locale. + */ + function SetDateLocale($locale = 'En') + { + $this->locale = $locale; + switch ($locale) { + default: + case 'En': + $this->fmtDate = "Y-m-d"; + $this->fmtTimeStamp = "Y-m-d H:i:s"; + break; + + case 'Fr': + case 'Ro': + case 'It': + $this->fmtDate = "d-m-Y"; + $this->fmtTimeStamp = "d-m-Y H:i:s"; + break; + + case 'Ge': + $this->fmtDate = "d.m.Y"; + $this->fmtTimeStamp = "d.m.Y H:i:s"; + break; + } } - } - /** - * $meta contains the desired type, which could be... - * C for character. You will have to define the precision yourself. - * X for teXt. For unlimited character lengths. - * B for Binary - * F for floating point, with no need to define scale and precision - * N for decimal numbers, you will have to define the (scale, precision) yourself - * D for date - * T for timestamp - * L for logical/Boolean - * I for integer - * R for autoincrement counter/integer - * and if you want to use double-byte, add a 2 to the end, like C2 or X2. - * - * - * @return the actual type of the data or false if no such type available - */ - function ActualType($meta) - { - switch($meta) { - case 'C': - case 'X': - return 'VARCHAR'; - case 'B': + /** + * $meta contains the desired type, which could be... + * C for character. You will have to define the precision yourself. + * X for teXt. For unlimited character lengths. + * B for Binary + * F for floating point, with no need to define scale and precision + * N for decimal numbers, you will have to define the (scale, precision) yourself + * D for date + * T for timestamp + * L for logical/Boolean + * I for integer + * R for autoincrement counter/integer + * and if you want to use double-byte, add a 2 to the end, like C2 or X2. + * + * + * @return the actual type of the data or false if no such type available + */ + function ActualType($meta) + { + switch ($meta) { + case 'C': + case 'X': + return 'VARCHAR'; + case 'B': - case 'D': - case 'T': - case 'L': + case 'D': + case 'T': + case 'L': - case 'R': + case 'R': - case 'I': - case 'N': - return false; + case 'I': + case 'N': + return false; + } } - } - /** - * Close Connection - */ - function Close() - { - return $this->_close(); + /** + * Close Connection + */ + function Close() + { + return $this->_close(); - // "Simon Lee" <simon@mediaroad.com> reports that persistent connections need - // to be closed too! - //if ($this->_isPersistentConnection != true) return $this->_close(); - //else return true; - } + // "Simon Lee" <simon@mediaroad.com> reports that persistent connections need + // to be closed too! + //if ($this->_isPersistentConnection != true) return $this->_close(); + //else return true; + } - /** - * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans(). - * - * @return true if succeeded or false if database does not support transactions - */ - function BeginTrans() {return false;} + /** + * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans(). + * + * @return true if succeeded or false if database does not support transactions + */ + function BeginTrans() + { + return false; + } - /** - * If database does not support transactions, always return true as data always commited - * - * @param $ok set to false to rollback transaction, true to commit - * - * @return true/false. - */ - function CommitTrans($ok=true) - { return true;} + /** + * If database does not support transactions, always return true as data always commited + * + * @param $ok set to false to rollback transaction, true to commit + * + * @return true/false. + */ + function CommitTrans($ok = true) + { + return true; + } - /** - * If database does not support transactions, rollbacks always fail, so return false - * - * @return true/false. - */ - function RollbackTrans() - { return false;} + /** + * If database does not support transactions, rollbacks always fail, so return false + * + * @return true/false. + */ + function RollbackTrans() + { + return false; + } - /** - * return the databases that the driver can connect to. - * Some databases will return an empty array. - * - * @return an array of database names. - */ + /** + * return the databases that the driver can connect to. + * Some databases will return an empty array. + * + * @return an array of database names. + */ function MetaDatabases() { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; if ($this->metaDatabasesSQL) { $save = $ADODB_FETCH_MODE; @@ -1850,397 +1859,398 @@ return false; } - /** - * @param ttype can either be 'VIEW' or 'TABLE' or false. - * If false, both views and tables are returned. - * "VIEW" returns only views - * "TABLE" returns only tables - * @param showSchema returns the schema/user with the table name, eg. USER.TABLE - * @param mask is the input mask - only supported by oci8 and postgresql - * - * @return array of tables for current database. - */ - function &MetaTables($ttype=false,$showSchema=false,$mask=false) - { - global $ADODB_FETCH_MODE; + /** + * @param ttype can either be 'VIEW' or 'TABLE' or false. + * If false, both views and tables are returned. + * "VIEW" returns only views + * "TABLE" returns only tables + * @param showSchema returns the schema/user with the table name, eg. USER.TABLE + * @param mask is the input mask - only supported by oci8 and postgresql + * + * @return array of tables for current database. + */ + function &MetaTables($ttype = false, $showSchema = false, $mask = false) + { + global $ADODB_FETCH_MODE; - if ($mask) return false; + if ($mask) return false; - if ($this->metaTablesSQL) { - // complicated state saving by the need for backward compat - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->metaTablesSQL) { + // complicated state saving by the need for backward compat + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - $rs = $this->Execute($this->metaTablesSQL); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; + $rs = $this->Execute($this->metaTablesSQL); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; - if ($rs === false) return false; - $arr =& $rs->GetArray(); - $arr2 = array(); + if ($rs === false) return false; + $arr =& $rs->GetArray(); + $arr2 = array(); - if ($hast = ($ttype && isset($arr[0][1]))) { - $showt = strncmp($ttype,'T',1); - } + if ($hast = ($ttype && isset($arr[0][1]))) { + $showt = strncmp($ttype, 'T', 1); + } - for ($i=0; $i < sizeof($arr); $i++) { - if ($hast) { - if ($showt == 0) { - if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]); - } else { - if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]); - } - } else - $arr2[] = trim($arr[$i][0]); + for ($i = 0; $i < sizeof($arr); $i++) { + if ($hast) { + if ($showt == 0) { + if (strncmp($arr[$i][1], 'T', 1) == 0) $arr2[] = trim($arr[$i][0]); + } else { + if (strncmp($arr[$i][1], 'V', 1) == 0) $arr2[] = trim($arr[$i][0]); + } + } else + $arr2[] = trim($arr[$i][0]); + } + $rs->Close(); + return $arr2; } - $rs->Close(); - return $arr2; + return false; } - return false; - } - function _findschema(&$table,&$schema) - { - if (!$schema && ($at = strpos($table,'.')) !== false) { - $schema = substr($table,0,$at); - $table = substr($table,$at+1); + function _findschema(&$table, &$schema) + { + if (!$schema && ($at = strpos($table, '.')) !== false) { + $schema = substr($table, 0, $at); + $table = substr($table, $at + 1); + } } - } - /** - * List columns in a database as an array of ADOFieldObjects. - * See top of file for definition of object. - * - * @param table table name to query - * @param upper uppercase table name (required by some databases) - * @schema is optional database schema to use - not supported by all databases. - * - * @return array of ADOFieldObjects for current table. - */ - function &MetaColumns($table,$upper=true) - { - global $ADODB_FETCH_MODE; - - if (!empty($this->metaColumnsSQL)) { - - $schema = false; - $this->_findschema($table,$schema); - - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table)); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - if ($rs === false) return false; - - $retarr = array(); - while (!$rs->EOF) { //print_r($rs->fields); - $fld =& new ADOFieldObject(); - $fld->name = $upper ? strtoupper($rs->fields[0]) : $rs->fields[0]; - $fld->type = $rs->fields[1]; - if (isset($rs->fields[3]) && $rs->fields[3]) { - if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3]; - $fld->scale = $rs->fields[4]; - if ($fld->scale>0) $fld->max_length += 1; - } else - $fld->max_length = $rs->fields[2]; + /** + * List columns in a database as an array of ADOFieldObjects. + * See top of file for definition of object. + * + * @param table table name to query + * @param upper uppercase table name (required by some databases) + * @schema is optional database schema to use - not supported by all databases. + * + * @return array of ADOFieldObjects for current table. + */ + function &MetaColumns($table, $upper = true) + { + global $ADODB_FETCH_MODE; - if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; - else $retarr[$fld->name] = $fld; - $rs->MoveNext(); + if (!empty($this->metaColumnsSQL)) { + + $schema = false; + $this->_findschema($table, $schema); + + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + $rs = $this->Execute(sprintf($this->metaColumnsSQL, ($upper) ? strtoupper($table) : $table)); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if ($rs === false) return false; + + $retarr = array(); + while (!$rs->EOF) { //print_r($rs->fields); + $fld =& new ADOFieldObject(); + $fld->name = $upper ? strtoupper($rs->fields[0]) : $rs->fields[0]; + $fld->type = $rs->fields[1]; + if (isset($rs->fields[3]) && $rs->fields[3]) { + if ($rs->fields[3] > 0) $fld->max_length = $rs->fields[3]; + $fld->scale = $rs->fields[4]; + if ($fld->scale > 0) $fld->max_length += 1; + } else + $fld->max_length = $rs->fields[2]; + + if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; + else $retarr[$fld->name] = $fld; + $rs->MoveNext(); + } + $rs->Close(); + return $retarr; } - $rs->Close(); - return $retarr; + return false; } - return false; - } - /** - * List indexes on a table as an array. - * @param table table name to query - * @param primary include primary keys. - * - * @return array of indexes on current table. - */ - function &MetaIndexes($table, $primary = false, $owner = false) - { - return FALSE; - } + /** + * List indexes on a table as an array. + * @param table table name to query + * @param primary include primary keys. + * + * @return array of indexes on current table. + */ + function &MetaIndexes($table, $primary = false, $owner = false) + { + return FALSE; + } - /** - * List columns names in a table as an array. - * @param table table name to query - * - * @return array of column names for current table. - */ - function &MetaColumnNames($table) - { - $objarr =& $this->MetaColumns($table); - if (!is_array($objarr)) return false; + /** + * List columns names in a table as an array. + * @param table table name to query + * + * @return array of column names for current table. + */ + function &MetaColumnNames($table) + { + $objarr =& $this->MetaColumns($table); + if (!is_array($objarr)) return false; - $arr = array(); - foreach($objarr as $v) { - $arr[strtoupper($v->name)] = $v->name; + $arr = array(); + foreach ($objarr as $v) { + $arr[strtoupper($v->name)] = $v->name; + } + return $arr; } - return $arr; - } - /** - * Different SQL databases used different methods to combine strings together. - * This function provides a wrapper. - * - * param s variable number of string parameters - * - * Usage: $db->Concat($str1,$str2); - * - * @return concatenated string - */ - function Concat() - { - $arr = func_get_args(); - return implode($this->concat_operator, $arr); - } + /** + * Different SQL databases used different methods to combine strings together. + * This function provides a wrapper. + * + * param s variable number of string parameters + * + * Usage: $db->Concat($str1,$str2); + * + * @return concatenated string + */ + function Concat() + { + $arr = func_get_args(); + return implode($this->concat_operator, $arr); + } - /** - * Converts a date "d" to a string that the database can understand. - * - * @param d a date in Unix date time format. - * - * @return date string in database date format - */ - function DBDate($d) - { - if (empty($d) && $d !== 0) return 'null'; + /** + * Converts a date "d" to a string that the database can understand. + * + * @param d a date in Unix date time format. + * + * @return date string in database date format + */ + function DBDate($d) + { + if (empty($d) && $d !== 0) return 'null'; - if (is_string($d) && !is_numeric($d)) { - if ($d === 'null' || strncmp($d,"'",1) === 0) return $d; - if ($this->isoDates) return "'$d'"; - $d = ADOConnection::UnixDate($d); - } + if (is_string($d) && !is_numeric($d)) { + if ($d === 'null' || strncmp($d, "'", 1) === 0) return $d; + if ($this->isoDates) return "'$d'"; + $d = ADOConnection::UnixDate($d); + } - return adodb_date($this->fmtDate,$d); - } + return adodb_date($this->fmtDate, $d); + } - /** - * Converts a timestamp "ts" to a string that the database can understand. - * - * @param ts a timestamp in Unix date time format. - * - * @return timestamp string in database timestamp format - */ - function DBTimeStamp($ts) - { - if (empty($ts) && $ts !== 0) return 'null'; + /** + * Converts a timestamp "ts" to a string that the database can understand. + * + * @param ts a timestamp in Unix date time format. + * + * @return timestamp string in database timestamp format + */ + function DBTimeStamp($ts) + { + if (empty($ts) && $ts !== 0) return 'null'; - # strlen(14) allows YYYYMMDDHHMMSS format - if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) - return adodb_date($this->fmtTimeStamp,$ts); + # strlen(14) allows YYYYMMDDHHMMSS format + if (!is_string($ts) || (is_numeric($ts) && strlen($ts) < 14)) + return adodb_date($this->fmtTimeStamp, $ts); - if ($ts === 'null') return $ts; - if ($this->isoDates && strlen($ts) !== 14) return "'$ts'"; + if ($ts === 'null') return $ts; + if ($this->isoDates && strlen($ts) !== 14) return "'$ts'"; - $ts = ADOConnection::UnixTimeStamp($ts); - return adodb_date($this->fmtTimeStamp,$ts); - } + $ts = ADOConnection::UnixTimeStamp($ts); + return adodb_date($this->fmtTimeStamp, $ts); + } - /** - * Also in ADORecordSet. - * @param $v is a date string in YYYY-MM-DD format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - function UnixDate($v) - { - if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", - ($v), $rr)) return false; + /** + * Also in ADORecordSet. + * @param $v is a date string in YYYY-MM-DD format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixDate($v) + { + if (!preg_match("|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", + ($v), $rr) + ) return false; - if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0; - // h-m-s-MM-DD-YY - return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); - } + if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0; + // h-m-s-MM-DD-YY + return @adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]); + } - /** - * Also in ADORecordSet. - * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - function UnixTimeStamp($v) - { - if (!preg_match( - "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", - ($v), $rr)) return false; + /** + * Also in ADORecordSet. + * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixTimeStamp($v) + { + if (!preg_match( + "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", + ($v), $rr) + ) return false; - if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0; + if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2] <= 1) return 0; - // h-m-s-MM-DD-YY - if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); - return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); - } + // h-m-s-MM-DD-YY + if (!isset($rr[5])) return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]); + return @adodb_mktime($rr[5], $rr[6], $rr[7], $rr[2], $rr[3], $rr[1]); + } - /** - * Also in ADORecordSet. - * - * Format database date based on user defined format. - * - * @param v is the character date in YYYY-MM-DD format, returned by database - * @param fmt is the format to apply to it, using date() - * - * @return a date formated as user desires - */ + /** + * Also in ADORecordSet. + * + * Format database date based on user defined format. + * + * @param v is the character date in YYYY-MM-DD format, returned by database + * @param fmt is the format to apply to it, using date() + * + * @return a date formated as user desires + */ - function UserDate($v,$fmt='Y-m-d') - { - $tt = $this->UnixDate($v); - // $tt == -1 if pre TIMESTAMP_FIRST_YEAR - if (($tt === false || $tt == -1) && $v != false) return $v; - else if ($tt == 0) return $this->emptyDate; - else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR - } + function UserDate($v, $fmt = 'Y-m-d') + { + $tt = $this->UnixDate($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + else if ($tt == 0) return $this->emptyDate; + else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR + } - return adodb_date($fmt,$tt); + return adodb_date($fmt, $tt); - } + } /** - * - * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format - * @param fmt is the format to apply to it, using date() - * - * @return a timestamp formated as user desires - */ - function UserTimeStamp($v,$fmt='Y-m-d H:i:s') - { - # strlen(14) allows YYYYMMDDHHMMSS format - if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v); - $tt = $this->UnixTimeStamp($v); - // $tt == -1 if pre TIMESTAMP_FIRST_YEAR - if (($tt === false || $tt == -1) && $v != false) return $v; - if ($tt == 0) return $this->emptyTimeStamp; - return adodb_date($fmt,$tt); - } + * + * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format + * @param fmt is the format to apply to it, using date() + * + * @return a timestamp formated as user desires + */ + function UserTimeStamp($v, $fmt = 'Y-m-d H:i:s') + { + # strlen(14) allows YYYYMMDDHHMMSS format + if (is_numeric($v) && strlen($v) < 14) return adodb_date($fmt, $v); + $tt = $this->UnixTimeStamp($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + if ($tt == 0) return $this->emptyTimeStamp; + return adodb_date($fmt, $tt); + } - /** - * Quotes a string, without prefixing nor appending quotes. - */ - function addq($s, $magicq=false) - { - if (!$magicq) { + /** + * Quotes a string, without prefixing nor appending quotes. + */ + function addq($s, $magicq = false) + { + if (!$magicq) { - if ($this->replaceQuote[0] == '\\'){ - // only since php 4.0.5 - $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); - //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); + if ($this->replaceQuote[0] == '\\') { + // only since php 4.0.5 + $s = adodb_str_replace(array('\\', "\0"), array('\\\\', "\\\0"), $s); + //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); + } + return str_replace("'", $this->replaceQuote, $s); } - return str_replace("'",$this->replaceQuote,$s); - } - // undo magic quotes for " - $s = str_replace('\\"','"',$s); + // undo magic quotes for " + $s = str_replace('\\"', '"', $s); - if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything - return $s; - else {// change \' to '' for sybase/mssql - $s = str_replace('\\\\','\\',$s); - return str_replace("\\'",$this->replaceQuote,$s); + if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything + return $s; + else { // change \' to '' for sybase/mssql + $s = str_replace('\\\\', '\\', $s); + return str_replace("\\'", $this->replaceQuote, $s); + } } - } - /** - * Correctly quotes a string so that all strings are escaped. We prefix and append - * to the string single-quotes. - * An example is $db->qstr("Don't bother",magic_quotes_runtime()); - * - * @param s the string to quote - * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc(). - * This undoes the stupidity of magic quotes for GPC. - * - * @return quoted string to be sent back to database - */ - function qstr($s,$magic_quotes=false) - { - if (!$magic_quotes) { + /** + * Correctly quotes a string so that all strings are escaped. We prefix and append + * to the string single-quotes. + * An example is $db->qstr("Don't bother",magic_quotes_runtime()); + * + * @param s the string to quote + * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc(). + * This undoes the stupidity of magic quotes for GPC. + * + * @return quoted string to be sent back to database + */ + function qstr($s, $magic_quotes = false) + { + if (!$magic_quotes) { - if ($this->replaceQuote[0] == '\\'){ - // only since php 4.0.5 - $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); - //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); + if ($this->replaceQuote[0] == '\\') { + // only since php 4.0.5 + $s = adodb_str_replace(array('\\', "\0"), array('\\\\', "\\\0"), $s); + //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); + } + return "'" . str_replace("'", $this->replaceQuote, $s) . "'"; } - return "'".str_replace("'",$this->replaceQuote,$s)."'"; - } - // undo magic quotes for " - $s = str_replace('\\"','"',$s); + // undo magic quotes for " + $s = str_replace('\\"', '"', $s); - if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything - return "'$s'"; - else {// change \' to '' for sybase/mssql - $s = str_replace('\\\\','\\',$s); - return "'".str_replace("\\'",$this->replaceQuote,$s)."'"; + if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything + return "'$s'"; + else { // change \' to '' for sybase/mssql + $s = str_replace('\\\\', '\\', $s); + return "'" . str_replace("\\'", $this->replaceQuote, $s) . "'"; + } } - } - /** - * Will select the supplied $page number from a recordset, given that it is paginated in pages of - * $nrows rows per page. It also saves two boolean values saying if the given page is the first - * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. - * - * See readme.htm#ex8 for an example of usage. - * - * @param sql - * @param nrows is the number of rows per page to get - * @param page is the page number to get (1-based) - * @param [inputarr] array of bind variables - * @param [secs2cache] is a private parameter only used by jlim - * @return the recordset ($rs->databaseType == 'array') - * - * NOTE: phpLens uses a different algorithm and does not use PageExecute(). - * - */ - function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) - { - global $ADODB_INCLUDED_LIB; - if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); - if ($this->pageExecuteCountRows) return _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache); - return _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache); + /** + * Will select the supplied $page number from a recordset, given that it is paginated in pages of + * $nrows rows per page. It also saves two boolean values saying if the given page is the first + * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. + * + * See readme.htm#ex8 for an example of usage. + * + * @param sql + * @param nrows is the number of rows per page to get + * @param page is the page number to get (1-based) + * @param [inputarr] array of bind variables + * @param [secs2cache] is a private parameter only used by jlim + * @return the recordset ($rs->databaseType == 'array') + * + * NOTE: phpLens uses a different algorithm and does not use PageExecute(). + * + */ + function &PageExecute($sql, $nrows, $page, $inputarr = false, $secs2cache = 0) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR . '/adodb-lib.inc.php'); + if ($this->pageExecuteCountRows) return _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache); + return _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache); - } + } - /** - * Will select the supplied $page number from a recordset, given that it is paginated in pages of - * $nrows rows per page. It also saves two boolean values saying if the given page is the first - * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. - * - * @param secs2cache seconds to cache data, set to 0 to force query - * @param sql - * @param nrows is the number of rows per page to get - * @param page is the page number to get (1-based) - * @param [inputarr] array of bind variables - * @return the recordset ($rs->databaseType == 'array') - */ - function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) - { - /*switch($this->dataProvider) { + /** + * Will select the supplied $page number from a recordset, given that it is paginated in pages of + * $nrows rows per page. It also saves two boolean values saying if the given page is the first + * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. + * + * @param secs2cache seconds to cache data, set to 0 to force query + * @param sql + * @param nrows is the number of rows per page to get + * @param page is the page number to get (1-based) + * @param [inputarr] array of bind variables + * @return the recordset ($rs->databaseType == 'array') + */ + function &CachePageExecute($secs2cache, $sql, $nrows, $page, $inputarr = false) + { + /*switch($this->dataProvider) { case 'postgres': case 'mysql': break; default: $secs2cache = 0; break; }*/ - $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache); - return $rs; - } - -} // end class ADOConnection + $rs =& $this->PageExecute($sql, $nrows, $page, $inputarr, $secs2cache); + return $rs; + } + } // end class ADOConnection //============================================================================================== @@ -2248,18 +2258,21 @@ //============================================================================================== /** - * Internal placeholder for record objects. Used by ADORecordSet->FetchObj(). - */ - class ADOFetchObj { - }; + * Internal placeholder for record objects. Used by ADORecordSet->FetchObj(). + */ + class ADOFetchObj + { + } + + ; //============================================================================================== // CLASS ADORecordSet_empty //============================================================================================== /** - * Lightweight recordset when there are no records to be returned - */ + * Lightweight recordset when there are no records to be returned + */ class ADORecordSet_empty { var $dataProvider = 'empty'; @@ -2268,946 +2281,1003 @@ var $_numOfRows = 0; var $fields = false; var $connection = false; - function RowCount() {return 0;} - function RecordCount() {return 0;} - function PO_RecordCount(){return 0;} - function Close(){return true;} - function FetchRow() {return false;} - function FieldCount(){ return 0;} + + function RowCount() + { + return 0; + } + + function RecordCount() + { + return 0; + } + + function PO_RecordCount() + { + return 0; + } + + function Close() + { + return true; + } + + function FetchRow() + { + return false; + } + + function FieldCount() + { + return 0; + } } //============================================================================================== // DATE AND TIME FUNCTIONS //============================================================================================== - include_once(ADODB_DIR.'/adodb-time.inc.php'); + include_once(ADODB_DIR . '/adodb-time.inc.php'); //============================================================================================== // CLASS ADORecordSet //============================================================================================== - if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php'); - else include_once(ADODB_DIR.'/adodb-iterator.inc.php'); - /** + if (PHP_VERSION < 5) include_once(ADODB_DIR . '/adodb-php4.inc.php'); + else include_once(ADODB_DIR . '/adodb-iterator.inc.php'); + /** * RecordSet class that represents the dataset returned by the database. * To keep memory overhead low, this class holds only the current row in memory. * No prefetching of data is done, so the RecordCount() can return -1 ( which * means recordcount not known). */ - class ADORecordSet extends ADODB_BASE_RS { - /* + class ADORecordSet extends ADODB_BASE_RS + { + /* * public variables */ - var $dataProvider = "native"; - var $fields = false; /// holds the current row data - var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob - /// in other words, we use a text area for editing. - var $canSeek = false; /// indicates that seek is supported - var $sql; /// sql text - var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object. - - var $emptyTimeStamp = ' '; /// what to display when $time==0 - var $emptyDate = ' '; /// what to display when $time==0 - var $debug = false; - var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets - - var $bind = false; /// used by Fields() to hold array - should be private? - var $fetchMode; /// default fetch mode - var $connection = false; /// the parent connection - /* + var $dataProvider = "native"; + var $fields = false; /// holds the current row data + var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob + /// in other words, we use a text area for editing. + var $canSeek = false; /// indicates that seek is supported + var $sql; /// sql text + var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object. + + var $emptyTimeStamp = ' '; /// what to display when $time==0 + var $emptyDate = ' '; /// what to display when $time==0 + var $debug = false; + var $timeCreated = 0; /// datetime in Unix format rs created -- for cached recordsets + + var $bind = false; /// used by Fields() to hold array - should be private? + var $fetchMode; /// default fetch mode + var $connection = false; /// the parent connection + /* * private variables */ - var $_numOfRows = -1; /** number of rows, or -1 */ - var $_numOfFields = -1; /** number of fields in recordset */ - var $_queryID = -1; /** This variable keeps the result link identifier. */ - var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */ - var $_closed = false; /** has recordset been closed */ - var $_inited = false; /** Init() should only be called once */ - var $_obj; /** Used by FetchObj */ - var $_names; /** Used by FetchObj */ - - var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */ - var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */ - var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */ - var $_lastPageNo = -1; - var $_maxRecordCount = 0; - var $datetime = false; - - /** - * Constructor - * - * @param queryID this is the queryID returned by ADOConnection->_query() - * - */ - function ADORecordSet($queryID) - { - $this->_queryID = $queryID; - } + var $_numOfRows = -1; + /** number of rows, or -1 */ + var $_numOfFields = -1; + /** number of fields in recordset */ + var $_queryID = -1; + /** This variable keeps the result link identifier. */ + var $_currentRow = -1; + /** This variable keeps the current row in the Recordset. */ + var $_closed = false; + /** has recordset been closed */ + var $_inited = false; + /** Init() should only be called once */ + var $_obj; + /** Used by FetchObj */ + var $_names; + /** Used by FetchObj */ + + var $_currentPage = -1; + /** Added by Iván Oliva to implement recordset pagination */ + var $_atFirstPage = false; + /** Added by Iván Oliva to implement recordset pagination */ + var $_atLastPage = false; + /** Added by Iván Oliva to implement recordset pagination */ + var $_lastPageNo = -1; + var $_maxRecordCount = 0; + var $datetime = false; + /** + * Constructor + * + * @param queryID this is the queryID returned by ADOConnection->_query() + * + */ + function ADORecordSet($queryID) + { + $this->_queryID = $queryID; + } - function Init() - { - if ($this->_inited) return; - $this->_inited = true; - if ($this->_queryID) @$this->_initrs(); - else { - $this->_numOfRows = 0; - $this->_numOfFields = 0; - } - if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) { + function Init() + { + if ($this->_inited) return; + $this->_inited = true; + if ($this->_queryID) @$this->_initrs(); + else { + $this->_numOfRows = 0; + $this->_numOfFields = 0; + } + if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) { - $this->_currentRow = 0; - if ($this->EOF = ($this->_fetch() === false)) { - $this->_numOfRows = 0; // _numOfRows could be -1 + $this->_currentRow = 0; + if ($this->EOF = ($this->_fetch() === false)) { + $this->_numOfRows = 0; // _numOfRows could be -1 + } + } else { + $this->EOF = true; } - } else { - $this->EOF = true; } - } - /** - * Generate a SELECT tag string from a recordset, and return the string. - * If the recordset has 2 cols, we treat the 1st col as the containing - * the text to display to the user, and 2nd col as the return value. Default - * strings are compared with the FIRST column. - * - * @param name name of SELECT tag - * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox. - * @param [blank1stItem] true to leave the 1st item in list empty - * @param [multiple] true for listbox, false for popup - * @param [size] #rows to show for listbox. not used by popup - * @param [selectAttr] additional attributes to defined for SELECT tag. - * useful for holding javascript onChange='...' handlers. - & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with - * column 0 (1st col) if this is true. This is not documented. - * - * @return HTML - * - * changes by glen.davies@cce.ac.nz to support multiple hilited items - */ - function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false, - $size=0, $selectAttr='',$compareFields0=true) - { - global $ADODB_INCLUDED_LIB; - if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple, - $size, $selectAttr,$compareFields0); - } - - /** - * Generate a SELECT tag string from a recordset, and return the string. - * If the recordset has 2 cols, we treat the 1st col as the containing - * the text to display to the user, and 2nd col as the return value. Default - * strings are compared with the SECOND column. - * - */ - function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='') - { - global $ADODB_INCLUDED_LIB; - if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple, - $size, $selectAttr,false); - } + /** + * Generate a SELECT tag string from a recordset, and return the string. + * If the recordset has 2 cols, we treat the 1st col as the containing + * the text to display to the user, and 2nd col as the return value. Default + * strings are compared with the FIRST column. + * + * @param name name of SELECT tag + * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox. + * @param [blank1stItem] true to leave the 1st item in list empty + * @param [multiple] true for listbox, false for popup + * @param [size] #rows to show for listbox. not used by popup + * @param [selectAttr] additional attributes to defined for SELECT tag. + * useful for holding javascript onChange='...' handlers. + & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with + * column 0 (1st col) if this is true. This is not documented. + * + * @return HTML + * + * changes by glen.davies@cce.ac.nz to support multiple hilited items + */ + function GetMenu($name, $defstr = '', $blank1stItem = true, $multiple = false, + $size = 0, $selectAttr = '', $compareFields0 = true) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR . '/adodb-lib.inc.php'); + return _adodb_getmenu($this, $name, $defstr, $blank1stItem, $multiple, + $size, $selectAttr, $compareFields0); + } + /** + * Generate a SELECT tag string from a recordset, and return the string. + * If the recordset has 2 cols, we treat the 1st col as the containing + * the text to display to the user, and 2nd col as the return value. Default + * strings are compared with the SECOND column. + * + */ + function GetMenu2($name, $defstr = '', $blank1stItem = true, $multiple = false, $size = 0, $selectAttr = '') + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR . '/adodb-lib.inc.php'); + return _adodb_getmenu($this, $name, $defstr, $blank1stItem, $multiple, + $size, $selectAttr, false); + } - /** - * return recordset as a 2-dimensional array. - * - * @param [nRows] is the number of rows to return. -1 means every row. - * - * @return an array indexed by the rows (0-based) from the recordset - */ - function &GetArray($nRows = -1) - { - global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows); - $results = array(); - $cnt = 0; - while (!$this->EOF && $nRows != $cnt) { - $results[] = $this->fields; - $this->MoveNext(); - $cnt++; + /** + * return recordset as a 2-dimensional array. + * + * @param [nRows] is the number of rows to return. -1 means every row. + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function &GetArray($nRows = -1) + { + global $ADODB_EXTENSION; + if ($ADODB_EXTENSION) return adodb_getall($this, $nRows); + + $results = array(); + $cnt = 0; + while (!$this->EOF && $nRows != $cnt) { + $results[] = $this->fields; + $this->MoveNext(); + $cnt++; + } + return $results; } - return $results; - } - function &GetAll($nRows = -1) - { - $arr =& $this->GetArray($nRows); - return $arr; - } + function &GetAll($nRows = -1) + { + $arr =& $this->GetArray($nRows); + return $arr; + } - /* + /* * Some databases allow multiple recordsets to be returned. This function * will return true if there is a next recordset, or false if no more. */ - function NextRecordSet() - { - return false; - } - - /** - * return recordset as a 2-dimensional array. - * Helper function for ADOConnection->SelectLimit() - * - * @param offset is the row to start calculations from (1-based) - * @param [nrows] is the number of rows to return - * - * @return an array indexed by the rows (0-based) from the recordset - */ - function &GetArrayLimit($nrows,$offset=-1) - { - if ($offset <= 0) { - $arr =& $this->GetArray($nrows); - return $arr; + function NextRecordSet() + { + return false; } - $this->Move($offset); + /** + * return recordset as a 2-dimensional array. + * Helper function for ADOConnection->SelectLimit() + * + * @param offset is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to return + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function &GetArrayLimit($nrows, $offset = -1) + { + if ($offset <= 0) { + $arr =& $this->GetArray($nrows); + return $arr; + } - $results = array(); - $cnt = 0; - while (!$this->EOF && $nrows != $cnt) { - $results[$cnt++] = $this->fields; - $this->MoveNext(); - } + $this->Move($offset); - return $results; - } + $results = array(); + $cnt = 0; + while (!$this->EOF && $nrows != $cnt) { + $results[$cnt++] = $this->fields; + $this->MoveNext(); + } + return $results; + } - /** - * Synonym for GetArray() for compatibility with ADO. - * - * @param [nRows] is the number of rows to return. -1 means every row. - * - * @return an array indexed by the rows (0-based) from the recordset - */ - function &GetRows($nRows = -1) - { - $arr =& $this->GetArray($nRows); - return $arr; - } - /** - * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. - * The first column is treated as the key and is not included in the array. - * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless - * $force_array == true. - * - * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional - * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing, - * read the source. - * - * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and - * instead of returning array[col0] => array(remaining cols), return array[col0] => col1 - * - * @return an associative array indexed by the first column of the array, - * or false if the data has less than 2 cols. - */ - function &GetAssoc($force_array = false, $first2cols = false) { - $cols = $this->_numOfFields; - if ($cols < 2) { - return false; + /** + * Synonym for GetArray() for compatibility with ADO. + * + * @param [nRows] is the number of rows to return. -1 means every row. + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function &GetRows($nRows = -1) + { + $arr =& $this->GetArray($nRows); + return $arr; } - $numIndex = isset($this->fields[0]); - $results = array(); - if (!$first2cols && ($cols > 2 || $force_array)) { - if ($numIndex) { - while (!$this->EOF) { - $results[trim($this->fields[0])] = array_slice($this->fields, 1); - $this->MoveNext(); - } - } else { - while (!$this->EOF) { - $results[trim(reset($this->fields))] = array_slice($this->fields, 1); - $this->MoveNext(); - } + /** + * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. + * The first column is treated as the key and is not included in the array. + * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless + * $force_array == true. + * + * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional + * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing, + * read the source. + * + * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and + * instead of returning array[col0] => array(remaining cols), return array[col0] => col1 + * + * @return an associative array indexed by the first column of the array, + * or false if the data has less than 2 cols. + */ + function &GetAssoc($force_array = false, $first2cols = false) + { + $cols = $this->_numOfFields; + if ($cols < 2) { + return false; } - } else { - // return scalar values - if ($numIndex) { - while (!$this->EOF) { - // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string - $results[trim(($this->fields[0]))] = $this->fields[1]; - $this->MoveNext(); + $numIndex = isset($this->fields[0]); + $results = array(); + + if (!$first2cols && ($cols > 2 || $force_array)) { + if ($numIndex) { + while (!$this->EOF) { + $results[trim($this->fields[0])] = array_slice($this->fields, 1); + $this->MoveNext(); + } + } else { + while (!$this->EOF) { + $results[trim(reset($this->fields))] = array_slice($this->fields, 1); + $this->MoveNext(); + } } } else { - while (!$this->EOF) { - // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string - $v1 = trim(reset($this->fields)); - $v2 = ''.next($this->fields); - $results[$v1] = $v2; - $this->MoveNext(); + // return scalar values + if ($numIndex) { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $results[trim(($this->fields[0]))] = $this->fields[1]; + $this->MoveNext(); + } + } else { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $v1 = trim(reset($this->fields)); + $v2 = '' . next($this->fields); + $results[$v1] = $v2; + $this->MoveNext(); + } } } + return $results; } - return $results; - } - - - /** - * - * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format - * @param fmt is the format to apply to it, using date() - * - * @return a timestamp formated as user desires - */ - function UserTimeStamp($v,$fmt='Y-m-d H:i:s') - { - if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v); - $tt = $this->UnixTimeStamp($v); - // $tt == -1 if pre TIMESTAMP_FIRST_YEAR - if (($tt === false || $tt == -1) && $v != false) return $v; - if ($tt === 0) return $this->emptyTimeStamp; - return adodb_date($fmt,$tt); - } - /** - * @param v is the character date in YYYY-MM-DD format, returned by database - * @param fmt is the format to apply to it, using date() - * - * @return a date formated as user desires - */ - function UserDate($v,$fmt='Y-m-d') - { - $tt = $this->UnixDate($v); - // $tt == -1 if pre TIMESTAMP_FIRST_YEAR - if (($tt === false || $tt == -1) && $v != false) return $v; - else if ($tt == 0) return $this->emptyDate; - else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR + /** + * + * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format + * @param fmt is the format to apply to it, using date() + * + * @return a timestamp formated as user desires + */ + function UserTimeStamp($v, $fmt = 'Y-m-d H:i:s') + { + if (is_numeric($v) && strlen($v) < 14) return adodb_date($fmt, $v); + $tt = $this->UnixTimeStamp($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + if ($tt === 0) return $this->emptyTimeStamp; + return adodb_date($fmt, $tt); } - return adodb_date($fmt,$tt); - } + /** + * @param v is the character date in YYYY-MM-DD format, returned by database + * @param fmt is the format to apply to it, using date() + * + * @return a date formated as user desires + */ + function UserDate($v, $fmt = 'Y-m-d') + { + $tt = $this->UnixDate($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + else if ($tt == 0) return $this->emptyDate; + else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR + } + return adodb_date($fmt, $tt); - /** - * @param $v is a date string in YYYY-MM-DD format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - function UnixDate($v) - { + } - if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", - ($v), $rr)) return false; - if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0; - // h-m-s-MM-DD-YY - return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); - } + /** + * @param $v is a date string in YYYY-MM-DD format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixDate($v) + { + if (!preg_match("|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", + ($v), $rr) + ) return false; - /** - * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - function UnixTimeStamp($v) - { + if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0; + // h-m-s-MM-DD-YY + return @adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]); + } - if (!preg_match( - "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", - ($v), $rr)) return false; - if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0; - // h-m-s-MM-DD-YY - if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); - return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); - } + /** + * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixTimeStamp($v) + { + if (!preg_match( + "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", + ($v), $rr) + ) return false; + if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2] <= 1) return 0; - /** - * PEAR DB Compat - do not use internally - */ - function Free() - { - return $this->Close(); - } + // h-m-s-MM-DD-YY + if (!isset($rr[5])) return adodb_mktime(0, 0, 0, $rr[2], $rr[3], $rr[1]); + return @adodb_mktime($rr[5], $rr[6], $rr[7], $rr[2], $rr[3], $rr[1]); + } - /** - * PEAR DB compat, number of rows - */ - function NumRows() - { - return $this->_numOfRows; - } + /** + * PEAR DB Compat - do not use internally + */ + function Free() + { + return $this->Close(); + } - /** - * PEAR DB compat, number of cols - */ - function NumCols() - { - return $this->_numOfFields; - } + /** + * PEAR DB compat, number of rows + */ + function NumRows() + { + return $this->_numOfRows; + } - /** - * Fetch a row, returning false if no more rows. - * This is PEAR DB compat mode. - * - * @return false or array containing the current record - */ - function &FetchRow() - { - if ($this->EOF) return false; - $arr = $this->fields; - $this->_currentRow++; - if (!$this->_fetch()) $this->EOF = true; - return $arr; - } + /** + * PEAR DB compat, number of cols + */ + function NumCols() + { + return $this->_numOfFields; + } - /** - * Fetch a row, returning PEAR_Error if no more rows. - * This is PEAR DB compat mode. - * - * @return DB_OK or error object - */ - function FetchInto(&$arr) - { - if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false; - $arr = $this->fields; - $this->MoveNext(); - return 1; // DB_OK - } + /** + * Fetch a row, returning false if no more rows. + * This is PEAR DB compat mode. + * + * @return false or array containing the current record + */ + function &FetchRow() + { + if ($this->EOF) return false; + $arr = $this->fields; + $this->_currentRow++; + if (!$this->_fetch()) $this->EOF = true; + return $arr; + } - /** - * Move to the first row in the recordset. Many databases do NOT support this. - * - * @return true or false - */ - function MoveFirst() - { - if ($this->_currentRow == 0) return true; - return $this->Move(0); - } + /** + * Fetch a row, returning PEAR_Error if no more rows. + * This is PEAR DB compat mode. + * + * @return DB_OK or error object + */ + function FetchInto(&$arr) + { + if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF', -1) : false; + $arr = $this->fields; + $this->MoveNext(); + return 1; // DB_OK + } - /** - * Move to the last row in the recordset. - * - * @return true or false - */ - function MoveLast() - { - if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1); - if ($this->EOF) return false; - while (!$this->EOF) { - $f = $this->fields; - $this->MoveNext(); + /** + * Move to the first row in the recordset. Many databases do NOT support this. + * + * @return true or false + */ + function MoveFirst() + { + if ($this->_currentRow == 0) return true; + return $this->Move(0); } - $this->fields = $f; - $this->EOF = false; - return true; - } - /** - * Move to next record in the recordset. - * - * @return true if there still rows available, or false if there are no more rows (EOF). - */ - function MoveNext() - { - if (!$this->EOF) { - $this->_currentRow++; - if ($this->_fetch()) return true; + /** + * Move to the last row in the recordset. + * + * @return true or false + */ + function MoveLast() + { + if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows - 1); + if ($this->EOF) return false; + while (!$this->EOF) { + $f = $this->fields; + $this->MoveNext(); + } + $this->fields = $f; + $this->EOF = false; + return true; } - $this->EOF = true; - /* -- tested error handling when scrolling cursor -- seems useless. + + + /** + * Move to next record in the recordset. + * + * @return true if there still rows available, or false if there are no more rows (EOF). + */ + function MoveNext() + { + if (!$this->EOF) { + $this->_currentRow++; + if ($this->_fetch()) return true; + } + $this->EOF = true; + /* -- tested error handling when scrolling cursor -- seems useless. $conn = $this->connection; if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) { $fn = $conn->raiseErrorFn; $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database); } */ - return false; - } + return false; + } - /** - * Random access to a specific row in the recordset. Some databases do not support - * access to previous rows in the databases (no scrolling backwards). - * - * @param rowNumber is the row to move to (0-based) - * - * @return true if there still rows available, or false if there are no more rows (EOF). - */ - function Move($rowNumber = 0) - { - $this->EOF = false; - if ($rowNumber == $this->_currentRow) return true; - if ($rowNumber >= $this->_numOfRows) - if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2; + /** + * Random access to a specific row in the recordset. Some databases do not support + * access to previous rows in the databases (no scrolling backwards). + * + * @param rowNumber is the row to move to (0-based) + * + * @return true if there still rows available, or false if there are no more rows (EOF). + */ + function Move($rowNumber = 0) + { + $this->EOF = false; + if ($rowNumber == $this->_currentRow) return true; + if ($rowNumber >= $this->_numOfRows) + if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows - 2; - if ($this->canSeek) { + if ($this->canSeek) { - if ($this->_seek($rowNumber)) { - $this->_currentRow = $rowNumber; - if ($this->_fetch()) { - return true; - } - } else { - $this->EOF = true; - return false; - } - } else { - if ($rowNumber < $this->_currentRow) return false; - global $ADODB_EXTENSION; - if ($ADODB_EXTENSION) { - while (!$this->EOF && $this->_currentRow < $rowNumber) { - adodb_movenext($this); + if ($this->_seek($rowNumber)) { + $this->_currentRow = $rowNumber; + if ($this->_fetch()) { + return true; + } + } else { + $this->EOF = true; + return false; } } else { + if ($rowNumber < $this->_currentRow) return false; + global $ADODB_EXTENSION; + if ($ADODB_EXTENSION) { + while (!$this->EOF && $this->_currentRow < $rowNumber) { + adodb_movenext($this); + } + } else { - while (! $this->EOF && $this->_currentRow < $rowNumber) { - $this->_currentRow++; + while (!$this->EOF && $this->_currentRow < $rowNumber) { + $this->_currentRow++; - if (!$this->_fetch()) $this->EOF = true; + if (!$this->_fetch()) $this->EOF = true; + } } + return !($this->EOF); } - return !($this->EOF); - } - $this->fields = false; - $this->EOF = true; - return false; - } + $this->fields = false; + $this->EOF = true; + return false; + } - /** - * Get the value of a field in the current row by column name. - * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM. - * - * @param colname is the field to access - * - * @return the value of $colname column - */ - function Fields($colname) - { - return $this->fields[$colname]; - } + /** + * Get the value of a field in the current row by column name. + * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM. + * + * @param colname is the field to access + * + * @return the value of $colname column + */ + function Fields($colname) + { + return $this->fields[$colname]; + } - function GetAssocKeys($upper=true) - { - $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { - $o =& $this->FetchField($i); - if ($upper === 2) $this->bind[$o->name] = $i; - else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i; + function GetAssocKeys($upper = true) + { + $this->bind = array(); + for ($i = 0; $i < $this->_numOfFields; $i++) { + $o =& $this->FetchField($i); + if ($upper === 2) $this->bind[$o->name] = $i; + else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i; + } } - } - /** - * Use associative array to get fields array for databases that do not support - * associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it - * - * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC - * before you execute your SQL statement, and access $rs->fields['col'] directly. - * - * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField - */ - function &GetRowAssoc($upper=1) - { - $record = array(); - // if (!$this->fields) return $record; + /** + * Use associative array to get fields array for databases that do not support + * associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it + * + * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC + * before you execute your SQL statement, and access $rs->fields['col'] directly. + * + * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField + */ + function &GetRowAssoc($upper = 1) + { + $record = array(); + // if (!$this->fields) return $record; - if (!$this->bind) { - $this->GetAssocKeys($upper); - } + if (!$this->bind) { + $this->GetAssocKeys($upper); + } - foreach($this->bind as $k => $v) { - $record[$k] = $this->fields[$v]; - } + foreach ($this->bind as $k => $v) { + $record[$k] = $this->fields[$v]; + } - return $record; - } + return $record; + } - /** - * Clean up recordset - * - * @return true or false - */ - function Close() - { - // free connection object - this seems to globally free the object - // and not merely the reference, so don't do this... - // $this->connection = false; - if (!$this->_closed) { - $this->_closed = true; - return $this->_close(); - } else - return true; - } + /** + * Clean up recordset + * + * @return true or false + */ + function Close() + { + // free connection object - this seems to globally free the object + // and not merely the reference, so don't do this... + // $this->connection = false; + if (!$this->_closed) { + $this->_closed = true; + return $this->_close(); + } else + return true; + } - /** - * synonyms RecordCount and RowCount - * - * @return the number of rows or -1 if this is not supported - */ - function RecordCount() {return $this->_numOfRows;} + /** + * synonyms RecordCount and RowCount + * + * @return the number of rows or -1 if this is not supported + */ + function RecordCount() + { + return $this->_numOfRows; + } - /* + /* * If we are using PageExecute(), this will return the maximum possible rows * that can be returned when paging a recordset. */ - function MaxRecordCount() - { - return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount(); - } + function MaxRecordCount() + { + return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount(); + } - /** - * synonyms RecordCount and RowCount - * - * @return the number of rows or -1 if this is not supported - */ - function RowCount() {return $this->_numOfRows;} + /** + * synonyms RecordCount and RowCount + * + * @return the number of rows or -1 if this is not supported + */ + function RowCount() + { + return $this->_numOfRows; + } - /** - * Portable RecordCount. Pablo Roca <pabloroca@mvps.org> - * - * @return the number of records from a previous SELECT. All databases support this. - * - * But aware possible problems in multiuser environments. For better speed the table - * must be indexed by the condition. Heavy test this before deploying. - */ - function PO_RecordCount($table="", $condition="") { + /** + * Portable RecordCount. Pablo Roca <pabloroca@mvps.org> + * + * @return the number of records from a previous SELECT. All databases support this. + * + * But aware possible problems in multiuser environments. For better speed the table + * must be indexed by the condition. Heavy test this before deploying. + */ + function PO_RecordCount($table = "", $condition = "") + { - $lnumrows = $this->_numOfRows; - // the database doesn't support native recordcount, so we do a workaround - if ($lnumrows == -1 && $this->connection) { - IF ($table) { - if ($condition) $condition = " WHERE " . $condition; - $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition"); - if ($resultrows) $lnumrows = reset($resultrows->fields); + $lnumrows = $this->_numOfRows; + // the database doesn't support native recordcount, so we do a workaround + if ($lnumrows == -1 && $this->connection) { + IF ($table) { + if ($condition) $condition = " WHERE " . $condition; + $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition"); + if ($resultrows) $lnumrows = reset($resultrows->fields); + } } + return $lnumrows; } - return $lnumrows; - } - /** - * @return the current row in the recordset. If at EOF, will return the last row. 0-based. - */ - function CurrentRow() {return $this->_currentRow;} + /** + * @return the current row in the recordset. If at EOF, will return the last row. 0-based. + */ + function CurrentRow() + { + return $this->_currentRow; + } - /** - * synonym for CurrentRow -- for ADO compat - * - * @return the current row in the recordset. If at EOF, will return the last row. 0-based. - */ - function AbsolutePosition() {return $this->_currentRow;} + /** + * synonym for CurrentRow -- for ADO compat + * + * @return the current row in the recordset. If at EOF, will return the last row. 0-based. + */ + function AbsolutePosition() + { + return $this->_currentRow; + } - /** - * @return the number of columns in the recordset. Some databases will set this to 0 - * if no records are returned, others will return the number of columns in the query. - */ - function FieldCount() {return $this->_numOfFields;} + /** + * @return the number of columns in the recordset. Some databases will set this to 0 + * if no records are returned, others will return the number of columns in the query. + */ + function FieldCount() + { + return $this->_numOfFields; + } - /** - * Get the ADOFieldObject of a specific column. - * - * @param fieldoffset is the column position to access(0-based). - * - * @return the ADOFieldObject for that column, or false. - */ - function &FetchField($fieldoffset) - { - // must be defined by child class - } + /** + * Get the ADOFieldObject of a specific column. + * + * @param fieldoffset is the column position to access(0-based). + * + * @return the ADOFieldObject for that column, or false. + */ + function &FetchField($fieldoffset) + { + // must be defined by child class + } - /** - * Get the ADOFieldObjects of all columns in an array. - * - */ - function FieldTypesArray() - { - $arr = array(); - for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) - $arr[] = $this->FetchField($i); - return $arr; - } + /** + * Get the ADOFieldObjects of all columns in an array. + * + */ + function FieldTypesArray() + { + $arr = array(); + for ($i = 0, $max = $this->_numOfFields; $i < $max; $i++) + $arr[] = $this->FetchField($i); + return $arr; + } - /** - * Return the fields array of the current row as an object for convenience. - * The default case is lowercase field names. - * - * @return the object with the properties set to the fields of the current row - */ - function &FetchObj() - { - $o =& $this->FetchObject(false); - return $o; - } + /** + * Return the fields array of the current row as an object for convenience. + * The default case is lowercase field names. + * + * @return the object with the properties set to the fields of the current row + */ + function &FetchObj() + { + $o =& $this->FetchObject(false); + return $o; + } - /** - * Return the fields array of the current row as an object for convenience. - * The default case is uppercase. - * - * @param $isupper to set the object property names to uppercase - * - * @return the object with the properties set to the fields of the current row - */ - function &FetchObject($isupper=true) - { - if (empty($this->_obj)) { - $this->_obj =& new ADOFetchObj(); - $this->_names = array(); - for ($i=0; $i <$this->_numOfFields; $i++) { - $f = $this->FetchField($i); - $this->_names[] = $f->name; + /** + * Return the fields array of the current row as an object for convenience. + * The default case is uppercase. + * + * @param $isupper to set the object property names to uppercase + * + * @return the object with the properties set to the fields of the current row + */ + function &FetchObject($isupper = true) + { + if (empty($this->_obj)) { + $this->_obj =& new ADOFetchObj(); + $this->_names = array(); + for ($i = 0; $i < $this->_numOfFields; $i++) { + $f = $this->FetchField($i); + $this->_names[] = $f->name; + } } + $i = 0; + $o = &$this->_obj; + for ($i = 0; $i < $this->_numOfFields; $i++) { + $name = $this->_names[$i]; + if ($isupper) $n = strtoupper($name); + else $n = $name; + + $o->$n = $this->Fields($name); + } + return $o; } - $i = 0; - $o = &$this->_obj; - for ($i=0; $i <$this->_numOfFields; $i++) { - $name = $this->_names[$i]; - if ($isupper) $n = strtoupper($name); - else $n = $name; - $o->$n = $this->Fields($name); + /** + * Return the fields array of the current row as an object for convenience. + * The default is lower-case field names. + * + * @return the object with the properties set to the fields of the current row, + * or false if EOF + * + * Fixed bug reported by tim@orotech.net + */ + function &FetchNextObj() + { + return $this->FetchNextObject(false); } - return $o; - } - - /** - * Return the fields array of the current row as an object for convenience. - * The default is lower-case field names. - * - * @return the object with the properties set to the fields of the current row, - * or false if EOF - * - * Fixed bug reported by tim@orotech.net - */ - function &FetchNextObj() - { - return $this->FetchNextObject(false); - } - /** - * Return the fields array of the current row as an object for convenience. - * The default is upper case field names. - * - * @param $isupper to set the object property names to uppercase - * - * @return the object with the properties set to the fields of the current row, - * or false if EOF - * - * Fixed bug reported by tim@orotech.net - */ - function &FetchNextObject($isupper=true) - { - $o = false; - if ($this->_numOfRows != 0 && !$this->EOF) { - $o = $this->FetchObject($isupper); - $this->_currentRow++; - if ($this->_fetch()) return $o; + /** + * Return the fields array of the current row as an object for convenience. + * The default is upper case field names. + * + * @param $isupper to set the object property names to uppercase + * + * @return the object with the properties set to the fields of the current row, + * or false if EOF + * + * Fixed bug reported by tim@orotech.net + */ + function &FetchNextObject($isupper = true) + { + $o = false; + if ($this->_numOfRows != 0 && !$this->EOF) { + $o = $this->FetchObject($isupper); + $this->_currentRow++; + if ($this->_fetch()) return $o; + } + $this->EOF = true; + return $o; } - $this->EOF = true; - return $o; - } - /** - * Get the metatype of the column. This is used for formatting. This is because - * many databases use different names for the same type, so we transform the original - * type to our standardised version which uses 1 character codes: - * - * @param t is the type passed in. Normally is ADOFieldObject->type. - * @param len is the maximum length of that field. This is because we treat character - * fields bigger than a certain size as a 'B' (blob). - * @param fieldobj is the field object returned by the database driver. Can hold - * additional info (eg. primary_key for mysql). - * - * @return the general type of the data: - * C for character < 200 chars - * X for teXt (>= 200 chars) - * B for Binary - * N for numeric floating point - * D for date - * T for timestamp - * L for logical/Boolean - * I for integer - * R for autoincrement counter/integer - * - * - */ - function MetaType($t,$len=-1,$fieldobj=false) - { - if (is_object($t)) { - $fieldobj = $t; - $t = $fieldobj->type; - $len = $fieldobj->max_length; - } - // changed in 2.32 to hashing instead of switch stmt for speed... - static $typeMap = array( - 'VARCHAR' => 'C', - 'VARCHAR2' => 'C', - 'CHAR' => 'C', - 'C' => 'C', - 'STRING' => 'C', - 'NCHAR' => 'C', - 'NVARCHAR' => 'C', - 'VARYING' => 'C', - 'BPCHAR' => 'C', - 'CHARACTER' => 'C', - 'INTERVAL' => 'C', # Postgres - ## - 'LONGCHAR' => 'X', - 'TEXT' => 'X', - 'NTEXT' => 'X', - 'M' => 'X', - 'X' => 'X', - 'CLOB' => 'X', - 'NCLOB' => 'X', - 'LVARCHAR' => 'X', - ## - 'BLOB' => 'B', - 'IMAGE' => 'B', - 'BINARY' => 'B', - 'VARBINARY' => 'B', - 'LONGBINARY' => 'B', - 'B' => 'B', - ## - 'YEAR' => 'D', // mysql - 'DATE' => 'D', - 'D' => 'D', - ## - 'TIME' => 'T', - 'TIMESTAMP' => 'T', - 'DATETIME' => 'T', - 'TIMESTAMPTZ' => 'T', - 'T' => 'T', - ## - 'BOOL' => 'L', - 'BOOLEAN' => 'L', - 'BIT' => 'L', - 'L' => 'L', - ## - 'COUNTER' => 'R', - 'R' => 'R', - 'SERIAL' => 'R', // ifx - 'INT IDENTITY' => 'R', - ## - 'INT' => 'I', - 'INTEGER' => 'I', - 'INTEGER UNSIGNED' => 'I', - 'SHORT' => 'I', - 'TINYINT' => 'I', - 'SMALLINT' => 'I', - 'I' => 'I', - ## - 'LONG' => 'N', // interbase is numeric, oci8 is blob - 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers - 'DECIMAL' => 'N', - 'DEC' => 'N', - 'REAL' => 'N', - 'DOUBLE' => 'N', - 'DOUBLE PRECISION' => 'N', - 'SMALLFLOAT' => 'N', - 'FLOAT' => 'N', - 'NUMBER' => 'N', - 'NUM' => 'N', - 'NUMERIC' => 'N', - 'MONEY' => 'N', - - ## informix 9.2 - 'SQLINT' => 'I', - 'SQLSERIAL' => 'I', - 'SQLSMINT' => 'I', - 'SQLSMFLOAT' => 'N', - 'SQLFLOAT' => 'N', - 'SQLMONEY' => 'N', - 'SQLDECIMAL' => 'N', - 'SQLDATE' => 'D', - 'SQLVCHAR' => 'C', - 'SQLCHAR' => 'C', - 'SQLDTIME' => 'T', - 'SQLINTERVAL' => 'N', - 'SQLBYTES' => 'B', - 'SQLTEXT' => 'X' - ); - - $tmap = false; - $t = strtoupper($t); - $tmap = @$typeMap[$t]; - switch ($tmap) { - case 'C': - - // is the char field is too long, return as text field... - if ($this->blobSize >= 0) { - if ($len > $this->blobSize) return 'X'; - } elseif ($len > 250) { - return 'X'; - } - return 'C'; - - case 'I': - if (!empty($fieldobj->primary_key)) return 'R'; - return 'I'; - - case false: - return 'N'; - - case 'B': - if (isset($fieldobj->binary)) - return ($fieldobj->binary) ? 'B' : 'X'; - return 'B'; - - case 'D': - if (!empty($this->datetime)) return 'T'; - return 'D'; - - default: - if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B'; - return $tmap; + /** + * Get the metatype of the column. This is used for formatting. This is because + * many databases use different names for the same type, so we transform the original + * type to our standardised version which uses 1 character codes: + * + * @param t is the type passed in. Normally is ADOFieldObject->type. + * @param len is the maximum length of that field. This is because we treat character + * fields bigger than a certain size as a 'B' (blob). + * @param fieldobj is the field object returned by the database driver. Can hold + * additional info (eg. primary_key for mysql). + * + * @return the general type of the data: + * C for character < 200 chars + * X for teXt (>= 200 chars) + * B for Binary + * N for numeric floating point + * D for date + * T for timestamp + * L for logical/Boolean + * I for integer + * R for autoincrement counter/integer + * + * + */ + function MetaType($t, $len = -1, $fieldobj = false) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } + // changed in 2.32 to hashing instead of switch stmt for speed... + static $typeMap = array( + 'VARCHAR' => 'C', + 'VARCHAR2' => 'C', + 'CHAR' => 'C', + 'C' => 'C', + 'STRING' => 'C', + 'NCHAR' => 'C', + 'NVARCHAR' => 'C', + 'VARYING' => 'C', + 'BPCHAR' => 'C', + 'CHARACTER' => 'C', + 'INTERVAL' => 'C', # Postgres + ## + 'LONGCHAR' => 'X', + 'TEXT' => 'X', + 'NTEXT' => 'X', + 'M' => 'X', + 'X' => 'X', + 'CLOB' => 'X', + 'NCLOB' => 'X', + 'LVARCHAR' => 'X', + ## + 'BLOB' => 'B', + 'IMAGE' => 'B', + 'BINARY' => 'B', + 'VARBINARY' => 'B', + 'LONGBINARY' => 'B', + 'B' => 'B', + ## + 'YEAR' => 'D', // mysql + 'DATE' => 'D', + 'D' => 'D', + ## + 'TIME' => 'T', + 'TIMESTAMP' => 'T', + 'DATETIME' => 'T', + 'TIMESTAMPTZ' => 'T', + 'T' => 'T', + ## + 'BOOL' => 'L', + 'BOOLEAN' => 'L', + 'BIT' => 'L', + 'L' => 'L', + ## + 'COUNTER' => 'R', + 'R' => 'R', + 'SERIAL' => 'R', // ifx + 'INT IDENTITY' => 'R', + ## + 'INT' => 'I', + 'INTEGER' => 'I', + 'INTEGER UNSIGNED' => 'I', + 'SHORT' => 'I', + 'TINYINT' => 'I', + 'SMALLINT' => 'I', + 'I' => 'I', + ## + 'LONG' => 'N', // interbase is numeric, oci8 is blob + 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers + 'DECIMAL' => 'N', + 'DEC' => 'N', + 'REAL' => 'N', + 'DOUBLE' => 'N', + 'DOUBLE PRECISION' => 'N', + 'SMALLFLOAT' => 'N', + 'FLOAT' => 'N', + 'NUMBER' => 'N', + 'NUM' => 'N', + 'NUMERIC' => 'N', + 'MONEY' => 'N', + + ## informix 9.2 + 'SQLINT' => 'I', + 'SQLSERIAL' => 'I', + 'SQLSMINT' => 'I', + 'SQLSMFLOAT' => 'N', + 'SQLFLOAT' => 'N', + 'SQLMONEY' => 'N', + 'SQLDECIMAL' => 'N', + 'SQLDATE' => 'D', + 'SQLVCHAR' => 'C', + 'SQLCHAR' => 'C', + 'SQLDTIME' => 'T', + 'SQLINTERVAL' => 'N', + 'SQLBYTES' => 'B', + 'SQLTEXT' => 'X' + ); + + $tmap = false; + $t = strtoupper($t); + $tmap = @$typeMap[$t]; + switch ($tmap) { + case 'C': + + // is the char field is too long, return as text field... + if ($this->blobSize >= 0) { + if ($len > $this->blobSize) return 'X'; + } elseif ($len > 250) { + return 'X'; + } + return 'C'; + + case 'I': + if (!empty($fieldobj->primary_key)) return 'R'; + return 'I'; + + case false: + return 'N'; + + case 'B': + if (isset($fieldobj->binary)) + return ($fieldobj->binary) ? 'B' : 'X'; + return 'B'; + + case 'D': + if (!empty($this->datetime)) return 'T'; + return 'D'; + + default: + if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B'; + return $tmap; + } } - } - function _close() {} + function _close() + { + } - /** - * set/returns the current recordset page when paginating - */ - function AbsolutePage($page=-1) - { - if ($page != -1) $this->_currentPage = $page; - return $this->_currentPage; - } + /** + * set/returns the current recordset page when paginating + */ + function AbsolutePage($page = -1) + { + if ($page != -1) $this->_currentPage = $page; + return $this->_currentPage; + } - /** - * set/returns the status of the atFirstPage flag when paginating - */ - function AtFirstPage($status=false) - { - if ($status != false) $this->_atFirstPage = $status; - return $this->_atFirstPage; - } + /** + * set/returns the status of the atFirstPage flag when paginating + */ + function AtFirstPage($status = false) + { + if ($status != false) $this->_atFirstPage = $status; + return $this->_atFirstPage; + } - function LastPageNo($page = false) - { - if ($page != false) $this->_lastPageNo = $page; - return $this->_lastPageNo; - } + function LastPageNo($page = false) + { + if ($page != false) $this->_lastPageNo = $page; + return $this->_lastPageNo; + } - /** - * set/returns the status of the atLastPage flag when paginating - */ - function AtLastPage($status=false) - { - if ($status != false) $this->_atLastPage = $status; - return $this->_atLastPage; - } + /** + * set/returns the status of the atLastPage flag when paginating + */ + function AtLastPage($status = false) + { + if ($status != false) $this->_atLastPage = $status; + return $this->_atLastPage; + } -} // end class ADORecordSet + } // end class ADORecordSet //============================================================================================== // CLASS ADORecordSet_array @@ -3224,23 +3294,24 @@ { var $databaseType = 'array'; - var $_array; // holds the 2-dimensional data array - var $_types; // the array of types of each column (C B I L M) - var $_colnames; // names of each column in array - var $_skiprow1; // skip 1st row because it holds column names + var $_array; // holds the 2-dimensional data array + var $_types; // the array of types of each column (C B I L M) + var $_colnames; // names of each column in array + var $_skiprow1; // skip 1st row because it holds column names var $_fieldarr; // holds array of field objects var $canSeek = true; var $affectedrows = false; var $insertid = false; var $sql = ''; var $compat = false; + /** * Constructor * */ - function ADORecordSet_array($fakeid=1) + function ADORecordSet_array($fakeid = 1) { - global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH; + global $ADODB_FETCH_MODE, $ADODB_COMPAT_FETCH; // fetch() on EOF does not delete $this->fields $this->compat = !empty($ADODB_COMPAT_FETCH); @@ -3260,19 +3331,20 @@ * @param [colnames] array of column names. If set, then the first row of * $array should not hold the column names. */ - function InitArray($array,$typearr,$colnames=false) + function InitArray($array, $typearr, $colnames = false) { $this->_array = $array; $this->_types = $typearr; if ($colnames) { $this->_skiprow1 = false; $this->_colnames = $colnames; - } else { + } else { $this->_skiprow1 = true; $this->_colnames = $array[0]; } $this->Init(); } + /** * Setup the Array and datatype file objects * @@ -3281,17 +3353,17 @@ * unless paramter $colnames is used. * @param fieldarr holds an array of ADOFieldObject's. */ - function InitArrayFields(&$array,&$fieldarr) + function InitArrayFields(&$array, &$fieldarr) { $this->_array =& $array; - $this->_skiprow1= false; + $this->_skiprow1 = false; if ($fieldarr) { $this->_fieldobjects =& $fieldarr; } $this->Init(); } - function &GetArray($nRows=-1) + function &GetArray($nRows = -1) { if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) { return $this->_array; @@ -3303,11 +3375,11 @@ function _initrs() { - $this->_numOfRows = sizeof($this->_array); + $this->_numOfRows = sizeof($this->_array); if ($this->_skiprow1) $this->_numOfRows -= 1; - $this->_numOfFields =(isset($this->_fieldobjects)) ? - sizeof($this->_fieldobjects):sizeof($this->_types); + $this->_numOfFields = (isset($this->_fieldobjects)) ? + sizeof($this->_fieldobjects) : sizeof($this->_types); } /* Use associative array to get fields array */ @@ -3317,7 +3389,7 @@ if (!$this->bind) { $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { + for ($i = 0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } @@ -3330,9 +3402,9 @@ if (isset($this->_fieldobjects)) { return $this->_fieldobjects[$fieldOffset]; } - $o = new ADOFieldObject(); + $o = new ADOFieldObject(); $o->name = $this->_colnames[$fieldOffset]; - $o->type = $this->_types[$fieldOffset]; + $o->type = $this->_types[$fieldOffset]; $o->max_length = -1; // length not known return $o; @@ -3408,22 +3480,26 @@ */ function ADOLoadCode($dbType) { - global $ADODB_LASTDB; + global $ADODB_LASTDB; if (!$dbType) return false; $db = strtolower($dbType); switch ($db) { - case 'maxsql': $db = 'mysqlt'; break; + case 'maxsql': + $db = 'mysqlt'; + break; case 'postgres': - case 'pgsql': $db = 'postgres7'; break; + case 'pgsql': + $db = 'postgres7'; + break; } - @include_once(ADODB_DIR."/drivers/adodb-".$db.".inc.php"); + @include_once(ADODB_DIR . "/drivers/adodb-" . $db . ".inc.php"); $ADODB_LASTDB = $db; $ok = class_exists("ADODB_" . $db); if ($ok) return $db; - $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php"; + $file = ADODB_DIR . "/drivers/adodb-" . $db . ".inc.php"; if (!file_exists($file)) ADOConnection::outp("Missing file: $file"); else ADOConnection::outp("Syntax error in file: $file"); return false; @@ -3432,7 +3508,7 @@ /** * synonym for ADONewConnection for people like me who cannot remember the correct name */ - function &NewADOConnection($db='') + function &NewADOConnection($db = '') { $tmp =& ADONewConnection($db); return $tmp; @@ -3446,17 +3522,17 @@ * * @return the freshly created instance of the Connection class. */ - function &ADONewConnection($db='') + function &ADONewConnection($db = '') { - GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB; + GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB; - if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); + if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE', 2); $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false; if (!empty($ADODB_NEWCONNECTION)) { $obj = $ADODB_NEWCONNECTION($db); if ($obj) { - if ($errorfn) $obj->raiseErrorFn = $errorfn; + if ($errorfn) $obj->raiseErrorFn = $errorfn; return $obj; } } @@ -3467,19 +3543,19 @@ if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db); if (!$db) { - if ($errorfn) { + if ($errorfn) { // raise an error $ignore = false; $errorfn('ADONewConnection', 'ADONewConnection', -998, - "could not load the database driver for '$db", - $db,false,$ignore); + "could not load the database driver for '$db", + $db, false, $ignore); } else - ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false); + ADOConnection::outp("<p>ADONewConnection: Unable to load database driver '$db'</p>", false); return false; } - $cls = 'ADODB_'.$db; + $cls = 'ADODB_' . $db; if (!class_exists($cls)) { adodb_backtrace(); return false; @@ -3492,26 +3568,28 @@ } // $perf == true means called by NewPerfMonitor() - function _adodb_getdriver($provider,$drivername,$perf=false) + function _adodb_getdriver($provider, $drivername, $perf = false) { if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado') $drivername = $provider; else { - if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5); - else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4); + if (substr($drivername, 0, 5) == 'odbc_') $drivername = substr($drivername, 5); + else if (substr($drivername, 0, 4) == 'ado_') $drivername = substr($drivername, 4); else - switch($drivername) { - case 'oracle': $drivername = 'oci8';break; - //case 'sybase': $drivername = 'mssql';break; - case 'access': + switch ($drivername) { + case 'oracle': + $drivername = 'oci8'; + break; + //case 'sybase': $drivername = 'mssql';break; + case 'access': if ($perf) $drivername = ''; break; - case 'db2': + case 'db2': break; - default: - $drivername = 'generic'; - break; - } + default: + $drivername = 'generic'; + break; + } } return $drivername; @@ -3519,10 +3597,10 @@ function &NewPerfMonitor(&$conn) { - $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true); + $drivername = _adodb_getdriver($conn->dataProvider, $conn->databaseType, true); if (!$drivername || $drivername == 'generic') return false; - include_once(ADODB_DIR.'/adodb-perf.inc.php'); - @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php"); + include_once(ADODB_DIR . '/adodb-perf.inc.php'); + @include_once(ADODB_DIR . "/perf/perf-$drivername.inc.php"); $class = "Perf_$drivername"; if (!class_exists($class)) return false; $perf =& new $class($conn); @@ -3532,11 +3610,11 @@ function &NewDataDictionary(&$conn) { - $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType); + $drivername = _adodb_getdriver($conn->dataProvider, $conn->databaseType); - include_once(ADODB_DIR.'/adodb-lib.inc.php'); - include_once(ADODB_DIR.'/adodb-datadict.inc.php'); - $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php"; + include_once(ADODB_DIR . '/adodb-lib.inc.php'); + include_once(ADODB_DIR . '/adodb-datadict.inc.php'); + $path = ADODB_DIR . "/datadict/datadict-$drivername.inc.php"; if (!file_exists($path)) { ADOConnection::outp("Database driver '$path' not available"); @@ -3557,50 +3635,50 @@ /** - * Save a file $filename and its $contents (normally for caching) with file locking - */ - function adodb_write_file($filename, $contents,$debug=false) + * Save a file $filename and its $contents (normally for caching) with file locking + */ + 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) { + # 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); + $mtime = substr(str_replace(' ', '_', microtime()), 2); // getmypid() actually returns 0 on Win98 - never mind! - $tmpname = $filename.uniqid($mtime).getmypid(); - if (!($fd = fopen($tmpname,'a'))) return false; - $ok = ftruncate($fd,0); - if (!fwrite($fd,$contents)) $ok = false; + $tmpname = $filename . uniqid($mtime) . getmypid(); + if (!($fd = fopen($tmpname, 'a'))) return false; + $ok = ftruncate($fd, 0); + if (!fwrite($fd, $contents)) $ok = false; fclose($fd); - chmod($tmpname,0644); + chmod($tmpname, 0644); // the tricky moment @unlink($filename); - if (!@rename($tmpname,$filename)) { + if (!@rename($tmpname, $filename)) { unlink($tmpname); $ok = false; } if (!$ok) { - if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed')); + 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)) { - $ok = fwrite( $fd, $contents ); + $ok = fwrite($fd, $contents); fclose($fd); - chmod($filename,0644); - }else { + chmod($filename, 0644); + } else { fclose($fd); - if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n"); + if ($debug) ADOConnection::outp(" Failed acquiring lock for $filename<br>\n"); $ok = false; } @@ -3613,7 +3691,9 @@ function adodb_pr($var) { if (isset($_SERVER['HTTP_USER_AGENT'])) { - echo " <pre>\n";print_r($var);echo "</pre>\n"; + echo " <pre>\n"; + print_r($var); + echo "</pre>\n"; } else print_r($var); } @@ -3624,13 +3704,13 @@ @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then). @param levels Number of levels to display */ - function adodb_backtrace($printOrArr=true,$levels=9999) + function adodb_backtrace($printOrArr = true, $levels = 9999) { $s = ''; if (PHPVERSION() < 4.3) return; - $html = (isset($_SERVER['HTTP_USER_AGENT'])); - $fmt = ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s"; + $html = (isset($_SERVER['HTTP_USER_AGENT'])); + $fmt = ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s"; $MAXSTRLEN = 64; @@ -3639,34 +3719,34 @@ if (is_array($printOrArr)) $traceArr = $printOrArr; else $traceArr = debug_backtrace(); array_shift($traceArr); - $tabs = sizeof($traceArr)-1; + $tabs = sizeof($traceArr) - 1; foreach ($traceArr as $arr) { $levels -= 1; if ($levels < 0) break; $args = array(); - for ($i=0; $i < $tabs; $i++) $s .= ($html) ? '   ' : "\t"; + for ($i = 0; $i < $tabs; $i++) $s .= ($html) ? '   ' : "\t"; $tabs -= 1; if ($html) $s .= '<font face="Courier New,Courier">'; - if (isset($arr['class'])) $s .= $arr['class'].'.'; + if (isset($arr['class'])) $s .= $arr['class'] . '.'; if (isset($arr['args'])) - foreach($arr['args'] as $v) { - if (is_null($v)) $args[] = 'null'; - else if (is_array($v)) $args[] = 'Array['.sizeof($v).']'; - else if (is_object($v)) $args[] = 'Object:'.get_class($v); - else if (is_bool($v)) $args[] = $v ? 'true' : 'false'; - else { - $v = (string) @$v; - $str = htmlspecialchars(substr($v,0,$MAXSTRLEN)); - if (strlen($v) > $MAXSTRLEN) $str .= '...'; - $args[] = $str; + foreach ($arr['args'] as $v) { + if (is_null($v)) $args[] = 'null'; + else if (is_array($v)) $args[] = 'Array[' . sizeof($v) . ']'; + else if (is_object($v)) $args[] = 'Object:' . get_class($v); + else if (is_bool($v)) $args[] = $v ? 'true' : 'false'; + else { + $v = (string)@$v; + $str = htmlspecialchars(substr($v, 0, $MAXSTRLEN)); + if (strlen($v) > $MAXSTRLEN) $str .= '...'; + $args[] = $str; + } } - } - $s .= $arr['function'].'('.implode(', ',$args).')'; + $s .= $arr['function'] . '(' . implode(', ', $args) . ')'; - $s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file'])); + $s .= @sprintf($fmt, $arr['line'], $arr['file'], basename($arr['file'])); $s .= "\n"; } diff --git a/lib/WikiDB/adodb/drivers/adodb-access.inc.php b/lib/WikiDB/adodb/drivers/adodb-access.inc.php index 7f7f8f163..92b5cb277 100644 --- a/lib/WikiDB/adodb/drivers/adodb-access.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-access.inc.php @@ -11,72 +11,78 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese Microsoft Access data driver. Requires ODBC. Works only on MS Windows. */ if (!defined('_ADODB_ODBC_LAYER')) { - include(ADODB_DIR."/drivers/adodb-odbc.inc.php"); + include(ADODB_DIR . "/drivers/adodb-odbc.inc.php"); } - if (!defined('_ADODB_ACCESS')) { - define('_ADODB_ACCESS',1); +if (!defined('_ADODB_ACCESS')) { + define('_ADODB_ACCESS', 1); -class ADODB_access extends ADODB_odbc { - var $databaseType = 'access'; - var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE - var $fmtDate = "#Y-m-d#"; - var $fmtTimeStamp = "#Y-m-d h:i:sA#"; // note not comma - var $_bindInputArray = false; // strangely enough, setting to true does not work reliably - var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')"; - var $sysTimeStamp = 'NOW'; - var $hasTransactions = false; - - function ADODB_access() - { - global $ADODB_EXTENSION; - - $ADODB_EXTENSION = false; - $this->ADODB_odbc(); - } - - function Time() + class ADODB_access extends ADODB_odbc { - return time(); - } + var $databaseType = 'access'; + var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE + var $fmtDate = "#Y-m-d#"; + var $fmtTimeStamp = "#Y-m-d h:i:sA#"; // note not comma + var $_bindInputArray = false; // strangely enough, setting to true does not work reliably + var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')"; + var $sysTimeStamp = 'NOW'; + var $hasTransactions = false; - function BeginTrans() { return false;} + function ADODB_access() + { + global $ADODB_EXTENSION; - function IfNull( $field, $ifNull ) - { - return " IIF(IsNull($field), $ifNull, $field) "; // if Access - } -/* - function &MetaTables() - { - global $ADODB_FETCH_MODE; + $ADODB_EXTENSION = false; + $this->ADODB_odbc(); + } - $savem = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - $qid = odbc_tables($this->_connectionID); - $rs = new ADORecordSet_odbc($qid); - $ADODB_FETCH_MODE = $savem; - if (!$rs) return false; + function Time() + { + return time(); + } - $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change; + function BeginTrans() + { + return false; + } - $arr = &$rs->GetArray(); - //print_pre($arr); - $arr2 = array(); - for ($i=0; $i < sizeof($arr); $i++) { - if ($arr[$i][2] && $arr[$i][3] != 'SYSTEM TABLE') - $arr2[] = $arr[$i][2]; + function IfNull($field, $ifNull) + { + return " IIF(IsNull($field), $ifNull, $field) "; // if Access } - return $arr2; - }*/ -} + /* + function &MetaTables() + { + global $ADODB_FETCH_MODE; -class ADORecordSet_access extends ADORecordSet_odbc { + $savem = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + $qid = odbc_tables($this->_connectionID); + $rs = new ADORecordSet_odbc($qid); + $ADODB_FETCH_MODE = $savem; + if (!$rs) return false; - var $databaseType = "access"; + $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change; - function ADORecordSet_access($id,$mode=false) + $arr = &$rs->GetArray(); + //print_pre($arr); + $arr2 = array(); + for ($i=0; $i < sizeof($arr); $i++) { + if ($arr[$i][2] && $arr[$i][3] != 'SYSTEM TABLE') + $arr2[] = $arr[$i][2]; + } + return $arr2; + }*/ + } + + class ADORecordSet_access extends ADORecordSet_odbc { - return $this->ADORecordSet_odbc($id,$mode); + + var $databaseType = "access"; + + function ADORecordSet_access($id, $mode = false) + { + return $this->ADORecordSet_odbc($id, $mode); + } } -}// class + // class } diff --git a/lib/WikiDB/adodb/drivers/adodb-ado.inc.php b/lib/WikiDB/adodb/drivers/adodb-ado.inc.php index b035543a7..d87937e6f 100644 --- a/lib/WikiDB/adodb/drivers/adodb-ado.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-ado.inc.php @@ -10,11 +10,12 @@ Set tabs to 4 for best viewing. Microsoft ADO data driver. Requires ADO. Works only on MS Windows. */ - define("_ADODB_ADO_LAYER", 1 ); +define("_ADODB_ADO_LAYER", 1); /*-------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------*/ -class ADODB_ado extends ADOConnection { +class ADODB_ado extends ADOConnection +{ var $databaseType = "ado"; var $_bindInputArray = false; var $fmtDate = "'Y-m-d'"; @@ -53,21 +54,21 @@ class ADODB_ado extends ADOConnection { // you can also pass a connection string like this: // // $DB->Connect('USER ID=sa;PASSWORD=pwd;SERVER=mangrove;DATABASE=ai',false,false,'SQLOLEDB'); - function _connect($argHostname, $argUsername, $argPassword, $argProvider= 'MSDASQL') + function _connect($argHostname, $argUsername, $argPassword, $argProvider = 'MSDASQL') { $u = 'UID'; $p = 'PWD'; if (!empty($this->charPage)) - $dbc = new COM('ADODB.Connection',null,$this->charPage); + $dbc = new COM('ADODB.Connection', null, $this->charPage); else $dbc = new COM('ADODB.Connection'); - if (! $dbc) return false; + if (!$dbc) return false; /* special support if provider is mssql or access */ - if ($argProvider=='mssql') { - $u = 'User Id'; //User parameter name for OLEDB + if ($argProvider == 'mssql') { + $u = 'User Id'; //User parameter name for OLEDB $p = 'Password'; $argProvider = "SQLOLEDB"; // SQL Server Provider @@ -76,85 +77,85 @@ class ADODB_ado extends ADOConnection { //use trusted conection for SQL if username not specified if (!$argUsername) $argHostname .= ";Trusted_Connection=Yes"; - } elseif ($argProvider=='access') + } elseif ($argProvider == 'access') $argProvider = "Microsoft.Jet.OLEDB.4.0"; // Microsoft Jet Provider if ($argProvider) $dbc->Provider = $argProvider; if ($argUsername) $argHostname .= ";$u=$argUsername"; - if ($argPassword)$argHostname .= ";$p=$argPassword"; + if ($argPassword) $argHostname .= ";$p=$argPassword"; - if ($this->debug) ADOConnection::outp( "Host=".$argHostname."<BR>\n version=$dbc->version"); + if ($this->debug) ADOConnection::outp("Host=" . $argHostname . "<BR>\n version=$dbc->version"); // @ added below for php 4.0.1 and earlier - @$dbc->Open((string) $argHostname); + @$dbc->Open((string)$argHostname); $this->_connectionID = $dbc; $dbc->CursorLocation = $this->_cursor_location; - return $dbc->State > 0; + return $dbc->State > 0; } // returns true or false - function _pconnect($argHostname, $argUsername, $argPassword, $argProvider='MSDASQL') + function _pconnect($argHostname, $argUsername, $argPassword, $argProvider = 'MSDASQL') { - return $this->_connect($argHostname,$argUsername,$argPassword,$argProvider); + return $this->_connect($argHostname, $argUsername, $argPassword, $argProvider); } -/* - adSchemaCatalogs = 1, - adSchemaCharacterSets = 2, - adSchemaCollations = 3, - adSchemaColumns = 4, - adSchemaCheckConstraints = 5, - adSchemaConstraintColumnUsage = 6, - adSchemaConstraintTableUsage = 7, - adSchemaKeyColumnUsage = 8, - adSchemaReferentialContraints = 9, - adSchemaTableConstraints = 10, - adSchemaColumnsDomainUsage = 11, - adSchemaIndexes = 12, - adSchemaColumnPrivileges = 13, - adSchemaTablePrivileges = 14, - adSchemaUsagePrivileges = 15, - adSchemaProcedures = 16, - adSchemaSchemata = 17, - adSchemaSQLLanguages = 18, - adSchemaStatistics = 19, - adSchemaTables = 20, - adSchemaTranslations = 21, - adSchemaProviderTypes = 22, - adSchemaViews = 23, - adSchemaViewColumnUsage = 24, - adSchemaViewTableUsage = 25, - adSchemaProcedureParameters = 26, - adSchemaForeignKeys = 27, - adSchemaPrimaryKeys = 28, - adSchemaProcedureColumns = 29, - adSchemaDBInfoKeywords = 30, - adSchemaDBInfoLiterals = 31, - adSchemaCubes = 32, - adSchemaDimensions = 33, - adSchemaHierarchies = 34, - adSchemaLevels = 35, - adSchemaMeasures = 36, - adSchemaProperties = 37, - adSchemaMembers = 38 - -*/ + /* + adSchemaCatalogs = 1, + adSchemaCharacterSets = 2, + adSchemaCollations = 3, + adSchemaColumns = 4, + adSchemaCheckConstraints = 5, + adSchemaConstraintColumnUsage = 6, + adSchemaConstraintTableUsage = 7, + adSchemaKeyColumnUsage = 8, + adSchemaReferentialContraints = 9, + adSchemaTableConstraints = 10, + adSchemaColumnsDomainUsage = 11, + adSchemaIndexes = 12, + adSchemaColumnPrivileges = 13, + adSchemaTablePrivileges = 14, + adSchemaUsagePrivileges = 15, + adSchemaProcedures = 16, + adSchemaSchemata = 17, + adSchemaSQLLanguages = 18, + adSchemaStatistics = 19, + adSchemaTables = 20, + adSchemaTranslations = 21, + adSchemaProviderTypes = 22, + adSchemaViews = 23, + adSchemaViewColumnUsage = 24, + adSchemaViewTableUsage = 25, + adSchemaProcedureParameters = 26, + adSchemaForeignKeys = 27, + adSchemaPrimaryKeys = 28, + adSchemaProcedureColumns = 29, + adSchemaDBInfoKeywords = 30, + adSchemaDBInfoLiterals = 31, + adSchemaCubes = 32, + adSchemaDimensions = 33, + adSchemaHierarchies = 34, + adSchemaLevels = 35, + adSchemaMeasures = 36, + adSchemaProperties = 37, + adSchemaMembers = 38 + + */ function &MetaTables() { - $arr= array(); + $arr = array(); $dbc = $this->_connectionID; - $adors=@$dbc->OpenSchema(20);//tables - if ($adors){ - $f = $adors->Fields(2);//table/view name - $t = $adors->Fields(3);//table type - while (!$adors->EOF){ - $tt=substr($t->value,0,6); - if ($tt!='SYSTEM' && $tt !='ACCESS') - $arr[]=$f->value; + $adors = @$dbc->OpenSchema(20); //tables + if ($adors) { + $f = $adors->Fields(2); //table/view name + $t = $adors->Fields(3); //table type + while (!$adors->EOF) { + $tt = substr($t->value, 0, 6); + if ($tt != 'SYSTEM' && $tt != 'ACCESS') + $arr[] = $f->value; //print $f->value . ' ' . $t->value.'<br>'; $adors->MoveNext(); } @@ -167,14 +168,14 @@ class ADODB_ado extends ADOConnection { function &MetaColumns($table) { $table = strtoupper($table); - $arr= array(); + $arr = array(); $dbc = $this->_connectionID; - $adors=@$dbc->OpenSchema(4);//tables + $adors = @$dbc->OpenSchema(4); //tables - if ($adors){ - $t = $adors->Fields(2);//table/view name - while (!$adors->EOF){ + if ($adors) { + $t = $adors->Fields(2); //table/view name + while (!$adors->EOF) { if (strtoupper($t->Value) == $table) { @@ -183,7 +184,7 @@ class ADODB_ado extends ADOConnection { $fld->name = $c->Value; $fld->type = 'CHAR'; // cannot discover type in ADO! $fld->max_length = -1; - $arr[strtoupper($fld->name)]=$fld; + $arr[strtoupper($fld->name)] = $fld; } $adors->MoveNext(); @@ -195,26 +196,26 @@ class ADODB_ado extends ADOConnection { } /* returns queryID or false */ - function &_query($sql,$inputarr=false) + function &_query($sql, $inputarr = false) { $dbc = $this->_connectionID; - // return rs + // return rs if ($inputarr) { if (!empty($this->charPage)) - $oCmd = new COM('ADODB.Command',null,$this->charPage); + $oCmd = new COM('ADODB.Command', null, $this->charPage); else $oCmd = new COM('ADODB.Command'); $oCmd->ActiveConnection = $dbc; $oCmd->CommandText = $sql; $oCmd->CommandType = 1; - foreach($inputarr as $val) { + foreach ($inputarr as $val) { // name, type, direction 1 = input, len, $this->adoParameterType = 130; - $p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val); + $p = $oCmd->CreateParameter('name', $this->adoParameterType, 1, strlen($val), $val); //print $p->Type.' '.$p->value; $oCmd->Parameters->Append($p); } @@ -225,7 +226,7 @@ class ADODB_ado extends ADOConnection { return $rs; } - $rs = @$dbc->Execute($sql,$this->_affectedRows, $this->_execute_option); + $rs = @$dbc->Execute($sql, $this->_affectedRows, $this->_execute_option); /* $rs = new COM('ADODB.Recordset'); if ($rs) { @@ -233,7 +234,7 @@ class ADODB_ado extends ADOConnection { } */ if ($dbc->Errors->Count > 0) return false; - if (! $rs) return false; + if (!$rs) return false; if ($rs->State == 0) return true; // 0 = adStateClosed means no records returned return $rs; @@ -245,16 +246,17 @@ class ADODB_ado extends ADOConnection { if (isset($this->_thisTransactions)) if (!$this->_thisTransactions) return false; - else { - $o = $this->_connectionID->Properties("Transaction DDL"); - $this->_thisTransactions = $o ? true : false; - if (!$o) return false; - } + else { + $o = $this->_connectionID->Properties("Transaction DDL"); + $this->_thisTransactions = $o ? true : false; + if (!$o) return false; + } @$this->_connectionID->BeginTrans(); $this->transCnt += 1; return true; } - function CommitTrans($ok=true) + + function CommitTrans($ok = true) { if (!$ok) return $this->RollbackTrans(); if ($this->transOff) return true; @@ -263,7 +265,9 @@ class ADODB_ado extends ADOConnection { if ($this->transCnt) @$this->transCnt -= 1; return true; } - function RollbackTrans() { + + function RollbackTrans() + { if ($this->transOff) return true; @$this->_connectionID->RollbackTrans(); if ($this->transCnt) @$this->transCnt -= 1; @@ -276,7 +280,7 @@ class ADODB_ado extends ADOConnection { { $errc = $this->_connectionID->Errors; if ($errc->Count == 0) return ''; - $err = $errc->Item($errc->Count-1); + $err = $errc->Item($errc->Count - 1); return $err->Description; } @@ -284,7 +288,7 @@ class ADODB_ado extends ADOConnection { { $errc = $this->_connectionID->Errors; if ($errc->Count == 0) return 0; - $err = $errc->Item($errc->Count-1); + $err = $errc->Item($errc->Count - 1); return $err->NativeError; } @@ -302,7 +306,8 @@ class ADODB_ado extends ADOConnection { Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordSet_ado extends ADORecordSet { +class ADORecordSet_ado extends ADORecordSet +{ var $bind = false; var $databaseType = "ado"; @@ -310,23 +315,24 @@ class ADORecordSet_ado extends ADORecordSet { var $_tarr = false; // caches the types var $_flds; // and field objects var $canSeek = true; - var $hideErrors = true; + var $hideErrors = true; - function ADORecordSet_ado($id,$mode=false) + function ADORecordSet_ado($id, $mode = false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } $this->fetchMode = $mode; - return $this->ADORecordSet($id,$mode); + return $this->ADORecordSet($id, $mode); } // returns the field object - function FetchField($fieldOffset = -1) { - $off=$fieldOffset+1; // offsets begin at 1 + function FetchField($fieldOffset = -1) + { + $off = $fieldOffset + 1; // offsets begin at 1 - $o= new ADOFieldObject(); + $o = new ADOFieldObject(); $rs = $this->_queryID; $f = $rs->Fields($fieldOffset); $o->name = $f->Name; @@ -345,13 +351,13 @@ class ADORecordSet_ado extends ADORecordSet { if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname]; if (!$this->bind) { $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { + for ($i = 0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } function _initrs() @@ -363,101 +369,101 @@ class ADORecordSet_ado extends ADORecordSet { $this->_numOfFields = $f->Count; } - // should only be used to move forward as we normally use forward-only cursors + // should only be used to move forward as we normally use forward-only cursors function _seek($row) { - $rs = $this->_queryID; + $rs = $this->_queryID; // absoluteposition doesn't work -- my maths is wrong ? // $rs->AbsolutePosition->$row-2; // return true; if ($this->_currentRow > $row) return false; - @$rs->Move((integer)$row - $this->_currentRow-1); //adBookmarkFirst + @$rs->Move((integer)$row - $this->_currentRow - 1); //adBookmarkFirst return true; } -/* - OLEDB types - - enum DBTYPEENUM - { DBTYPE_EMPTY = 0, - DBTYPE_NULL = 1, - DBTYPE_I2 = 2, - DBTYPE_I4 = 3, - DBTYPE_R4 = 4, - DBTYPE_R8 = 5, - DBTYPE_CY = 6, - DBTYPE_DATE = 7, - DBTYPE_BSTR = 8, - DBTYPE_IDISPATCH = 9, - DBTYPE_ERROR = 10, - DBTYPE_BOOL = 11, - DBTYPE_VARIANT = 12, - DBTYPE_IUNKNOWN = 13, - DBTYPE_DECIMAL = 14, - DBTYPE_UI1 = 17, - DBTYPE_ARRAY = 0x2000, - DBTYPE_BYREF = 0x4000, - DBTYPE_I1 = 16, - DBTYPE_UI2 = 18, - DBTYPE_UI4 = 19, - DBTYPE_I8 = 20, - DBTYPE_UI8 = 21, - DBTYPE_GUID = 72, - DBTYPE_VECTOR = 0x1000, - DBTYPE_RESERVED = 0x8000, - DBTYPE_BYTES = 128, - DBTYPE_STR = 129, - DBTYPE_WSTR = 130, - DBTYPE_NUMERIC = 131, - DBTYPE_UDT = 132, - DBTYPE_DBDATE = 133, - DBTYPE_DBTIME = 134, - DBTYPE_DBTIMESTAMP = 135 - - ADO Types - - adEmpty = 0, - adTinyInt = 16, - adSmallInt = 2, - adInteger = 3, - adBigInt = 20, - adUnsignedTinyInt = 17, - adUnsignedSmallInt = 18, - adUnsignedInt = 19, - adUnsignedBigInt = 21, - adSingle = 4, - adDouble = 5, - adCurrency = 6, - adDecimal = 14, - adNumeric = 131, - adBoolean = 11, - adError = 10, - adUserDefined = 132, - adVariant = 12, - adIDispatch = 9, - adIUnknown = 13, - adGUID = 72, - adDate = 7, - adDBDate = 133, - adDBTime = 134, - adDBTimeStamp = 135, - adBSTR = 8, - adChar = 129, - adVarChar = 200, - adLongVarChar = 201, - adWChar = 130, - adVarWChar = 202, - adLongVarWChar = 203, - adBinary = 128, - adVarBinary = 204, - adLongVarBinary = 205, - adChapter = 136, - adFileTime = 64, - adDBFileTime = 137, - adPropVariant = 138, - adVarNumeric = 139 -*/ - function MetaType($t,$len=-1,$fieldobj=false) + /* + OLEDB types + + enum DBTYPEENUM + { DBTYPE_EMPTY = 0, + DBTYPE_NULL = 1, + DBTYPE_I2 = 2, + DBTYPE_I4 = 3, + DBTYPE_R4 = 4, + DBTYPE_R8 = 5, + DBTYPE_CY = 6, + DBTYPE_DATE = 7, + DBTYPE_BSTR = 8, + DBTYPE_IDISPATCH = 9, + DBTYPE_ERROR = 10, + DBTYPE_BOOL = 11, + DBTYPE_VARIANT = 12, + DBTYPE_IUNKNOWN = 13, + DBTYPE_DECIMAL = 14, + DBTYPE_UI1 = 17, + DBTYPE_ARRAY = 0x2000, + DBTYPE_BYREF = 0x4000, + DBTYPE_I1 = 16, + DBTYPE_UI2 = 18, + DBTYPE_UI4 = 19, + DBTYPE_I8 = 20, + DBTYPE_UI8 = 21, + DBTYPE_GUID = 72, + DBTYPE_VECTOR = 0x1000, + DBTYPE_RESERVED = 0x8000, + DBTYPE_BYTES = 128, + DBTYPE_STR = 129, + DBTYPE_WSTR = 130, + DBTYPE_NUMERIC = 131, + DBTYPE_UDT = 132, + DBTYPE_DBDATE = 133, + DBTYPE_DBTIME = 134, + DBTYPE_DBTIMESTAMP = 135 + + ADO Types + + adEmpty = 0, + adTinyInt = 16, + adSmallInt = 2, + adInteger = 3, + adBigInt = 20, + adUnsignedTinyInt = 17, + adUnsignedSmallInt = 18, + adUnsignedInt = 19, + adUnsignedBigInt = 21, + adSingle = 4, + adDouble = 5, + adCurrency = 6, + adDecimal = 14, + adNumeric = 131, + adBoolean = 11, + adError = 10, + adUserDefined = 132, + adVariant = 12, + adIDispatch = 9, + adIUnknown = 13, + adGUID = 72, + adDate = 7, + adDBDate = 133, + adDBTime = 134, + adDBTimeStamp = 135, + adBSTR = 8, + adChar = 129, + adVarChar = 200, + adLongVarChar = 201, + adWChar = 130, + adVarWChar = 202, + adLongVarWChar = 203, + adBinary = 128, + adVarBinary = 204, + adLongVarBinary = 205, + adChapter = 136, + adFileTime = 64, + adDBFileTime = 137, + adPropVariant = 138, + adVarNumeric = 139 + */ + function MetaType($t, $len = -1, $fieldobj = false) { if (is_object($t)) { $fieldobj = $t; @@ -468,43 +474,47 @@ class ADORecordSet_ado extends ADORecordSet { if (!is_numeric($t)) return $t; switch ($t) { - case 0: - case 12: // variant - case 8: // bstr - case 129: //char - case 130: //wc - case 200: // varc - case 202:// varWC - case 128: // bin - case 204: // varBin - case 72: // guid - if ($len <= $this->blobSize) return 'C'; - - case 201: - case 203: - return 'X'; - case 128: - case 204: - case 205: - return 'B'; - case 7: - case 133: return 'D'; - - case 134: - case 135: return 'T'; - - case 11: return 'L'; - - case 16:// adTinyInt = 16, - case 2://adSmallInt = 2, - case 3://adInteger = 3, - case 4://adBigInt = 20, - case 17://adUnsignedTinyInt = 17, - case 18://adUnsignedSmallInt = 18, - case 19://adUnsignedInt = 19, - case 20://adUnsignedBigInt = 21, - return 'I'; - default: return 'N'; + case 0: + case 12: // variant + case 8: // bstr + case 129: //char + case 130: //wc + case 200: // varc + case 202: // varWC + case 128: // bin + case 204: // varBin + case 72: // guid + if ($len <= $this->blobSize) return 'C'; + + case 201: + case 203: + return 'X'; + case 128: + case 204: + case 205: + return 'B'; + case 7: + case 133: + return 'D'; + + case 134: + case 135: + return 'T'; + + case 11: + return 'L'; + + case 16: // adTinyInt = 16, + case 2: //adSmallInt = 2, + case 3: //adInteger = 3, + case 4: //adBigInt = 20, + case 17: //adUnsignedTinyInt = 17, + case 18: //adUnsignedSmallInt = 18, + case 19: //adUnsignedInt = 19, + case 20: //adUnsignedBigInt = 21, + return 'I'; + default: + return 'N'; } } @@ -521,7 +531,7 @@ class ADORecordSet_ado extends ADORecordSet { if (!$this->_tarr) { $tarr = array(); $flds = array(); - for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) { + for ($i = 0, $max = $this->_numOfFields; $i < $max; $i++) { $f = $rs->Fields($i); $flds[] = $f; $tarr[] = $f->Type; @@ -533,34 +543,34 @@ class ADORecordSet_ado extends ADORecordSet { $t = reset($this->_tarr); $f = reset($this->_flds); - if ($this->hideErrors) $olde = error_reporting(E_ERROR|E_CORE_ERROR);// sometimes $f->value be null - for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) { - - switch($t) { - case 135: // timestamp - if (!strlen((string)$f->value)) $this->fields[] = false; - else $this->fields[] = adodb_date('Y-m-d H:i:s',(float)$f->value); - break; - case 133:// A date value (yyyymmdd) - if ($val = $f->value) { - $this->fields[] = substr($val,0,4).'-'.substr($val,4,2).'-'.substr($val,6,2); - } else + if ($this->hideErrors) $olde = error_reporting(E_ERROR | E_CORE_ERROR); // sometimes $f->value be null + for ($i = 0, $max = $this->_numOfFields; $i < $max; $i++) { + + switch ($t) { + case 135: // timestamp + if (!strlen((string)$f->value)) $this->fields[] = false; + else $this->fields[] = adodb_date('Y-m-d H:i:s', (float)$f->value); + break; + case 133: // A date value (yyyymmdd) + if ($val = $f->value) { + $this->fields[] = substr($val, 0, 4) . '-' . substr($val, 4, 2) . '-' . substr($val, 6, 2); + } else + $this->fields[] = false; + break; + case 7: // adDate + if (!strlen((string)$f->value)) $this->fields[] = false; + else $this->fields[] = adodb_date('Y-m-d', (float)$f->value); + break; + case 1: // null $this->fields[] = false; - break; - case 7: // adDate - if (!strlen((string)$f->value)) $this->fields[] = false; - else $this->fields[] = adodb_date('Y-m-d',(float)$f->value); - break; - case 1: // null - $this->fields[] = false; - break; - case 6: // currency is not supported properly; - ADOConnection::outp( '<b>'.$f->Name.': currency type not supported by PHP</b>'); - $this->fields[] = (float) $f->value; - break; - default: - $this->fields[] = $f->value; - break; + break; + case 6: // currency is not supported properly; + ADOConnection::outp('<b>' . $f->Name . ': currency type not supported by PHP</b>'); + $this->fields[] = (float)$f->value; + break; + default: + $this->fields[] = $f->value; + break; } //print " $f->value $t, "; $f = next($this->_flds); @@ -575,28 +585,29 @@ class ADORecordSet_ado extends ADORecordSet { return true; } - function NextRecordSet() - { - $rs = $this->_queryID; - $this->_queryID = $rs->NextRecordSet(); - //$this->_queryID = $this->_QueryId->NextRecordSet(); - if ($this->_queryID == null) return false; - - $this->_currentRow = -1; - $this->_currentPage = -1; - $this->bind = false; - $this->fields = false; - $this->_flds = false; - $this->_tarr = false; + function NextRecordSet() + { + $rs = $this->_queryID; + $this->_queryID = $rs->NextRecordSet(); + //$this->_queryID = $this->_QueryId->NextRecordSet(); + if ($this->_queryID == null) return false; + + $this->_currentRow = -1; + $this->_currentPage = -1; + $this->bind = false; + $this->fields = false; + $this->_flds = false; + $this->_tarr = false; - $this->_inited = false; - $this->Init(); - return true; - } + $this->_inited = false; + $this->Init(); + return true; + } - function _close() { + function _close() + { $this->_flds = false; - @$this->_queryID->Close();// by Pete Dishman (peterd@telephonetics.co.uk) + @$this->_queryID->Close(); // by Pete Dishman (peterd@telephonetics.co.uk) $this->_queryID = false; } diff --git a/lib/WikiDB/adodb/drivers/adodb-ado_access.inc.php b/lib/WikiDB/adodb/drivers/adodb-ado_access.inc.php index 48438ae2b..6baffb702 100644 --- a/lib/WikiDB/adodb/drivers/adodb-ado_access.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-ado_access.inc.php @@ -12,14 +12,15 @@ Set tabs to 4 for best viewing. */ if (!defined('_ADODB_ADO_LAYER')) { - include(ADODB_DIR."/drivers/adodb-ado.inc.php"); + include(ADODB_DIR . "/drivers/adodb-ado.inc.php"); } -class ADODB_ado_access extends ADODB_ado { +class ADODB_ado_access extends ADODB_ado +{ var $databaseType = 'ado_access'; - var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE + var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE var $fmtDate = "#Y-m-d#"; - var $fmtTimeStamp = "#Y-m-d h:i:sA#";// note no comma + var $fmtTimeStamp = "#Y-m-d h:i:sA#"; // note no comma var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')"; var $sysTimeStamp = 'NOW'; var $hasTransactions = false; @@ -29,16 +30,20 @@ class ADODB_ado_access extends ADODB_ado { $this->ADODB_ado(); } - function BeginTrans() { return false;} + function BeginTrans() + { + return false; + } } -class ADORecordSet_ado_access extends ADORecordSet_ado { +class ADORecordSet_ado_access extends ADORecordSet_ado +{ var $databaseType = "ado_access"; - function ADORecordSet_ado_access($id,$mode=false) + function ADORecordSet_ado_access($id, $mode = false) { - return $this->ADORecordSet_ado($id,$mode); + return $this->ADORecordSet_ado($id, $mode); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-ado_mssql.inc.php b/lib/WikiDB/adodb/drivers/adodb-ado_mssql.inc.php index 2f942b925..cb46e932b 100644 --- a/lib/WikiDB/adodb/drivers/adodb-ado_mssql.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-ado_mssql.inc.php @@ -16,10 +16,11 @@ Set tabs to 4 for best viewing. */ if (!defined('_ADODB_ADO_LAYER')) { - include(ADODB_DIR."/drivers/adodb-ado.inc.php"); + include(ADODB_DIR . "/drivers/adodb-ado.inc.php"); } -class ADODB_ado_mssql extends ADODB_ado { +class ADODB_ado_mssql extends ADODB_ado +{ var $databaseType = 'ado_mssql'; var $hasTop = 'top'; var $sysDate = 'GetDate()'; @@ -50,12 +51,13 @@ class ADODB_ado_mssql extends ADODB_ado { } -class ADORecordSet_ado_mssql extends ADORecordSet_ado { +class ADORecordSet_ado_mssql extends ADORecordSet_ado +{ var $databaseType = 'ado_mssql'; - function ADORecordSet_ado_mssql($id,$mode=false) + function ADORecordSet_ado_mssql($id, $mode = false) { - return $this->ADORecordSet_ado($id,$mode); + return $this->ADORecordSet_ado($id, $mode); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-borland_ibase.inc.php b/lib/WikiDB/adodb/drivers/adodb-borland_ibase.inc.php index a953769b0..051102ace 100644 --- a/lib/WikiDB/adodb/drivers/adodb-borland_ibase.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-borland_ibase.inc.php @@ -12,9 +12,10 @@ Set tabs to 4 for best viewing. */ -include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php"); +include_once(ADODB_DIR . "/drivers/adodb-ibase.inc.php"); -class ADODB_borland_ibase extends ADODB_ibase { +class ADODB_borland_ibase extends ADODB_ibase +{ var $databaseType = "borland_ibase"; function ADODB_borland_ibase() @@ -25,12 +26,18 @@ class ADODB_borland_ibase extends ADODB_ibase { function ServerInfo() { $arr['dialect'] = $this->dialect; - switch($arr['dialect']) { - case '': - case '1': $s = 'Interbase 6.5, Dialect 1'; break; - case '2': $s = 'Interbase 6.5, Dialect 2'; break; - default: - case '3': $s = 'Interbase 6.5, Dialect 3'; break; + switch ($arr['dialect']) { + case '': + case '1': + $s = 'Interbase 6.5, Dialect 1'; + break; + case '2': + $s = 'Interbase 6.5, Dialect 2'; + break; + default: + case '3': + $s = 'Interbase 6.5, Dialect 3'; + break; } $arr['version'] = '6.5'; $arr['description'] = $s; @@ -42,13 +49,13 @@ class ADODB_borland_ibase extends ADODB_ibase { // SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2 // Firebird uses // SELECT FIRST 5 SKIP 2 col1, col2 FROM TABLE - function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) { if ($nrows > 0) { if ($offset <= 0) $str = " ROWS $nrows "; else { - $a = $offset+1; - $b = $offset+$nrows; + $a = $offset + 1; + $b = $offset + $nrows; $str = " ROWS $a TO $b"; } } else { @@ -59,19 +66,22 @@ class ADODB_borland_ibase extends ADODB_ibase { $sql .= $str; return ($secs2cache) ? - $this->CacheExecute($secs2cache,$sql,$inputarr) + $this->CacheExecute($secs2cache, $sql, $inputarr) : - $this->Execute($sql,$inputarr); + $this->Execute($sql, $inputarr); } -}; +} + +; -class ADORecordSet_borland_ibase extends ADORecordSet_ibase { +class ADORecordSet_borland_ibase extends ADORecordSet_ibase +{ var $databaseType = "borland_ibase"; - function ADORecordSet_borland_ibase($id,$mode=false) + function ADORecordSet_borland_ibase($id, $mode = false) { - $this->ADORecordSet_ibase($id,$mode); + $this->ADORecordSet_ibase($id, $mode); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-csv.inc.php b/lib/WikiDB/adodb/drivers/adodb-csv.inc.php index 036d10bbc..47da70cf4 100644 --- a/lib/WikiDB/adodb/drivers/adodb-csv.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-csv.inc.php @@ -11,185 +11,187 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese Transactions not supported yet. */ -if (! defined("_ADODB_CSV_LAYER")) { - define("_ADODB_CSV_LAYER", 1 ); - -include_once(ADODB_DIR.'/adodb-csvlib.inc.php'); - -class ADODB_csv extends ADOConnection { - var $databaseType = 'csv'; - var $databaseProvider = 'csv'; - var $hasInsertID = true; - var $hasAffectedRows = true; - var $fmtTimeStamp = "'Y-m-d H:i:s'"; - var $_affectedrows=0; - var $_insertid=0; - var $_url; - var $replaceQuote = "''"; // string to use to replace quotes - var $hasTransactions = false; - var $_errorNo = false; - - function ADODB_csv() - { - } - - function _insertid() - { - return $this->_insertid; - } +if (!defined("_ADODB_CSV_LAYER")) { + define("_ADODB_CSV_LAYER", 1); - function _affectedrows() - { - return $this->_affectedrows; - } - - function &MetaDatabases() - { - return false; - } + include_once(ADODB_DIR . '/adodb-csvlib.inc.php'); - // returns true or false - function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) + class ADODB_csv extends ADOConnection { - if (strtolower(substr($argHostname,0,7)) !== 'http://') return false; - $this->_url = $argHostname; - return true; - } + var $databaseType = 'csv'; + var $databaseProvider = 'csv'; + var $hasInsertID = true; + var $hasAffectedRows = true; + var $fmtTimeStamp = "'Y-m-d H:i:s'"; + var $_affectedrows = 0; + var $_insertid = 0; + var $_url; + var $replaceQuote = "''"; // string to use to replace quotes + var $hasTransactions = false; + var $_errorNo = false; + + function ADODB_csv() + { + } - // returns true or false - function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - if (strtolower(substr($argHostname,0,7)) !== 'http://') return false; - $this->_url = $argHostname; - return true; - } + function _insertid() + { + return $this->_insertid; + } - function &MetaColumns($table) - { - return false; - } + function _affectedrows() + { + return $this->_affectedrows; + } - // parameters use PostgreSQL convention, not MySQL - function &SelectLimit($sql,$nrows=-1,$offset=-1) - { - global $ADODB_FETCH_MODE; - - $url = $this->_url.'?sql='.urlencode($sql)."&nrows=$nrows&fetch=". - (($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE). - "&offset=$offset"; - $err = false; - $rs = csv2rs($url,$err,false); - - if ($this->debug) print "$url<br><i>$err</i><br>"; - - $at = strpos($err,'::::'); - if ($at === false) { - $this->_errorMsg = $err; - $this->_errorNo = (integer)$err; - } else { - $this->_errorMsg = substr($err,$at+4,1024); - $this->_errorNo = -9999; + function &MetaDatabases() + { + return false; } - if ($this->_errorNo) - if ($fn = $this->raiseErrorFn) { - $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,''); - } - if (is_object($rs)) { + // returns true or false + function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + if (strtolower(substr($argHostname, 0, 7)) !== 'http://') return false; + $this->_url = $argHostname; + return true; + } - $rs->databaseType='csv'; - $rs->fetchMode = ($this->fetchMode !== false) ? $this->fetchMode : $ADODB_FETCH_MODE; - $rs->connection = &$this; + // returns true or false + function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + if (strtolower(substr($argHostname, 0, 7)) !== 'http://') return false; + $this->_url = $argHostname; + return true; } - return $rs; - } - // returns queryID or false - function &_Execute($sql,$inputarr=false) - { - global $ADODB_FETCH_MODE; + function &MetaColumns($table) + { + return false; + } - if (!$this->_bindInputArray && $inputarr) { - $sqlarr = explode('?',$sql); - $sql = ''; - $i = 0; - foreach($inputarr as $v) { + // parameters use PostgreSQL convention, not MySQL + function &SelectLimit($sql, $nrows = -1, $offset = -1) + { + global $ADODB_FETCH_MODE; + + $url = $this->_url . '?sql=' . urlencode($sql) . "&nrows=$nrows&fetch=" . + (($this->fetchMode !== false) ? $this->fetchMode : $ADODB_FETCH_MODE) . + "&offset=$offset"; + $err = false; + $rs = csv2rs($url, $err, false); + + if ($this->debug) print "$url<br><i>$err</i><br>"; + + $at = strpos($err, '::::'); + if ($at === false) { + $this->_errorMsg = $err; + $this->_errorNo = (integer)$err; + } else { + $this->_errorMsg = substr($err, $at + 4, 1024); + $this->_errorNo = -9999; + } + if ($this->_errorNo) + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $sql, ''); + } - $sql .= $sqlarr[$i]; - if (gettype($v) == 'string') - $sql .= $this->qstr($v); - else if ($v === null) - $sql .= 'NULL'; - else - $sql .= $v; - $i += 1; + if (is_object($rs)) { + $rs->databaseType = 'csv'; + $rs->fetchMode = ($this->fetchMode !== false) ? $this->fetchMode : $ADODB_FETCH_MODE; + $rs->connection = &$this; } - $sql .= $sqlarr[$i]; - if ($i+1 != sizeof($sqlarr)) - print "Input Array does not match ?: ".htmlspecialchars($sql); - $inputarr = false; + return $rs; } - $url = $this->_url.'?sql='.urlencode($sql)."&fetch=". - (($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE); - $err = false; - - $rs = csv2rs($url,$err,false); - if ($this->debug) print urldecode($url)."<br><i>$err</i><br>"; - $at = strpos($err,'::::'); - if ($at === false) { - $this->_errorMsg = $err; - $this->_errorNo = (integer)$err; - } else { - $this->_errorMsg = substr($err,$at+4,1024); - $this->_errorNo = -9999; - } + // returns queryID or false + function &_Execute($sql, $inputarr = false) + { + global $ADODB_FETCH_MODE; + + if (!$this->_bindInputArray && $inputarr) { + $sqlarr = explode('?', $sql); + $sql = ''; + $i = 0; + foreach ($inputarr as $v) { + + $sql .= $sqlarr[$i]; + if (gettype($v) == 'string') + $sql .= $this->qstr($v); + else if ($v === null) + $sql .= 'NULL'; + else + $sql .= $v; + $i += 1; + + } + $sql .= $sqlarr[$i]; + if ($i + 1 != sizeof($sqlarr)) + print "Input Array does not match ?: " . htmlspecialchars($sql); + $inputarr = false; + } - if ($this->_errorNo) - if ($fn = $this->raiseErrorFn) { - $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr); + $url = $this->_url . '?sql=' . urlencode($sql) . "&fetch=" . + (($this->fetchMode !== false) ? $this->fetchMode : $ADODB_FETCH_MODE); + $err = false; + + $rs = csv2rs($url, $err, false); + if ($this->debug) print urldecode($url) . "<br><i>$err</i><br>"; + $at = strpos($err, '::::'); + if ($at === false) { + $this->_errorMsg = $err; + $this->_errorNo = (integer)$err; + } else { + $this->_errorMsg = substr($err, $at + 4, 1024); + $this->_errorNo = -9999; } - if (is_object($rs)) { - $rs->fetchMode = ($this->fetchMode !== false) ? $this->fetchMode : $ADODB_FETCH_MODE; - $this->_affectedrows = $rs->affectedrows; - $this->_insertid = $rs->insertid; - $rs->databaseType='csv'; - $rs->connection = &$this; + if ($this->_errorNo) + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $sql, $inputarr); + } + if (is_object($rs)) { + $rs->fetchMode = ($this->fetchMode !== false) ? $this->fetchMode : $ADODB_FETCH_MODE; + + $this->_affectedrows = $rs->affectedrows; + $this->_insertid = $rs->insertid; + $rs->databaseType = 'csv'; + $rs->connection = &$this; + } + return $rs; } - return $rs; - } - /* Returns: the last error message from previous database operation */ - function ErrorMsg() - { + /* Returns: the last error message from previous database operation */ + function ErrorMsg() + { return $this->_errorMsg; - } + } - /* Returns: the last error number from previous database operation */ - function ErrorNo() - { - return $this->_errorNo; - } + /* Returns: the last error number from previous database operation */ + function ErrorNo() + { + return $this->_errorNo; + } - // returns true or false - function _close() - { - return true; - } -} // class + // returns true or false + function _close() + { + return true; + } + } // class -class ADORecordset_csv extends ADORecordset { - function ADORecordset_csv($id,$mode=false) + class ADORecordset_csv extends ADORecordset { - $this->ADORecordset($id,$mode); - } + function ADORecordset_csv($id, $mode = false) + { + $this->ADORecordset($id, $mode); + } - function _close() - { - return true; + function _close() + { + return true; + } } -} } // define diff --git a/lib/WikiDB/adodb/drivers/adodb-db2.inc.php b/lib/WikiDB/adodb/drivers/adodb-db2.inc.php index 450194bae..69b3d59e1 100644 --- a/lib/WikiDB/adodb/drivers/adodb-db2.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-db2.inc.php @@ -80,227 +80,232 @@ Connect() when using the CLI interface. From Halmai Csongor csongor.halmai#nexum */ if (!defined('_ADODB_ODBC_LAYER')) { - include(ADODB_DIR."/drivers/adodb-odbc.inc.php"); + include(ADODB_DIR . "/drivers/adodb-odbc.inc.php"); } -if (!defined('ADODB_DB2')){ -define('ADODB_DB2',1); - -class ADODB_DB2 extends ADODB_odbc { - var $databaseType = "db2"; - var $concat_operator = '||'; - var $sysDate = 'CURRENT_DATE'; - var $sysTimeStamp = 'CURRENT TIMESTAMP'; - // The complete string representation of a timestamp has the form - // yyyy-mm-dd-hh.mm.ss.nnnnnn. - var $fmtTimeStamp = "'Y-m-d-H.i.s'"; - var $ansiOuter = true; - var $identitySQL = 'values IDENTITY_VAL_LOCAL()'; - var $_bindInputArray = false; - var $upperCase = 'upper'; - - function ADODB_DB2() - { - if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC; - $this->ADODB_odbc(); - } +if (!defined('ADODB_DB2')) { + define('ADODB_DB2', 1); - function IfNull( $field, $ifNull ) + class ADODB_DB2 extends ADODB_odbc { - return " COALESCE($field, $ifNull) "; // if DB2 UDB - } + var $databaseType = "db2"; + var $concat_operator = '||'; + var $sysDate = 'CURRENT_DATE'; + var $sysTimeStamp = 'CURRENT TIMESTAMP'; + // The complete string representation of a timestamp has the form + // yyyy-mm-dd-hh.mm.ss.nnnnnn. + var $fmtTimeStamp = "'Y-m-d-H.i.s'"; + var $ansiOuter = true; + var $identitySQL = 'values IDENTITY_VAL_LOCAL()'; + var $_bindInputArray = false; + var $upperCase = 'upper'; + + function ADODB_DB2() + { + if (strncmp(PHP_OS, 'WIN', 3) === 0) $this->curmode = SQL_CUR_USE_ODBC; + $this->ADODB_odbc(); + } - function ServerInfo() - { - //odbc_setoption($this->_connectionID,1,101 /*SQL_ATTR_ACCESS_MODE*/, 1 /*SQL_MODE_READ_ONLY*/); - $vers = $this->GetOne('select versionnumber from sysibm.sysversions'); - //odbc_setoption($this->_connectionID,1,101, 0 /*SQL_MODE_READ_WRITE*/); - return array('description'=>'DB2 ODBC driver', 'version'=>$vers); - } + function IfNull($field, $ifNull) + { + return " COALESCE($field, $ifNull) "; // if DB2 UDB + } - function _insertid() - { - return $this->GetOne($this->identitySQL); - } + function ServerInfo() + { + //odbc_setoption($this->_connectionID,1,101 /*SQL_ATTR_ACCESS_MODE*/, 1 /*SQL_MODE_READ_ONLY*/); + $vers = $this->GetOne('select versionnumber from sysibm.sysversions'); + //odbc_setoption($this->_connectionID,1,101, 0 /*SQL_MODE_READ_WRITE*/); + return array('description' => 'DB2 ODBC driver', 'version' => $vers); + } - function RowLock($tables,$where) - { - if ($this->_autocommit) $this->BeginTrans(); - return $this->GetOne("select 1 as ignore from $tables where $where for update"); - } + function _insertid() + { + return $this->GetOne($this->identitySQL); + } - function &MetaTables($ttype=false,$showSchema=false) - { - global $ADODB_FETCH_MODE; + function RowLock($tables, $where) + { + if ($this->_autocommit) $this->BeginTrans(); + return $this->GetOne("select 1 as ignore from $tables where $where for update"); + } - $savem = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - $qid = odbc_tables($this->_connectionID); + function &MetaTables($ttype = false, $showSchema = false) + { + global $ADODB_FETCH_MODE; - $rs = new ADORecordSet_odbc($qid); + $savem = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + $qid = odbc_tables($this->_connectionID); - $ADODB_FETCH_MODE = $savem; - if (!$rs) return false; + $rs = new ADORecordSet_odbc($qid); - $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change; + $ADODB_FETCH_MODE = $savem; + if (!$rs) return false; - $arr =& $rs->GetArray(); - //print_r($arr); + $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change; - $rs->Close(); - $arr2 = array(); + $arr =& $rs->GetArray(); + //print_r($arr); - if ($ttype) { - $isview = strncmp($ttype,'V',1) === 0; - } - for ($i=0; $i < sizeof($arr); $i++) { + $rs->Close(); + $arr2 = array(); - if (!$arr[$i][2]) continue; - if (strncmp($arr[$i][1],'SYS',3) === 0) continue; + if ($ttype) { + $isview = strncmp($ttype, 'V', 1) === 0; + } + for ($i = 0; $i < sizeof($arr); $i++) { - $type = $arr[$i][3]; + if (!$arr[$i][2]) continue; + if (strncmp($arr[$i][1], 'SYS', 3) === 0) continue; - if ($showSchema) $arr[$i][2] = $arr[$i][1].'.'.$arr[$i][2]; + $type = $arr[$i][3]; - if ($ttype) { - if ($isview) { - if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2]; - } elseif (strncmp($type,'T',1) === 0) $arr2[] = $arr[$i][2]; - } elseif (strncmp($type,'S',1) !== 0) $arr2[] = $arr[$i][2]; + if ($showSchema) $arr[$i][2] = $arr[$i][1] . '.' . $arr[$i][2]; + + if ($ttype) { + if ($isview) { + if (strncmp($type, 'V', 1) === 0) $arr2[] = $arr[$i][2]; + } elseif (strncmp($type, 'T', 1) === 0) $arr2[] = $arr[$i][2]; + } elseif (strncmp($type, 'S', 1) !== 0) $arr2[] = $arr[$i][2]; + } + return $arr2; } - return $arr2; - } - // Format date column in sql string given an input format that understands Y M D - function SQLDate($fmt, $col=false) - { - // use right() and replace() ? - if (!$col) $col = $this->sysDate; - $s = ''; - - $len = strlen($fmt); - for ($i=0; $i < $len; $i++) { - if ($s) $s .= '||'; - $ch = $fmt[$i]; - switch($ch) { - case 'Y': - case 'y': - $s .= "char(year($col))"; - break; - case 'M': - $s .= "substr(monthname($col),1,3)"; - break; - case 'm': - $s .= "right(digits(month($col)),2)"; - break; - case 'D': - case 'd': - $s .= "right(digits(day($col)),2)"; - break; - case 'H': - case 'h': - if ($col != $this->sysDate) $s .= "right(digits(hour($col)),2)"; - else $s .= "''"; - break; - case 'i': - case 'I': - if ($col != $this->sysDate) - $s .= "right(digits(minute($col)),2)"; - else $s .= "''"; - break; - case 'S': - case 's': - if ($col != $this->sysDate) - $s .= "right(digits(second($col)),2)"; - else $s .= "''"; - break; - default: - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); + // Format date column in sql string given an input format that understands Y M D + function SQLDate($fmt, $col = false) + { + // use right() and replace() ? + if (!$col) $col = $this->sysDate; + $s = ''; + + $len = strlen($fmt); + for ($i = 0; $i < $len; $i++) { + if ($s) $s .= '||'; + $ch = $fmt[$i]; + switch ($ch) { + case 'Y': + case 'y': + $s .= "char(year($col))"; + break; + case 'M': + $s .= "substr(monthname($col),1,3)"; + break; + case 'm': + $s .= "right(digits(month($col)),2)"; + break; + case 'D': + case 'd': + $s .= "right(digits(day($col)),2)"; + break; + case 'H': + case 'h': + if ($col != $this->sysDate) $s .= "right(digits(hour($col)),2)"; + else $s .= "''"; + break; + case 'i': + case 'I': + if ($col != $this->sysDate) + $s .= "right(digits(minute($col)),2)"; + else $s .= "''"; + break; + case 'S': + case 's': + if ($col != $this->sysDate) + $s .= "right(digits(second($col)),2)"; + else $s .= "''"; + break; + default: + if ($ch == '\\') { + $i++; + $ch = substr($fmt, $i, 1); + } + $s .= $this->qstr($ch); } - $s .= $this->qstr($ch); } + return $s; } - return $s; - } - function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputArr=false) - { - if ($offset <= 0) { - // could also use " OPTIMIZE FOR $nrows ROWS " - if ($nrows >= 0) $sql .= " FETCH FIRST $nrows ROWS ONLY "; - $rs =& $this->Execute($sql,$inputArr); - } else { - if ($offset > 0 && $nrows < 0); - else { - $nrows += $offset; - $sql .= " FETCH FIRST $nrows ROWS ONLY "; + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputArr = false) + { + if ($offset <= 0) { + // could also use " OPTIMIZE FOR $nrows ROWS " + if ($nrows >= 0) $sql .= " FETCH FIRST $nrows ROWS ONLY "; + $rs =& $this->Execute($sql, $inputArr); + } else { + if ($offset > 0 && $nrows < 0) ; + else { + $nrows += $offset; + $sql .= " FETCH FIRST $nrows ROWS ONLY "; + } + $rs =& ADOConnection::SelectLimit($sql, -1, $offset, $inputArr); } - $rs =& ADOConnection::SelectLimit($sql,-1,$offset,$inputArr); + + return $rs; } - return $rs; } -}; + ; -class ADORecordSet_db2 extends ADORecordSet_odbc { - - var $databaseType = "db2"; - - function ADORecordSet_db2($id,$mode=false) + class ADORecordSet_db2 extends ADORecordSet_odbc { - $this->ADORecordSet_odbc($id,$mode); - } - function MetaType($t,$len=-1,$fieldobj=false) - { - if (is_object($t)) { - $fieldobj = $t; - $t = $fieldobj->type; - $len = $fieldobj->max_length; - } + var $databaseType = "db2"; - switch (strtoupper($t)) { - case 'VARCHAR': - case 'CHAR': - case 'CHARACTER': - if ($len <= $this->blobSize) return 'C'; - - case 'LONGCHAR': - case 'TEXT': - case 'CLOB': - case 'DBCLOB': // double-byte - return 'X'; - - case 'BLOB': - case 'GRAPHIC': - case 'VARGRAPHIC': - return 'B'; - - case 'DATE': - return 'D'; - - case 'TIME': - case 'TIMESTAMP': - return 'T'; - - //case 'BOOLEAN': - //case 'BIT': - // return 'L'; - - //case 'COUNTER': - // return 'R'; + function ADORecordSet_db2($id, $mode = false) + { + $this->ADORecordSet_odbc($id, $mode); + } - case 'INT': - case 'INTEGER': - case 'BIGINT': - case 'SMALLINT': - return 'I'; + function MetaType($t, $len = -1, $fieldobj = false) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } - default: return 'N'; + switch (strtoupper($t)) { + case 'VARCHAR': + case 'CHAR': + case 'CHARACTER': + if ($len <= $this->blobSize) return 'C'; + + case 'LONGCHAR': + case 'TEXT': + case 'CLOB': + case 'DBCLOB': // double-byte + return 'X'; + + case 'BLOB': + case 'GRAPHIC': + case 'VARGRAPHIC': + return 'B'; + + case 'DATE': + return 'D'; + + case 'TIME': + case 'TIMESTAMP': + return 'T'; + + //case 'BOOLEAN': + //case 'BIT': + // return 'L'; + + //case 'COUNTER': + // return 'R'; + + case 'INT': + case 'INTEGER': + case 'BIGINT': + case 'SMALLINT': + return 'I'; + + default: + return 'N'; + } } } -} } //define diff --git a/lib/WikiDB/adodb/drivers/adodb-fbsql.inc.php b/lib/WikiDB/adodb/drivers/adodb-fbsql.inc.php index aa3e13a39..6b2c9020d 100644 --- a/lib/WikiDB/adodb/drivers/adodb-fbsql.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-fbsql.inc.php @@ -8,251 +8,262 @@ Set tabs to 8. */ -if (! defined("_ADODB_FBSQL_LAYER")) { - define("_ADODB_FBSQL_LAYER", 1 ); - -class ADODB_fbsql extends ADOConnection { - var $databaseType = 'fbsql'; - 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 = false; - - function ADODB_fbsql() - { - } +if (!defined("_ADODB_FBSQL_LAYER")) { + define("_ADODB_FBSQL_LAYER", 1); - function _insertid() + class ADODB_fbsql extends ADOConnection { + var $databaseType = 'fbsql'; + 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 = false; + + function ADODB_fbsql() + { + } + + function _insertid() + { return fbsql_insert_id($this->_connectionID); - } + } - function _affectedrows() - { + function _affectedrows() + { return fbsql_affected_rows($this->_connectionID); - } - - function &MetaDatabases() - { - $qid = fbsql_list_dbs($this->_connectionID); - $arr = array(); - $i = 0; - $max = fbsql_num_rows($qid); - while ($i < $max) { - $arr[] = fbsql_tablename($qid,$i); - $i += 1; } - return $arr; - } - - // returns concatenated string - function Concat() - { - $s = ""; - $arr = func_get_args(); - $first = true; - - $s = implode(',',$arr); - if (sizeof($arr) > 0) return "CONCAT($s)"; - else return ''; - } - - // returns true or false - function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - $this->_connectionID = fbsql_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) - { - $this->_connectionID = fbsql_pconnect($argHostname,$argUsername,$argPassword); - if ($this->_connectionID === false) return false; - if ($argDatabasename) return $this->SelectDB($argDatabasename); - return true; - } + function &MetaDatabases() + { + $qid = fbsql_list_dbs($this->_connectionID); + $arr = array(); + $i = 0; + $max = fbsql_num_rows($qid); + while ($i < $max) { + $arr[] = fbsql_tablename($qid, $i); + $i += 1; + } + return $arr; + } - function &MetaColumns($table) - { - if ($this->metaColumnsSQL) { + // returns concatenated string + function Concat() + { + $s = ""; + $arr = func_get_args(); + $first = true; - $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); + $s = implode(',', $arr); + if (sizeof($arr) > 0) return "CONCAT($s)"; + else return ''; + } - if ($rs === false) return false; + // returns true or false + function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + $this->_connectionID = fbsql_connect($argHostname, $argUsername, $argPassword); + if ($this->_connectionID === false) return false; + if ($argDatabasename) return $this->SelectDB($argDatabasename); + return true; + } - $retarr = array(); - while (!$rs->EOF){ - $fld = new ADOFieldObject(); - $fld->name = $rs->fields[0]; - $fld->type = $rs->fields[1]; + // returns true or false + function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + $this->_connectionID = fbsql_pconnect($argHostname, $argUsername, $argPassword); + if ($this->_connectionID === false) return false; + if ($argDatabasename) return $this->SelectDB($argDatabasename); + return true; + } - // split type into type(length): - if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) { - $fld->type = $query_array[1]; - $fld->max_length = $query_array[2]; - } else { - $fld->max_length = -1; + function &MetaColumns($table) + { + if ($this->metaColumnsSQL) { + + $rs = $this->Execute(sprintf($this->metaColumnsSQL, $table)); + + if ($rs === false) return false; + + $retarr = array(); + while (!$rs->EOF) { + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $fld->type = $rs->fields[1]; + + // split type into type(length): + if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = $query_array[2]; + } else { + $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($fld->type, 'blob') !== false); + + $retarr[strtoupper($fld->name)] = $fld; + $rs->MoveNext(); } - $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($fld->type,'blob') !== false); - - $retarr[strtoupper($fld->name)] = $fld; - $rs->MoveNext(); + $rs->Close(); + return $retarr; } - $rs->Close(); - return $retarr; + return false; } - return false; - } - // returns true or false - function SelectDB($dbName) - { - $this->databaseName = $dbName; - if ($this->_connectionID) { - return @fbsql_select_db($dbName,$this->_connectionID); + // returns true or false + function SelectDB($dbName) + { + $this->databaseName = $dbName; + if ($this->_connectionID) { + return @fbsql_select_db($dbName, $this->_connectionID); + } else return false; } - else return false; - } - // returns queryID or false - function _query($sql,$inputarr) - { - return fbsql_query("$sql;",$this->_connectionID); - } + // returns queryID or false + function _query($sql, $inputarr) + { + return fbsql_query("$sql;", $this->_connectionID); + } - /* Returns: the last error message from previous database operation */ - function ErrorMsg() - { - $this->_errorMsg = @fbsql_error($this->_connectionID); + /* Returns: the last error message from previous database operation */ + function ErrorMsg() + { + $this->_errorMsg = @fbsql_error($this->_connectionID); return $this->_errorMsg; - } - - /* Returns: the last error number from previous database operation */ - function ErrorNo() - { - return @fbsql_errno($this->_connectionID); - } - - // returns true or false - function _close() - { - return @fbsql_close($this->_connectionID); - } + } -} + /* Returns: the last error number from previous database operation */ + function ErrorNo() + { + return @fbsql_errno($this->_connectionID); + } -/*-------------------------------------------------------------------------------------- - Class Name: Recordset ---------------------------------------------------------------------------------------*/ + // returns true or false + function _close() + { + return @fbsql_close($this->_connectionID); + } -class ADORecordSet_fbsql extends ADORecordSet{ + } - var $databaseType = "fbsql"; - var $canSeek = true; + /*-------------------------------------------------------------------------------------- + Class Name: Recordset + --------------------------------------------------------------------------------------*/ - function ADORecordSet_fbsql($queryID,$mode=false) + class ADORecordSet_fbsql extends ADORecordSet { - if (!$mode) { - global $ADODB_FETCH_MODE; - $mode = $ADODB_FETCH_MODE; - } - switch ($mode) { - case ADODB_FETCH_NUM: $this->fetchMode = FBSQL_NUM; break; - default: - case ADODB_FETCH_BOTH: $this->fetchMode = FBSQL_BOTH; break; - case ADODB_FETCH_ASSOC: $this->fetchMode = FBSQL_ASSOC; break; - } - return $this->ADORecordSet($queryID); - } - function _initrs() - { - GLOBAL $ADODB_COUNTRECS; - $this->_numOfRows = ($ADODB_COUNTRECS) ? @fbsql_num_rows($this->_queryID):-1; - $this->_numOfFields = @fbsql_num_fields($this->_queryID); - } + var $databaseType = "fbsql"; + var $canSeek = true; - function &FetchField($fieldOffset = -1) { - if ($fieldOffset != -1) { - $o = @fbsql_fetch_field($this->_queryID, $fieldOffset); - //$o->max_length = -1; // fbsql returns the max length less spaces -- so it is unrealiable - $f = @fbsql_field_flags($this->_queryID,$fieldOffset); - $o->binary = (strpos($f,'binary')!== false); + function ADORecordSet_fbsql($queryID, $mode = false) + { + if (!$mode) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } + switch ($mode) { + case ADODB_FETCH_NUM: + $this->fetchMode = FBSQL_NUM; + break; + default: + case ADODB_FETCH_BOTH: + $this->fetchMode = FBSQL_BOTH; + break; + case ADODB_FETCH_ASSOC: + $this->fetchMode = FBSQL_ASSOC; + break; + } + return $this->ADORecordSet($queryID); } - else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ - $o = @fbsql_fetch_field($this->_queryID);// fbsql returns the max length less spaces -- so it is unrealiable - //$o->max_length = -1; + + function _initrs() + { + GLOBAL $ADODB_COUNTRECS; + $this->_numOfRows = ($ADODB_COUNTRECS) ? @fbsql_num_rows($this->_queryID) : -1; + $this->_numOfFields = @fbsql_num_fields($this->_queryID); } - return $o; - } + function &FetchField($fieldOffset = -1) + { + if ($fieldOffset != -1) { + $o = @fbsql_fetch_field($this->_queryID, $fieldOffset); + //$o->max_length = -1; // fbsql returns the max length less spaces -- so it is unrealiable + $f = @fbsql_field_flags($this->_queryID, $fieldOffset); + $o->binary = (strpos($f, 'binary') !== false); + } else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ + $o = @fbsql_fetch_field($this->_queryID); // fbsql returns the max length less spaces -- so it is unrealiable + //$o->max_length = -1; + } - function _seek($row) - { - return @fbsql_data_seek($this->_queryID,$row); - } + return $o; + } - function _fetch($ignore_fields=false) - { - $this->fields = @fbsql_fetch_array($this->_queryID,$this->fetchMode); - return ($this->fields == true); - } + function _seek($row) + { + return @fbsql_data_seek($this->_queryID, $row); + } - function _close() { - return @fbsql_free_result($this->_queryID); - } + function _fetch($ignore_fields = false) + { + $this->fields = @fbsql_fetch_array($this->_queryID, $this->fetchMode); + return ($this->fields == true); + } - function MetaType($t,$len=-1,$fieldobj=false) - { - if (is_object($t)) { - $fieldobj = $t; - $t = $fieldobj->type; - $len = $fieldobj->max_length; + function _close() + { + return @fbsql_free_result($this->_queryID); } - $len = -1; // fbsql max_length is not accurate - switch (strtoupper($t)) { - case 'CHARACTER': - case 'CHARACTER VARYING': - case 'BLOB': - case 'CLOB': - case 'BIT': - case 'BIT VARYING': - if ($len <= $this->blobSize) return 'C'; - - // so we have to check whether binary... - case 'IMAGE': - case 'LONGBLOB': - case 'BLOB': - case 'MEDIUMBLOB': - return !empty($fieldobj->binary) ? 'B' : 'X'; - - case 'DATE': return 'D'; - - case 'TIME': - case 'TIME WITH TIME ZONE': - case 'TIMESTAMP': - case 'TIMESTAMP WITH TIME ZONE': return 'T'; - - case 'PRIMARY_KEY': - return 'R'; - case 'INTEGER': - case 'SMALLINT': - case 'BOOLEAN': - - if (!empty($fieldobj->primary_key)) return 'R'; - else return 'I'; - - default: return 'N'; + + function MetaType($t, $len = -1, $fieldobj = false) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } + $len = -1; // fbsql max_length is not accurate + switch (strtoupper($t)) { + case 'CHARACTER': + case 'CHARACTER VARYING': + case 'BLOB': + case 'CLOB': + case 'BIT': + case 'BIT VARYING': + if ($len <= $this->blobSize) return 'C'; + + // so we have to check whether binary... + case 'IMAGE': + case 'LONGBLOB': + case 'BLOB': + case 'MEDIUMBLOB': + return !empty($fieldobj->binary) ? 'B' : 'X'; + + case 'DATE': + return 'D'; + + case 'TIME': + case 'TIME WITH TIME ZONE': + case 'TIMESTAMP': + case 'TIMESTAMP WITH TIME ZONE': + return 'T'; + + case 'PRIMARY_KEY': + return 'R'; + case 'INTEGER': + case 'SMALLINT': + case 'BOOLEAN': + + if (!empty($fieldobj->primary_key)) return 'R'; + else return 'I'; + + default: + return 'N'; + } } - } -} //class + } //class } // defined diff --git a/lib/WikiDB/adodb/drivers/adodb-firebird.inc.php b/lib/WikiDB/adodb/drivers/adodb-firebird.inc.php index b68a2d984..9df234729 100644 --- a/lib/WikiDB/adodb/drivers/adodb-firebird.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-firebird.inc.php @@ -10,10 +10,12 @@ Set tabs to 4 for best viewing. */ -include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php"); +include_once(ADODB_DIR . "/drivers/adodb-ibase.inc.php"); -class ADODB_firebird extends ADODB_ibase { +class ADODB_firebird extends ADODB_ibase +{ var $databaseType = "firebird"; + function ADODB_firebird() { $this->ADODB_ibase(); @@ -22,12 +24,18 @@ class ADODB_firebird extends ADODB_ibase { function ServerInfo() { $arr['dialect'] = $this->dialect; - switch($arr['dialect']) { - case '': - case '1': $s = 'Firebird Dialect 1'; break; - case '2': $s = 'Firebird Dialect 2'; break; - default: - case '3': $s = 'Firebird Dialect 3'; break; + switch ($arr['dialect']) { + case '': + case '1': + $s = 'Firebird Dialect 1'; + break; + case '2': + $s = 'Firebird Dialect 2'; + break; + default: + case '3': + $s = 'Firebird Dialect 3'; + break; } $arr['version'] = ADOConnection::_findvers($s); $arr['description'] = $s; @@ -37,29 +45,32 @@ class ADODB_firebird extends ADODB_ibase { // Note that Interbase 6.5 uses this ROWS instead - don't you love forking wars! // SELECT col1, col2 FROM table ROWS 5 -- get 5 rows // SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2 - function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $secs=0) + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs = 0) { $str = 'SELECT '; if ($nrows >= 0) $str .= "FIRST $nrows "; - $str .=($offset>=0) ? "SKIP $offset " : ''; + $str .= ($offset >= 0) ? "SKIP $offset " : ''; - $sql = preg_replace('/^[ \t]*select/i',$str,$sql); + $sql = preg_replace('/^[ \t]*select/i', $str, $sql); if ($secs) - $rs =& $this->CacheExecute($secs,$sql,$inputarr); + $rs =& $this->CacheExecute($secs, $sql, $inputarr); else - $rs =& $this->Execute($sql,$inputarr); + $rs =& $this->Execute($sql, $inputarr); return $rs; } -}; +} + +; -class ADORecordSet_firebird extends ADORecordSet_ibase { +class ADORecordSet_firebird extends ADORecordSet_ibase +{ var $databaseType = "firebird"; - function ADORecordSet_firebird($id,$mode=false) + function ADORecordSet_firebird($id, $mode = false) { - $this->ADORecordSet_ibase($id,$mode); + $this->ADORecordSet_ibase($id, $mode); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-ibase.inc.php b/lib/WikiDB/adodb/drivers/adodb-ibase.inc.php index 44ecdfba0..49741a760 100644 --- a/lib/WikiDB/adodb/drivers/adodb-ibase.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-ibase.inc.php @@ -23,14 +23,15 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese $conn->Execute("insert into table (id, col1,...) values ($id, $val1,...)"); */ -class ADODB_ibase extends ADOConnection { +class ADODB_ibase extends ADOConnection +{ var $databaseType = "ibase"; var $dataProvider = "ibase"; var $replaceQuote = "''"; // string to use to replace quotes var $ibase_timefmt = '%Y-%m-%d'; // For hours,mins,secs change to '%Y-%m-%d %H:%M:%S'; var $fmtDate = "'Y-m-d'"; var $fmtTimeStamp = "'Y-m-d, H:i:s'"; - var $concat_operator='||'; + var $concat_operator = '||'; var $_transactionID; var $metaTablesSQL = "select rdb\$relation_name from rdb\$relations where rdb\$relation_name not like 'RDB\$%'"; //OPN STUFF start @@ -50,10 +51,10 @@ class ADODB_ibase extends ADOConnection { function ADODB_ibase() { - if (defined('IBASE_DEFAULT')) $this->ibasetrans = IBASE_DEFAULT; - } + if (defined('IBASE_DEFAULT')) $this->ibasetrans = IBASE_DEFAULT; + } - function MetaPrimaryKeys($table,$owner_notused=false,$internalKey=false) + function MetaPrimaryKeys($table, $owner_notused = false, $internalKey = false) { if ($internalKey) return array('RDB$DB_KEY'); @@ -61,23 +62,29 @@ class ADODB_ibase extends ADOConnection { $sql = 'SELECT S.RDB$FIELD_NAME AFIELDNAME FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME=S.RDB$INDEX_NAME - WHERE I.RDB$RELATION_NAME=\''.$table.'\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\' + WHERE I.RDB$RELATION_NAME=\'' . $table . '\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\' ORDER BY I.RDB$INDEX_NAME,S.RDB$FIELD_POSITION'; - $a = $this->GetCol($sql,false,true); - if ($a && sizeof($a)>0) return $a; + $a = $this->GetCol($sql, false, true); + if ($a && sizeof($a) > 0) return $a; return false; } function ServerInfo() { $arr['dialect'] = $this->dialect; - switch($arr['dialect']) { - case '': - case '1': $s = 'Interbase 5.5 or earlier'; break; - case '2': $s = 'Interbase 5.6'; break; - default: - case '3': $s = 'Interbase 6.0'; break; + switch ($arr['dialect']) { + case '': + case '1': + $s = 'Interbase 5.5 or earlier'; + break; + case '2': + $s = 'Interbase 5.6'; + break; + default: + case '3': + $s = 'Interbase 6.0'; + break; } $arr['version'] = ADOConnection::_findvers($s); $arr['description'] = $s; @@ -89,11 +96,11 @@ class ADODB_ibase extends ADOConnection { if ($this->transOff) return true; $this->transCnt += 1; $this->autoCommit = false; - $this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID); + $this->_transactionID = $this->_connectionID; //ibase_trans($this->ibasetrans, $this->_connectionID); return $this->_transactionID; } - function CommitTrans($ok=true) + function CommitTrans($ok = true) { if (!$ok) return $this->RollbackTrans(); if ($this->transOff) return true; @@ -101,7 +108,7 @@ class ADODB_ibase extends ADOConnection { $ret = false; $this->autoCommit = true; if ($this->_transactionID) { - //print ' commit '; + //print ' commit '; $ret = ibase_commit($this->_transactionID); } $this->_transactionID = false; @@ -115,13 +122,13 @@ class ADODB_ibase extends ADOConnection { $ret = false; $this->autoCommit = true; if ($this->_transactionID) - $ret = ibase_rollback($this->_transactionID); + $ret = ibase_rollback($this->_transactionID); $this->_transactionID = false; return $ret; } - function &MetaIndexes ($table, $primary = FALSE, $owner=false) + function &MetaIndexes($table, $primary = FALSE, $owner = false) { // save old fetch mode global $ADODB_FETCH_MODE; @@ -129,10 +136,10 @@ class ADODB_ibase extends ADOConnection { $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; if ($this->fetchMode !== FALSE) { - $savem = $this->SetFetchMode(FALSE); + $savem = $this->SetFetchMode(FALSE); } $table = strtoupper($table); - $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'"; + $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '" . $table . "'"; if (!$primary) { $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'"; } else { @@ -149,20 +156,22 @@ class ADODB_ibase extends ADOConnection { return FALSE; } - $indexes = array (); + $indexes = array(); while ($row = $rs->FetchRow()) { $index = $row[0]; - if (!isset($indexes[$index])) { - if (is_null($row[3])) {$row[3] = 0;} - $indexes[$index] = array( - 'unique' => ($row[3] == 1), - 'columns' => array() - ); - } - $sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '".$name."' ORDER BY RDB\$FIELD_POSITION ASC"; + if (!isset($indexes[$index])) { + if (is_null($row[3])) { + $row[3] = 0; + } + $indexes[$index] = array( + 'unique' => ($row[3] == 1), + 'columns' => array() + ); + } + $sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '" . $name . "' ORDER BY RDB\$FIELD_POSITION ASC"; $rs1 = $this->Execute($sql); while ($row1 = $rs1->FetchRow()) { - $indexes[$index]['columns'][$row1[2]] = $row1[1]; + $indexes[$index]['columns'][$row1[2]] = $row1[1]; } } // restore fetchmode @@ -175,18 +184,18 @@ class ADODB_ibase extends ADOConnection { } // See http://community.borland.com/article/0,1410,25844,00.html - function RowLock($tables,$where,$col) + function RowLock($tables, $where, $col) { if ($this->autoCommit) $this->BeginTrans(); $this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim? return 1; } - function CreateSequence($seqname,$startID=1) + function CreateSequence($seqname, $startID = 1) { - $ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" )); + $ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))")); if (!$ok) return false; - return $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';'); + return $this->Execute("SET GENERATOR $seqname TO " . ($startID - 1) . ';'); } function DropSequence($seqname) @@ -195,16 +204,16 @@ class ADODB_ibase extends ADOConnection { $this->Execute("delete from RDB\$GENERATORS where RDB\$GENERATOR_NAME='$seqname'"); } - function GenID($seqname='adodbseq',$startID=1) + function GenID($seqname = 'adodbseq', $startID = 1) { $getnext = ("SELECT Gen_ID($seqname,1) FROM RDB\$DATABASE"); $rs = @$this->Execute($getnext); if (!$rs) { - $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" )); - $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';'); + $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))")); + $this->Execute("SET GENERATOR $seqname TO " . ($startID - 1) . ';'); $rs = $this->Execute($getnext); } - if ($rs && !$rs->EOF) $this->genID = (integer) reset($rs->fields); + if ($rs && !$rs->EOF) $this->genID = (integer)reset($rs->fields); else $this->genID = 0; // false if ($rs) $rs->Close(); @@ -214,7 +223,7 @@ class ADODB_ibase extends ADOConnection { function SelectDB($dbName) { - return false; + return false; } function _handleerror() @@ -224,22 +233,22 @@ class ADODB_ibase extends ADOConnection { function ErrorNo() { - if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg,$arr)) return (integer) $arr[1]; + if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg, $arr)) return (integer)$arr[1]; else return 0; } function ErrorMsg() { - return $this->_errorMsg; + return $this->_errorMsg; } - // returns true or false + // returns true or false function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('ibase_pconnect')) return false; - if ($argDatabasename) $argHostname .= ':'.$argDatabasename; - $this->_connectionID = ibase_connect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect); - if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html + if ($argDatabasename) $argHostname .= ':' . $argDatabasename; + $this->_connectionID = ibase_connect($argHostname, $argUsername, $argPassword, $this->charSet, $this->buffers, $this->dialect); + if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html $this->replaceQuote = "''"; } if ($this->_connectionID === false) { @@ -250,12 +259,13 @@ class ADODB_ibase extends ADOConnection { ibase_timefmt($this->ibase_timefmt); return true; } - // returns true or false + + // returns true or false function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('ibase_pconnect')) return false; - if ($argDatabasename) $argHostname .= ':'.$argDatabasename; - $this->_connectionID = ibase_pconnect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect); + if ($argDatabasename) $argHostname .= ':' . $argDatabasename; + $this->_connectionID = ibase_pconnect($argHostname, $argUsername, $argPassword, $this->charSet, $this->buffers, $this->dialect); if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html $this->replaceQuote = "''"; } @@ -270,14 +280,14 @@ class ADODB_ibase extends ADOConnection { function Prepare($sql) { - $stmt = ibase_prepare($this->_connectionID,$sql); + $stmt = ibase_prepare($this->_connectionID, $sql); if (!$stmt) return false; - return array($sql,$stmt); + return array($sql, $stmt); } - // returns query ID if successful, otherwise false - // there have been reports of problems with nested queries - the code is probably not re-entrant? - function _query($sql,$iarr=false) + // returns query ID if successful, otherwise false + // there have been reports of problems with nested queries - the code is probably not re-entrant? + function _query($sql, $iarr = false) { if (!$this->autoCommit && $this->_transactionID) { @@ -292,21 +302,38 @@ class ADODB_ibase extends ADOConnection { $sql = $sql[1]; if (is_array($iarr)) { - if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4 - if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack - $fnarr =& array_merge( array($sql) , $iarr); - $ret = call_user_func_array($fn,$fnarr); + if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4 + if (!isset($iarr[0])) $iarr[0] = ''; // PHP5 compat hack + $fnarr =& array_merge(array($sql), $iarr); + $ret = call_user_func_array($fn, $fnarr); } else { - switch(sizeof($iarr)) { - case 1: $ret = $fn($sql,$iarr[0]); break; - case 2: $ret = $fn($sql,$iarr[0],$iarr[1]); break; - case 3: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2]); break; - case 4: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break; - case 5: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break; - case 6: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break; - case 7: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break; - default: ADOConnection::outp( "Too many parameters to ibase query $sql"); - case 8: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break; + switch (sizeof($iarr)) { + case 1: + $ret = $fn($sql, $iarr[0]); + break; + case 2: + $ret = $fn($sql, $iarr[0], $iarr[1]); + break; + case 3: + $ret = $fn($sql, $iarr[0], $iarr[1], $iarr[2]); + break; + case 4: + $ret = $fn($sql, $iarr[0], $iarr[1], $iarr[2], $iarr[3]); + break; + case 5: + $ret = $fn($sql, $iarr[0], $iarr[1], $iarr[2], $iarr[3], $iarr[4]); + break; + case 6: + $ret = $fn($sql, $iarr[0], $iarr[1], $iarr[2], $iarr[3], $iarr[4], $iarr[5]); + break; + case 7: + $ret = $fn($sql, $iarr[0], $iarr[1], $iarr[2], $iarr[3], $iarr[4], $iarr[5], $iarr[6]); + break; + default: + ADOConnection::outp("Too many parameters to ibase query $sql"); + case 8: + $ret = $fn($sql, $iarr[0], $iarr[1], $iarr[2], $iarr[3], $iarr[4], $iarr[5], $iarr[6], $iarr[7]); + break; } } } else $ret = $fn($sql); @@ -315,23 +342,40 @@ class ADODB_ibase extends ADOConnection { if (is_array($iarr)) { if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4 - if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack - $fnarr =& array_merge( array($conn,$sql) , $iarr); - $ret = call_user_func_array($fn,$fnarr); + if (!isset($iarr[0])) $iarr[0] = ''; // PHP5 compat hack + $fnarr =& array_merge(array($conn, $sql), $iarr); + $ret = call_user_func_array($fn, $fnarr); } else { - switch(sizeof($iarr)) { - case 1: $ret = $fn($conn,$sql,$iarr[0]); break; - case 2: $ret = $fn($conn,$sql,$iarr[0],$iarr[1]); break; - case 3: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2]); break; - case 4: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break; - case 5: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break; - case 6: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break; - case 7: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break; - default: ADOConnection::outp( "Too many parameters to ibase query $sql"); - case 8: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break; + switch (sizeof($iarr)) { + case 1: + $ret = $fn($conn, $sql, $iarr[0]); + break; + case 2: + $ret = $fn($conn, $sql, $iarr[0], $iarr[1]); + break; + case 3: + $ret = $fn($conn, $sql, $iarr[0], $iarr[1], $iarr[2]); + break; + case 4: + $ret = $fn($conn, $sql, $iarr[0], $iarr[1], $iarr[2], $iarr[3]); + break; + case 5: + $ret = $fn($conn, $sql, $iarr[0], $iarr[1], $iarr[2], $iarr[3], $iarr[4]); + break; + case 6: + $ret = $fn($conn, $sql, $iarr[0], $iarr[1], $iarr[2], $iarr[3], $iarr[4], $iarr[5]); + break; + case 7: + $ret = $fn($conn, $sql, $iarr[0], $iarr[1], $iarr[2], $iarr[3], $iarr[4], $iarr[5], $iarr[6]); + break; + default: + ADOConnection::outp("Too many parameters to ibase query $sql"); + case 8: + $ret = $fn($conn, $sql, $iarr[0], $iarr[1], $iarr[2], $iarr[3], $iarr[4], $iarr[5], $iarr[6], $iarr[7]); + break; } } - } else $ret = $fn($conn,$sql); + } else $ret = $fn($conn, $sql); } if ($docommit && $ret === true) ibase_commit($this->_connectionID); @@ -339,12 +383,12 @@ class ADODB_ibase extends ADOConnection { return $ret; } - // returns true or false - function _close() - { + // returns true or false + function _close() + { if (!$this->autoCommit) @ibase_rollback($this->_connectionID); return @ibase_close($this->_connectionID); - } + } //OPN STUFF start function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $isInterbase6) @@ -352,11 +396,11 @@ class ADODB_ibase extends ADOConnection { $fscale = abs($fscale); $fld->max_length = $flen; $fld->scale = null; - switch($ftype){ + switch ($ftype) { case 7: case 8: if ($isInterbase6) { - switch($fsubtype){ + switch ($fsubtype) { case 0: $fld->type = ($ftype == 7 ? 'smallint' : 'integer'); break; @@ -372,7 +416,7 @@ class ADODB_ibase extends ADOConnection { break; } // switch } else { - if ($fscale !=0) { + if ($fscale != 0) { $fld->type = 'decimal'; $fld->scale = $fscale; $fld->max_length = ($ftype == 7 ? 4 : 9); @@ -383,7 +427,7 @@ class ADODB_ibase extends ADOConnection { break; case 16: if ($isInterbase6) { - switch($fsubtype){ + switch ($fsubtype) { case 0: $fld->type = 'decimal'; $fld->max_length = 18; @@ -409,7 +453,7 @@ class ADODB_ibase extends ADOConnection { $fld->type = 'char'; break; case 27: - if ($fscale !=0) { + if ($fscale != 0) { $fld->type = 'decimal'; $fld->max_length = 15; $fld->scale = 5; @@ -440,25 +484,26 @@ class ADODB_ibase extends ADOConnection { break; } // switch } + //OPN STUFF end - // returns array of ADOFieldObjects for current table + // returns array of ADOFieldObjects for current table function &MetaColumns($table) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; if ($this->metaColumnsSQL) { $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table))); + $rs = $this->Execute(sprintf($this->metaColumnsSQL, strtoupper($table))); $ADODB_FETCH_MODE = $save; if ($rs === false) return false; $retarr = array(); //OPN STUFF start - $isInterbase6 = ($this->dialect==3 ? true : false); + $isInterbase6 = ($this->dialect == 3 ? true : false); //OPN STUFF end while (!$rs->EOF) { //print_r($rs->fields); $fld = new ADOFieldObject(); @@ -471,20 +516,27 @@ class ADODB_ibase extends ADOConnection { if (isset($rs->fields[2])) { $fld->has_default = true; - $d = substr($rs->fields[2],strlen('default ')); - switch ($fld->type) - { - case 'smallint': - case 'integer': $fld->default_value = (int) $d; break; - case 'char': - case 'blob': - case 'text': - case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break; - case 'double': - case 'float': $fld->default_value = (float) $d; break; - default: $fld->default_value = $d; break; + $d = substr($rs->fields[2], strlen('default ')); + switch ($fld->type) { + case 'smallint': + case 'integer': + $fld->default_value = (int)$d; + break; + case 'char': + case 'blob': + case 'text': + case 'varchar': + $fld->default_value = (string)substr($d, 1, strlen($d) - 2); + break; + case 'double': + case 'float': + $fld->default_value = (float)$d; + break; + default: + $fld->default_value = $d; + break; } - // case 35:$tt = 'TIMESTAMP'; break; + // case 35:$tt = 'TIMESTAMP'; break; } if ((isset($rs->fields[5])) && ($fld->type == 'blob')) { $fld->sub_type = $rs->fields[5]; @@ -503,11 +555,11 @@ class ADODB_ibase extends ADOConnection { return false; } - function BlobEncode( $blob ) + function BlobEncode($blob) { - $blobid = ibase_blob_create( $this->_connectionID); - ibase_blob_add( $blobid, $blob ); - return ibase_blob_close( $blobid ); + $blobid = ibase_blob_create($this->_connectionID); + ibase_blob_add($blobid, $blob); + return ibase_blob_close($blobid); } // since we auto-decode all blob's since 2.42, @@ -518,31 +570,29 @@ class ADODB_ibase extends ADOConnection { } - - // old blobdecode function // still used to auto-decode all blob's - function _BlobDecode( $blob ) + function _BlobDecode($blob) { - $blobid = ibase_blob_open( $blob ); - $realblob = ibase_blob_get( $blobid,$this->maxblobsize); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr> - while($string = ibase_blob_get($blobid, 8192)){ + $blobid = ibase_blob_open($blob); + $realblob = ibase_blob_get($blobid, $this->maxblobsize); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr> + while ($string = ibase_blob_get($blobid, 8192)) { $realblob .= $string; } - ibase_blob_close( $blobid ); + ibase_blob_close($blobid); - return( $realblob ); + return ($realblob); } - function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') + function UpdateBlobFile($table, $column, $path, $where, $blobtype = 'BLOB') { - $fd = fopen($path,'rb'); + $fd = fopen($path, 'rb'); if ($fd === false) return false; $blob_id = ibase_blob_create($this->_connectionID); /* fill with data */ - while ($val = fread($fd,32768)){ + while ($val = fread($fd, 32768)) { ibase_blob_add($blob_id, $val); } @@ -550,7 +600,7 @@ class ADODB_ibase extends ADOConnection { $blob_id_str = ibase_blob_close($blob_id); fclose($fd); - return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; + return $this->Execute("UPDATE $table SET $column=(?) WHERE $where", array($blob_id_str)) != false; } /* @@ -562,96 +612,96 @@ class ADODB_ibase extends ADOConnection { $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); */ - function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') + function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB') { - $blob_id = ibase_blob_create($this->_connectionID); + $blob_id = ibase_blob_create($this->_connectionID); - // ibase_blob_add($blob_id, $val); + // ibase_blob_add($blob_id, $val); - // replacement that solves the problem by which only the first modulus 64K / - // of $val are stored at the blob field //////////////////////////////////// - // Thx Abel Berenstein aberenstein#afip.gov.ar - $len = strlen($val); - $chunk_size = 32768; - $tail_size = $len % $chunk_size; - $n_chunks = ($len - $tail_size) / $chunk_size; + // replacement that solves the problem by which only the first modulus 64K / + // of $val are stored at the blob field //////////////////////////////////// + // Thx Abel Berenstein aberenstein#afip.gov.ar + $len = strlen($val); + $chunk_size = 32768; + $tail_size = $len % $chunk_size; + $n_chunks = ($len - $tail_size) / $chunk_size; - for ($n = 0; $n < $n_chunks; $n++) { - $start = $n * $chunk_size; - $data = substr($val, $start, $chunk_size); - ibase_blob_add($blob_id, $data); - } + for ($n = 0; $n < $n_chunks; $n++) { + $start = $n * $chunk_size; + $data = substr($val, $start, $chunk_size); + ibase_blob_add($blob_id, $data); + } - if ($tail_size) { - $start = $n_chunks * $chunk_size; - $data = substr($val, $start, $tail_size); - ibase_blob_add($blob_id, $data); - } - // end replacement ///////////////////////////////////////////////////////// + if ($tail_size) { + $start = $n_chunks * $chunk_size; + $data = substr($val, $start, $tail_size); + ibase_blob_add($blob_id, $data); + } + // end replacement ///////////////////////////////////////////////////////// - $blob_id_str = ibase_blob_close($blob_id); + $blob_id_str = ibase_blob_close($blob_id); - return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; + return $this->Execute("UPDATE $table SET $column=(?) WHERE $where", array($blob_id_str)) != false; } - function OldUpdateBlob($table,$column,$val,$where,$blobtype='BLOB') + function OldUpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB') { $blob_id = ibase_blob_create($this->_connectionID); ibase_blob_add($blob_id, $val); $blob_id_str = ibase_blob_close($blob_id); - return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; + return $this->Execute("UPDATE $table SET $column=(?) WHERE $where", array($blob_id_str)) != false; } // Format date column in sql string given an input format that understands Y M D // Only since Interbase 6.0 - uses EXTRACT // problem - does not zero-fill the day and month yet - function SQLDate($fmt, $col=false) + function SQLDate($fmt, $col = false) { if (!$col) $col = $this->sysDate; $s = ''; $len = strlen($fmt); - for ($i=0; $i < $len; $i++) { + for ($i = 0; $i < $len; $i++) { if ($s) $s .= '||'; $ch = $fmt[$i]; - switch($ch) { - case 'Y': - case 'y': - $s .= "extract(year from $col)"; - break; - case 'M': - case 'm': - $s .= "extract(month from $col)"; - break; - case 'Q': - case 'q': - $s .= "cast(((extract(month from $col)+2) / 3) as integer)"; - break; - case 'D': - case 'd': - $s .= "(extract(day from $col))"; - break; - case 'H': - case 'h': - $s .= "(extract(hour from $col))"; - break; - case 'I': - case 'i': - $s .= "(extract(minute from $col))"; - break; - case 'S': - case 's': - $s .= "CAST((extract(second from $col)) AS INTEGER)"; - break; - - default: - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); - } - $s .= $this->qstr($ch); - break; + switch ($ch) { + case 'Y': + case 'y': + $s .= "extract(year from $col)"; + break; + case 'M': + case 'm': + $s .= "extract(month from $col)"; + break; + case 'Q': + case 'q': + $s .= "cast(((extract(month from $col)+2) / 3) as integer)"; + break; + case 'D': + case 'd': + $s .= "(extract(day from $col))"; + break; + case 'H': + case 'h': + $s .= "(extract(hour from $col))"; + break; + case 'I': + case 'i': + $s .= "(extract(minute from $col))"; + break; + case 'S': + case 's': + $s .= "CAST((extract(second from $col)) AS INTEGER)"; + break; + + default: + if ($ch == '\\') { + $i++; + $ch = substr($fmt, $i, 1); + } + $s .= $this->qstr($ch); + break; } } return $s; @@ -666,15 +716,15 @@ class ADORecordset_ibase extends ADORecordSet { var $databaseType = "ibase"; - var $bind=false; + var $bind = false; var $_cacheType; - function ADORecordset_ibase($id,$mode=false) + function ADORecordset_ibase($id, $mode = false) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; - $this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode; - return $this->ADORecordSet($id); + $this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode; + return $this->ADORecordSet($id); } /* Returns: an object containing field information. @@ -684,25 +734,25 @@ class ADORecordset_ibase extends ADORecordSet function &FetchField($fieldOffset = -1) { - $fld = new ADOFieldObject; - $ibf = ibase_field_info($this->_queryID,$fieldOffset); - $fld->name = strtolower($ibf['alias']); - if (empty($fld->name)) $fld->name = strtolower($ibf['name']); - $fld->type = $ibf['type']; - $fld->max_length = $ibf['length']; - return $fld; + $fld = new ADOFieldObject; + $ibf = ibase_field_info($this->_queryID, $fieldOffset); + $fld->name = strtolower($ibf['alias']); + if (empty($fld->name)) $fld->name = strtolower($ibf['name']); + $fld->type = $ibf['type']; + $fld->max_length = $ibf['length']; + return $fld; } function _initrs() { - $this->_numOfRows = -1; - $this->_numOfFields = @ibase_num_fields($this->_queryID); + $this->_numOfRows = -1; + $this->_numOfFields = @ibase_num_fields($this->_queryID); - // cache types for blob decode check - for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { - $f1 = $this->FetchField($i); - $this->_cacheType[] = $f1->type; - } + // cache types for blob decode check + for ($i = 0, $max = $this->_numOfFields; $i < $max; $i++) { + $f1 = $this->FetchField($i); + $this->_cacheType[] = $f1->type; + } } function _seek($row) @@ -724,8 +774,8 @@ class ADORecordset_ibase extends ADORecordSet //$ADODB_ANSI_PADDING_OFF=1; $rtrim = !empty($ADODB_ANSI_PADDING_OFF); - for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { - if ($this->_cacheType[$i]=="BLOB") { + for ($i = 0, $max = $this->_numOfFields; $i < $max; $i++) { + if ($this->_cacheType[$i] == "BLOB") { if (isset($f[$i])) { $f[$i] = $this->connection->_BlobDecode($f[$i]); } else { @@ -745,7 +795,7 @@ class ADORecordset_ibase extends ADORecordSet if ($this->fetchMode == ADODB_FETCH_ASSOC) { $this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE); } elseif ($this->fetchMode == ADODB_FETCH_BOTH) { - $this->fields =& array_merge($this->fields,$this->GetRowAssoc(ADODB_ASSOC_CASE)); + $this->fields =& array_merge($this->fields, $this->GetRowAssoc(ADODB_ASSOC_CASE)); } return true; } @@ -756,22 +806,22 @@ class ADORecordset_ibase extends ADORecordSet if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname]; if (!$this->bind) { $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { + for ($i = 0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } function _close() { - return @ibase_free_result($this->_queryID); + return @ibase_free_result($this->_queryID); } - function MetaType($t,$len=-1,$fieldobj=false) + function MetaType($t, $len = -1, $fieldobj = false) { if (is_object($t)) { $fieldobj = $t; @@ -779,27 +829,30 @@ class ADORecordset_ibase extends ADORecordSet $len = $fieldobj->max_length; } switch (strtoupper($t)) { - case 'CHAR': - return 'C'; - - case 'TEXT': - case 'VARCHAR': - case 'VARYING': - if ($len <= $this->blobSize) return 'C'; - return 'X'; - case 'BLOB': - return 'B'; - - case 'TIMESTAMP': - case 'DATE': return 'D'; - - //case 'T': return 'T'; - - //case 'L': return 'L'; - case 'INT': - case 'SHORT': - case 'INTEGER': return 'I'; - default: return 'N'; + case 'CHAR': + return 'C'; + + case 'TEXT': + case 'VARCHAR': + case 'VARYING': + if ($len <= $this->blobSize) return 'C'; + return 'X'; + case 'BLOB': + return 'B'; + + case 'TIMESTAMP': + case 'DATE': + return 'D'; + + //case 'T': return 'T'; + + //case 'L': return 'L'; + case 'INT': + case 'SHORT': + case 'INTEGER': + return 'I'; + default: + return 'N'; } } diff --git a/lib/WikiDB/adodb/drivers/adodb-informix.inc.php b/lib/WikiDB/adodb/drivers/adodb-informix.inc.php index f521c41c2..a32bb9a6c 100644 --- a/lib/WikiDB/adodb/drivers/adodb-informix.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-informix.inc.php @@ -1,29 +1,32 @@ <?php /** -* @version V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). 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 -* -* Informix 9 driver that supports SELECT FIRST -* -*/ -include_once(ADODB_DIR.'/drivers/adodb-informix72.inc.php'); + * @version V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). 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 + * + * Informix 9 driver that supports SELECT FIRST + * + */ +include_once(ADODB_DIR . '/drivers/adodb-informix72.inc.php'); -class ADODB_informix extends ADODB_informix72 { +class ADODB_informix extends ADODB_informix72 +{ var $databaseType = "informix"; var $hasTop = 'FIRST'; var $ansiOuter = true; } -class ADORecordset_informix extends ADORecordset_informix72 { +class ADORecordset_informix extends ADORecordset_informix72 +{ var $databaseType = "informix"; - function ADORecordset_informix($id,$mode=false) + + function ADORecordset_informix($id, $mode = false) { - $this->ADORecordset_informix72($id,$mode); + $this->ADORecordset_informix72($id, $mode); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-informix72.inc.php b/lib/WikiDB/adodb/drivers/adodb-informix72.inc.php index 3543a7f48..9f64dbaf4 100644 --- a/lib/WikiDB/adodb/drivers/adodb-informix72.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-informix72.inc.php @@ -14,9 +14,10 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim. All rights reserved. */ -if (!defined('IFX_SCROLL')) define('IFX_SCROLL',1); +if (!defined('IFX_SCROLL')) define('IFX_SCROLL', 1); -class ADODB_informix72 extends ADOConnection { +class ADODB_informix72 extends ADOConnection +{ var $databaseType = "informix72"; var $dataProvider = "informix"; var $replaceQuote = "''"; // string to use to replace quotes @@ -26,9 +27,9 @@ class ADODB_informix72 extends ADOConnection { var $hasAffectedRows = true; var $upperCase = 'upper'; var $substr = 'substr'; - var $metaTablesSQL="select tabname from systables"; + var $metaTablesSQL = "select tabname from systables"; var $metaColumnsSQL = -"select c.colname, c.coltype, c.collength, d.default + "select c.colname, c.coltype, c.collength, d.default from syscolumns c, systables t,sysdefaults d where c.tabid=t.tabid and d.tabid=t.tabid and d.colno=c.colno and tabname='%s'"; @@ -39,7 +40,7 @@ class ADODB_informix72 extends ADOConnection { var $has_insertid = true; var $_autocommit = true; - var $_bindInputArray = true; // set to true if ADOConnection.Execute() permits binding of array parameters. + var $_bindInputArray = true; // set to true if ADOConnection.Execute() permits binding of array parameters. var $sysDate = 'TODAY'; var $sysTimeStamp = 'CURRENT'; var $cursorType = IFX_SCROLL; // IFX_SCROLL or IFX_HOLD or 0 @@ -64,21 +65,21 @@ class ADODB_informix72 extends ADOConnection { if (isset($this->version)) return $this->version; $arr['description'] = $this->GetOne("select DBINFO('version','full') from systables where tabid = 1"); - $arr['version'] = $this->GetOne("select DBINFO('version','major')||"."||DBINFO('version','minor') from systables where tabid = 1"); + $arr['version'] = $this->GetOne("select DBINFO('version','major')||" . "||DBINFO('version','minor') from systables where tabid = 1"); $this->version = $arr; return $arr; } function _insertid() { - $sqlca =ifx_getsqlca($this->lastQuery); + $sqlca = ifx_getsqlca($this->lastQuery); return @$sqlca["sqlerrd1"]; } function _affectedrows() { if ($this->lastQuery) { - return @ifx_affected_rows ($this->lastQuery); + return @ifx_affected_rows($this->lastQuery); } return 0; } @@ -92,7 +93,7 @@ class ADODB_informix72 extends ADOConnection { return true; } - function CommitTrans($ok=true) + function CommitTrans($ok = true) { if (!$ok) return $this->RollbackTrans(); if ($this->transOff) return true; @@ -111,7 +112,7 @@ class ADODB_informix72 extends ADOConnection { return true; } - function RowLock($tables,$where) + function RowLock($tables, $where) { if ($this->_autocommit) $this->BeginTrans(); return $this->GetOne("select 1 as ignore from $tables where $where for update"); @@ -129,20 +130,20 @@ class ADODB_informix72 extends ADOConnection { function ErrorNo() { - preg_match("/.*SQLCODE=([^\]]*)/",ifx_error(),$parse); //!EOS + preg_match("/.*SQLCODE=([^\]]*)/", ifx_error(), $parse); //!EOS if (is_array($parse) && isset($parse[1])) return (int)$parse[1]; return 0; } function &MetaColumns($table) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; if (!empty($this->metaColumnsSQL)) { $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)); + $rs = $this->Execute(sprintf($this->metaColumnsSQL, $table)); if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; if ($rs === false) return false; @@ -154,8 +155,8 @@ class ADODB_informix72 extends ADOConnection { $fld->type = $rs->fields[1]; $fld->max_length = $rs->fields[2]; if (trim($rs->fields[3]) != "AAAAAA 0") { - $fld->has_default = 1; - $fld->default_value = $rs->fields[3]; + $fld->has_default = 1; + $fld->default_value = $rs->fields[3]; } else { $fld->has_default = 0; } @@ -171,98 +172,95 @@ class ADODB_informix72 extends ADOConnection { return false; } - function &xMetaColumns($table) - { - return ADOConnection::MetaColumns($table,false); - } + function &xMetaColumns($table) + { + return ADOConnection::MetaColumns($table, false); + } - function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB') - { - $type = ($blobtype == 'TEXT') ? 1 : 0; - $blobid = ifx_create_blob($type,0,$val); - return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blobid)); - } + function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB') + { + $type = ($blobtype == 'TEXT') ? 1 : 0; + $blobid = ifx_create_blob($type, 0, $val); + return $this->Execute("UPDATE $table SET $column=(?) WHERE $where", array($blobid)); + } - function BlobDecode($blobid) - { - return function_exists('ifx_byteasvarchar') ? $blobid : @ifx_get_blob($blobid); - } + function BlobDecode($blobid) + { + return function_exists('ifx_byteasvarchar') ? $blobid : @ifx_get_blob($blobid); + } // returns true or false - function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) + function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('ifx_connect')) return false; $dbs = $argDatabasename . "@" . $argHostname; if ($argHostname) putenv("INFORMIXSERVER=$argHostname"); - putenv("INFORMIXSERVER=".trim($argHostname)); - $this->_connectionID = ifx_connect($dbs,$argUsername,$argPassword); + putenv("INFORMIXSERVER=" . trim($argHostname)); + $this->_connectionID = ifx_connect($dbs, $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) + function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('ifx_connect')) return false; $dbs = $argDatabasename . "@" . $argHostname; - putenv("INFORMIXSERVER=".trim($argHostname)); - $this->_connectionID = ifx_pconnect($dbs,$argUsername,$argPassword); + putenv("INFORMIXSERVER=" . trim($argHostname)); + $this->_connectionID = ifx_pconnect($dbs, $argUsername, $argPassword); if ($this->_connectionID === false) return false; #if ($argDatabasename) return $this->SelectDB($argDatabasename); return true; } -/* - // ifx_do does not accept bind parameters - weird ??? - function Prepare($sql) - { - $stmt = ifx_prepare($sql); - if (!$stmt) return $sql; - else return array($sql,$stmt); - } -*/ + + /* + // ifx_do does not accept bind parameters - weird ??? + function Prepare($sql) + { + $stmt = ifx_prepare($sql); + if (!$stmt) return $sql; + else return array($sql,$stmt); + } + */ // returns query ID if successful, otherwise false - function _query($sql,$inputarr) + function _query($sql, $inputarr) { - global $ADODB_COUNTRECS; + global $ADODB_COUNTRECS; - // String parameters have to be converted using ifx_create_char - if ($inputarr) { - foreach($inputarr as $v) { - if (gettype($v) == 'string') { - $tab[] = ifx_create_char($v); + // String parameters have to be converted using ifx_create_char + if ($inputarr) { + foreach ($inputarr as $v) { + if (gettype($v) == 'string') { + $tab[] = ifx_create_char($v); + } else { + $tab[] = $v; + } } - else { - $tab[] = $v; + } + + // In case of select statement, we use a scroll cursor in order + // to be able to call "move", or "movefirst" statements + if (!$ADODB_COUNTRECS && preg_match("/^\s*select/is", $sql)) { + if ($inputarr) { + $this->lastQuery = ifx_query($sql, $this->_connectionID, $this->cursorType, $tab); + } else { + $this->lastQuery = ifx_query($sql, $this->_connectionID, $this->cursorType); } - } - } - - // In case of select statement, we use a scroll cursor in order - // to be able to call "move", or "movefirst" statements - if (!$ADODB_COUNTRECS && preg_match("/^\s*select/is", $sql)) { - if ($inputarr) { - $this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType, $tab); - } - else { - $this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType); - } - } - else { - if ($inputarr) { - $this->lastQuery = ifx_query($sql,$this->_connectionID, $tab); - } - else { - $this->lastQuery = ifx_query($sql,$this->_connectionID); - } - } - - // Following line have been commented because autocommit mode is - // not supported by informix SE 7.2 - - //if ($this->_autocommit) ifx_query('COMMIT',$this->_connectionID); + } else { + if ($inputarr) { + $this->lastQuery = ifx_query($sql, $this->_connectionID, $tab); + } else { + $this->lastQuery = ifx_query($sql, $this->_connectionID); + } + } + + // Following line have been commented because autocommit mode is + // not supported by informix SE 7.2 + + //if ($this->_autocommit) ifx_query('COMMIT',$this->_connectionID); return $this->lastQuery; } @@ -279,13 +277,14 @@ class ADODB_informix72 extends ADOConnection { Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordset_informix72 extends ADORecordSet { +class ADORecordset_informix72 extends ADORecordSet +{ var $databaseType = "informix72"; var $canSeek = true; var $_fieldprops = false; - function ADORecordset_informix72($id,$mode=false) + function ADORecordset_informix72($id, $mode = false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -303,14 +302,14 @@ class ADORecordset_informix72 extends ADORecordSet { { if (empty($this->_fieldprops)) { $fp = ifx_fieldproperties($this->_queryID); - foreach($fp as $k => $v) { + foreach ($fp as $k => $v) { $o = new ADOFieldObject; $o->name = $k; $arr = explode(';', $v); //"SQLTYPE;length;precision;scale;ISNULLABLE" $o->type = $arr[0]; $o->max_length = $arr[1]; $this->_fieldprops[] = $o; - $o->not_null = $arr[4]=="N"; + $o->not_null = $arr[4] == "N"; } } return $this->_fieldprops[$fieldOffset]; @@ -327,47 +326,47 @@ class ADORecordset_informix72 extends ADORecordSet { return @ifx_fetch_row($this->_queryID, $row); } - function MoveLast() - { - $this->fields = @ifx_fetch_row($this->_queryID, "LAST"); - if ($this->fields) $this->EOF = false; - $this->_currentRow = -1; + function MoveLast() + { + $this->fields = @ifx_fetch_row($this->_queryID, "LAST"); + if ($this->fields) $this->EOF = false; + $this->_currentRow = -1; - if ($this->fetchMode == ADODB_FETCH_NUM) { - foreach($this->fields as $v) { - $arr[] = $v; - } - $this->fields = $arr; - } + if ($this->fetchMode == ADODB_FETCH_NUM) { + foreach ($this->fields as $v) { + $arr[] = $v; + } + $this->fields = $arr; + } - return true; - } + return true; + } - function MoveFirst() + function MoveFirst() { - $this->fields = @ifx_fetch_row($this->_queryID, "FIRST"); - if ($this->fields) $this->EOF = false; - $this->_currentRow = 0; + $this->fields = @ifx_fetch_row($this->_queryID, "FIRST"); + if ($this->fields) $this->EOF = false; + $this->_currentRow = 0; - if ($this->fetchMode == ADODB_FETCH_NUM) { - foreach($this->fields as $v) { - $arr[] = $v; - } - $this->fields = $arr; - } + if ($this->fetchMode == ADODB_FETCH_NUM) { + foreach ($this->fields as $v) { + $arr[] = $v; + } + $this->fields = $arr; + } - return true; - } + return true; + } - function _fetch($ignore_fields=false) - { + function _fetch($ignore_fields = false) + { $this->fields = @ifx_fetch_row($this->_queryID); if (!is_array($this->fields)) return false; if ($this->fetchMode == ADODB_FETCH_NUM) { - foreach($this->fields as $v) { + foreach ($this->fields as $v) { $arr[] = $v; } $this->fields = $arr; diff --git a/lib/WikiDB/adodb/drivers/adodb-ldap.inc.php b/lib/WikiDB/adodb/drivers/adodb-ldap.inc.php index e2ce1be37..68710f67c 100644 --- a/lib/WikiDB/adodb/drivers/adodb-ldap.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-ldap.inc.php @@ -9,7 +9,8 @@ Joshua Eldridge (joshuae74#hotmail.com) */ -class ADODB_ldap extends ADOConnection { +class ADODB_ldap extends ADOConnection +{ var $databaseType = 'ldap'; var $dataProvider = 'ldap'; @@ -28,47 +29,47 @@ class ADODB_ldap extends ADOConnection { // returns true or false - function _connect( $host, $username, $password, $ldapbase ) + function _connect($host, $username, $password, $ldapbase) { - if ( !function_exists( 'ldap_connect' ) ) return false; + if (!function_exists('ldap_connect')) return false; - $conn_info = array( $host ); + $conn_info = array($host); - if ( strstr( $host, ':' ) ) { - $conn_info = explode(':', $host); - } + if (strstr($host, ':')) { + $conn_info = explode(':', $host); + } - $this->_connectionID = ldap_connect( $conn_info[0], $conn_info[1] ) - or die( 'Could not connect to ' . $this->_connectionID ); - if ($username && $password) { - $bind = ldap_bind( $this->_connectionID, $username, $password ) - or die( 'Could not bind to ' . $this->_connectionID . ' with $username & $password'); - } else { - $bind = ldap_bind( $this->_connectionID ) - or die( 'Could not bind anonymously to ' . $this->_connectionID ); - } - return $this->_connectionID; + $this->_connectionID = ldap_connect($conn_info[0], $conn_info[1]) + or die('Could not connect to ' . $this->_connectionID); + if ($username && $password) { + $bind = ldap_bind($this->_connectionID, $username, $password) + or die('Could not bind to ' . $this->_connectionID . ' with $username & $password'); + } else { + $bind = ldap_bind($this->_connectionID) + or die('Could not bind anonymously to ' . $this->_connectionID); + } + return $this->_connectionID; } /* returns _queryID or false */ - function _query($sql,$inputarr) + function _query($sql, $inputarr) { - $rs = ldap_search( $this->_connectionID, $this->database, $sql ); - return $rs; + $rs = ldap_search($this->_connectionID, $this->database, $sql); + return $rs; } /* closes the LDAP connection */ function _close() { - @ldap_close( $this->_connectionID ); + @ldap_close($this->_connectionID); $this->_connectionID = false; } function ServerInfo() { - if( is_array( $this->version ) ) return $this->version; + if (is_array($this->version)) return $this->version; $version = array(); /* Determines how aliases are handled during search. @@ -81,16 +82,16 @@ class ADODB_ldap extends ADOConnection { aliases are dereferenced when locating the base object but not during the search. Default: LDAP_DEREF_NEVER */ - ldap_get_option( $this->_connectionID, LDAP_OPT_DEREF, $version['LDAP_OPT_DEREF'] ) ; - switch ( $version['LDAP_OPT_DEREF'] ) { - case 0: - $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_NEVER'; - case 1: - $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_SEARCHING'; - case 2: - $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_FINDING'; - case 3: - $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_ALWAYS'; + ldap_get_option($this->_connectionID, LDAP_OPT_DEREF, $version['LDAP_OPT_DEREF']); + switch ($version['LDAP_OPT_DEREF']) { + case 0: + $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_NEVER'; + case 1: + $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_SEARCHING'; + case 2: + $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_FINDING'; + case 3: + $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_ALWAYS'; } /* @@ -98,9 +99,9 @@ class ADODB_ldap extends ADOConnection { LDAP_NO_LIMIT (0) means no limit. Default: LDAP_NO_LIMIT */ - ldap_get_option( $this->_connectionID, LDAP_OPT_SIZELIMIT, $version['LDAP_OPT_SIZELIMIT'] ); - if ( $version['LDAP_OPT_SIZELIMIT'] == 0 ) { - $version['LDAP_OPT_SIZELIMIT'] = 'LDAP_NO_LIMIT'; + ldap_get_option($this->_connectionID, LDAP_OPT_SIZELIMIT, $version['LDAP_OPT_SIZELIMIT']); + if ($version['LDAP_OPT_SIZELIMIT'] == 0) { + $version['LDAP_OPT_SIZELIMIT'] = 'LDAP_NO_LIMIT'; } /* @@ -108,9 +109,9 @@ class ADODB_ldap extends ADOConnection { LDAP_NO_LIMIT (0) means no limit. Default: LDAP_NO_LIMIT */ - ldap_get_option( $this->_connectionID, LDAP_OPT_TIMELIMIT, $version['LDAP_OPT_TIMELIMIT'] ); - if ( $version['LDAP_OPT_TIMELIMIT'] == 0 ) { - $version['LDAP_OPT_TIMELIMIT'] = 'LDAP_NO_LIMIT'; + ldap_get_option($this->_connectionID, LDAP_OPT_TIMELIMIT, $version['LDAP_OPT_TIMELIMIT']); + if ($version['LDAP_OPT_TIMELIMIT'] == 0) { + $version['LDAP_OPT_TIMELIMIT'] = 'LDAP_NO_LIMIT'; } /* @@ -119,11 +120,11 @@ class ADODB_ldap extends ADOConnection { LDAP_OPT_OFF Default: ON */ - ldap_get_option( $this->_connectionID, LDAP_OPT_REFERRALS, $version['LDAP_OPT_REFERRALS'] ); - if ( $version['LDAP_OPT_REFERRALS'] == 0 ) { - $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_OFF'; + ldap_get_option($this->_connectionID, LDAP_OPT_REFERRALS, $version['LDAP_OPT_REFERRALS']); + if ($version['LDAP_OPT_REFERRALS'] == 0) { + $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_OFF'; } else { - $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_ON'; + $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_ON'; } /* @@ -132,11 +133,11 @@ class ADODB_ldap extends ADOConnection { LDAP_OPT_OFF Default: OFF */ - ldap_get_option( $this->_connectionID, LDAP_OPT_RESTART, $version['LDAP_OPT_RESTART'] ); - if ( $version['LDAP_OPT_RESTART'] == 0 ) { - $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_OFF'; + ldap_get_option($this->_connectionID, LDAP_OPT_RESTART, $version['LDAP_OPT_RESTART']); + if ($version['LDAP_OPT_RESTART'] == 0) { + $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_OFF'; } else { - $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_ON'; + $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_ON'; } /* @@ -145,18 +146,18 @@ class ADODB_ldap extends ADOConnection { LDAP_VERSION3 (3) Default: LDAP_VERSION2 (2) */ - ldap_get_option( $this->_connectionID, LDAP_OPT_PROTOCOL_VERSION, $version['LDAP_OPT_PROTOCOL_VERSION'] ); - if ( $version['LDAP_OPT_PROTOCOL_VERSION'] == 2 ) { - $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION2'; + ldap_get_option($this->_connectionID, LDAP_OPT_PROTOCOL_VERSION, $version['LDAP_OPT_PROTOCOL_VERSION']); + if ($version['LDAP_OPT_PROTOCOL_VERSION'] == 2) { + $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION2'; } else { - $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION3'; + $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION3'; } /* The host name (or list of hosts) for the primary LDAP server. */ - ldap_get_option( $this->_connectionID, LDAP_OPT_HOST_NAME, $version['LDAP_OPT_HOST_NAME'] ); - ldap_get_option( $this->_connectionID, OPT_ERROR_NUMBER, $version['OPT_ERROR_NUMBER'] ); - ldap_get_option( $this->_connectionID, OPT_ERROR_STRING, $version['OPT_ERROR_STRING'] ); - ldap_get_option( $this->_connectionID, LDAP_OPT_MATCHED_DN, $version['LDAP_OPT_MATCHED_DN'] ); + ldap_get_option($this->_connectionID, LDAP_OPT_HOST_NAME, $version['LDAP_OPT_HOST_NAME']); + ldap_get_option($this->_connectionID, OPT_ERROR_NUMBER, $version['OPT_ERROR_NUMBER']); + ldap_get_option($this->_connectionID, OPT_ERROR_STRING, $version['OPT_ERROR_STRING']); + ldap_get_option($this->_connectionID, LDAP_OPT_MATCHED_DN, $version['LDAP_OPT_MATCHED_DN']); return $this->version = $version; @@ -167,31 +168,31 @@ class ADODB_ldap extends ADOConnection { Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordSet_ldap extends ADORecordSet{ +class ADORecordSet_ldap extends ADORecordSet +{ var $databaseType = "ldap"; var $canSeek = false; var $_entryID; /* keeps track of the entry resource identifier */ - function ADORecordSet_ldap($queryID,$mode=false) + function ADORecordSet_ldap($queryID, $mode = false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } - switch ($mode) - { - case ADODB_FETCH_NUM: - $this->fetchMode = LDAP_NUM; - break; - case ADODB_FETCH_ASSOC: - $this->fetchMode = LDAP_ASSOC; - break; - default: - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH: - $this->fetchMode = LDAP_BOTH; - break; + switch ($mode) { + case ADODB_FETCH_NUM: + $this->fetchMode = LDAP_NUM; + break; + case ADODB_FETCH_ASSOC: + $this->fetchMode = LDAP_ASSOC; + break; + default: + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + $this->fetchMode = LDAP_BOTH; + break; } $this->ADORecordSet($queryID); @@ -199,12 +200,12 @@ class ADORecordSet_ldap extends ADORecordSet{ function _initrs() { - /* - This could be teaked to respect the $COUNTRECS directive from ADODB - It's currently being used in the _fetch() function and the - GetAssoc() function - */ - $this->_numOfRows = ldap_count_entries( $this->connection->_connectionID, $this->_queryID ); + /* + This could be teaked to respect the $COUNTRECS directive from ADODB + It's currently being used in the _fetch() function and the + GetAssoc() function + */ + $this->_numOfRows = ldap_count_entries($this->connection->_connectionID, $this->_queryID); } @@ -215,18 +216,18 @@ class ADORecordSet_ldap extends ADORecordSet{ { $records = $this->_numOfRows; $results = array(); - for ( $i=0; $i < $records; $i++ ) { - foreach ( $this->fields as $k=>$v ) { - if ( is_array( $v ) ) { - if ( $v['count'] == 1 ) { - $results[$i][$k] = $v[0]; - } else { - array_shift( $v ); - $results[$i][$k] = $v; - } + for ($i = 0; $i < $records; $i++) { + foreach ($this->fields as $k => $v) { + if (is_array($v)) { + if ($v['count'] == 1) { + $results[$i][$k] = $v[0]; + } else { + array_shift($v); + $results[$i][$k] = $v; } } } + } return $results; } @@ -234,12 +235,12 @@ class ADORecordSet_ldap extends ADORecordSet{ function &GetRowAssoc() { $results = array(); - foreach ( $this->fields as $k=>$v ) { - if ( is_array( $v ) ) { - if ( $v['count'] == 1 ) { + foreach ($this->fields as $k => $v) { + if (is_array($v)) { + if ($v['count'] == 1) { $results[$k] = $v[0]; } else { - array_shift( $v ); + array_shift($v); $results[$k] = $v; } } @@ -251,16 +252,16 @@ class ADORecordSet_ldap extends ADORecordSet{ function GetRowNums() { $results = array(); - foreach ( $this->fields as $k=>$v ) { - static $i = 0; - if (is_array( $v )) { - if ( $v['count'] == 1 ) { + foreach ($this->fields as $k => $v) { + static $i = 0; + if (is_array($v)) { + if ($v['count'] == 1) { $results[$i] = $v[0]; } else { - array_shift( $v ); + array_shift($v); $results[$i] = $v; } - $i++; + $i++; } } return $results; @@ -268,36 +269,37 @@ class ADORecordSet_ldap extends ADORecordSet{ function _fetch() { - if ( $this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0 ) + if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0) return false; - if ( $this->_currentRow == 0 ) { - $this->_entryID = ldap_first_entry( $this->connection->_connectionID, $this->_queryID ); + if ($this->_currentRow == 0) { + $this->_entryID = ldap_first_entry($this->connection->_connectionID, $this->_queryID); } else { - $this->_entryID = ldap_next_entry( $this->connection->_connectionID, $this->_entryID ); + $this->_entryID = ldap_next_entry($this->connection->_connectionID, $this->_entryID); } - $this->fields = ldap_get_attributes( $this->connection->_connectionID, $this->_entryID ); + $this->fields = ldap_get_attributes($this->connection->_connectionID, $this->_entryID); $this->_numOfFields = $this->fields['count']; - switch ( $this->fetchMode ) { + switch ($this->fetchMode) { case LDAP_ASSOC: - $this->fields = $this->GetRowAssoc(); - break; + $this->fields = $this->GetRowAssoc(); + break; case LDAP_NUM: - $this->fields = $this->GetRowNums(); - break; + $this->fields = $this->GetRowNums(); + break; case LDAP_BOTH: default: - break; + break; } - return ( is_array( $this->fields ) ); + return (is_array($this->fields)); } - function _close() { - @ldap_free_result( $this->_queryID ); + function _close() + { + @ldap_free_result($this->_queryID); $this->_queryID = false; } diff --git a/lib/WikiDB/adodb/drivers/adodb-mssql.inc.php b/lib/WikiDB/adodb/drivers/adodb-mssql.inc.php index 4b11ed072..903c0d86b 100644 --- a/lib/WikiDB/adodb/drivers/adodb-mssql.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-mssql.inc.php @@ -35,14 +35,14 @@ Set tabs to 4 for best viewing. // has datetime converstion to YYYY-MM-DD format, and also mssql_fetch_assoc if (ADODB_PHPVER >= 0x4300) { // docs say 4.2.0, but testing shows only since 4.3.0 does it work! - @ini_set('mssql.datetimeconvert',0); + @ini_set('mssql.datetimeconvert', 0); } else { -global $ADODB_mssql_mths; // array, months must be upper-case + global $ADODB_mssql_mths; // array, months must be upper-case $ADODB_mssql_date_order = 'mdy'; $ADODB_mssql_mths = array( - 'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6, - 'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12); + 'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6, + 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' => 10, 'NOV' => 11, 'DEC' => 12); } //--------------------------------------------------------------------------- @@ -51,10 +51,10 @@ global $ADODB_mssql_mths; // array, months must be upper-case // Not required for PHP 4.2.0 and above. function AutoDetect_MSSQL_Date_Order($conn) { -global $ADODB_mssql_date_order; + global $ADODB_mssql_date_order; $adate = $conn->GetOne('select getdate()'); if ($adate) { - $anum = (int) $adate; + $anum = (int)$adate; if ($anum > 0) { if ($anum > 31) { //ADOConnection::outp( "MSSQL: YYYY-MM-DD date format not supported currently"); @@ -65,7 +65,8 @@ global $ADODB_mssql_date_order; } } -class ADODB_mssql extends ADOConnection { +class ADODB_mssql extends ADOConnection +{ var $databaseType = "mssql"; var $dataProvider = "mssql"; var $replaceQuote = "''"; // string to use to replace quotes @@ -77,13 +78,13 @@ class ADODB_mssql extends ADOConnection { var $upperCase = 'upper'; var $hasAffectedRows = true; var $metaDatabasesSQL = "select name from sysdatabases where name <> 'master'"; - var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE','dtproperties'))"; + var $metaTablesSQL = "select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE','dtproperties'))"; var $metaColumnsSQL = # xtype==61 is datetime -"select c.name,t.name,c.length, + "select c.name,t.name,c.length, (case when c.xusertype=61 then 0 else c.xprec end), (case when c.xusertype=61 then 0 else c.xscale end) from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'"; - var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE + var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE var $hasGenID = true; var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)'; var $sysTimeStamp = 'GetDate()'; @@ -101,12 +102,12 @@ class ADODB_mssql extends ADOConnection { function ADODB_mssql() { - $this->_has_mssql_init = (strnatcmp(PHP_VERSION,'4.1.0')>=0); + $this->_has_mssql_init = (strnatcmp(PHP_VERSION, '4.1.0') >= 0); } function ServerInfo() { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $stmt = $this->PrepareSP('sp_server_info'); $val = 2; @@ -116,7 +117,7 @@ class ADODB_mssql extends ADOConnection { } else $savem = $this->SetFetchMode(ADODB_FETCH_NUM); - $this->Parameter($stmt,$val,'attribute_id'); + $this->Parameter($stmt, $val, 'attribute_id'); $row = $this->GetRow($stmt); //$row = $this->GetRow("execute sp_server_info 2"); @@ -131,19 +132,19 @@ class ADODB_mssql extends ADOConnection { return $arr; } - function IfNull( $field, $ifNull ) + function IfNull($field, $ifNull) { return " ISNULL($field, $ifNull) "; // if MS SQL Server } function _insertid() { - // SCOPE_IDENTITY() - // Returns the last IDENTITY value inserted into an IDENTITY column in - // the same scope. A scope is a module -- a stored procedure, trigger, - // function, or batch. Thus, two statements are in the same scope if - // they are in the same stored procedure, function, or batch. - return $this->GetOne($this->identitySQL); + // SCOPE_IDENTITY() + // Returns the last IDENTITY value inserted into an IDENTITY column in + // the same scope. A scope is a module -- a stored procedure, trigger, + // function, or batch. Thus, two statements are in the same scope if + // they are in the same stored procedure, function, or batch. + return $this->GetOne($this->identitySQL); } function _affectedrows() @@ -153,20 +154,20 @@ class ADODB_mssql extends ADOConnection { var $_dropSeqSQL = "drop table %s"; - function CreateSequence($seq='adodbseq',$start=1) + function CreateSequence($seq = 'adodbseq', $start = 1) { $start -= 1; $this->Execute("create table $seq (id float(53))"); $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)"); if (!$ok) { - $this->Execute('ROLLBACK TRANSACTION adodbseq'); - return false; + $this->Execute('ROLLBACK TRANSACTION adodbseq'); + return false; } $this->Execute('COMMIT TRANSACTION adodbseq'); return true; } - function GenID($seq='adodbseq',$start=1) + function GenID($seq = 'adodbseq', $start = 1) { //$this->debug=1; $this->Execute('BEGIN TRANSACTION adodbseq'); @@ -189,73 +190,73 @@ class ADODB_mssql extends ADOConnection { //return $this->GetOne("SELECT CONVERT(varchar(255), NEWID()) AS 'Char'"); } - function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) { if ($nrows > 0 && $offset <= 0) { $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql); - $rs =& $this->Execute($sql,$inputarr); + '/(^\s*select\s+(distinctrow|distinct)?)/i', '\\1 ' . $this->hasTop . " $nrows ", $sql); + $rs =& $this->Execute($sql, $inputarr); } else - $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + $rs =& ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); return $rs; } // Format date column in sql string given an input format that understands Y M D - function SQLDate($fmt, $col=false) + function SQLDate($fmt, $col = false) { if (!$col) $col = $this->sysTimeStamp; $s = ''; $len = strlen($fmt); - for ($i=0; $i < $len; $i++) { + for ($i = 0; $i < $len; $i++) { if ($s) $s .= '+'; $ch = $fmt[$i]; - switch($ch) { - case 'Y': - case 'y': - $s .= "datename(yyyy,$col)"; - break; - case 'M': - $s .= "convert(char(3),$col,0)"; - break; - case 'm': - $s .= "replace(str(month($col),2),' ','0')"; - break; - case 'Q': - case 'q': - $s .= "datename(quarter,$col)"; - break; - case 'D': - case 'd': - $s .= "replace(str(day($col),2),' ','0')"; - break; - case 'h': - $s .= "substring(convert(char(14),$col,0),13,2)"; - break; - - case 'H': - $s .= "replace(str(datepart(hh,$col),2),' ','0')"; - break; - - case 'i': - $s .= "replace(str(datepart(mi,$col),2),' ','0')"; - break; - case 's': - $s .= "replace(str(datepart(ss,$col),2),' ','0')"; - break; - case 'a': - case 'A': - $s .= "substring(convert(char(19),$col,0),18,2)"; - break; - - default: - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); - } - $s .= $this->qstr($ch); - break; + switch ($ch) { + case 'Y': + case 'y': + $s .= "datename(yyyy,$col)"; + break; + case 'M': + $s .= "convert(char(3),$col,0)"; + break; + case 'm': + $s .= "replace(str(month($col),2),' ','0')"; + break; + case 'Q': + case 'q': + $s .= "datename(quarter,$col)"; + break; + case 'D': + case 'd': + $s .= "replace(str(day($col),2),' ','0')"; + break; + case 'h': + $s .= "substring(convert(char(14),$col,0),13,2)"; + break; + + case 'H': + $s .= "replace(str(datepart(hh,$col),2),' ','0')"; + break; + + case 'i': + $s .= "replace(str(datepart(mi,$col),2),' ','0')"; + break; + case 's': + $s .= "replace(str(datepart(ss,$col),2),' ','0')"; + break; + case 'a': + case 'A': + $s .= "substring(convert(char(19),$col,0),18,2)"; + break; + + default: + if ($ch == '\\') { + $i++; + $ch = substr($fmt, $i, 1); + } + $s .= $this->qstr($ch); + break; } } return $s; @@ -265,11 +266,11 @@ class ADODB_mssql extends ADOConnection { { if ($this->transOff) return true; $this->transCnt += 1; - $this->Execute('BEGIN TRAN'); - return true; + $this->Execute('BEGIN TRAN'); + return true; } - function CommitTrans($ok=true) + function CommitTrans($ok = true) { if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); @@ -277,6 +278,7 @@ class ADODB_mssql extends ADOConnection { $this->Execute('COMMIT TRAN'); return true; } + function RollbackTrans() { if ($this->transOff) return true; @@ -297,22 +299,22 @@ class ADODB_mssql extends ADOConnection { See http://www.swynk.com/friends/achigrik/SQL70Locks.asp */ - function RowLock($tables,$where) + function RowLock($tables, $where) { if (!$this->transCnt) $this->BeginTrans(); return $this->GetOne("select top 1 null as ignore from $tables with (ROWLOCK,HOLDLOCK) where $where"); } - function MetaForeignKeys($table, $owner=false, $upper=false) + function MetaForeignKeys($table, $owner = false, $upper = false) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; $table = $this->qstr(strtoupper($table)); $sql = -"select object_name(constid) as constraint_name, + "select object_name(constid) as constraint_name, col_name(fkeyid, fkey) as column_name, object_name(rkeyid) as referenced_table_name, col_name(rkeyid, rkey) as referenced_column_name @@ -325,16 +327,16 @@ order by constraint_name, referenced_table_name, keyno"; $ADODB_FETCH_MODE = $save; $arr = false; - foreach($constraints as $constr) { + foreach ($constraints as $constr) { //print_r($constr); - $arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3]; + $arr[$constr[0]][$constr[2]][] = $constr[1] . '=' . $constr[3]; } if (!$arr) return false; $arr2 = false; - foreach($arr as $k => $v) { - foreach($v as $a => $b) { + foreach ($arr as $k => $v) { + foreach ($v as $a => $b) { if ($upper) $a = strtoupper($a); $arr2[$a] = $b; } @@ -345,23 +347,23 @@ order by constraint_name, referenced_table_name, keyno"; //From: Fernando Moreira <FMoreira@imediata.pt> function MetaDatabases() { - if(@mssql_select_db("master")) { - $qry=$this->metaDatabasesSQL; - if($rs=@mssql_query($qry)){ - $tmpAr=$ar=array(); - while($tmpAr=@mssql_fetch_row($rs)) - $ar[]=$tmpAr[0]; - @mssql_select_db($this->databaseName); - if(sizeof($ar)) - return($ar); - else - return(false); - } else { - @mssql_select_db($this->databaseName); - return(false); - } - } - return(false); + if (@mssql_select_db("master")) { + $qry = $this->metaDatabasesSQL; + if ($rs = @mssql_query($qry)) { + $tmpAr = $ar = array(); + while ($tmpAr = @mssql_fetch_row($rs)) + $ar[] = $tmpAr[0]; + @mssql_select_db($this->databaseName); + if (sizeof($ar)) + return ($ar); + else + return (false); + } else { + @mssql_select_db($this->databaseName); + return (false); + } + } + return (false); } // "Stein-Aksel Basma" <basma@accelero.no> @@ -374,18 +376,18 @@ order by constraint_name, referenced_table_name, keyno"; 'PRIMARY KEY' and k.table_name = '$table'"; $a = $this->GetCol($sql); - if ($a && sizeof($a)>0) return $a; + if ($a && sizeof($a) > 0) return $a; return false; } - function &MetaTables($ttype=false,$showSchema=false,$mask=false) + function &MetaTables($ttype = false, $showSchema = false, $mask = false) { if ($mask) { $save = $this->metaTablesSQL; $mask = $this->qstr(($mask)); $this->metaTablesSQL .= " AND name like $mask"; } - $ret =& ADOConnection::MetaTables($ttype,$showSchema); + $ret =& ADOConnection::MetaTables($ttype, $showSchema); if ($mask) { $this->metaTablesSQL = $save; @@ -398,13 +400,12 @@ order by constraint_name, referenced_table_name, keyno"; $this->databaseName = $dbName; if ($this->_connectionID) { return @mssql_select_db($dbName); - } - else return false; + } else return false; } function ErrorMsg() { - if (empty($this->_errorMsg)){ + if (empty($this->_errorMsg)) { $this->_errorMsg = mssql_get_last_message(); } return $this->_errorMsg; @@ -416,19 +417,19 @@ order by constraint_name, referenced_table_name, keyno"; if (empty($this->_errorMsg)) { $this->_errorMsg = mssql_get_last_message(); } - $id = @mssql_query("select @@ERROR",$this->_connectionID); + $id = @mssql_query("select @@ERROR", $this->_connectionID); if (!$id) return false; $arr = mssql_fetch_array($id); @mssql_free_result($id); if (is_array($arr)) return $arr[0]; - else return -1; + else return -1; } // returns true or false function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('mssql_pconnect')) return false; - $this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword); + $this->_connectionID = mssql_connect($argHostname, $argUsername, $argPassword); if ($this->_connectionID === false) return false; if ($argDatabasename) return $this->SelectDB($argDatabasename); return true; @@ -438,7 +439,7 @@ order by constraint_name, referenced_table_name, keyno"; function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('mssql_pconnect')) return false; - $this->_connectionID = mssql_pconnect($argHostname,$argUsername,$argPassword); + $this->_connectionID = mssql_pconnect($argHostname, $argUsername, $argPassword); if ($this->_connectionID === false) return false; // persistent connections can forget to rollback on crash, so we do it here. @@ -452,24 +453,24 @@ order by constraint_name, referenced_table_name, keyno"; function Prepare($sql) { - $sqlarr = explode('?',$sql); + $sqlarr = explode('?', $sql); if (sizeof($sqlarr) <= 1) return $sql; $sql2 = $sqlarr[0]; for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) { - $sql2 .= '@P'.($i-1) . $sqlarr[$i]; + $sql2 .= '@P' . ($i - 1) . $sqlarr[$i]; } - return array($sql,$this->qstr($sql2),$max); + return array($sql, $this->qstr($sql2), $max); } function PrepareSP($sql) { if (!$this->_has_mssql_init) { - ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0"); + ADOConnection::outp("PrepareSP: mssql_init only available since PHP 4.1.0"); return $sql; } - $stmt = mssql_init($sql,$this->_connectionID); - if (!$stmt) return $sql; - return array($sql,$stmt); + $stmt = mssql_init($sql, $this->_connectionID); + if (!$stmt) return $sql; + return array($sql, $stmt); } /* @@ -490,28 +491,36 @@ order by constraint_name, referenced_table_name, keyno"; See mssql_bind documentation at php.net. */ - function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=4000, $type=false) + function Parameter(&$stmt, &$var, $name, $isOutput = false, $maxLen = 4000, $type = false) { if (!$this->_has_mssql_init) { - ADOConnection::outp( "Parameter: mssql_bind only available since PHP 4.1.0"); + ADOConnection::outp("Parameter: mssql_bind only available since PHP 4.1.0"); return $sql; } $isNull = is_null($var); // php 4.0.4 and above... if ($type === false) - switch(gettype($var)) { - default: - case 'string': $type = SQLCHAR; break; - case 'double': $type = SQLFLT8; break; - case 'integer': $type = SQLINT4; break; - case 'boolean': $type = SQLINT1; break; # SQLBIT not supported in 4.1.0 + switch (gettype($var)) { + default: + case 'string': + $type = SQLCHAR; + break; + case 'double': + $type = SQLFLT8; + break; + case 'integer': + $type = SQLINT4; + break; + case 'boolean': + $type = SQLINT1; + break; # SQLBIT not supported in 4.1.0 } - if ($this->debug) { + if ($this->debug) { $prefix = ($isOutput) ? 'Out' : 'In'; $ztype = (empty($type)) ? 'false' : $type; - ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);"); + ADOConnection::outp("{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);"); } /* See http://phplens.com/lens/lensforum/msgs.php?id=7231 @@ -522,7 +531,7 @@ order by constraint_name, referenced_table_name, keyno"; see how it works. - type: one of this new supported PHP constants. SQLTEXT, SQLVARCHAR,SQLCHAR, SQLINT1,SQLINT2, SQLINT4, SQLBIT,SQLFLT8 */ - if ($name !== 'RETVAL') $name = '@'.$name; + if ($name !== 'RETVAL') $name = '@' . $name; return mssql_bind($stmt[1], $name, $var, $type, $isOutput, $isNull, $maxLen); } @@ -538,14 +547,14 @@ order by constraint_name, referenced_table_name, keyno"; ; Valid range 0 - 2147483647. Default = 4096. mssql.textsize = 0 ; zero to pass through */ - function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') + function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB') { - $sql = "UPDATE $table SET $column=0x".bin2hex($val)." WHERE $where"; + $sql = "UPDATE $table SET $column=0x" . bin2hex($val) . " WHERE $where"; return $this->Execute($sql) != false; } // returns query ID if successful, otherwise false - function _query($sql,$inputarr) + function _query($sql, $inputarr) { $this->_errorMsg = false; if (is_array($inputarr)) { @@ -557,7 +566,7 @@ order by constraint_name, referenced_table_name, keyno"; $params = ''; $decl = ''; $i = 0; - foreach($inputarr as $v) { + foreach ($inputarr as $v) { if ($decl) { $decl .= ', '; $params .= ', '; @@ -566,20 +575,20 @@ order by constraint_name, referenced_table_name, keyno"; $len = strlen($v); if ($len == 0) $len = 1; - if ($len > 4000 ) { + if ($len > 4000) { // NVARCHAR is max 4000 chars. Let's use NTEXT $decl .= "@P$i NTEXT"; } else { $decl .= "@P$i NVARCHAR($len)"; } - $params .= "@P$i=N". (strncmp($v,"'",1)==0? $v : $this->qstr($v)); + $params .= "@P$i=N" . (strncmp($v, "'", 1) == 0 ? $v : $this->qstr($v)); } elseif (is_integer($v)) { $decl .= "@P$i INT"; - $params .= "@P$i=".$v; + $params .= "@P$i=" . $v; } else { $decl .= "@P$i FLOAT"; - $params .= "@P$i=".$v; + $params .= "@P$i=" . $v; } $i += 1; } @@ -592,7 +601,7 @@ order by constraint_name, referenced_table_name, keyno"; $rez = mssql_execute($sql[1]); } else { - $rez = mssql_query($sql,$this->_connectionID); + $rez = mssql_query($sql, $this->_connectionID); } return $rez; } @@ -622,14 +631,15 @@ order by constraint_name, referenced_table_name, keyno"; Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordset_mssql extends ADORecordSet { +class ADORecordset_mssql extends ADORecordSet +{ var $databaseType = "mssql"; var $canSeek = true; var $hasFetchAssoc; // see http://phplens.com/lens/lensforum/msgs.php?id=6083 // _mths works only in non-localised system - function ADORecordset_mssql($id,$mode=false) + function ADORecordset_mssql($id, $mode = false) { // freedts check... $this->hasFetchAssoc = function_exists('mssql_fetch_assoc'); @@ -639,14 +649,14 @@ class ADORecordset_mssql extends ADORecordSet { $mode = $ADODB_FETCH_MODE; } $this->fetchMode = $mode; - return $this->ADORecordSet($id,$mode); + return $this->ADORecordSet($id, $mode); } function _initrs() { - GLOBAL $ADODB_COUNTRECS; - $this->_numOfRows = ($ADODB_COUNTRECS)? @mssql_num_rows($this->_queryID):-1; + GLOBAL $ADODB_COUNTRECS; + $this->_numOfRows = ($ADODB_COUNTRECS) ? @mssql_num_rows($this->_queryID) : -1; $this->_numOfFields = @mssql_num_fields($this->_queryID); } @@ -669,13 +679,13 @@ class ADORecordset_mssql extends ADORecordSet { if ($this->fetchMode != ADODB_FETCH_NUM) return $this->fields[$colname]; if (!$this->bind) { $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { + for ($i = 0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } /* Returns: an object containing field information. @@ -687,8 +697,7 @@ class ADORecordset_mssql extends ADORecordSet { { if ($fieldOffset != -1) { return @mssql_fetch_field($this->_queryID, $fieldOffset); - } - else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ + } else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ return @mssql_fetch_field($this->_queryID); } return null; @@ -710,15 +719,14 @@ class ADORecordset_mssql extends ADORecordSet { if ($this->fetchMode & ADODB_FETCH_NUM) { //ADODB_FETCH_BOTH mode $this->fields = @mssql_fetch_array($this->_queryID); - } - else { - if ($this->hasFetchAssoc) {// only for PHP 4.2.0 or later - $this->fields = @mssql_fetch_assoc($this->_queryID); + } else { + if ($this->hasFetchAssoc) { // only for PHP 4.2.0 or later + $this->fields = @mssql_fetch_assoc($this->_queryID); } else { $flds = @mssql_fetch_array($this->_queryID); if (is_array($flds)) { $fassoc = array(); - foreach($flds as $k => $v) { + foreach ($flds as $k => $v) { if (is_numeric($k)) continue; $fassoc[$k] = $v; } @@ -730,11 +738,11 @@ class ADORecordset_mssql extends ADORecordSet { if (is_array($this->fields)) { if (ADODB_ASSOC_CASE == 0) { - foreach($this->fields as $k=>$v) { + foreach ($this->fields as $k => $v) { $this->fields[strtolower($k)] = $v; } } elseif (ADODB_ASSOC_CASE == 1) { - foreach($this->fields as $k=>$v) { + foreach ($this->fields as $k => $v) { $this->fields[strtoupper($k)] = $v; } } @@ -751,7 +759,7 @@ class ADORecordset_mssql extends ADORecordSet { // INSERT UPDATE DELETE returns false even if no error occurs in 4.0.4 // also the date format has been changed from YYYY-mm-dd to dd MMM YYYY in 4.0.4. Idiot! - function _fetch($ignore_fields=false) + function _fetch($ignore_fields = false) { if ($this->fetchMode & ADODB_FETCH_ASSOC) { if ($this->fetchMode & ADODB_FETCH_NUM) { @@ -764,7 +772,7 @@ class ADORecordset_mssql extends ADORecordSet { $this->fields = @mssql_fetch_array($this->_queryID); if (is_array($$this->fields)) { $fassoc = array(); - foreach($$this->fields as $k => $v) { + foreach ($$this->fields as $k => $v) { if (is_integer($k)) continue; $fassoc[$k] = $v; } @@ -775,11 +783,11 @@ class ADORecordset_mssql extends ADORecordSet { if (!$this->fields) { } elseif (ADODB_ASSOC_CASE == 0) { - foreach($this->fields as $k=>$v) { + foreach ($this->fields as $k => $v) { $this->fields[strtolower($k)] = $v; } } elseif (ADODB_ASSOC_CASE == 1) { - foreach($this->fields as $k=>$v) { + foreach ($this->fields as $k => $v) { $this->fields[strtoupper($k)] = $v; } } @@ -798,6 +806,7 @@ class ADORecordset_mssql extends ADORecordSet { $this->_queryID = false; return $rez; } + // mssql uses a default date like Dec 30 2000 12:00AM function UnixDate($v) { @@ -812,83 +821,86 @@ class ADORecordset_mssql extends ADORecordSet { } -class ADORecordSet_array_mssql extends ADORecordSet_array { - function ADORecordSet_array_mssql($id=-1,$mode=false) +class ADORecordSet_array_mssql extends ADORecordSet_array +{ + function ADORecordSet_array_mssql($id = -1, $mode = false) { - $this->ADORecordSet_array($id,$mode); + $this->ADORecordSet_array($id, $mode); } - // mssql uses a default date like Dec 30 2000 12:00AM + // mssql uses a default date like Dec 30 2000 12:00AM function UnixDate($v) { - if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v); + if (is_numeric(substr($v, 0, 1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v); - global $ADODB_mssql_mths,$ADODB_mssql_date_order; + global $ADODB_mssql_mths, $ADODB_mssql_date_order; //Dec 30 2000 12:00AM if ($ADODB_mssql_date_order == 'dmy') { - if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4})|" ,$v, $rr)) { + if (!preg_match("|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4})|", $v, $rr)) { return parent::UnixDate($v); } if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; $theday = $rr[1]; - $themth = substr(strtoupper($rr[2]),0,3); + $themth = substr(strtoupper($rr[2]), 0, 3); } else { - if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})|" ,$v, $rr)) { + if (!preg_match("|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})|", $v, $rr)) { return parent::UnixDate($v); } if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; $theday = $rr[2]; - $themth = substr(strtoupper($rr[1]),0,3); + $themth = substr(strtoupper($rr[1]), 0, 3); } $themth = $ADODB_mssql_mths[$themth]; if ($themth <= 0) return false; // h-m-s-MM-DD-YY - return mktime(0,0,0,$themth,$theday,$rr[3]); + return mktime(0, 0, 0, $themth, $theday, $rr[3]); } function UnixTimeStamp($v) { - if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v); + if (is_numeric(substr($v, 0, 1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v); - global $ADODB_mssql_mths,$ADODB_mssql_date_order; + global $ADODB_mssql_mths, $ADODB_mssql_date_order; //Dec 30 2000 12:00AM - if ($ADODB_mssql_date_order == 'dmy') { - if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|" - ,$v, $rr)) return parent::UnixTimeStamp($v); + if ($ADODB_mssql_date_order == 'dmy') { + if (!preg_match("|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|" + , $v, $rr) + ) return parent::UnixTimeStamp($v); if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; $theday = $rr[1]; - $themth = substr(strtoupper($rr[2]),0,3); + $themth = substr(strtoupper($rr[2]), 0, 3); } else { - if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|" - ,$v, $rr)) return parent::UnixTimeStamp($v); + if (!preg_match("|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|" + , $v, $rr) + ) return parent::UnixTimeStamp($v); if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; $theday = $rr[2]; - $themth = substr(strtoupper($rr[1]),0,3); + $themth = substr(strtoupper($rr[1]), 0, 3); } $themth = $ADODB_mssql_mths[$themth]; if ($themth <= 0) return false; switch (strtoupper($rr[6])) { - case 'P': - if ($rr[4]<12) $rr[4] += 12; - break; - case 'A': - if ($rr[4]==12) $rr[4] = 0; - break; - default: - break; + case 'P': + if ($rr[4] < 12) $rr[4] += 12; + break; + case 'A': + if ($rr[4] == 12) $rr[4] = 0; + break; + default: + break; } // h-m-s-MM-DD-YY - return mktime($rr[4],$rr[5],0,$themth,$theday,$rr[3]); + return mktime($rr[4], $rr[5], 0, $themth, $theday, $rr[3]); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-mssqlnative.inc.php b/lib/WikiDB/adodb/drivers/adodb-mssqlnative.inc.php index eb0589803..f74af9b3a 100644 --- a/lib/WikiDB/adodb/drivers/adodb-mssqlnative.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-mssqlnative.inc.php @@ -25,17 +25,20 @@ if (!function_exists('sqlsrv_configure')) { } if (!function_exists('sqlsrv_set_error_handling')) { - function sqlsrv_set_error_handling($constant) { + function sqlsrv_set_error_handling($constant) + { sqlsrv_configure("WarningsReturnAsErrors", $constant); } } if (!function_exists('sqlsrv_log_set_severity')) { - function sqlsrv_log_set_severity($constant) { + function sqlsrv_log_set_severity($constant) + { sqlsrv_configure("LogSeverity", $constant); } } if (!function_exists('sqlsrv_log_set_subsystems')) { - function sqlsrv_log_set_subsystems($constant) { + function sqlsrv_log_set_subsystems($constant) + { sqlsrv_configure("LogSubsystems", $constant); } } @@ -67,13 +70,13 @@ if (!function_exists('sqlsrv_log_set_subsystems')) { // has datetime converstion to YYYY-MM-DD format, and also mssql_fetch_assoc if (ADODB_PHPVER >= 0x4300) { // docs say 4.2.0, but testing shows only since 4.3.0 does it work! - ini_set('mssql.datetimeconvert',0); + ini_set('mssql.datetimeconvert', 0); } else { - global $ADODB_mssql_mths; // array, months must be upper-case + global $ADODB_mssql_mths; // array, months must be upper-case $ADODB_mssql_date_order = 'mdy'; $ADODB_mssql_mths = array( - 'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6, - 'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12); + 'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6, + 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' => 10, 'NOV' => 11, 'DEC' => 12); } //--------------------------------------------------------------------------- @@ -85,7 +88,7 @@ function AutoDetect_MSSQL_Date_Order($conn) global $ADODB_mssql_date_order; $adate = $conn->GetOne('select getdate()'); if ($adate) { - $anum = (int) $adate; + $anum = (int)$adate; if ($anum > 0) { if ($anum > 31) { //ADOConnection::outp( "MSSQL: YYYY-MM-DD date format not supported currently"); @@ -96,7 +99,8 @@ function AutoDetect_MSSQL_Date_Order($conn) } } -class ADODB_mssqlnative extends ADOConnection { +class ADODB_mssqlnative extends ADOConnection +{ var $databaseType = "mssqlnative"; var $dataProvider = "mssqlnative"; var $replaceQuote = "''"; // string to use to replace quotes @@ -108,13 +112,13 @@ class ADODB_mssqlnative extends ADOConnection { var $hasAffectedRows = true; var $poorAffectedRows = false; var $metaDatabasesSQL = "select name from sys.sysdatabases where name <> 'master'"; - var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE','dtproperties'))"; + var $metaTablesSQL = "select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE','dtproperties'))"; var $metaColumnsSQL = # xtype==61 is datetime "select c.name,t.name,c.length, (case when c.xusertype=61 then 0 else c.xprec end), (case when c.xusertype=61 then 0 else c.xscale end) from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'"; - var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE + var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE var $hasGenID = true; var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)'; var $sysTimeStamp = 'GetDate()'; @@ -133,8 +137,8 @@ class ADODB_mssqlnative extends ADOConnection { { if ($this->debug) { error_log("<pre>"); - sqlsrv_set_error_handling( SQLSRV_ERRORS_LOG_ALL ); - sqlsrv_log_set_severity( SQLSRV_LOG_SEVERITY_ALL ); + sqlsrv_set_error_handling(SQLSRV_ERRORS_LOG_ALL); + sqlsrv_log_set_severity(SQLSRV_LOG_SEVERITY_ALL); sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL); sqlsrv_configure('warnings_return_as_errors', 0); } else { @@ -154,40 +158,40 @@ class ADODB_mssqlnative extends ADOConnection { } else $savem = $this->SetFetchMode(ADODB_FETCH_NUM); $arrServerInfo = sqlsrv_server_info($this->_connectionID); - $arr['description'] = $arrServerInfo['SQLServerName'].' connected to '.$arrServerInfo['CurrentDatabase']; - $arr['version'] = $arrServerInfo['SQLServerVersion'];//ADOConnection::_findvers($arr['description']); + $arr['description'] = $arrServerInfo['SQLServerName'] . ' connected to ' . $arrServerInfo['CurrentDatabase']; + $arr['version'] = $arrServerInfo['SQLServerVersion']; //ADOConnection::_findvers($arr['description']); return $arr; } - function IfNull( $field, $ifNull ) + function IfNull($field, $ifNull) { return " ISNULL($field, $ifNull) "; // if MS SQL Server } function _insertid() { - // SCOPE_IDENTITY() - // Returns the last IDENTITY value inserted into an IDENTITY column in - // the same scope. A scope is a module -- a stored procedure, trigger, - // function, or batch. Thus, two statements are in the same scope if - // they are in the same stored procedure, function, or batch. + // SCOPE_IDENTITY() + // Returns the last IDENTITY value inserted into an IDENTITY column in + // the same scope. A scope is a module -- a stored procedure, trigger, + // function, or batch. Thus, two statements are in the same scope if + // they are in the same stored procedure, function, or batch. return $this->GetOne($this->identitySQL); } function _affectedrows() { - return sqlsrv_rows_affected($this->_queryID); + return sqlsrv_rows_affected($this->_queryID); } - function CreateSequence($seq='adodbseq',$start=1) + function CreateSequence($seq = 'adodbseq', $start = 1) { - if($this->debug) error_log("<hr>CreateSequence($seq,$start)"); + if ($this->debug) error_log("<hr>CreateSequence($seq,$start)"); sqlsrv_begin_transaction($this->_connectionID); $start -= 1; - $this->Execute("create table $seq (id int)");//was float(53) + $this->Execute("create table $seq (id int)"); //was float(53) $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)"); if (!$ok) { - if($this->debug) error_log("<hr>Error: ROLLBACK"); + if ($this->debug) error_log("<hr>Error: ROLLBACK"); sqlsrv_rollback($this->_connectionID); return false; } @@ -195,16 +199,16 @@ class ADODB_mssqlnative extends ADOConnection { return true; } - function GenID($seq='adodbseq',$start=1) + function GenID($seq = 'adodbseq', $start = 1) { - if($this->debug) error_log("<hr>GenID($seq,$start)"); + if ($this->debug) error_log("<hr>GenID($seq,$start)"); sqlsrv_begin_transaction($this->_connectionID); $ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1"); if (!$ok) { $this->Execute("create table $seq (id int)"); $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)"); if (!$ok) { - if($this->debug) error_log("<hr>Error: ROLLBACK"); + if ($this->debug) error_log("<hr>Error: ROLLBACK"); sqlsrv_rollback($this->_connectionID); return false; } @@ -213,65 +217,65 @@ class ADODB_mssqlnative extends ADOConnection { } $num = $this->GetOne("select id from $seq"); sqlsrv_commit($this->_connectionID); - if($this->debug) error_log(" Returning: $num"); + if ($this->debug) error_log(" Returning: $num"); return $num; } // Format date column in sql string given an input format that understands Y M D - function SQLDate($fmt, $col=false) + function SQLDate($fmt, $col = false) { if (!$col) $col = $this->sysTimeStamp; $s = ''; $len = strlen($fmt); - for ($i=0; $i < $len; $i++) { + for ($i = 0; $i < $len; $i++) { if ($s) $s .= '+'; $ch = $fmt[$i]; - switch($ch) { - case 'Y': - case 'y': - $s .= "datename(yyyy,$col)"; - break; - case 'M': - $s .= "convert(char(3),$col,0)"; - break; - case 'm': - $s .= "replace(str(month($col),2),' ','0')"; - break; - case 'Q': - case 'q': - $s .= "datename(quarter,$col)"; - break; - case 'D': - case 'd': - $s .= "replace(str(day($col),2),' ','0')"; - break; - case 'h': - $s .= "substring(convert(char(14),$col,0),13,2)"; - break; - - case 'H': - $s .= "replace(str(datepart(hh,$col),2),' ','0')"; - break; - - case 'i': - $s .= "replace(str(datepart(mi,$col),2),' ','0')"; - break; - case 's': - $s .= "replace(str(datepart(ss,$col),2),' ','0')"; - break; - case 'a': - case 'A': - $s .= "substring(convert(char(19),$col,0),18,2)"; - break; - - default: - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); - } - $s .= $this->qstr($ch); - break; + switch ($ch) { + case 'Y': + case 'y': + $s .= "datename(yyyy,$col)"; + break; + case 'M': + $s .= "convert(char(3),$col,0)"; + break; + case 'm': + $s .= "replace(str(month($col),2),' ','0')"; + break; + case 'Q': + case 'q': + $s .= "datename(quarter,$col)"; + break; + case 'D': + case 'd': + $s .= "replace(str(day($col),2),' ','0')"; + break; + case 'h': + $s .= "substring(convert(char(14),$col,0),13,2)"; + break; + + case 'H': + $s .= "replace(str(datepart(hh,$col),2),' ','0')"; + break; + + case 'i': + $s .= "replace(str(datepart(mi,$col),2),' ','0')"; + break; + case 's': + $s .= "replace(str(datepart(ss,$col),2),' ','0')"; + break; + case 'a': + case 'A': + $s .= "substring(convert(char(19),$col,0),18,2)"; + break; + + default: + if ($ch == '\\') { + $i++; + $ch = substr($fmt, $i, 1); + } + $s .= $this->qstr($ch); + break; } } return $s; @@ -284,10 +288,10 @@ class ADODB_mssqlnative extends ADOConnection { $this->transCnt += 1; if ($this->debug) error_log('<hr>begin transaction'); sqlsrv_begin_transaction($this->_connectionID); - return true; + return true; } - function CommitTrans($ok=true) + function CommitTrans($ok = true) { if ($this->transOff) return true; if ($this->debug) error_log('<hr>commit transaction'); @@ -296,6 +300,7 @@ class ADODB_mssqlnative extends ADOConnection { sqlsrv_commit($this->_connectionID); return true; } + function RollbackTrans() { if ($this->transOff) return true; @@ -305,15 +310,15 @@ class ADODB_mssqlnative extends ADOConnection { return true; } - function SetTransactionMode( $transaction_mode ) + function SetTransactionMode($transaction_mode) { - $this->_transmode = $transaction_mode; + $this->_transmode = $transaction_mode; if (empty($transaction_mode)) { $this->Execute('SET TRANSACTION ISOLATION LEVEL READ COMMITTED'); return; } - if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode; - $this->Execute("SET TRANSACTION ".$transaction_mode); + if (!stristr($transaction_mode, 'isolation')) $transaction_mode = 'ISOLATION LEVEL ' . $transaction_mode; + $this->Execute("SET TRANSACTION " . $transaction_mode); } /* @@ -328,7 +333,7 @@ class ADODB_mssqlnative extends ADOConnection { See http://www.swynk.com/friends/achigrik/SQL70Locks.asp */ - function RowLock($tables,$where,$col='top 1 null as ignore') + function RowLock($tables, $where, $col = 'top 1 null as ignore') { if (!$this->transCnt) $this->BeginTrans(); return $this->GetOne("select $col from $tables with (ROWLOCK,HOLDLOCK) where $where"); @@ -339,22 +344,21 @@ class ADODB_mssqlnative extends ADOConnection { $this->database = $dbName; $this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions if ($this->_connectionID) { - $rs = $this->Execute('USE '.$dbName); - if($rs) { + $rs = $this->Execute('USE ' . $dbName); + if ($rs) { return true; } else return false; - } - else return false; + } else return false; } function ErrorMsg() { $retErrors = sqlsrv_errors(SQLSRV_ERR_ALL); - if($retErrors != null) { - foreach($retErrors as $arrError) { - $this->_errorMsg .= "SQLState: ".$arrError[ 'SQLSTATE']."\n"; - $this->_errorMsg .= "Error Code: ".$arrError[ 'code']."\n"; - $this->_errorMsg .= "Message: ".$arrError[ 'message']."\n"; + if ($retErrors != null) { + foreach ($retErrors as $arrError) { + $this->_errorMsg .= "SQLState: " . $arrError['SQLSTATE'] . "\n"; + $this->_errorMsg .= "Error Code: " . $arrError['code'] . "\n"; + $this->_errorMsg .= "Message: " . $arrError['message'] . "\n"; } } else { $this->_errorMsg = "No errors found"; @@ -366,7 +370,7 @@ class ADODB_mssqlnative extends ADOConnection { { if ($this->_logsql && $this->_errorCode !== false) return $this->_errorCode; $err = sqlsrv_errors(SQLSRV_ERR_ALL); - if($err[0]) return $err[0]['code']; + if ($err[0]) return $err[0]['code']; else return -1; } @@ -374,11 +378,11 @@ class ADODB_mssqlnative extends ADOConnection { function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('sqlsrv_connect')) return null; - $connectionInfo = array("Database"=>$argDatabasename,'UID'=>$argUsername,'PWD'=>$argPassword); - if ($this->debug) error_log("<hr>connecting... hostname: $argHostname params: ".var_export($connectionInfo,true)); + $connectionInfo = array("Database" => $argDatabasename, 'UID' => $argUsername, 'PWD' => $argPassword); + if ($this->debug) error_log("<hr>connecting... hostname: $argHostname params: " . var_export($connectionInfo, true)); //if ($this->debug) error_log("<hr>_connectionID before: ".serialize($this->_connectionID)); - if(!($this->_connectionID = sqlsrv_connect($argHostname,$connectionInfo))) { - if ($this->debug) error_log( "<hr><b>errors</b>: ".print_r( sqlsrv_errors(), true)); + if (!($this->_connectionID = sqlsrv_connect($argHostname, $connectionInfo))) { + if ($this->debug) error_log("<hr><b>errors</b>: " . print_r(sqlsrv_errors(), true)); return false; } //if ($this->debug) error_log(" _connectionID after: ".serialize($this->_connectionID)); @@ -395,9 +399,9 @@ class ADODB_mssqlnative extends ADOConnection { function Prepare($sql) { - $stmt = sqlsrv_prepare( $this->_connectionID, $sql); - if (!$stmt) return $sql; - return array($sql,$stmt); + $stmt = sqlsrv_prepare($this->_connectionID, $sql); + if (!$stmt) return $sql; + return array($sql, $stmt); } // returns concatenated string @@ -418,7 +422,7 @@ class ADODB_mssqlnative extends ADOConnection { } array_walk($arr, create_function('&$v', '$v = "CAST(" . $v . " AS VARCHAR(255))";')); - $s = implode('+',$arr); + $s = implode('+', $arr); if (sizeof($arr) > 0) return "$s"; return ''; @@ -436,38 +440,38 @@ class ADODB_mssqlnative extends ADOConnection { ; Valid range 0 - 2147483647. Default = 4096. mssql.textsize = 0 ; zero to pass through */ - function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') + function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB') { if (strtoupper($blobtype) == 'CLOB') { $sql = "UPDATE $table SET $column='" . $val . "' WHERE $where"; return $this->Execute($sql) != false; } - $sql = "UPDATE $table SET $column=0x".bin2hex($val)." WHERE $where"; + $sql = "UPDATE $table SET $column=0x" . bin2hex($val) . " WHERE $where"; return $this->Execute($sql) != false; } // returns query ID if successful, otherwise false - function _query($sql,$inputarr=false) + function _query($sql, $inputarr = false) { $this->_errorMsg = false; if (is_array($inputarr)) { - $rez = sqlsrv_query($this->_connectionID,$sql,$inputarr); + $rez = sqlsrv_query($this->_connectionID, $sql, $inputarr); } elseif (is_array($sql)) { - $rez = sqlsrv_query($this->_connectionID,$sql[1],$inputarr); + $rez = sqlsrv_query($this->_connectionID, $sql[1], $inputarr); } else { - $rez = sqlsrv_query($this->_connectionID,$sql); + $rez = sqlsrv_query($this->_connectionID, $sql); } - if ($this->debug) error_log("<hr>running query: ".var_export($sql,true)."<hr>input array: ".var_export($inputarr,true)."<hr>result: ".var_export($rez,true));//"<hr>connection: ".serialize($this->_connectionID) + if ($this->debug) error_log("<hr>running query: " . var_export($sql, true) . "<hr>input array: " . var_export($inputarr, true) . "<hr>result: " . var_export($rez, true)); //"<hr>connection: ".serialize($this->_connectionID) //fix for returning true on anything besides select statements if (is_array($sql)) $sql = $sql[1]; $sql = ltrim($sql); - if(stripos($sql, 'SELECT') !== 0 && $rez !== false) { + if (stripos($sql, 'SELECT') !== 0 && $rez !== false) { if ($this->debug) error_log(" isn't a select query, returning boolean true"); return true; } //end fix - if(!$rez) $rez = false; + if (!$rez) $rez = false; return $rez; } @@ -491,7 +495,7 @@ class ADODB_mssqlnative extends ADOConnection { return ADORecordSet_array_mssql::UnixTimeStamp($v); } - function &MetaIndexes($table,$primary=false) + function &MetaIndexes($table, $primary = false) { $table = $this->qstr($table); @@ -531,7 +535,7 @@ class ADODB_mssqlnative extends ADOConnection { return $indexes; } - function MetaForeignKeys($table, $owner=false, $upper=false) + function MetaForeignKeys($table, $owner = false, $upper = false) { global $ADODB_FETCH_MODE; @@ -553,16 +557,16 @@ class ADODB_mssqlnative extends ADOConnection { $ADODB_FETCH_MODE = $save; $arr = false; - foreach($constraints as $constr) { + foreach ($constraints as $constr) { //print_r($constr); - $arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3]; + $arr[$constr[0]][$constr[2]][] = $constr[1] . '=' . $constr[3]; } if (!$arr) return false; $arr2 = false; - foreach($arr as $k => $v) { - foreach($v as $a => $b) { + foreach ($arr as $k => $v) { + foreach ($v as $a => $b) { if ($upper) $a = strtoupper($a); $arr2[$a] = $b; } @@ -577,11 +581,11 @@ class ADODB_mssqlnative extends ADOConnection { $rs =& $this->Execute($this->metaDatabasesSQL); $rows = $rs->GetRows(); $ret = array(); - for($i=0;$i<count($rows);$i++) { + for ($i = 0; $i < count($rows); $i++) { $ret[] = $rows[$i][0]; } $this->SelectDB($this->database); - if($ret) + if ($ret) return $ret; else return false; @@ -594,7 +598,7 @@ class ADODB_mssqlnative extends ADOConnection { global $ADODB_FETCH_MODE; $schema = ''; - $this->_findschema($table,$schema); + $this->_findschema($table, $schema); if (!$schema) $schema = $this->database; if ($schema) $schema = "and k.table_catalog like '$schema%'"; @@ -608,20 +612,20 @@ class ADODB_mssqlnative extends ADOConnection { $a = $this->GetCol($sql); $ADODB_FETCH_MODE = $savem; - if ($a && sizeof($a)>0) return $a; + if ($a && sizeof($a) > 0) return $a; $false = false; return $false; } - function &MetaTables($ttype=false,$showSchema=false,$mask=false) + function &MetaTables($ttype = false, $showSchema = false, $mask = false) { if ($mask) { $save = $this->metaTablesSQL; $mask = $this->qstr(($mask)); $this->metaTablesSQL .= " AND name like $mask"; } - $ret =& ADOConnection::MetaTables($ttype,$showSchema); + $ret =& ADOConnection::MetaTables($ttype, $showSchema); if ($mask) { $this->metaTablesSQL = $save; @@ -634,14 +638,16 @@ class ADODB_mssqlnative extends ADOConnection { Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordset_mssqlnative extends ADORecordSet { +class ADORecordset_mssqlnative extends ADORecordSet +{ var $databaseType = "mssqlnative"; var $canSeek = false; var $fieldOffset = 0; + // _mths works only in non-localised system - function ADORecordset_mssqlnative($id,$mode=false) + function ADORecordset_mssqlnative($id, $mode = false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -649,7 +655,7 @@ class ADORecordset_mssqlnative extends ADORecordSet { } $this->fetchMode = $mode; - return $this->ADORecordSet($id,$mode); + return $this->ADORecordSet($id, $mode); } @@ -660,9 +666,9 @@ class ADORecordset_mssqlnative extends ADORecordSet { /*$retRowsAff = sqlsrv_rows_affected($this->_queryID);//"If you need to determine the number of rows a query will return before retrieving the actual results, appending a SELECT COUNT ... query would let you get that information, and then a call to next_result would move you to the "real" results." error_log("rowsaff: ".serialize($retRowsAff)); $this->_numOfRows = ($ADODB_COUNTRECS)? $retRowsAff:-1;*/ - $this->_numOfRows = -1;//not supported + $this->_numOfRows = -1; //not supported $fieldmeta = sqlsrv_field_metadata($this->_queryID); - $this->_numOfFields = ($fieldmeta)? count($fieldmeta):-1; + $this->_numOfFields = ($fieldmeta) ? count($fieldmeta) : -1; if ($this->connection->debug) error_log("(after) _numOfRows: {$this->_numOfRows} _numOfFields: {$this->_numOfFields}"); } @@ -685,7 +691,7 @@ class ADORecordset_mssqlnative extends ADORecordSet { if ($this->fetchMode != ADODB_FETCH_NUM) return $this->fields[$colname]; if (!$this->bind) { $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { + for ($i = 0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } @@ -701,25 +707,25 @@ class ADORecordset_mssqlnative extends ADORecordSet { function &FetchField($fieldOffset = -1) { - if ($this->connection->debug) error_log("<hr>fetchfield: $fieldOffset, fetch array: <pre>".print_r($this->fields,true)."</pre> backtrace: ".adodb_backtrace(false)); + if ($this->connection->debug) error_log("<hr>fetchfield: $fieldOffset, fetch array: <pre>" . print_r($this->fields, true) . "</pre> backtrace: " . adodb_backtrace(false)); if ($fieldOffset != -1) $this->fieldOffset = $fieldOffset; $arrKeys = array_keys($this->fields); - if(array_key_exists($this->fieldOffset,$arrKeys) && !array_key_exists($arrKeys[$this->fieldOffset],$this->fields)) { + if (array_key_exists($this->fieldOffset, $arrKeys) && !array_key_exists($arrKeys[$this->fieldOffset], $this->fields)) { $f = false; } else { - $f = $this->fields[ $arrKeys[$this->fieldOffset] ]; - if($fieldOffset == -1) $this->fieldOffset++; + $f = $this->fields[$arrKeys[$this->fieldOffset]]; + if ($fieldOffset == -1) $this->fieldOffset++; } if (empty($f)) { - $f = false;//PHP Notice: Only variable references should be returned by reference + $f = false; //PHP Notice: Only variable references should be returned by reference } return $f; } function _seek($row) { - return false;//There is no support for cursors in the driver at this time. All data is returned via forward-only streams. + return false; //There is no support for cursors in the driver at this time. All data is returned via forward-only streams. } // speedup @@ -730,7 +736,7 @@ class ADORecordset_mssqlnative extends ADORecordSet { if ($this->EOF) return false; $this->_currentRow++; - if ($this->connection->debug) error_log("_currentRow: ".$this->_currentRow); + if ($this->connection->debug) error_log("_currentRow: " . $this->_currentRow); if ($this->_fetch()) return true; $this->EOF = true; @@ -742,36 +748,36 @@ class ADORecordset_mssqlnative extends ADORecordSet { // INSERT UPDATE DELETE returns false even if no error occurs in 4.0.4 // also the date format has been changed from YYYY-mm-dd to dd MMM YYYY in 4.0.4. Idiot! - function _fetch($ignore_fields=false) + function _fetch($ignore_fields = false) { if ($this->connection->debug) error_log("_fetch()"); if ($this->fetchMode & ADODB_FETCH_ASSOC) { if ($this->fetchMode & ADODB_FETCH_NUM) { if ($this->connection->debug) error_log("fetch mode: both"); - $this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_BOTH); + $this->fields = @sqlsrv_fetch_array($this->_queryID, SQLSRV_FETCH_BOTH); } else { if ($this->connection->debug) error_log("fetch mode: assoc"); - $this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_ASSOC); + $this->fields = @sqlsrv_fetch_array($this->_queryID, SQLSRV_FETCH_ASSOC); } if (ADODB_ASSOC_CASE == 0) { - foreach($this->fields as $k=>$v) { + foreach ($this->fields as $k => $v) { $this->fields[strtolower($k)] = $v; } } elseif (ADODB_ASSOC_CASE == 1) { - foreach($this->fields as $k=>$v) { + foreach ($this->fields as $k => $v) { $this->fields[strtoupper($k)] = $v; } } } else { if ($this->connection->debug) error_log("fetch mode: num"); - $this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_NUMERIC); + $this->fields = @sqlsrv_fetch_array($this->_queryID, SQLSRV_FETCH_NUMERIC); } - if(is_array($this->fields) && array_key_exists(1,$this->fields) && !array_key_exists(0,$this->fields)) {//fix fetch numeric keys since they're not 0 based + if (is_array($this->fields) && array_key_exists(1, $this->fields) && !array_key_exists(0, $this->fields)) { //fix fetch numeric keys since they're not 0 based $arrFixed = array(); - foreach($this->fields as $key=>$value) { - if(is_numeric($key)) { - $arrFixed[$key-1] = $value; + foreach ($this->fields as $key => $value) { + if (is_numeric($key)) { + $arrFixed[$key - 1] = $value; } else { $arrFixed[$key] = $value; } @@ -779,15 +785,15 @@ class ADORecordset_mssqlnative extends ADORecordSet { //if($this->connection->debug) error_log("<hr>fixing non 0 based return array, old: ".print_r($this->fields,true)." new: ".print_r($arrFixed,true)); $this->fields = $arrFixed; } - if(is_array($this->fields)) { - foreach($this->fields as $key=>$value) { - if (is_object($value) && method_exists($value, 'format')) {//is DateTime object + if (is_array($this->fields)) { + foreach ($this->fields as $key => $value) { + if (is_object($value) && method_exists($value, 'format')) { //is DateTime object $this->fields[$key] = $value->format("Y-m-d\TH:i:s\Z"); } } } - if($this->fields === null) $this->fields = false; - if ($this->connection->debug) error_log("<hr>after _fetch, fields: <pre>".print_r($this->fields,true)." backtrace: ".adodb_backtrace(false)); + if ($this->fields === null) $this->fields = false; + if ($this->connection->debug) error_log("<hr>after _fetch, fields: <pre>" . print_r($this->fields, true) . " backtrace: " . adodb_backtrace(false)); return $this->fields; } @@ -806,90 +812,93 @@ class ADORecordset_mssqlnative extends ADORecordSet { return ADORecordSet_array_mssqlnative::UnixDate($v); } - function UnixTimeStamp($v) + function UnixTimeStamp($v) { return ADORecordSet_array_mssqlnative::UnixTimeStamp($v); } } -class ADORecordSet_array_mssqlnative extends ADORecordSet_array { - function ADORecordSet_array_mssqlnative($id=-1,$mode=false) +class ADORecordSet_array_mssqlnative extends ADORecordSet_array +{ + function ADORecordSet_array_mssqlnative($id = -1, $mode = false) { - $this->ADORecordSet_array($id,$mode); + $this->ADORecordSet_array($id, $mode); } - // mssql uses a default date like Dec 30 2000 12:00AM - function UnixDate($v) + // mssql uses a default date like Dec 30 2000 12:00AM + function UnixDate($v) { - if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v); + if (is_numeric(substr($v, 0, 1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v); - global $ADODB_mssql_mths,$ADODB_mssql_date_order; + global $ADODB_mssql_mths, $ADODB_mssql_date_order; //Dec 30 2000 12:00AM if ($ADODB_mssql_date_order == 'dmy') { - if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4})|" ,$v, $rr)) { + if (!preg_match("|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4})|", $v, $rr)) { return parent::UnixDate($v); } if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; $theday = $rr[1]; - $themth = substr(strtoupper($rr[2]),0,3); + $themth = substr(strtoupper($rr[2]), 0, 3); } else { - if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})|" ,$v, $rr)) { + if (!preg_match("|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})|", $v, $rr)) { return parent::UnixDate($v); } if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; $theday = $rr[2]; - $themth = substr(strtoupper($rr[1]),0,3); + $themth = substr(strtoupper($rr[1]), 0, 3); } $themth = $ADODB_mssql_mths[$themth]; if ($themth <= 0) return false; // h-m-s-MM-DD-YY - return mktime(0,0,0,$themth,$theday,$rr[3]); + return mktime(0, 0, 0, $themth, $theday, $rr[3]); } - function UnixTimeStamp($v) + function UnixTimeStamp($v) { - if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v); + if (is_numeric(substr($v, 0, 1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v); - global $ADODB_mssql_mths,$ADODB_mssql_date_order; + global $ADODB_mssql_mths, $ADODB_mssql_date_order; //Dec 30 2000 12:00AM - if ($ADODB_mssql_date_order == 'dmy') { - if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|" - ,$v, $rr)) return parent::UnixTimeStamp($v); + if ($ADODB_mssql_date_order == 'dmy') { + if (!preg_match("|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|" + , $v, $rr) + ) return parent::UnixTimeStamp($v); if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; $theday = $rr[1]; - $themth = substr(strtoupper($rr[2]),0,3); + $themth = substr(strtoupper($rr[2]), 0, 3); } else { - if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|" - ,$v, $rr)) return parent::UnixTimeStamp($v); + if (!preg_match("|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|" + , $v, $rr) + ) return parent::UnixTimeStamp($v); if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; $theday = $rr[2]; - $themth = substr(strtoupper($rr[1]),0,3); + $themth = substr(strtoupper($rr[1]), 0, 3); } $themth = $ADODB_mssql_mths[$themth]; if ($themth <= 0) return false; switch (strtoupper($rr[6])) { - case 'P': - if ($rr[4]<12) $rr[4] += 12; - break; - case 'A': - if ($rr[4]==12) $rr[4] = 0; - break; - default: - break; + case 'P': + if ($rr[4] < 12) $rr[4] += 12; + break; + case 'A': + if ($rr[4] == 12) $rr[4] = 0; + break; + default: + break; } // h-m-s-MM-DD-YY - return mktime($rr[4],$rr[5],0,$themth,$theday,$rr[3]); + return mktime($rr[4], $rr[5], 0, $themth, $theday, $rr[3]); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-mssqlpo.inc.php b/lib/WikiDB/adodb/drivers/adodb-mssqlpo.inc.php index f8e4cc405..ab08fcac3 100644 --- a/lib/WikiDB/adodb/drivers/adodb-mssqlpo.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-mssqlpo.inc.php @@ -1,26 +1,27 @@ <?php /** -* @version V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). 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 -* -* Portable MSSQL Driver that supports || instead of + -* -*/ + * @version V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). 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 + * + * Portable MSSQL Driver that supports || instead of + + * + */ /* The big difference between mssqlpo and it's parent mssql is that mssqlpo supports the more standard || string concatenation operator. */ -include_once(ADODB_DIR.'/drivers/adodb-mssql.inc.php'); +include_once(ADODB_DIR . '/drivers/adodb-mssql.inc.php'); -class ADODB_mssqlpo extends ADODB_mssql { +class ADODB_mssqlpo extends ADODB_mssql +{ var $databaseType = "mssqlpo"; var $concat_operator = '||'; @@ -32,26 +33,28 @@ class ADODB_mssqlpo extends ADODB_mssql { function PrepareSP($sql) { if (!$this->_has_mssql_init) { - ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0"); + ADOConnection::outp("PrepareSP: mssql_init only available since PHP 4.1.0"); return $sql; } - if (is_string($sql)) $sql = str_replace('||','+',$sql); - $stmt = mssql_init($sql,$this->_connectionID); - if (!$stmt) return $sql; - return array($sql,$stmt); + if (is_string($sql)) $sql = str_replace('||', '+', $sql); + $stmt = mssql_init($sql, $this->_connectionID); + if (!$stmt) return $sql; + return array($sql, $stmt); } - function _query($sql,$inputarr) + function _query($sql, $inputarr) { - if (is_string($sql)) $sql = str_replace('||','+',$sql); - return ADODB_mssql::_query($sql,$inputarr); + if (is_string($sql)) $sql = str_replace('||', '+', $sql); + return ADODB_mssql::_query($sql, $inputarr); } } -class ADORecordset_mssqlpo extends ADORecordset_mssql { +class ADORecordset_mssqlpo extends ADORecordset_mssql +{ var $databaseType = "mssqlpo"; - function ADORecordset_mssqlpo($id,$mode=false) + + function ADORecordset_mssqlpo($id, $mode = false) { - $this->ADORecordset_mssql($id,$mode); + $this->ADORecordset_mssql($id, $mode); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-mysql.inc.php b/lib/WikiDB/adodb/drivers/adodb-mysql.inc.php index 1835ec1cd..95c3b1c97 100644 --- a/lib/WikiDB/adodb/drivers/adodb-mysql.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-mysql.inc.php @@ -12,659 +12,666 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese 28 Feb 2001: MetaColumns bug fix - suggested by Freek Dijkstra (phpeverywhere@macfreek.com) */ -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 $upperCase = 'upper'; - 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 - - function ADODB_mysql() - { - } - - 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 - } +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 $upperCase = 'upper'; + 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 + + function ADODB_mysql() + { + } - function &MetaTables($ttype=false,$showSchema=false,$mask=false) - { - if ($mask) { - $save = $this->metaTablesSQL; - $mask = $this->qstr($mask); - $this->metaTablesSQL .= " like $mask"; + function ServerInfo() + { + $arr['description'] = ADOConnection::GetOne("select version()"); + $arr['version'] = ADOConnection::_findvers($arr['description']); + return $arr; } - $ret =& ADOConnection::MetaTables($ttype,$showSchema); - if ($mask) { - $this->metaTablesSQL = $save; + function IfNull($field, $ifNull) + { + return " IFNULL($field, $ifNull) "; // if MySQL } - return $ret; - } - function &MetaIndexes ($table, $primary = FALSE, $owner=false) - { - // save old fetch mode - global $ADODB_FETCH_MODE; + function &MetaTables($ttype = false, $showSchema = false, $mask = false) + { + if ($mask) { + $save = $this->metaTablesSQL; + $mask = $this->qstr($mask); + $this->metaTablesSQL .= " like $mask"; + } + $ret =& ADOConnection::MetaTables($ttype, $showSchema); - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== FALSE) { - $savem = $this->SetFetchMode(FALSE); + if ($mask) { + $this->metaTablesSQL = $save; + } + return $ret; } - // get index details - $rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table)); + function &MetaIndexes($table, $primary = FALSE, $owner = 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); + } + + // get index details + $rs = $this->Execute(sprintf('SHOW INDEX FROM %s', $table)); - // restore fetchmode - if (isset($savem)) { + // restore fetchmode + if (isset($savem)) { $this->SetFetchMode($savem); - } - $ADODB_FETCH_MODE = $save; + } + $ADODB_FETCH_MODE = $save; - if (!is_object($rs)) { + if (!is_object($rs)) { return FALSE; - } + } - $indexes = array (); + $indexes = array(); - // parse index data into array - while ($row = $rs->FetchRow()) { + // parse index data into array + while ($row = $rs->FetchRow()) { if ($primary == FALSE AND $row[2] == 'PRIMARY') { - continue; + continue; } if (!isset($indexes[$row[2]])) { - $indexes[$row[2]] = array( - 'unique' => ($row[1] == 0), - 'columns' => array() - ); + $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']); - } + // sort columns by order in the index + foreach (array_keys($indexes) as $index) { + ksort($indexes[$index]['columns']); + } - return $indexes; - } + return $indexes; + } - // if magic quotes disabled, use mysql_real_escape_string() - function qstr($s,$magic_quotes=false) - { - if (!$magic_quotes) { + // if magic quotes disabled, use mysql_real_escape_string() + function qstr($s, $magic_quotes = false) + { + if (!$magic_quotes) { - if (ADODB_PHPVER >= 0x4300) { - if (is_resource($this->_connectionID)) - return "'".mysql_real_escape_string($s,$this->_connectionID)."'"; - } - if ($this->replaceQuote[0] == '\\'){ - $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); + 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) . "'"; } - return "'".str_replace("'",$this->replaceQuote,$s)."'"; + + // undo magic quotes for " + $s = str_replace('\\"', '"', $s); + return "'$s'"; } - // undo magic quotes for " - $s = str_replace('\\"','"',$s); - return "'$s'"; - } + function _insertid() + { + return mysql_insert_id($this->_connectionID); + } - function _insertid() - { - return mysql_insert_id($this->_connectionID); - } + function GetOne($sql, $inputarr = false) + { + $rs =& $this->SelectLimit($sql, 1, -1, $inputarr); + if ($rs) { + $rs->Close(); + if ($rs->EOF) return false; + return reset($rs->fields); + } - function GetOne($sql,$inputarr=false) - { - $rs =& $this->SelectLimit($sql,1,-1,$inputarr); - if ($rs) { - $rs->Close(); - if ($rs->EOF) return false; - return reset($rs->fields); + return false; } - return false; - } - - function _affectedrows() - { + function _affectedrows() + { return mysql_affected_rows($this->_connectionID); - } + } - // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html - // Reference on Last_Insert_ID on the recommended way to simulate sequences - var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);"; - var $_genSeqSQL = "create table %s (id int not null)"; - var $_genSeq2SQL = "insert into %s values (%s)"; - var $_dropSeqSQL = "drop table %s"; + // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html + // Reference on Last_Insert_ID on the recommended way to simulate sequences + var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);"; + var $_genSeqSQL = "create table %s (id int not null)"; + var $_genSeq2SQL = "insert into %s values (%s)"; + var $_dropSeqSQL = "drop table %s"; - function CreateSequence($seqname='adodbseq',$startID=1) - { - if (empty($this->_genSeqSQL)) return false; - $u = strtoupper($seqname); + 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)); - } + $ok = $this->Execute(sprintf($this->_genSeqSQL, $seqname)); + if (!$ok) return false; + return $this->Execute(sprintf($this->_genSeq2SQL, $seqname, $startID - 1)); + } - function GenID($seqname='adodbseq',$startID=1) - { - // post-nuke sets hasGenID to false - if (!$this->hasGenID) return false; - - $savelog = $this->_logsql; - $this->_logsql = false; - $getnext = sprintf($this->_genIDSQL,$seqname); - $holdtransOK = $this->_transOK; // save the current status - $rs = @$this->Execute($getnext); - if (!$rs) { - if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset - $u = strtoupper($seqname); - $this->Execute(sprintf($this->_genSeqSQL,$seqname)); - $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); - $rs = $this->Execute($getnext); - } - $this->genID = mysql_insert_id($this->_connectionID); + function GenID($seqname = 'adodbseq', $startID = 1) + { + // post-nuke sets hasGenID to false + if (!$this->hasGenID) return false; + + $savelog = $this->_logsql; + $this->_logsql = false; + $getnext = sprintf($this->_genIDSQL, $seqname); + $holdtransOK = $this->_transOK; // save the current status + $rs = @$this->Execute($getnext); + if (!$rs) { + if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset + $u = strtoupper($seqname); + $this->Execute(sprintf($this->_genSeqSQL, $seqname)); + $this->Execute(sprintf($this->_genSeq2SQL, $seqname, $startID - 1)); + $rs = $this->Execute($getnext); + } + $this->genID = mysql_insert_id($this->_connectionID); - if ($rs) $rs->Close(); + if ($rs) $rs->Close(); - $this->_logsql = $savelog; - return $this->genID; - } + $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; - } + 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) { - case 'Y': - case 'y': - $s .= '%Y'; - break; - case 'Q': - case 'q': - $s .= "'),Quarter($col)"; - - if ($len > $i+1) $s .= ",DATE_FORMAT($col,'"; - else $s .= ",('"; - $concat = true; - break; - case 'M': - $s .= '%b'; - break; - - case 'm': - $s .= '%m'; - break; - case 'D': - case 'd': - $s .= '%d'; - 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; - - default: - - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); + // 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) { + case 'Y': + case 'y': + $s .= '%Y'; + break; + case 'Q': + case 'q': + $s .= "'),Quarter($col)"; + + if ($len > $i + 1) $s .= ",DATE_FORMAT($col,'"; + else $s .= ",('"; + $concat = true; + break; + case 'M': + $s .= '%b'; + break; + + case 'm': + $s .= '%m'; + break; + case 'D': + case 'd': + $s .= '%d'; + 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; + + default: + + if ($ch == '\\') { + $i++; + $ch = substr($fmt, $i, 1); + } + $s .= $ch; + break; } - $s .= $ch; - break; } + $s .= "')"; + if ($concat) $s = "CONCAT($s)"; + return $s; } - $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(); + // 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 ''; - } + // 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; - return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)"; - } + function OffsetDate($dayFraction, $date = false) + { + if (!$date) $date = $this->sysDate; + return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)"; + } - // returns true or false - function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - 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 _connect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + 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 (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; - } + // returns true or false + function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + 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 _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + $this->forceNewConnect = true; + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); + } - function &MetaColumns($table) - { + function &MetaColumns($table) + { - if ($this->metaColumnsSQL) { - global $ADODB_FETCH_MODE; + if ($this->metaColumnsSQL) { + global $ADODB_FETCH_MODE; - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + $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)); + $rs = $this->Execute(sprintf($this->metaColumnsSQL, $table)); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; - if ($rs === 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 (strpos($type,',') && 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; - } else { - $fld->max_length = -1; - $fld->type = $type; - } - /* - // split type into type(length): - if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { - $fld->type = $query_array[1]; - $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; - } else { - $fld->max_length = -1; - $fld->type = $type; - }*/ - $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($fld->type,'blob') !== false); - - if (!$fld->binary) { - $d = $rs->fields[4]; - if ($d != "" && $d != "NULL") { - $fld->has_default = true; - $fld->default_value = $d; + if ($rs === 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 (strpos($type, ',') && 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; + } else { + $fld->max_length = -1; + $fld->type = $type; + } + /* + // split type into type(length): + if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; } else { - $fld->has_default = false; + $fld->max_length = -1; + $fld->type = $type; + }*/ + $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($fld->type, 'blob') !== 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(); } - if ($save == ADODB_FETCH_NUM) $retarr[] = $fld; - else $retarr[strtoupper($fld->name)] = $fld; - $rs->MoveNext(); + $rs->Close(); + return $retarr; } - $rs->Close(); - return $retarr; + return false; } - return false; - } - // returns true or false - function SelectDB($dbName) - { - $this->databaseName = $dbName; - if ($this->_connectionID) { - return @mysql_select_db($dbName,$this->_connectionID); + // returns true or false + function SelectDB($dbName) + { + $this->databaseName = $dbName; + if ($this->_connectionID) { + return @mysql_select_db($dbName, $this->_connectionID); + } else return false; } - else return false; - } - // parameters use PostgreSQL convention, not MySQL - function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0) - { - $offsetStr =($offset>=0) ? "$offset," : ''; + // parameters use PostgreSQL convention, not MySQL + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs = 0) + { + $offsetStr = ($offset >= 0) ? "$offset," : ''; - if ($secs) - $rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr); - else - $rs =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr); - return $rs; - } + if ($secs) + $rs =& $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows", $inputarr); + else + $rs =& $this->Execute($sql . " LIMIT $offsetStr$nrows", $inputarr); + return $rs; + } - // returns queryID or false - function _query($sql,$inputarr) - { - //global $ADODB_COUNTRECS; - //if($ADODB_COUNTRECS) - return mysql_query($sql,$this->_connectionID); - //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6 - } + // returns queryID or false + function _query($sql, $inputarr) + { + //global $ADODB_COUNTRECS; + //if($ADODB_COUNTRECS) + return mysql_query($sql, $this->_connectionID); + //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6 + } - /* Returns: the last error message from previous database operation */ - function ErrorMsg() - { + /* 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; - } + 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: 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; + } - // 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 C field - */ - function CharMax() - { - return 255; - } + /* + * Maximum size of X field + */ + function TextMax() + { + return 4294967295; + } - /* - * Maximum size of X field - */ - function TextMax() - { - return 4294967295; } -} + /*-------------------------------------------------------------------------------------- + Class Name: Recordset + --------------------------------------------------------------------------------------*/ -/*-------------------------------------------------------------------------------------- - Class Name: Recordset ---------------------------------------------------------------------------------------*/ + class ADORecordSet_mysql extends ADORecordSet + { -class ADORecordSet_mysql extends ADORecordSet{ + var $databaseType = "mysql"; + var $canSeek = true; - 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; + default: + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + $this->fetchMode = MYSQL_BOTH; + break; + } - function ADORecordSet_mysql($queryID,$mode=false) - { - if ($mode === false) { - global $ADODB_FETCH_MODE; - $mode = $ADODB_FETCH_MODE; + $this->ADORecordSet($queryID); } - switch ($mode) + + function _initrs() { - case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; - case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; - default: - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break; + //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); } - $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) + { - function &FetchField($fieldOffset = -1) - { + if ($fieldOffset != -1) { + $o = @mysql_fetch_field($this->_queryID, $fieldOffset); + $f = @mysql_field_flags($this->_queryID, $fieldOffset); + $o->max_length = @mysql_field_len($this->_queryID, $fieldOffset); // suggested by: Jim Nicholson (jnich@att.com) + //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable + $o->binary = (strpos($f, 'binary') !== false); + } else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ + $o = @mysql_fetch_field($this->_queryID); + $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com) + //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable + } - if ($fieldOffset != -1) { - $o = @mysql_fetch_field($this->_queryID, $fieldOffset); - $f = @mysql_field_flags($this->_queryID,$fieldOffset); - $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com) - //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable - $o->binary = (strpos($f,'binary')!== false); + return $o; } - else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ - $o = @mysql_fetch_field($this->_queryID); - $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com) - //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable - } - - return $o; - } - function &GetRowAssoc($upper=true) - { - if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $this->fields; - $row =& ADORecordSet::GetRowAssoc($upper); - return $row; - } + function &GetRowAssoc($upper = true) + { + if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $this->fields; + $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; + /* 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)]]; } - return $this->fields[$this->bind[strtoupper($colname)]]; - } - function _seek($row) - { - if ($this->_numOfRows == 0) return false; - return @mysql_data_seek($this->_queryID,$row); - } + function _seek($row) + { + if ($this->_numOfRows == 0) return false; + return @mysql_data_seek($this->_queryID, $row); + } - // 10% speedup to move MoveNext to child class - function MoveNext() - { - //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return adodb_movenext($this); + // 10% speedup to move MoveNext to child class + function MoveNext() + { + //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return adodb_movenext($this); - if ($this->EOF) return false; + if ($this->EOF) return false; - $this->_currentRow++; - $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode); - if (is_array($this->fields)) return true; + $this->_currentRow++; + $this->fields = @mysql_fetch_array($this->_queryID, $this->fetchMode); + if (is_array($this->fields)) return true; - $this->EOF = true; + $this->EOF = true; - /* -- tested raising an error -- appears pointless - $conn = $this->connection; - if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) { - $fn = $conn->raiseErrorFn; - $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database); + /* -- tested raising an error -- appears pointless + $conn = $this->connection; + if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) { + $fn = $conn->raiseErrorFn; + $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database); + } + */ + return false; } - */ - return false; - } - function _fetch() - { - $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode); - return is_array($this->fields); - } + 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 _close() + { + @mysql_free_result($this->_queryID); + $this->_queryID = false; + } - function MetaType($t,$len=-1,$fieldobj=false) - { - if (is_object($t)) { - $fieldobj = $t; - $t = $fieldobj->type; - $len = $fieldobj->max_length; - } - - $len = -1; // mysql max_length is not accurate - switch (strtoupper($t)) { - case 'STRING': - case 'CHAR': - case 'VARCHAR': - case 'TINYBLOB': - case 'TINYTEXT': - case 'ENUM': - case 'SET': - if ($len <= $this->blobSize) return 'C'; - - case 'TEXT': - case 'LONGTEXT': - case 'MEDIUMTEXT': - return 'X'; - - // php_mysql extension always returns 'blob' even if 'text' - // so we have to check whether binary... - case 'IMAGE': - case 'LONGBLOB': - case 'BLOB': - case 'MEDIUMBLOB': - return !empty($fieldobj->binary) ? 'B' : 'X'; - - case 'YEAR': - case 'DATE': return 'D'; - - case 'TIME': - case 'DATETIME': - case 'TIMESTAMP': return 'T'; - - case 'INT': - case 'INTEGER': - case 'BIGINT': - case 'TINYINT': - case 'MEDIUMINT': - case 'SMALLINT': - - if (!empty($fieldobj->primary_key)) return 'R'; - else return 'I'; - - default: return 'N'; + function MetaType($t, $len = -1, $fieldobj = false) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } + + $len = -1; // mysql max_length is not accurate + switch (strtoupper($t)) { + case 'STRING': + case 'CHAR': + case 'VARCHAR': + case 'TINYBLOB': + case 'TINYTEXT': + case 'ENUM': + case 'SET': + if ($len <= $this->blobSize) return 'C'; + + case 'TEXT': + case 'LONGTEXT': + case 'MEDIUMTEXT': + return 'X'; + + // php_mysql extension always returns 'blob' even if 'text' + // so we have to check whether binary... + case 'IMAGE': + case 'LONGBLOB': + case 'BLOB': + case 'MEDIUMBLOB': + return !empty($fieldobj->binary) ? 'B' : 'X'; + + case 'YEAR': + case 'DATE': + return 'D'; + + case 'TIME': + case 'DATETIME': + case 'TIMESTAMP': + return 'T'; + + case 'INT': + case 'INTEGER': + case 'BIGINT': + case 'TINYINT': + case 'MEDIUMINT': + case 'SMALLINT': + + if (!empty($fieldobj->primary_key)) return 'R'; + else return 'I'; + + default: + return 'N'; + } } - } -} + } } // Local Variables: diff --git a/lib/WikiDB/adodb/drivers/adodb-mysqli.inc.php b/lib/WikiDB/adodb/drivers/adodb-mysqli.inc.php index 1bf136d00..820553092 100644 --- a/lib/WikiDB/adodb/drivers/adodb-mysqli.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-mysqli.inc.php @@ -12,813 +12,787 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese 21 October 2003: MySQLi extension implementation by Arjen de Rijke (a.de.rijke@xs4all.nl) Based on adodb 3.40 */ -if (! defined("_ADODB_MYSQL_LAYER")) { - define("_ADODB_MYSQL_LAYER", 1 ); - -class ADODB_mysqli extends ADOConnection { - var $databaseType = 'mysqli'; - var $dataProvider = 'native'; - 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 $upperCase = 'upper'; - 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 $executeOnly = true; - var $substr = "substring"; - var $nameQuote = '`'; /// string to use to quote identifiers and names - //var $_bindInputArray = true; - - function ADODB_mysqli() - { - if(!extension_loaded("mysqli")) +if (!defined("_ADODB_MYSQL_LAYER")) { + define("_ADODB_MYSQL_LAYER", 1); + + class ADODB_mysqli extends ADOConnection + { + var $databaseType = 'mysqli'; + var $dataProvider = 'native'; + 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 $upperCase = 'upper'; + 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 $executeOnly = true; + var $substr = "substring"; + var $nameQuote = '`'; /// string to use to quote identifiers and names + //var $_bindInputArray = true; + + function ADODB_mysqli() { - trigger_error("You must have the MySQLi extension.", E_USER_ERROR); + if (!extension_loaded("mysqli")) { + trigger_error("You must have the MySQLi extension.", E_USER_ERROR); + } } - } - function IfNull( $field, $ifNull ) - { - return " IFNULL($field, $ifNull) "; // if MySQL - } - - function ServerInfo() - { - $arr['description'] = $this->GetOne("select version()"); - $arr['version'] = ADOConnection::_findvers($arr['description']); - return $arr; - } + function IfNull($field, $ifNull) + { + return " IFNULL($field, $ifNull) "; // if MySQL + } - function BeginTrans() - { - if ($this->transOff) return true; - $this->transCnt += 1; - $this->Execute('SET AUTOCOMMIT=0'); - $this->Execute('BEGIN'); - return true; - } + function ServerInfo() + { + $arr['description'] = $this->GetOne("select version()"); + $arr['version'] = ADOConnection::_findvers($arr['description']); + return $arr; + } - function CommitTrans($ok=true) - { - if ($this->transOff) return true; - if (!$ok) return $this->RollbackTrans(); + function BeginTrans() + { + if ($this->transOff) return true; + $this->transCnt += 1; + $this->Execute('SET AUTOCOMMIT=0'); + $this->Execute('BEGIN'); + return true; + } - if ($this->transCnt) $this->transCnt -= 1; - $this->Execute('COMMIT'); - $this->Execute('SET AUTOCOMMIT=1'); - return true; - } + function CommitTrans($ok = true) + { + if ($this->transOff) return true; + if (!$ok) return $this->RollbackTrans(); - function RollbackTrans() - { - if ($this->transOff) return true; - if ($this->transCnt) $this->transCnt -= 1; - $this->Execute('ROLLBACK'); - $this->Execute('SET AUTOCOMMIT=1'); - return true; - } + if ($this->transCnt) $this->transCnt -= 1; + $this->Execute('COMMIT'); + $this->Execute('SET AUTOCOMMIT=1'); + return true; + } - // if magic quotes disabled, use mysql_real_escape_string() - // From readme.htm: - // Quotes a string to be sent to the database. The $magic_quotes_enabled - // parameter may look funny, but the idea is if you are quoting a - // string extracted from a POST/GET variable, then - // pass get_magic_quotes_gpc() as the second parameter. This will - // ensure that the variable is not quoted twice, once by qstr and once - // by the magic_quotes_gpc. - // - //Eg. $s = $db->qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc()); - function qstr($s, $magic_quotes = false) - { - if (!$magic_quotes) { - if (ADODB_PHPVER >= 0x5000) { - // $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID); - return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'"; - } - else - { - trigger_error("phpver < 5 not implemented", E_USER_ERROR); - } - - 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 RollbackTrans() + { + if ($this->transOff) return true; + if ($this->transCnt) $this->transCnt -= 1; + $this->Execute('ROLLBACK'); + $this->Execute('SET AUTOCOMMIT=1'); + return true; + } - function _insertid() - { -// $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID); - $result = @mysqli_insert_id($this->_connectionID); - if ($result == -1){ - if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : " . $this->ErrorMsg()); - } - return $result; - } + // if magic quotes disabled, use mysql_real_escape_string() + // From readme.htm: + // Quotes a string to be sent to the database. The $magic_quotes_enabled + // parameter may look funny, but the idea is if you are quoting a + // string extracted from a POST/GET variable, then + // pass get_magic_quotes_gpc() as the second parameter. This will + // ensure that the variable is not quoted twice, once by qstr and once + // by the magic_quotes_gpc. + // + //Eg. $s = $db->qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc()); + function qstr($s, $magic_quotes = false) + { + if (!$magic_quotes) { + if (ADODB_PHPVER >= 0x5000) { + // $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID); + return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'"; + } else { + trigger_error("phpver < 5 not implemented", E_USER_ERROR); + } - // Only works for INSERT, UPDATE and DELETE query's - function _affectedrows() - { - // $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID); - $result = @mysqli_affected_rows($this->_connectionID); - if ($result == -1) { - if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : " . $this->ErrorMsg()); - } - return $result; - } + 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'"; + } - // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html - // Reference on Last_Insert_ID on the recommended way to simulate sequences - var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);"; - var $_genSeqSQL = "create table %s (id int not null)"; - var $_genSeq2SQL = "insert into %s values (%s)"; - var $_dropSeqSQL = "drop table %s"; + function _insertid() + { +// $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID); + $result = @mysqli_insert_id($this->_connectionID); + if ($result == -1) { + if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : " . $this->ErrorMsg()); + } + return $result; + } - function CreateSequence($seqname='adodbseq',$startID=1) - { - if (empty($this->_genSeqSQL)) return false; - $u = strtoupper($seqname); + // Only works for INSERT, UPDATE and DELETE query's + function _affectedrows() + { + // $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID); + $result = @mysqli_affected_rows($this->_connectionID); + if ($result == -1) { + if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : " . $this->ErrorMsg()); + } + return $result; + } - $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); - if (!$ok) return false; - return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); - } + // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html + // Reference on Last_Insert_ID on the recommended way to simulate sequences + var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);"; + var $_genSeqSQL = "create table %s (id int not null)"; + var $_genSeq2SQL = "insert into %s values (%s)"; + var $_dropSeqSQL = "drop table %s"; - function GenID($seqname='adodbseq',$startID=1) - { - // post-nuke sets hasGenID to false - if (!$this->hasGenID) return 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 + function CreateSequence($seqname = 'adodbseq', $startID = 1) + { + if (empty($this->_genSeqSQL)) return false; $u = strtoupper($seqname); - $this->Execute(sprintf($this->_genSeqSQL,$seqname)); - $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); - $rs = $this->Execute($getnext); + + $ok = $this->Execute(sprintf($this->_genSeqSQL, $seqname)); + if (!$ok) return false; + return $this->Execute(sprintf($this->_genSeq2SQL, $seqname, $startID - 1)); } - $this->genID = mysqli_insert_id($this->_connectionID); - if ($rs) $rs->Close(); + function GenID($seqname = 'adodbseq', $startID = 1) + { + // post-nuke sets hasGenID to false + if (!$this->hasGenID) return false; + + $getnext = sprintf($this->_genIDSQL, $seqname); + $holdtransOK = $this->_transOK; // save the current status + $rs = @$this->Execute($getnext); + if (!$rs) { + if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset + $u = strtoupper($seqname); + $this->Execute(sprintf($this->_genSeqSQL, $seqname)); + $this->Execute(sprintf($this->_genSeq2SQL, $seqname, $startID - 1)); + $rs = $this->Execute($getnext); + } + $this->genID = mysqli_insert_id($this->_connectionID); + + if ($rs) $rs->Close(); - return $this->genID; - } + return $this->genID; + } - function &MetaDatabases() - { - $query = "SHOW DATABASES"; - $ret =& $this->Execute($query); - return $ret; - } + function &MetaDatabases() + { + $query = "SHOW DATABASES"; + $ret =& $this->Execute($query); + return $ret; + } - function &MetaIndexes ($table, $primary = FALSE) - { + function &MetaIndexes($table, $primary = 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); + $savem = $this->SetFetchMode(FALSE); } // get index details - $rs = $this->Execute(sprintf('SHOW INDEXES FROM %s',$table)); + $rs = $this->Execute(sprintf('SHOW INDEXES FROM %s', $table)); // restore fetchmode if (isset($savem)) { - $this->SetFetchMode($savem); + $this->SetFetchMode($savem); } $ADODB_FETCH_MODE = $save; if (!is_object($rs)) { - return FALSE; + return FALSE; } - $indexes = array (); + $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]; + 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']); + foreach (array_keys($indexes) as $index) { + ksort($indexes[$index]['columns']); } return $indexes; - } + } - // 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) { - case 'Y': - case 'y': - $s .= '%Y'; - break; - case 'Q': - case 'q': - $s .= "'),Quarter($col)"; - - if ($len > $i+1) $s .= ",DATE_FORMAT($col,'"; - else $s .= ",('"; - $concat = true; - break; - case 'M': - $s .= '%b'; - break; - - case 'm': - $s .= '%m'; - break; - case 'D': - case 'd': - $s .= '%d'; - 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; - - default: - - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); + // 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) { + case 'Y': + case 'y': + $s .= '%Y'; + break; + case 'Q': + case 'q': + $s .= "'),Quarter($col)"; + + if ($len > $i + 1) $s .= ",DATE_FORMAT($col,'"; + else $s .= ",('"; + $concat = true; + break; + case 'M': + $s .= '%b'; + break; + + case 'm': + $s .= '%m'; + break; + case 'D': + case 'd': + $s .= '%d'; + 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; + + default: + + if ($ch == '\\') { + $i++; + $ch = substr($fmt, $i, 1); + } + $s .= $ch; + break; } - $s .= $ch; - break; } + $s .= "')"; + if ($concat) $s = "CONCAT($s)"; + return $s; } - $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(); + // 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 ''; - } + // suggestion by andrew005@mnogo.ru + $s = implode(',', $arr); + if (strlen($s) > 0) return "CONCAT($s)"; + else return ''; + } - // dayFraction is a day in floating point - function OffsetDate($dayFraction,$date=false) - { - if (!$date) - $date = $this->sysDate; - return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)"; - } + // dayFraction is a day in floating point + function OffsetDate($dayFraction, $date = false) + { + if (!$date) + $date = $this->sysDate; + return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)"; + } - // returns true or false - // To add: parameter int $port, - // parameter string $socket - function _connect($argHostname = NULL, - $argUsername = NULL, - $argPassword = NULL, - $argDatabasename = NULL) - { - // @ means: error surpression on - $this->_connectionID = @mysqli_init(); - - if (is_null($this->_connectionID)) - { - // mysqli_init only fails if insufficient memory - if ($this->debug) - ADOConnection::outp("mysqli_init() failed : " . $this->ErrorMsg()); - return false; - } - // Set connection options - // Not implemented now - // mysqli_options($this->_connection,,); - if (mysqli_real_connect($this->_connectionID, - $argHostname, - $argUsername, - $argPassword, - $argDatabasename)) - { - if ($argDatabasename) - { - return $this->SelectDB($argDatabasename); - } - - return true; - } - else - { - if ($this->debug) - ADOConnection::outp("Could't connect : " . $this->ErrorMsg()); - return false; - } - } - - // returns true or false - // How to force a persistent connection - function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - // not implemented in mysqli (yet)? - $this->_connectionID = mysqli_connect($argHostname, - $argUsername, - $argPassword, - $argDatabasename); - if ($this->_connectionID === false) return false; - // if ($this->autoRollback) $this->RollbackTrans(); - if ($argDatabasename) return $this->SelectDB($argDatabasename); - return true; - } - - // When is this used? Close old connection first? - // In _connect(), check $this->forceNewConnect? - function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - $this->forceNewConnect = true; - $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); - } - - function &MetaColumns($table) - { - if ($this->metaColumnsSQL) { - global $ADODB_FETCH_MODE; - $save = $ADODB_FETCH_MODE; - $rs = false; - switch($ADODB_FETCH_MODE) - { - case ADODB_FETCH_NUM: - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - $rs = $this->Execute(sprintf($this->metaColumnsSQL, - $table)); - - $ADODB_FETCH_MODE = $save; - if ($rs === false) break; - $retarr = array(); - while (!$rs->EOF){ - $fld = new ADOFieldObject(); - $fld->name = $rs->fields[0]; - $fld->type = $rs->fields[1]; - // split type into type(length): - if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) - { - $fld->type = $query_array[1]; - $fld->max_length = $query_array[2]; - } - else - { - $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($fld->type,'blob') !== false); - if (!$fld->binary) - { - $d = $rs->fields[4]; - $d = $rs->fields['Default']; - if ($d != "" && $d != "NULL") - { - $fld->has_default = true; - $fld->default_value = $d; - } - else - { - $fld->has_default = false; - } - } - $retarr[strtoupper($fld->name)] = $fld; - $rs->MoveNext(); - } - break; - case ADODB_FETCH_ASSOC: - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH: - $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; - $rs = $this->Execute(sprintf($this->metaColumnsSQL, - $table)); - $ADODB_FETCH_MODE = $save; - if ($rs === false) break; - $retarr = array(); - while (!$rs->EOF){ - $fld = new ADOFieldObject(); - $fld->name = $rs->fields['Field']; - $fld->type = $rs->fields['Type']; - - // split type into type(length): - if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) - { - $fld->type = $query_array[1]; - $fld->max_length = $query_array[2]; - } - else - { - $fld->max_length = -1; - } - $fld->not_null = ($rs->fields['Null'] != 'YES'); - $fld->primary_key = ($rs->fields['Key'] == 'PRI'); - $fld->auto_increment = (strpos($rs->fields['Extra'], 'auto_increment') !== false); - $fld->binary = (strpos($fld->type,'blob') !== false); - if (!$fld->binary) - { - $d = $rs->fields['Default']; - if ($d != "" && $d != "NULL") - { - $fld->has_default = true; - $fld->default_value = $d; + // returns true or false + // To add: parameter int $port, + // parameter string $socket + function _connect($argHostname = NULL, + $argUsername = NULL, + $argPassword = NULL, + $argDatabasename = NULL) + { + // @ means: error surpression on + $this->_connectionID = @mysqli_init(); + + if (is_null($this->_connectionID)) { + // mysqli_init only fails if insufficient memory + if ($this->debug) + ADOConnection::outp("mysqli_init() failed : " . $this->ErrorMsg()); + return false; } - else - { - $fld->has_default = false; + // Set connection options + // Not implemented now + // mysqli_options($this->_connection,,); + if (mysqli_real_connect($this->_connectionID, + $argHostname, + $argUsername, + $argPassword, + $argDatabasename) + ) { + if ($argDatabasename) { + return $this->SelectDB($argDatabasename); + } + + return true; + } else { + if ($this->debug) + ADOConnection::outp("Could't connect : " . $this->ErrorMsg()); + return false; } + } + + // returns true or false + // How to force a persistent connection + function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + // not implemented in mysqli (yet)? + $this->_connectionID = mysqli_connect($argHostname, + $argUsername, + $argPassword, + $argDatabasename); + if ($this->_connectionID === false) return false; + // if ($this->autoRollback) $this->RollbackTrans(); + if ($argDatabasename) return $this->SelectDB($argDatabasename); + return true; + } + + // When is this used? Close old connection first? + // In _connect(), check $this->forceNewConnect? + function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + $this->forceNewConnect = true; + $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); + } + + function &MetaColumns($table) + { + if ($this->metaColumnsSQL) { + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $rs = false; + switch ($ADODB_FETCH_MODE) { + case ADODB_FETCH_NUM: + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + $rs = $this->Execute(sprintf($this->metaColumnsSQL, + $table)); + + $ADODB_FETCH_MODE = $save; + if ($rs === false) break; + $retarr = array(); + while (!$rs->EOF) { + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $fld->type = $rs->fields[1]; + // split type into type(length): + if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = $query_array[2]; + } else { + $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($fld->type, 'blob') !== false); + if (!$fld->binary) { + $d = $rs->fields[4]; + $d = $rs->fields['Default']; + if ($d != "" && $d != "NULL") { + $fld->has_default = true; + $fld->default_value = $d; + } else { + $fld->has_default = false; + } + } + $retarr[strtoupper($fld->name)] = $fld; + $rs->MoveNext(); + } + break; + case ADODB_FETCH_ASSOC: + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + $rs = $this->Execute(sprintf($this->metaColumnsSQL, + $table)); + $ADODB_FETCH_MODE = $save; + if ($rs === false) break; + $retarr = array(); + while (!$rs->EOF) { + $fld = new ADOFieldObject(); + $fld->name = $rs->fields['Field']; + $fld->type = $rs->fields['Type']; + + // split type into type(length): + if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = $query_array[2]; + } else { + $fld->max_length = -1; + } + $fld->not_null = ($rs->fields['Null'] != 'YES'); + $fld->primary_key = ($rs->fields['Key'] == 'PRI'); + $fld->auto_increment = (strpos($rs->fields['Extra'], 'auto_increment') !== false); + $fld->binary = (strpos($fld->type, 'blob') !== false); + if (!$fld->binary) { + $d = $rs->fields['Default']; + if ($d != "" && $d != "NULL") { + $fld->has_default = true; + $fld->default_value = $d; + } else { + $fld->has_default = false; + } + } + $retarr[strtoupper($fld->name)] = $fld; + $rs->MoveNext(); + } + break; + default: + } + + if ($rs === false) return false; + $rs->Close(); + return $retarr; } - $retarr[strtoupper($fld->name)] = $fld; - $rs->MoveNext(); - } - break; - default: - } - - if ($rs === false) return false; - $rs->Close(); - return $retarr; - } - return false; - } + return false; + } - // returns true or false - function SelectDB($dbName) - { + // returns true or false + function SelectDB($dbName) + { // $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID); - $this->databaseName = $dbName; - if ($this->_connectionID) { - $result = @mysqli_select_db($this->_connectionID, $dbName); - if (!$result) { - ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->ErrorMsg()); + $this->databaseName = $dbName; + if ($this->_connectionID) { + $result = @mysqli_select_db($this->_connectionID, $dbName); + if (!$result) { + ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->ErrorMsg()); + } + return $result; } - return $result; + return false; } - return false; - } - // parameters use PostgreSQL convention, not MySQL - function &SelectLimit($sql, - $nrows = -1, - $offset = -1, - $inputarr = false, - $arg3 = false, - $secs = 0) - { - $offsetStr = ($offset >= 0) ? "$offset," : ''; + // parameters use PostgreSQL convention, not MySQL + function &SelectLimit($sql, + $nrows = -1, + $offset = -1, + $inputarr = false, + $arg3 = false, + $secs = 0) + { + $offsetStr = ($offset >= 0) ? "$offset," : ''; - if ($secs) - $rs =& $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3); - else - $rs =& $this->Execute($sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3); + if ($secs) + $rs =& $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows", $inputarr, $arg3); + else + $rs =& $this->Execute($sql . " LIMIT $offsetStr$nrows", $inputarr, $arg3); - return $rs; - } + return $rs; + } - function Prepare($sql) - { - return $sql; + function Prepare($sql) + { + return $sql; - $stmt = mysqli_prepare($this->_connectionID,$sql); - if (!$stmt) return false; - return array($sql,$stmt); - } + $stmt = mysqli_prepare($this->_connectionID, $sql); + if (!$stmt) return false; + return array($sql, $stmt); + } - // returns queryID or false - function _query($sql, $inputarr) - { - global $ADODB_COUNTRECS; + // returns queryID or false + function _query($sql, $inputarr) + { + global $ADODB_COUNTRECS; - if (is_array($sql)) { - $stmt = $sql[1]; - foreach($inputarr as $k => $v) { - if (is_string($v)) $a[] = MYSQLI_BIND_STRING; - else if (is_integer($v)) $a[] = MYSQLI_BIND_INT; - else $a[] = MYSQLI_BIND_DOUBLE; + if (is_array($sql)) { + $stmt = $sql[1]; + foreach ($inputarr as $k => $v) { + if (is_string($v)) $a[] = MYSQLI_BIND_STRING; + else if (is_integer($v)) $a[] = MYSQLI_BIND_INT; + else $a[] = MYSQLI_BIND_DOUBLE; - $fnarr =& array_merge( array($stmt,$a) , $inputarr); - $ret = call_user_func_array('mysqli_bind_param',$fnarr); + $fnarr =& array_merge(array($stmt, $a), $inputarr); + $ret = call_user_func_array('mysqli_bind_param', $fnarr); + } + $ret = mysqli_execute($stmt); + return $ret; } - $ret = mysqli_execute($stmt); - return $ret; - } - if (!$mysql_res = mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) { - if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg()); - return false; + if (!$mysql_res = mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) { + if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg()); + return false; + } + + return $mysql_res; } - return $mysql_res; - } + /* Returns: the last error message from previous database operation */ + function ErrorMsg() + { + if (empty($this->_connectionID)) + $this->_errorMsg = @mysqli_error(); + else + $this->_errorMsg = @mysqli_error($this->_connectionID); + return $this->_errorMsg; + } - /* Returns: the last error message from previous database operation */ - function ErrorMsg() - { - if (empty($this->_connectionID)) - $this->_errorMsg = @mysqli_error(); - else - $this->_errorMsg = @mysqli_error($this->_connectionID); - return $this->_errorMsg; - } - - /* Returns: the last error number from previous database operation */ - function ErrorNo() - { - if (empty($this->_connectionID)) - return @mysqli_errno(); - else - return @mysqli_errno($this->_connectionID); - } - - // returns true or false - function _close() - { - @mysqli_close($this->_connectionID); - $this->_connectionID = false; - } - - /* - * Maximum size of C field - */ - function CharMax() - { - return 255; - } + /* Returns: the last error number from previous database operation */ + function ErrorNo() + { + if (empty($this->_connectionID)) + return @mysqli_errno(); + else + return @mysqli_errno($this->_connectionID); + } - /* - * Maximum size of X field - */ - function TextMax() - { - return 4294967295; - } + // returns true or false + function _close() + { + @mysqli_close($this->_connectionID); + $this->_connectionID = false; + } + /* + * Maximum size of C field + */ + function CharMax() + { + return 255; + } -} + /* + * Maximum size of X field + */ + function TextMax() + { + return 4294967295; + } -/*-------------------------------------------------------------------------------------- - Class Name: Recordset ---------------------------------------------------------------------------------------*/ -class ADORecordSet_mysqli extends ADORecordSet{ + } - var $databaseType = "mysqli"; - var $canSeek = true; + /*-------------------------------------------------------------------------------------- + Class Name: Recordset + --------------------------------------------------------------------------------------*/ - function ADORecordSet_mysqli($queryID, $mode = false) + class ADORecordSet_mysqli extends ADORecordSet { - if ($mode === false) - { - global $ADODB_FETCH_MODE; - $mode = $ADODB_FETCH_MODE; - } - switch ($mode) - { - case ADODB_FETCH_NUM: - $this->fetchMode = MYSQLI_NUM; - break; - case ADODB_FETCH_ASSOC: - $this->fetchMode = MYSQLI_ASSOC; - break; - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH: - default: - $this->fetchMode = MYSQLI_ASSOC; - break; - } - $this->ADORecordSet($queryID); - } - function _initrs() - { - // mysqli_num_rows only return correct number, depens - // on the use of mysql_store_result and mysql_use_result - if (!$this->Connection->executeOnly) { - $this->_numOfRows = @mysqli_num_rows($this->_queryID); - $this->_numOfFields = @mysqli_num_fields($this->_queryID); - } - else { - $this->_numOfRows = 0; - $this->_numOfFields = 0; + var $databaseType = "mysqli"; + var $canSeek = true; + + function ADORecordSet_mysqli($queryID, $mode = false) + { + if ($mode === false) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } + switch ($mode) { + case ADODB_FETCH_NUM: + $this->fetchMode = MYSQLI_NUM; + break; + case ADODB_FETCH_ASSOC: + $this->fetchMode = MYSQLI_ASSOC; + break; + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + default: + $this->fetchMode = MYSQLI_ASSOC; + break; + } + $this->ADORecordSet($queryID); } - } - function &FetchField($fieldOffset = -1) - { - $fieldnr = $fieldOffset; - if ($fieldOffset != -1) { - $fieldOffset = mysqi_field_seek($this->_queryID, $fieldnr); - } - $o = mysqli_fetch_field($this->_queryID); - return $o; - } + function _initrs() + { + // mysqli_num_rows only return correct number, depens + // on the use of mysql_store_result and mysql_use_result + if (!$this->Connection->executeOnly) { + $this->_numOfRows = @mysqli_num_rows($this->_queryID); + $this->_numOfFields = @mysqli_num_fields($this->_queryID); + } else { + $this->_numOfRows = 0; + $this->_numOfFields = 0; + } + } - function &GetRowAssoc($upper = true) - { - if ($this->fetchMode == MYSQLI_ASSOC && !$upper) - return $this->fields; - $row =& ADORecordSet::GetRowAssoc($upper); - return $row; - } + function &FetchField($fieldOffset = -1) + { + $fieldnr = $fieldOffset; + if ($fieldOffset != -1) { + $fieldOffset = mysqi_field_seek($this->_queryID, $fieldnr); + } + $o = mysqli_fetch_field($this->_queryID); + return $o; + } - /* Use associative array to get fields array */ - function Fields($colname) - { - if ($this->fetchMode != MYSQLI_NUM) - return @$this->fields[$colname]; + function &GetRowAssoc($upper = true) + { + if ($this->fetchMode == MYSQLI_ASSOC && !$upper) + return $this->fields; + $row =& ADORecordSet::GetRowAssoc($upper); + return $row; + } - if (!$this->bind) { - $this->bind = array(); - for ($i = 0; $i < $this->_numOfFields; $i++) { - $o = $this->FetchField($i); - $this->bind[strtoupper($o->name)] = $i; + /* Use associative array to get fields array */ + function Fields($colname) + { + if ($this->fetchMode != MYSQLI_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)]]; } - } - return $this->fields[$this->bind[strtoupper($colname)]]; - } - function _seek($row) - { - if ($this->_numOfRows == 0) - return false; + function _seek($row) + { + if ($this->_numOfRows == 0) + return false; - if ($row < 0) - return false; + if ($row < 0) + return false; - mysqli_data_seek($this->_queryID, $row); - $this->EOF = false; - return true; - } + mysqli_data_seek($this->_queryID, $row); + $this->EOF = false; + return true; + } - // 10% speedup to move MoveNext to child class - // This is the only implementation that works now (23-10-2003). - // Other functions return no or the wrong results. - function MoveNext() - { - if ($this->EOF) - return false; - $this->_currentRow++; - switch($this->fetchMode) - { - case MYSQLI_NUM: - $this->fields = mysqli_fetch_array($this->_queryID); - break; - case MYSQLI_ASSOC: - case MYSQLI_BOTH: - $this->fields = mysqli_fetch_assoc($this->_queryID); - break; - default: - } - if (is_array($this->fields)) - return true; - $this->EOF = true; - return false; - } + // 10% speedup to move MoveNext to child class + // This is the only implementation that works now (23-10-2003). + // Other functions return no or the wrong results. + function MoveNext() + { + if ($this->EOF) + return false; + $this->_currentRow++; + switch ($this->fetchMode) { + case MYSQLI_NUM: + $this->fields = mysqli_fetch_array($this->_queryID); + break; + case MYSQLI_ASSOC: + case MYSQLI_BOTH: + $this->fields = mysqli_fetch_assoc($this->_queryID); + break; + default: + } + if (is_array($this->fields)) + return true; + $this->EOF = true; + return false; + } - function _fetch() - { - // mysqli_fetch_array($this->_queryID, MYSQLI_NUM) does not - // work (22-10-2003). But mysqli_fetch_array($this->_queryID) gives - // int resulttype should default to MYSQLI_BOTH,but give MYSQLI_NUM. + function _fetch() + { + // mysqli_fetch_array($this->_queryID, MYSQLI_NUM) does not + // work (22-10-2003). But mysqli_fetch_array($this->_queryID) gives + // int resulttype should default to MYSQLI_BOTH,but give MYSQLI_NUM. - // $this->fields = mysqli_fetch_fields($this->_queryID); - // $this->fields = mysqli_fetch_array($this->_queryID); //, $this->fetchMode); + // $this->fields = mysqli_fetch_fields($this->_queryID); + // $this->fields = mysqli_fetch_array($this->_queryID); //, $this->fetchMode); - $this->fields = mysqli_fetch_assoc($this->_queryID); // $this->fetchMode); - return is_array($this->fields); - } + $this->fields = mysqli_fetch_assoc($this->_queryID); // $this->fetchMode); + return is_array($this->fields); + } - function _close() - { - mysqli_free_result($this->_queryID); - $this->_queryID = false; - } + function _close() + { + mysqli_free_result($this->_queryID); + $this->_queryID = false; + } - function MetaType($t, $len = -1, $fieldobj = false) - { - if (is_object($t)) - { - $fieldobj = $t; - $t = $fieldobj->type; - $len = $fieldobj->max_length; - } - - $len = -1; // mysql max_length is not accurate - switch (strtoupper($t)) { - case 'STRING': - case 'CHAR': - case 'VARCHAR': - case 'TINYBLOB': - case 'TINYTEXT': - case 'ENUM': - case 'SET': - if ($len <= $this->blobSize) return 'C'; - - case 'TEXT': - case 'LONGTEXT': - case 'MEDIUMTEXT': - return 'X'; - - // php_mysql extension always returns 'blob' even if 'text' - // so we have to check whether binary... - case 'IMAGE': - case 'LONGBLOB': - case 'BLOB': - case 'MEDIUMBLOB': - return !empty($fieldobj->binary) ? 'B' : 'X'; - case 'YEAR': - case 'DATE': - return 'D'; - - case 'TIME': - case 'DATETIME': - case 'TIMESTAMP': return 'T'; - - case 'INT': - case 'INTEGER': - case 'BIGINT': - case 'TINYINT': - case 'MEDIUMINT': - case 'SMALLINT': - - if (!empty($fieldobj->primary_key)) return 'R'; - else return 'I'; - // Added floating-point types - // Maybe not necessery. - case 'FLOAT': - case 'DOUBLE': - // case 'DOUBLE PRECISION': - case 'DECIMAL': - case 'DEC': - case 'FIXED': - default: - return 'N'; - } - } + function MetaType($t, $len = -1, $fieldobj = false) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } -} + $len = -1; // mysql max_length is not accurate + switch (strtoupper($t)) { + case 'STRING': + case 'CHAR': + case 'VARCHAR': + case 'TINYBLOB': + case 'TINYTEXT': + case 'ENUM': + case 'SET': + if ($len <= $this->blobSize) return 'C'; + + case 'TEXT': + case 'LONGTEXT': + case 'MEDIUMTEXT': + return 'X'; + + // php_mysql extension always returns 'blob' even if 'text' + // so we have to check whether binary... + case 'IMAGE': + case 'LONGBLOB': + case 'BLOB': + case 'MEDIUMBLOB': + return !empty($fieldobj->binary) ? 'B' : 'X'; + case 'YEAR': + case 'DATE': + return 'D'; + + case 'TIME': + case 'DATETIME': + case 'TIMESTAMP': + return 'T'; + + case 'INT': + case 'INTEGER': + case 'BIGINT': + case 'TINYINT': + case 'MEDIUMINT': + case 'SMALLINT': + + if (!empty($fieldobj->primary_key)) return 'R'; + else return 'I'; + // Added floating-point types + // Maybe not necessery. + case 'FLOAT': + case 'DOUBLE': + // case 'DOUBLE PRECISION': + case 'DECIMAL': + case 'DEC': + case 'FIXED': + default: + return 'N'; + } + } + + } } diff --git a/lib/WikiDB/adodb/drivers/adodb-mysqlt.inc.php b/lib/WikiDB/adodb/drivers/adodb-mysqlt.inc.php index 859954602..fd880c3f9 100644 --- a/lib/WikiDB/adodb/drivers/adodb-mysqlt.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-mysqlt.inc.php @@ -13,9 +13,10 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese Requires mysql client. Works on Windows and Unix. */ -include_once(ADODB_DIR."/drivers/adodb-mysql.inc.php"); +include_once(ADODB_DIR . "/drivers/adodb-mysql.inc.php"); -class ADODB_mysqlt extends ADODB_mysql { +class ADODB_mysqlt extends ADODB_mysql +{ var $databaseType = 'mysqlt'; var $ansiOuter = true; // for Version 3.23.17 or later var $hasTransactions = true; @@ -29,7 +30,7 @@ class ADODB_mysqlt extends ADODB_mysql { return true; } - function CommitTrans($ok=true) + function CommitTrans($ok = true) { if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); @@ -51,11 +52,13 @@ class ADODB_mysqlt extends ADODB_mysql { } -class ADORecordSet_mysqlt extends ADORecordSet_mysql{ +class ADORecordSet_mysqlt extends ADORecordSet_mysql +{ var $databaseType = "mysqlt"; - function ADORecordSet_mysqlt($queryID,$mode=false) { - return $this->ADORecordSet_mysql($queryID,$mode); + function ADORecordSet_mysqlt($queryID, $mode = false) + { + return $this->ADORecordSet_mysql($queryID, $mode); } function MoveNext() @@ -64,7 +67,7 @@ class ADORecordSet_mysqlt extends ADORecordSet_mysql{ $this->_currentRow++; // using & below slows things down by 20%! - $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode); + $this->fields = @mysql_fetch_array($this->_queryID, $this->fetchMode); if ($this->fields) return true; $this->EOF = true; diff --git a/lib/WikiDB/adodb/drivers/adodb-netezza.inc.php b/lib/WikiDB/adodb/drivers/adodb-netezza.inc.php index 17aa49b6b..1e180a810 100644 --- a/lib/WikiDB/adodb/drivers/adodb-netezza.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-netezza.inc.php @@ -16,16 +16,17 @@ */ -include_once(ADODB_DIR.'/drivers/adodb-postgres64.inc.php'); +include_once(ADODB_DIR . '/drivers/adodb-postgres64.inc.php'); -class ADODB_netezza extends ADODB_postgres64 { +class ADODB_netezza extends ADODB_postgres64 +{ var $databaseType = 'netezza'; var $dataProvider = 'netezza'; var $hasInsertID = false; var $_resultid = false; - var $concat_operator='||'; - var $random = 'random'; - var $upperCase = 'upper'; + var $concat_operator = '||'; + var $random = 'random'; + var $upperCase = 'upper'; var $metaDatabasesSQL = "select objname from _v_object_data where objtype='database' order by 1"; var $metaTablesSQL = "select objname from _v_object_data where objtype='table' order by 1"; var $isoDates = true; // accepts dates in ISO format @@ -39,26 +40,26 @@ class ADODB_netezza extends ADODB_postgres64 { var $metaKeySQL = ""; var $hasAffectedRows = true; var $hasLimit = true; - var $true = 't'; // string that represents TRUE for a database - var $false = 'f'; // string that represents FALSE for a database - var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database + var $true = 't'; // string that represents TRUE for a database + var $false = 'f'; // string that represents FALSE for a database + var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt. var $ansiOuter = true; var $autoRollback = true; // apparently pgsql does not autorollback properly before 4.3.4 - // http://bugs.php.net/bug.php?id=25404 + // http://bugs.php.net/bug.php?id=25404 function ADODB_netezza() { } - function &MetaColumns($table,$upper=true) + function &MetaColumns($table, $upper = true) { - // Changed this function to support Netezza which has no concept of keys - // could posisbly work on other things from the system table later. + // Changed this function to support Netezza which has no concept of keys + // could posisbly work on other things from the system table later. - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $table = strtolower($table); @@ -66,7 +67,7 @@ class ADODB_netezza extends ADODB_postgres64 { $ADODB_FETCH_MODE = ADODB_FETCH_NUM; if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table)); + $rs =& $this->Execute(sprintf($this->metaColumnsSQL, $table, $table)); if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; @@ -81,39 +82,39 @@ class ADODB_netezza extends ADODB_postgres64 { // split them out here. if ($first = strstr($rs->fields[1], "(")) { - $fld->max_length = trim($first, "()"); + $fld->max_length = trim($first, "()"); } else { - $fld->max_length = -1; + $fld->max_length = -1; } if ($first = strpos($rs->fields[1], "(")) { - $fld->type = substr($rs->fields[1], 0, $first); + $fld->type = substr($rs->fields[1], 0, $first); } else { - $fld->type = $rs->fields[1]; + $fld->type = $rs->fields[1]; } switch ($fld->type) { - case "byteint": - case "boolean": - $fld->max_length = 1; - break; - case "smallint": - $fld->max_length = 2; - break; - case "integer": - case "numeric": - case "date": - $fld->max_length = 4; - break; - case "bigint": - case "time": - case "timestamp": - $fld->max_length = 8; - break; - case "timetz": - case "time with time zone": - $fld->max_length = 12; - break; + case "byteint": + case "boolean": + $fld->max_length = 1; + break; + case "smallint": + $fld->max_length = 2; + break; + case "integer": + case "numeric": + case "date": + $fld->max_length = 4; + break; + case "bigint": + case "time": + case "timestamp": + $fld->max_length = 8; + break; + case "timetz": + case "time with time zone": + $fld->max_length = 12; + break; } if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; @@ -137,19 +138,24 @@ class ADORecordSet_netezza extends ADORecordSet_postgres64 var $databaseType = "netezza"; var $canSeek = true; - function ADORecordSet_netezza($queryID,$mode=false) + function ADORecordSet_netezza($queryID, $mode = false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } - switch ($mode) - { - case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break; - case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break; - default: - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break; + switch ($mode) { + case ADODB_FETCH_NUM: + $this->fetchMode = PGSQL_NUM; + break; + case ADODB_FETCH_ASSOC: + $this->fetchMode = PGSQL_ASSOC; + break; + default: + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + $this->fetchMode = PGSQL_BOTH; + break; } $this->ADORecordSet($queryID); } @@ -157,8 +163,8 @@ class ADORecordSet_netezza extends ADORecordSet_postgres64 // _initrs modified to disable blob handling function _initrs() { - global $ADODB_COUNTRECS; - $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($this->_queryID):-1; + global $ADODB_COUNTRECS; + $this->_numOfRows = ($ADODB_COUNTRECS) ? @pg_numrows($this->_queryID) : -1; $this->_numOfFields = @pg_numfields($this->_queryID); } diff --git a/lib/WikiDB/adodb/drivers/adodb-oci8.inc.php b/lib/WikiDB/adodb/drivers/adodb-oci8.inc.php index 9d960717e..3e42846c9 100644 --- a/lib/WikiDB/adodb/drivers/adodb-oci8.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-oci8.inc.php @@ -35,11 +35,12 @@ NLS_DATE_FORMAT='RR-MM-DD' You can also modify the date format using the ALTER SESSION command. */ -class ADODB_oci8 extends ADOConnection { +class ADODB_oci8 extends ADOConnection +{ var $databaseType = 'oci8'; var $dataProvider = 'oci8'; var $replaceQuote = "''"; // string to use to replace quotes - var $concat_operator='||'; + var $concat_operator = '||'; var $sysDate = "TRUNC(SYSDATE)"; var $sysTimeStamp = 'SYSDATE'; var $metaDatabasesSQL = "SELECT USERNAME FROM ALL_USERS WHERE USERNAME NOT IN ('SYS','SYSTEM','DBSNMP','OUTLN') ORDER BY 1"; @@ -60,12 +61,12 @@ class ADODB_oci8 extends ADOConnection { var $_bind = false; var $_hasOCIFetchStatement = false; var $_getarray = false; // currently not working - var $leftOuter = ''; // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER + var $leftOuter = ''; // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER var $session_sharing_force_blob = false; // alter session on updateblob if set to true var $firstrows = true; // enable first rows optimization on SelectLimit() var $selectOffsetAlg1 = 100; // when to use 1st algorithm of selectlimit. - var $NLS_DATE_FORMAT = 'YYYY-MM-DD'; // To include time, use 'RRRR-MM-DD HH24:MI:SS' - var $useDBDateFormatForTextInput=false; + var $NLS_DATE_FORMAT = 'YYYY-MM-DD'; // To include time, use 'RRRR-MM-DD HH24:MI:SS' + var $useDBDateFormatForTextInput = false; var $datetime = false; // MetaType('DATE') returns 'D' (datetime==false) or 'T' (datetime == true) // var $ansiOuter = true; // if oracle9 @@ -78,13 +79,13 @@ class ADODB_oci8 extends ADOConnection { /* Function &MetaColumns($table) added by smondino@users.sourceforge.net*/ function &MetaColumns($table) { - global $ADODB_FETCH_MODE; + 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,strtoupper($table))); + $rs = $this->Execute(sprintf($this->metaColumnsSQL, strtoupper($table))); if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; @@ -92,16 +93,16 @@ class ADODB_oci8 extends ADOConnection { $retarr = array(); while (!$rs->EOF) { //print_r($rs->fields); $fld = new ADOFieldObject(); - $fld->name = $rs->fields[0]; - $fld->type = $rs->fields[1]; - $fld->max_length = $rs->fields[2]; + $fld->name = $rs->fields[0]; + $fld->type = $rs->fields[1]; + $fld->max_length = $rs->fields[2]; $fld->scale = $rs->fields[3]; if ($rs->fields[1] == 'NUMBER' && $rs->fields[3] == 0) { - $fld->type ='INT'; - $fld->max_length = $rs->fields[4]; + $fld->type = 'INT'; + $fld->max_length = $rs->fields[4]; } - $fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0); - $fld->binary = (strpos($fld->type,'BLOB') !== false); + $fld->not_null = (strncmp($rs->fields[5], 'NOT', 3) === 0); + $fld->binary = (strpos($fld->type, 'BLOB') !== false); $fld->default_value = $rs->fields[6]; if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; @@ -120,78 +121,78 @@ class ADODB_oci8 extends ADOConnection { return false; } -/* + /* - Multiple modes of connection are supported: + Multiple modes of connection are supported: - a. Local Database - $conn->Connect(false,'scott','tiger'); + a. Local Database + $conn->Connect(false,'scott','tiger'); - b. From tnsnames.ora - $conn->Connect(false,'scott','tiger',$tnsname); - $conn->Connect($tnsname,'scott','tiger'); + b. From tnsnames.ora + $conn->Connect(false,'scott','tiger',$tnsname); + $conn->Connect($tnsname,'scott','tiger'); - c. Server + service name - $conn->Connect($serveraddress,'scott,'tiger',$service_name); + c. Server + service name + $conn->Connect($serveraddress,'scott,'tiger',$service_name); - d. Server + SID - $conn->connectSID = true; - $conn->Connect($serveraddress,'scott,'tiger',$SID); + d. Server + SID + $conn->connectSID = true; + $conn->Connect($serveraddress,'scott,'tiger',$SID); -Example TNSName: ---------------- -NATSOFT.DOMAIN = - (DESCRIPTION = - (ADDRESS_LIST = - (ADDRESS = (PROTOCOL = TCP)(HOST = kermit)(PORT = 1523)) - ) - (CONNECT_DATA = - (SERVICE_NAME = natsoft.domain) - ) - ) + Example TNSName: + --------------- + NATSOFT.DOMAIN = + (DESCRIPTION = + (ADDRESS_LIST = + (ADDRESS = (PROTOCOL = TCP)(HOST = kermit)(PORT = 1523)) + ) + (CONNECT_DATA = + (SERVICE_NAME = natsoft.domain) + ) + ) - There are 3 connection modes, 0 = non-persistent, 1 = persistent, 2 = force new connection + There are 3 connection modes, 0 = non-persistent, 1 = persistent, 2 = force new connection -*/ - function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$mode=0) + */ + function _connect($argHostname, $argUsername, $argPassword, $argDatabasename, $mode = 0) { if (!function_exists('OCIPLogon')) return false; $this->_errorMsg = false; $this->_errorCode = false; - if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi> + if ($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi> if (empty($argDatabasename)) $argDatabasename = $argHostname; else { - if(strpos($argHostname,":")) { - $argHostinfo=explode(":",$argHostname); - $argHostname=$argHostinfo[0]; - $argHostport=$argHostinfo[1]; - } else { - $argHostport="1521"; - } + if (strpos($argHostname, ":")) { + $argHostinfo = explode(":", $argHostname); + $argHostname = $argHostinfo[0]; + $argHostport = $argHostinfo[1]; + } else { + $argHostport = "1521"; + } if ($this->connectSID) { - $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname - .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))"; + $argDatabasename = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=" . $argHostname + . ")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))"; } else - $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname - .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))"; + $argDatabasename = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=" . $argHostname + . ")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))"; } } - //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>"; - if ($mode==1) { - $this->_connectionID = OCIPLogon($argUsername,$argPassword, $argDatabasename); - if ($this->_connectionID && $this->autoRollback) OCIrollback($this->_connectionID); - } elseif ($mode==2) { - $this->_connectionID = OCINLogon($argUsername,$argPassword, $argDatabasename); + //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>"; + if ($mode == 1) { + $this->_connectionID = OCIPLogon($argUsername, $argPassword, $argDatabasename); + if ($this->_connectionID && $this->autoRollback) OCIrollback($this->_connectionID); + } elseif ($mode == 2) { + $this->_connectionID = OCINLogon($argUsername, $argPassword, $argDatabasename); } else { - $this->_connectionID = OCILogon($argUsername,$argPassword, $argDatabasename); + $this->_connectionID = OCILogon($argUsername, $argPassword, $argDatabasename); } if ($this->_connectionID === false) return false; if ($this->_initdate) { - $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'"); + $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='" . $this->NLS_DATE_FORMAT . "'"); } // looks like: @@ -199,7 +200,7 @@ NATSOFT.DOMAIN = // $vers = OCIServerVersion($this->_connectionID); // if (strpos($vers,'8i') !== false) $this->ansiOuter = true; return true; - } + } function ServerInfo() { @@ -208,16 +209,17 @@ NATSOFT.DOMAIN = $arr['version'] = ADOConnection::_findvers($arr['description']); return $arr; } - // returns true or false + + // returns true or false function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { - return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,1); + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, 1); } // returns true or false function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { - return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,2); + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, 2); } function _affectedrows() @@ -226,7 +228,7 @@ NATSOFT.DOMAIN = return 0; } - function IfNull( $field, $ifNull ) + function IfNull($field, $ifNull) { return " NVL($field, $ifNull) "; // if Oracle } @@ -237,7 +239,7 @@ NATSOFT.DOMAIN = if (empty($d) && $d !== 0) return 'null'; if (is_string($d)) $d = ADORecordSet::UnixDate($d); - return "TO_DATE(".adodb_date($this->fmtDate,$d).",'".$this->NLS_DATE_FORMAT."')"; + return "TO_DATE(" . adodb_date($this->fmtDate, $d) . ",'" . $this->NLS_DATE_FORMAT . "')"; } // format and return date string in database timestamp format @@ -245,23 +247,23 @@ NATSOFT.DOMAIN = { if (empty($ts) && $ts !== 0) return 'null'; if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts); - return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')"; + return 'TO_DATE(' . adodb_date($this->fmtTimeStamp, $ts) . ",'RRRR-MM-DD, HH:MI:SS AM')"; } - function RowLock($tables,$where) + function RowLock($tables, $where) { if ($this->autoCommit) $this->BeginTrans(); return $this->GetOne("select 1 as ignore from $tables where $where for update"); } - function &MetaTables($ttype=false,$showSchema=false,$mask=false) + function &MetaTables($ttype = false, $showSchema = false, $mask = false) { if ($mask) { $save = $this->metaTablesSQL; $mask = $this->qstr(strtoupper($mask)); $this->metaTablesSQL .= " AND table_name like $mask"; } - $ret =& ADOConnection::MetaTables($ttype,$showSchema); + $ret =& ADOConnection::MetaTables($ttype, $showSchema); if ($mask) { $this->metaTablesSQL = $save; @@ -278,7 +280,7 @@ NATSOFT.DOMAIN = return true; } - function CommitTrans($ok=true) + function CommitTrans($ok = true) { if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); @@ -338,69 +340,69 @@ NATSOFT.DOMAIN = } // Format date column in sql string given an input format that understands Y M D - function SQLDate($fmt, $col=false) + function SQLDate($fmt, $col = false) { if (!$col) $col = $this->sysTimeStamp; - $s = 'TO_CHAR('.$col.",'"; + $s = 'TO_CHAR(' . $col . ",'"; $len = strlen($fmt); - for ($i=0; $i < $len; $i++) { + for ($i = 0; $i < $len; $i++) { $ch = $fmt[$i]; - switch($ch) { - case 'Y': - case 'y': - $s .= 'YYYY'; - break; - case 'Q': - case 'q': - $s .= 'Q'; - break; + switch ($ch) { + case 'Y': + case 'y': + $s .= 'YYYY'; + break; + case 'Q': + case 'q': + $s .= 'Q'; + break; - case 'M': - $s .= 'Mon'; - break; + case 'M': + $s .= 'Mon'; + break; - case 'm': - $s .= 'MM'; - break; - case 'D': - case 'd': - $s .= 'DD'; - break; + case 'm': + $s .= 'MM'; + break; + case 'D': + case 'd': + $s .= 'DD'; + break; - case 'H': - $s.= 'HH24'; - break; + case 'H': + $s .= 'HH24'; + break; - case 'h': - $s .= 'HH'; - break; + case 'h': + $s .= 'HH'; + break; - case 'i': - $s .= 'MI'; - break; + case 'i': + $s .= 'MI'; + break; - case 's': - $s .= 'SS'; - break; + case 's': + $s .= 'SS'; + break; - case 'a': - case 'A': - $s .= 'AM'; - break; + case 'a': + case 'A': + $s .= 'AM'; + break; - default: - // handle escape characters... - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); - } - if (strpos('-/.:;, ',$ch) !== false) $s .= $ch; - else $s .= '"'.$ch.'"'; + default: + // handle escape characters... + if ($ch == '\\') { + $i++; + $ch = substr($fmt, $i, 1); + } + if (strpos('-/.:;, ', $ch) !== false) $s .= $ch; + else $s .= '"' . $ch . '"'; } } - return $s. "')"; + return $s . "')"; } /* @@ -418,14 +420,14 @@ NATSOFT.DOMAIN = This implementation does not appear to work with oracle 8.0.5 or earlier. Comment out this function then, and the slower SelectLimit() in the base class will be used. */ - function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) { // seems that oracle only supports 1 hint comment in 8i if ($this->firstrows) { - if (strpos($sql,'/*+') !== false) - $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql); + if (strpos($sql, '/*+') !== false) + $sql = str_replace('/*+ ', '/*+FIRST_ROWS ', $sql); else - $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql); + $sql = preg_replace('/^[ \t\n]*select/i', 'SELECT /*+FIRST_ROWS*/', $sql); } if ($offset < $this->selectOffsetAlg1) { @@ -442,103 +444,109 @@ NATSOFT.DOMAIN = } // note that $nrows = 0 still has to work ==> no rows returned - $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + $rs =& ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); return $rs; } else { - // Algorithm by Tomas V V Cox, from PEAR DB oci8.php + // Algorithm by Tomas V V Cox, from PEAR DB oci8.php - // Let Oracle return the name of the columns - $q_fields = "SELECT * FROM ($sql) WHERE NULL = NULL"; - if (!$stmt = OCIParse($this->_connectionID, $q_fields)) { - return false; - } + // Let Oracle return the name of the columns + $q_fields = "SELECT * FROM ($sql) WHERE NULL = NULL"; + if (!$stmt = OCIParse($this->_connectionID, $q_fields)) { + return false; + } - if (is_array($inputarr)) { - foreach($inputarr as $k => $v) { + if (is_array($inputarr)) { + foreach ($inputarr as $k => $v) { if (is_array($v)) { if (sizeof($v) == 2) // suggested by g.giunta@libero. - OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]); + OCIBindByName($stmt, ":$k", $inputarr[$k][0], $v[1]); else - OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]); + OCIBindByName($stmt, ":$k", $inputarr[$k][0], $v[1], $v[2]); } else { $len = -1; if ($v === ' ') $len = 1; - if (isset($bindarr)) { // is prepared sql, so no need to ocibindbyname again + if (isset($bindarr)) { // is prepared sql, so no need to ocibindbyname again $bindarr[$k] = $v; - } else { // dynamic sql, so rebind every time - OCIBindByName($stmt,":$k",$inputarr[$k],$len); + } else { // dynamic sql, so rebind every time + OCIBindByName($stmt, ":$k", $inputarr[$k], $len); } } } } - if (!OCIExecute($stmt, OCI_DEFAULT)) { - OCIFreeStatement($stmt); - return false; - } + if (!OCIExecute($stmt, OCI_DEFAULT)) { + OCIFreeStatement($stmt); + return false; + } - $ncols = OCINumCols($stmt); - for ( $i = 1; $i <= $ncols; $i++ ) { - $cols[] = '"'.OCIColumnName($stmt, $i).'"'; - } - $result = false; + $ncols = OCINumCols($stmt); + for ($i = 1; $i <= $ncols; $i++) { + $cols[] = '"' . OCIColumnName($stmt, $i) . '"'; + } + $result = false; - OCIFreeStatement($stmt); - $fields = implode(',', $cols); - $nrows += $offset; - $offset += 1; // in Oracle rownum starts at 1 + OCIFreeStatement($stmt); + $fields = implode(',', $cols); + $nrows += $offset; + $offset += 1; // in Oracle rownum starts at 1 if ($this->databaseType == 'oci8po') { - $sql = "SELECT $fields FROM". - "(SELECT rownum as adodb_rownum, $fields FROM". - " ($sql) WHERE rownum <= ?". - ") WHERE adodb_rownum >= ?"; - } else { - $sql = "SELECT $fields FROM". - "(SELECT rownum as adodb_rownum, $fields FROM". - " ($sql) WHERE rownum <= :adodb_nrows". - ") WHERE adodb_rownum >= :adodb_offset"; - } - $inputarr['adodb_nrows'] = $nrows; - $inputarr['adodb_offset'] = $offset; + $sql = "SELECT $fields FROM" . + "(SELECT rownum as adodb_rownum, $fields FROM" . + " ($sql) WHERE rownum <= ?" . + ") WHERE adodb_rownum >= ?"; + } else { + $sql = "SELECT $fields FROM" . + "(SELECT rownum as adodb_rownum, $fields FROM" . + " ($sql) WHERE rownum <= :adodb_nrows" . + ") WHERE adodb_rownum >= :adodb_offset"; + } + $inputarr['adodb_nrows'] = $nrows; + $inputarr['adodb_offset'] = $offset; - if ($secs2cache>0) $rs =& $this->CacheExecute($secs2cache, $sql,$inputarr); - else $rs =& $this->Execute($sql,$inputarr); + if ($secs2cache > 0) $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr); + else $rs =& $this->Execute($sql, $inputarr); return $rs; } } /** - * Usage: - * Store BLOBs and CLOBs - * - * Example: to store $var in a blob - * - * $conn->Execute('insert into TABLE (id,ablob) values(12,empty_blob())'); - * $conn->UpdateBlob('TABLE', 'ablob', $varHoldingBlob, 'ID=12', 'BLOB'); - * - * $blobtype supports 'BLOB' and 'CLOB', but you need to change to 'empty_clob()'. - * - * to get length of LOB: - * select DBMS_LOB.GETLENGTH(ablob) from TABLE - * - * If you are using CURSOR_SHARING = force, it appears this will case a segfault - * under oracle 8.1.7.0. Run: - * $db->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT'); - * before UpdateBlob() then... - */ + * Usage: + * Store BLOBs and CLOBs + * + * Example: to store $var in a blob + * + * $conn->Execute('insert into TABLE (id,ablob) values(12,empty_blob())'); + * $conn->UpdateBlob('TABLE', 'ablob', $varHoldingBlob, 'ID=12', 'BLOB'); + * + * $blobtype supports 'BLOB' and 'CLOB', but you need to change to 'empty_clob()'. + * + * to get length of LOB: + * select DBMS_LOB.GETLENGTH(ablob) from TABLE + * + * If you are using CURSOR_SHARING = force, it appears this will case a segfault + * under oracle 8.1.7.0. Run: + * $db->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT'); + * before UpdateBlob() then... + */ - function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') + function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB') { //if (strlen($val) < 4000) return $this->Execute("UPDATE $table SET $column=:blob WHERE $where",array('blob'=>$val)) != false; - switch(strtoupper($blobtype)) { - default: ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false; - case 'BLOB': $type = OCI_B_BLOB; break; - case 'CLOB': $type = OCI_B_CLOB; break; + switch (strtoupper($blobtype)) { + default: + ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); + return false; + case 'BLOB': + $type = OCI_B_BLOB; + break; + case 'CLOB': + $type = OCI_B_CLOB; + break; } if ($this->databaseType == 'oci8po') @@ -547,11 +555,11 @@ NATSOFT.DOMAIN = $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob"; $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB); - $arr['blob'] = array($desc,-1,$type); + $arr['blob'] = array($desc, -1, $type); if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT'); $commit = $this->autoCommit; if ($commit) $this->BeginTrans(); - $rs = ADODB_oci8::Execute($sql,$arr); + $rs = ADODB_oci8::Execute($sql, $arr); if ($rez = !empty($rs)) $desc->save($val); $desc->free(); if ($commit) $this->CommitTrans(); @@ -562,14 +570,20 @@ NATSOFT.DOMAIN = } /** - * Usage: store file pointed to by $var in a blob - */ - function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB') + * Usage: store file pointed to by $var in a blob + */ + function UpdateBlobFile($table, $column, $val, $where, $blobtype = 'BLOB') { - switch(strtoupper($blobtype)) { - default: ADOConnection::outp( "<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false; - case 'BLOB': $type = OCI_B_BLOB; break; - case 'CLOB': $type = OCI_B_CLOB; break; + switch (strtoupper($blobtype)) { + default: + ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); + return false; + case 'BLOB': + $type = OCI_B_BLOB; + break; + case 'CLOB': + $type = OCI_B_CLOB; + break; } if ($this->databaseType == 'oci8po') @@ -578,10 +592,10 @@ NATSOFT.DOMAIN = $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob"; $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB); - $arr['blob'] = array($desc,-1,$type); + $arr['blob'] = array($desc, -1, $type); $this->BeginTrans(); - $rs = ADODB_oci8::Execute($sql,$arr); + $rs = ADODB_oci8::Execute($sql, $arr); if ($rez = !empty($rs)) $desc->savefile($val); $desc->free(); $this->CommitTrans(); @@ -595,21 +609,21 @@ NATSOFT.DOMAIN = $stmt = $this->Prepare('insert into emp (empno, ename) values (:empno, :ename)'); */ - function Prepare($sql,$cursor=false) + function Prepare($sql, $cursor = false) { - static $BINDNUM = 0; + static $BINDNUM = 0; - $stmt = OCIParse($this->_connectionID,$sql); + $stmt = OCIParse($this->_connectionID, $sql); if (!$stmt) return false; $BINDNUM += 1; if (@OCIStatementType($stmt) == 'BEGIN') { - return array($sql,$stmt,0,$BINDNUM, ($cursor) ? OCINewCursor($this->_connectionID) : false); + return array($sql, $stmt, 0, $BINDNUM, ($cursor) ? OCINewCursor($this->_connectionID) : false); } - return array($sql,$stmt,0,$BINDNUM); + return array($sql, $stmt, 0, $BINDNUM); } /* @@ -627,15 +641,15 @@ NATSOFT.DOMAIN = array('VAR1' => 'Mr Bean')); */ - function &ExecuteCursor($sql,$cursorName='rs',$params=false) + function &ExecuteCursor($sql, $cursorName = 'rs', $params = false) { - $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor + $stmt = ADODB_oci8::Prepare($sql, true); # true to allocate OCINewCursor if (is_array($stmt) && sizeof($stmt) >= 5) { $this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR); if ($params) { - foreach($params as $k => $v) { - $this->Parameter($stmt,$params[$k], $k); + foreach ($params as $k => $v) { + $this->Parameter($stmt, $params[$k], $k); } } } @@ -672,26 +686,26 @@ NATSOFT.DOMAIN = Note that the order of parameters differs from OCIBindByName, because we default the names to :0, :1, :2 */ - function Bind(&$stmt,&$var,$size=4000,$type=false,$name=false) + function Bind(&$stmt, &$var, $size = 4000, $type = false, $name = false) { if (!is_array($stmt)) return false; if (($type == OCI_B_CURSOR) && sizeof($stmt) >= 5) { - return OCIBindByName($stmt[1],":".$name,$stmt[4],$size,$type); + return OCIBindByName($stmt[1], ":" . $name, $stmt[4], $size, $type); } if ($name == false) { - if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type); - else $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator + if ($type !== false) $rez = OCIBindByName($stmt[1], ":" . $name, $var, $size, $type); + else $rez = OCIBindByName($stmt[1], ":" . $stmt[2], $var, $size); // +1 byte for null terminator $stmt[2] += 1; - } elseif ($type == OCI_B_BLOB){ + } elseif ($type == OCI_B_BLOB) { //we have to create a new Descriptor here $_blob = OCINewDescriptor($this->_connectionID, OCI_D_LOB); - $rez = OCIBindByName($stmt[1], ":".$name, $_blob, -1, OCI_B_BLOB); + $rez = OCIBindByName($stmt[1], ":" . $name, $_blob, -1, OCI_B_BLOB); $rez = $_blob; } else { - if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type); - else $rez = OCIBindByName($stmt[1],":".$name,$var,$size); // +1 byte for null terminator + if ($type !== false) $rez = OCIBindByName($stmt[1], ":" . $name, $var, $size, $type); + else $rez = OCIBindByName($stmt[1], ":" . $name, $var, $size); // +1 byte for null terminator } return $rez; @@ -699,7 +713,7 @@ NATSOFT.DOMAIN = function Param($name) { - return ':'.$name; + return ':' . $name; } /* @@ -718,14 +732,14 @@ NATSOFT.DOMAIN = See OCIBindByName documentation at php.net. */ - function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false) + function Parameter(&$stmt, &$var, $name, $isOutput = false, $maxLen = 4000, $type = false) { - if ($this->debug) { - $prefix = ($isOutput) ? 'Out' : 'In'; - $ztype = (empty($type)) ? 'false' : $type; - ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);"); - } - return $this->Bind($stmt,$var,$maxLen,$type,$name); + if ($this->debug) { + $prefix = ($isOutput) ? 'Out' : 'In'; + $ztype = (empty($type)) ? 'false' : $type; + ADOConnection::outp("{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);"); + } + return $this->Bind($stmt, $var, $maxLen, $type, $name); } /* @@ -743,7 +757,7 @@ NATSOFT.DOMAIN = $db->$bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3); $db->execute($stmt); */ - function _query($sql,$inputarr) + function _query($sql, $inputarr) { if (is_array($sql)) { // is prepared sql @@ -754,43 +768,43 @@ NATSOFT.DOMAIN = if (is_array($inputarr)) { $bindpos = $sql[3]; if (isset($this->_bind[$bindpos])) { - // all tied up already + // all tied up already $bindarr = &$this->_bind[$bindpos]; } else { - // one statement to bind them all + // one statement to bind them all $bindarr = array(); - foreach($inputarr as $k => $v) { + foreach ($inputarr as $k => $v) { $bindarr[$k] = $v; - OCIBindByName($stmt,":$k",$bindarr[$k],4000); + OCIBindByName($stmt, ":$k", $bindarr[$k], 4000); } $this->_bind[$bindpos] = &$bindarr; } } } else { - $stmt=OCIParse($this->_connectionID,$sql); + $stmt = OCIParse($this->_connectionID, $sql); } $this->_stmt = $stmt; if (!$stmt) return false; - if (defined('ADODB_PREFETCH_ROWS')) @OCISetPrefetch($stmt,ADODB_PREFETCH_ROWS); + if (defined('ADODB_PREFETCH_ROWS')) @OCISetPrefetch($stmt, ADODB_PREFETCH_ROWS); if (is_array($inputarr)) { - foreach($inputarr as $k => $v) { + foreach ($inputarr as $k => $v) { if (is_array($v)) { if (sizeof($v) == 2) // suggested by g.giunta@libero. - OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]); + OCIBindByName($stmt, ":$k", $inputarr[$k][0], $v[1]); else - OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]); + OCIBindByName($stmt, ":$k", $inputarr[$k][0], $v[1], $v[2]); - if ($this->debug==99) echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>'; + if ($this->debug == 99) echo "name=:$k", ' var=' . $inputarr[$k][0], ' len=' . $v[1], ' type=' . $v[2], '<br>'; } else { $len = -1; if ($v === ' ') $len = 1; - if (isset($bindarr)) { // is prepared sql, so no need to ocibindbyname again + if (isset($bindarr)) { // is prepared sql, so no need to ocibindbyname again $bindarr[$k] = $v; - } else { // dynamic sql, so rebind every time - OCIBindByName($stmt,":$k",$inputarr[$k],$len); + } else { // dynamic sql, so rebind every time + OCIBindByName($stmt, ":$k", $inputarr[$k], $len); } } } @@ -798,7 +812,7 @@ NATSOFT.DOMAIN = $this->_errorMsg = false; $this->_errorCode = false; - if (OCIExecute($stmt,$this->_commit)) { + if (OCIExecute($stmt, $this->_commit)) { switch (@OCIStatementType($stmt)) { case "SELECT": @@ -837,11 +851,11 @@ NATSOFT.DOMAIN = $this->_connectionID = false; } - function MetaPrimaryKeys($table, $owner=false,$internalKey=false) + function MetaPrimaryKeys($table, $owner = false, $internalKey = false) { if ($internalKey) return array('ROWID'); - // tested with oracle 8.1.7 + // tested with oracle 8.1.7 $table = strtoupper($table); if ($owner) { $owner_clause = "AND ((a.OWNER = b.OWNER) AND (a.OWNER = UPPER('$owner')))"; @@ -859,22 +873,21 @@ SELECT /*+ RULE */ distinct b.column_name $owner_clause AND (a.constraint_name = b.constraint_name)"; - $rs = $this->Execute($sql); + $rs = $this->Execute($sql); if ($rs && !$rs->EOF) { $arr =& $rs->GetArray(); $a = array(); - foreach($arr as $v) { + foreach ($arr as $v) { $a[] = reset($v); } return $a; - } - else return false; + } else return false; } // http://gis.mit.edu/classes/11.521/sqlnotes/referential_integrity.html - function MetaForeignKeys($table, $owner=false) + function MetaForeignKeys($table, $owner = false) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; @@ -885,16 +898,16 @@ SELECT /*+ RULE */ distinct b.column_name } else $tabp = 'all_'; - $owner = ' and owner='.$this->qstr(strtoupper($owner)); + $owner = ' and owner=' . $this->qstr(strtoupper($owner)); $sql = -"select constraint_name,r_owner,r_constraint_name + "select constraint_name,r_owner,r_constraint_name from {$tabp}constraints where constraint_type = 'R' and table_name = $table $owner"; $constraints =& $this->GetArray($sql); $arr = false; - foreach($constraints as $constr) { + foreach ($constraints as $constr) { $cons = $this->qstr($constr[0]); $rowner = $this->qstr($constr[1]); $rcons = $this->qstr($constr[2]); @@ -902,8 +915,8 @@ SELECT /*+ RULE */ distinct b.column_name $tabcol = $this->GetArray("select table_name,column_name from {$tabp}cons_columns where owner=$rowner and constraint_name=$rcons order by position"); if ($cols && $tabcol) - for ($i=0, $max=sizeof($cols); $i < $max; $i++) { - $arr[$tabcol[$i][0]] = $cols[$i][0].'='.$tabcol[$i][1]; + for ($i = 0, $max = sizeof($cols); $i < $max; $i++) { + $arr[$tabcol[$i][0]] = $cols[$i][0] . '=' . $tabcol[$i][1]; } } $ADODB_FETCH_MODE = $save; @@ -925,33 +938,33 @@ SELECT /*+ RULE */ distinct b.column_name * Quotes a string. * An example is $db->qstr("Don't bother",magic_quotes_runtime()); * - * @param s the string to quote - * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc(). - * This undoes the stupidity of magic quotes for GPC. + * @param s the string to quote + * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc(). + * This undoes the stupidity of magic quotes for GPC. * * @return quoted string to be sent back to database */ - function qstr($s,$magic_quotes=false) + function qstr($s, $magic_quotes = false) { - $nofixquotes=false; + $nofixquotes = false; if (is_array($s)) adodb_backtrace(); - if ($this->noNullStrings && strlen($s)==0)$s = ' '; + if ($this->noNullStrings && strlen($s) == 0) $s = ' '; if (!$magic_quotes) { - if ($this->replaceQuote[0] == '\\'){ - $s = str_replace('\\','\\\\',$s); + if ($this->replaceQuote[0] == '\\') { + $s = str_replace('\\', '\\\\', $s); } - return "'".str_replace("'",$this->replaceQuote,$s)."'"; + return "'" . str_replace("'", $this->replaceQuote, $s) . "'"; } // undo magic quotes for " - $s = str_replace('\\"','"',$s); + $s = str_replace('\\"', '"', $s); - if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything + if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything return "'$s'"; - else {// change \' to '' for sybase/mssql - $s = str_replace('\\\\','\\',$s); - return "'".str_replace("\\'",$this->replaceQuote,$s)."'"; + else { // change \' to '' for sybase/mssql + $s = str_replace('\\\\', '\\', $s); + return "'" . str_replace("\\'", $this->replaceQuote, $s) . "'"; } } @@ -961,26 +974,33 @@ SELECT /*+ RULE */ distinct b.column_name Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordset_oci8 extends ADORecordSet { +class ADORecordset_oci8 extends ADORecordSet +{ var $databaseType = 'oci8'; - var $bind=false; + var $bind = false; var $_fieldobjs; + //var $_arr = false; - function ADORecordset_oci8($queryID,$mode=false) + function ADORecordset_oci8($queryID, $mode = false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } - switch ($mode) - { - default: - case ADODB_FETCH_NUM: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; - case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; + switch ($mode) { + default: + case ADODB_FETCH_NUM: + $this->fetchMode = OCI_NUM + OCI_RETURN_NULLS + OCI_RETURN_LOBS; + break; + case ADODB_FETCH_ASSOC: + $this->fetchMode = OCI_ASSOC + OCI_RETURN_NULLS + OCI_RETURN_LOBS; + break; + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + $this->fetchMode = OCI_NUM + OCI_ASSOC + OCI_RETURN_NULLS + OCI_RETURN_LOBS; + break; } $this->_queryID = $queryID; @@ -1021,31 +1041,31 @@ class ADORecordset_oci8 extends ADORecordSet { { $this->_numOfRows = -1; $this->_numOfFields = OCInumcols($this->_queryID); - if ($this->_numOfFields>0) { + if ($this->_numOfFields > 0) { $this->_fieldobjs = array(); $max = $this->_numOfFields; - for ($i=0;$i<$max; $i++) $this->_fieldobjs[] = $this->_FetchField($i); + for ($i = 0; $i < $max; $i++) $this->_fieldobjs[] = $this->_FetchField($i); } } - /* Returns: an object containing field information. - Get column information in the Recordset object. fetchField() can be used in order to obtain information about - fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by - fetchField() is retrieved. */ + /* Returns: an object containing field information. + Get column information in the Recordset object. fetchField() can be used in order to obtain information about + fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by + fetchField() is retrieved. */ function &_FetchField($fieldOffset = -1) { $fld = new ADOFieldObject; $fieldOffset += 1; - $fld->name =OCIcolumnname($this->_queryID, $fieldOffset); + $fld->name = OCIcolumnname($this->_queryID, $fieldOffset); $fld->type = OCIcolumntype($this->_queryID, $fieldOffset); $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset); - if ($fld->type == 'NUMBER') { - $p = OCIColumnPrecision($this->_queryID, $fieldOffset); + if ($fld->type == 'NUMBER') { + $p = OCIColumnPrecision($this->_queryID, $fieldOffset); $sc = OCIColumnScale($this->_queryID, $fieldOffset); if ($p != 0 && $sc == 0) $fld->type = 'INT'; //echo " $this->name ($p.$sc) "; - } + } return $fld; } @@ -1058,12 +1078,12 @@ class ADORecordset_oci8 extends ADORecordSet { // 10% speedup to move MoveNext to child class function MoveNext() { - //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return @adodb_movenext($this); + //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return @adodb_movenext($this); if ($this->EOF) return false; $this->_currentRow++; - if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) + if (@OCIfetchinto($this->_queryID, $this->fields, $this->fetchMode)) return true; $this->EOF = true; @@ -1071,16 +1091,16 @@ class ADORecordset_oci8 extends ADORecordSet { } /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */ - function &GetArrayLimit($nrows,$offset=-1) + function &GetArrayLimit($nrows, $offset = -1) { if ($offset <= 0) { $arr =& $this->GetArray($nrows); return $arr; } - for ($i=1; $i < $offset; $i++) + for ($i = 1; $i < $offset; $i++) if (!@OCIFetch($this->_queryID)) return array(); - if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array(); + if (!@OCIfetchinto($this->_queryID, $this->fields, $this->fetchMode)) return array(); $results = array(); $cnt = 0; while (!$this->EOF && $nrows != $cnt) { @@ -1096,13 +1116,13 @@ class ADORecordset_oci8 extends ADORecordSet { { if (!$this->bind) { $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { + for ($i = 0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } function _seek($row) @@ -1112,7 +1132,7 @@ class ADORecordset_oci8 extends ADORecordSet { function _fetch() { - return @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode); + return @OCIfetchinto($this->_queryID, $this->fields, $this->fetchMode); } /* close() only needs to be called if you are worried about using too much memory while your script @@ -1122,11 +1142,11 @@ class ADORecordset_oci8 extends ADORecordSet { { if ($this->connection->_stmt === $this->_queryID) $this->connection->_stmt = false; OCIFreeStatement($this->_queryID); - $this->_queryID = false; + $this->_queryID = false; } - function MetaType($t,$len=-1) + function MetaType($t, $len = -1) { if (is_object($t)) { $fieldobj = $t; @@ -1134,38 +1154,40 @@ class ADORecordset_oci8 extends ADORecordSet { $len = $fieldobj->max_length; } switch (strtoupper($t)) { - case 'VARCHAR': - case 'VARCHAR2': - case 'CHAR': - case 'VARBINARY': - case 'BINARY': - case 'NCHAR': - case 'NVARCHAR': - case 'NVARCHAR2': - if (isset($this) && $len <= $this->blobSize) return 'C'; - - case 'NCLOB': - case 'LONG': - case 'LONG VARCHAR': - case 'CLOB': - return 'X'; - - case 'LONG RAW': - case 'LONG VARBINARY': - case 'BLOB': - return 'B'; - - case 'DATE': - return ($this->connection->datetime) ? 'T' : 'D'; - - case 'TIMESTAMP': return 'T'; - - case 'INT': - case 'SMALLINT': - case 'INTEGER': - return 'I'; - - default: return 'N'; + case 'VARCHAR': + case 'VARCHAR2': + case 'CHAR': + case 'VARBINARY': + case 'BINARY': + case 'NCHAR': + case 'NVARCHAR': + case 'NVARCHAR2': + if (isset($this) && $len <= $this->blobSize) return 'C'; + + case 'NCLOB': + case 'LONG': + case 'LONG VARCHAR': + case 'CLOB': + return 'X'; + + case 'LONG RAW': + case 'LONG VARBINARY': + case 'BLOB': + return 'B'; + + case 'DATE': + return ($this->connection->datetime) ? 'T' : 'D'; + + case 'TIMESTAMP': + return 'T'; + + case 'INT': + case 'SMALLINT': + case 'INTEGER': + return 'I'; + + default: + return 'N'; } } } diff --git a/lib/WikiDB/adodb/drivers/adodb-oci805.inc.php b/lib/WikiDB/adodb/drivers/adodb-oci805.inc.php index e886dfcaf..0add18d19 100644 --- a/lib/WikiDB/adodb/drivers/adodb-oci805.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-oci805.inc.php @@ -10,11 +10,12 @@ * Latest version is available at http://php.weblogs.com * * Oracle 8.0.5 driver -*/ + */ -include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php'); +include_once(ADODB_DIR . '/drivers/adodb-oci8.inc.php'); -class ADODB_oci805 extends ADODB_oci8 { +class ADODB_oci805 extends ADODB_oci8 +{ var $databaseType = "oci805"; var $connectSID = true; @@ -23,13 +24,13 @@ class ADODB_oci805 extends ADODB_oci8 { $this->ADODB_oci8(); } - function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) { // seems that oracle only supports 1 hint comment in 8i - if (strpos($sql,'/*+') !== false) - $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql); + if (strpos($sql, '/*+') !== false) + $sql = str_replace('/*+ ', '/*+FIRST_ROWS ', $sql); else - $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql); + $sql = preg_replace('/^[ \t\n]*select/i', 'SELECT /*+FIRST_ROWS*/', $sql); /* The following is only available from 8.1.5 because order by in inline views not @@ -42,14 +43,16 @@ class ADODB_oci805 extends ADODB_oci8 { } */ - return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + return ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); } } -class ADORecordset_oci805 extends ADORecordset_oci8 { +class ADORecordset_oci805 extends ADORecordset_oci8 +{ var $databaseType = "oci805"; - function ADORecordset_oci805($id,$mode=false) + + function ADORecordset_oci805($id, $mode = false) { - $this->ADORecordset_oci8($id,$mode); + $this->ADORecordset_oci8($id, $mode); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-oci8po.inc.php b/lib/WikiDB/adodb/drivers/adodb-oci8po.inc.php index 201dec5b2..dc7566f12 100644 --- a/lib/WikiDB/adodb/drivers/adodb-oci8po.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-oci8po.inc.php @@ -17,9 +17,10 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim. All rights reserved. */ -include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php'); +include_once(ADODB_DIR . '/drivers/adodb-oci8.inc.php'); -class ADODB_oci8po extends ADODB_oci8 { +class ADODB_oci8po extends ADODB_oci8 +{ var $databaseType = 'oci8po'; var $dataProvider = 'oci8'; var $metaColumnsSQL = "select lower(cname),coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net @@ -35,34 +36,34 @@ class ADODB_oci8po extends ADODB_oci8 { return '?'; } - function Prepare($sql,$cursor=false) + function Prepare($sql, $cursor = false) { - $sqlarr = explode('?',$sql); + $sqlarr = explode('?', $sql); $sql = $sqlarr[0]; for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) { - $sql .= ':'.($i-1) . $sqlarr[$i]; + $sql .= ':' . ($i - 1) . $sqlarr[$i]; } - return ADODB_oci8::Prepare($sql,$cursor); + return ADODB_oci8::Prepare($sql, $cursor); } // emulate handling of parameters ? ?, replacing with :bind0 :bind1 - function _query($sql,$inputarr) + function _query($sql, $inputarr) { if (is_array($inputarr)) { $i = 0; if (is_array($sql)) { - foreach($inputarr as $v) { - $arr['bind'.$i++] = $v; + foreach ($inputarr as $v) { + $arr['bind' . $i++] = $v; } } else { - $sqlarr = explode('?',$sql); + $sqlarr = explode('?', $sql); $sql = $sqlarr[0]; - foreach($inputarr as $k => $v) { - $sql .= ":$k" . $sqlarr[++$i]; + foreach ($inputarr as $k => $v) { + $sql .= ":$k" . $sqlarr[++$i]; } } } - return ADODB_oci8::_query($sql,$inputarr); + return ADODB_oci8::_query($sql, $inputarr); } } @@ -70,44 +71,45 @@ class ADODB_oci8po extends ADODB_oci8 { Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordset_oci8po extends ADORecordset_oci8 { +class ADORecordset_oci8po extends ADORecordset_oci8 +{ var $databaseType = 'oci8po'; - function ADORecordset_oci8po($queryID,$mode=false) - { - $this->ADORecordset_oci8($queryID,$mode); - } + function ADORecordset_oci8po($queryID, $mode = false) + { + $this->ADORecordset_oci8($queryID, $mode); + } - function Fields($colname) - { - if ($this->fetchMode & OCI_ASSOC) return $this->fields[$colname]; + function Fields($colname) + { + if ($this->fetchMode & OCI_ASSOC) 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; - } + 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)]]; } + return $this->fields[$this->bind[strtoupper($colname)]]; + } - // lowercase field names... - function &_FetchField($fieldOffset = -1) - { - $fld = new ADOFieldObject; - $fieldOffset += 1; - $fld->name = strtolower(OCIcolumnname($this->_queryID, $fieldOffset)); - $fld->type = OCIcolumntype($this->_queryID, $fieldOffset); - $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset); - if ($fld->type == 'NUMBER') { - //$p = OCIColumnPrecision($this->_queryID, $fieldOffset); - $sc = OCIColumnScale($this->_queryID, $fieldOffset); - if ($sc == 0) $fld->type = 'INT'; - } - return $fld; + // lowercase field names... + function &_FetchField($fieldOffset = -1) + { + $fld = new ADOFieldObject; + $fieldOffset += 1; + $fld->name = strtolower(OCIcolumnname($this->_queryID, $fieldOffset)); + $fld->type = OCIcolumntype($this->_queryID, $fieldOffset); + $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset); + if ($fld->type == 'NUMBER') { + //$p = OCIColumnPrecision($this->_queryID, $fieldOffset); + $sc = OCIColumnScale($this->_queryID, $fieldOffset); + if ($sc == 0) $fld->type = 'INT'; } + return $fld; + } // 10% speedup to move MoveNext to child class function MoveNext() @@ -115,12 +117,12 @@ class ADORecordset_oci8po extends ADORecordset_oci8 { if (!$this->EOF) { $this->_currentRow++; - if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) { - global $ADODB_ANSI_PADDING_OFF; + if (@OCIfetchinto($this->_queryID, $this->fields, $this->fetchMode)) { + global $ADODB_ANSI_PADDING_OFF; if ($this->fetchMode & OCI_ASSOC) $this->_updatefields(); if (!empty($ADODB_ANSI_PADDING_OFF)) { - foreach($this->fields as $k => $v) { + foreach ($this->fields as $k => $v) { if (is_string($v)) $this->fields[$k] = rtrim($v); } } @@ -132,13 +134,13 @@ class ADORecordset_oci8po extends ADORecordset_oci8 { } /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */ - function &GetArrayLimit($nrows,$offset=-1) + function &GetArrayLimit($nrows, $offset = -1) { if ($offset <= 0) return $this->GetArray($nrows); - for ($i=1; $i < $offset; $i++) + for ($i = 1; $i < $offset; $i++) if (!@OCIFetch($this->_queryID)) return array(); - if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array(); + if (!@OCIfetchinto($this->_queryID, $this->fields, $this->fetchMode)) return array(); if ($this->fetchMode & OCI_ASSOC) $this->_updatefields(); $results = array(); $cnt = 0; @@ -158,7 +160,7 @@ class ADORecordset_oci8po extends ADORecordset_oci8 { $arr = array(); $lowercase = (ADODB_ASSOC_CASE == 0); - foreach($this->fields as $k => $v) { + foreach ($this->fields as $k => $v) { if (is_integer($k)) $arr[$k] = $v; else { if ($lowercase) @@ -172,16 +174,16 @@ class ADORecordset_oci8po extends ADORecordset_oci8 { function _fetch() { - $ret = @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode); + $ret = @OCIfetchinto($this->_queryID, $this->fields, $this->fetchMode); if ($ret) { - global $ADODB_ANSI_PADDING_OFF; + global $ADODB_ANSI_PADDING_OFF; - if ($this->fetchMode & OCI_ASSOC) $this->_updatefields(); - if (!empty($ADODB_ANSI_PADDING_OFF)) { - foreach($this->fields as $k => $v) { - if (is_string($v)) $this->fields[$k] = rtrim($v); - } + if ($this->fetchMode & OCI_ASSOC) $this->_updatefields(); + if (!empty($ADODB_ANSI_PADDING_OFF)) { + foreach ($this->fields as $k => $v) { + if (is_string($v)) $this->fields[$k] = rtrim($v); } + } } return $ret; } diff --git a/lib/WikiDB/adodb/drivers/adodb-odbc.inc.php b/lib/WikiDB/adodb/drivers/adodb-odbc.inc.php index 40f384e9c..889e5ef8c 100644 --- a/lib/WikiDB/adodb/drivers/adodb-odbc.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-odbc.inc.php @@ -10,12 +10,13 @@ Set tabs to 4 for best viewing. Requires ODBC. Works on Windows and Unix. */ - define("_ADODB_ODBC_LAYER", 2 ); +define("_ADODB_ODBC_LAYER", 2); /*-------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------*/ -class ADODB_odbc extends ADOConnection { +class ADODB_odbc extends ADOConnection +{ var $databaseType = "odbc"; var $fmtDate = "'Y-m-d'"; var $fmtTimeStamp = "'Y-m-d, h:i:sA'"; @@ -24,7 +25,7 @@ class ADODB_odbc extends ADOConnection { var $hasAffectedRows = true; var $binmode = ODBC_BINMODE_RETURN; var $useFetchArray = false; // setting this to true will make array elements in FETCH_ASSOC mode case-sensitive - // breaking backward-compat + // breaking backward-compat //var $longreadlen = 8000; // default number of chars to return for a Blob/Long field var $_bindInputArray = false; var $curmode = SQL_CUR_USE_DRIVER; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L @@ -50,7 +51,7 @@ class ADODB_odbc extends ADOConnection { if (!function_exists('odbc_data_source')) return false; - while(true) { + while (true) { $rez = odbc_data_source($this->_connectionID, $first ? SQL_FETCH_FIRST : SQL_FETCH_NEXT); @@ -69,20 +70,21 @@ class ADODB_odbc extends ADOConnection { } } - function CreateSequence($seqname='adodbseq',$start=1) + function CreateSequence($seqname = 'adodbseq', $start = 1) { if (empty($this->_genSeqSQL)) return false; - $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); + $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)); + return $this->Execute(sprintf($this->_dropSeqSQL, $seqname)); } /* @@ -91,16 +93,16 @@ class ADODB_odbc extends ADOConnection { Will return false if unable to generate an ID after $MAXLOOPS attempts. */ - function GenID($seq='adodbseq',$start=1) + 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) { + while (--$MAXLOOPS >= 0) { $num = $this->GetOne("select id from $seq"); if ($num === false) { - $this->Execute(sprintf($this->_genSeqSQL ,$seq)); + $this->Execute(sprintf($this->_genSeqSQL, $seq)); $start -= 1; $num = '0'; $ok = $this->Execute("insert into $seq values($start)"); @@ -115,7 +117,7 @@ class ADODB_odbc extends ADOConnection { } } if ($fn = $this->raiseErrorFn) { - $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num); + $fn($this->databaseType, 'GENID', -32000, "Unable to generate unique id after $MAXLOOPS attempts", $seq, $num); } return false; } @@ -136,15 +138,15 @@ class ADODB_odbc extends ADOConnection { if ($this->_haserrorfunctions) { if ($this->_errorCode !== false) { // bug in 4.0.6, error number can be corrupted string (should be 6 digits) - return (strlen($this->_errorCode)<=2) ? 0 : $this->_errorCode; + return (strlen($this->_errorCode) <= 2) ? 0 : $this->_errorCode; } if (empty($this->_connectionID)) $e = @odbc_error(); else $e = @odbc_error($this->_connectionID); - // bug in 4.0.6, error number can be corrupted string (should be 6 digits) - // so we check and patch - if (strlen($e)<=2) return 0; + // bug in 4.0.6, error number can be corrupted string (should be 6 digits) + // so we check and patch + if (strlen($e) <= 2) return 0; return $e; } else return ADOConnection::ErrorNo(); } @@ -153,7 +155,7 @@ class ADODB_odbc extends ADOConnection { // returns true or false function _connect($argDSN, $argUsername, $argPassword, $argDatabasename) { - global $php_errormsg; + global $php_errormsg; if (!function_exists('odbc_connect')) return false; @@ -161,8 +163,8 @@ class ADODB_odbc extends ADOConnection { ADOConnection::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter."); } $php_errormsg = ''; - if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword); - else $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode); + if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN, $argUsername, $argPassword); + else $this->_connectionID = odbc_connect($argDSN, $argUsername, $argPassword, $this->curmode); $this->_errorMsg = $php_errormsg; if (isset($this->connectStmt)) $this->Execute($this->connectStmt); @@ -173,7 +175,7 @@ class ADODB_odbc extends ADOConnection { // returns true or false function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename) { - global $php_errormsg; + global $php_errormsg; if (!function_exists('odbc_connect')) return false; @@ -181,9 +183,9 @@ class ADODB_odbc extends ADOConnection { if ($this->debug && $argDatabasename) { ADOConnection::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter."); } - // print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush(); - if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword); - else $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode); + // print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush(); + if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN, $argUsername, $argPassword); + else $this->_connectionID = odbc_pconnect($argDSN, $argUsername, $argPassword, $this->curmode); $this->_errorMsg = $php_errormsg; if ($this->_connectionID && $this->autoRollback) @odbc_rollback($this->_connectionID); @@ -198,17 +200,17 @@ class ADODB_odbc extends ADOConnection { if ($this->transOff) return true; $this->transCnt += 1; $this->_autocommit = false; - return odbc_autocommit($this->_connectionID,false); + return odbc_autocommit($this->_connectionID, false); } - function CommitTrans($ok=true) + function CommitTrans($ok = true) { if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); if ($this->transCnt) $this->transCnt -= 1; $this->_autocommit = true; $ret = odbc_commit($this->_connectionID); - odbc_autocommit($this->_connectionID,true); + odbc_autocommit($this->_connectionID, true); return $ret; } @@ -218,17 +220,17 @@ class ADODB_odbc extends ADOConnection { if ($this->transCnt) $this->transCnt -= 1; $this->_autocommit = true; $ret = odbc_rollback($this->_connectionID); - odbc_autocommit($this->_connectionID,true); + odbc_autocommit($this->_connectionID, true); return $ret; } function MetaPrimaryKeys($table) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $savem = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - $qid = @odbc_primarykeys($this->_connectionID,'','',$table); + $qid = @odbc_primarykeys($this->_connectionID, '', '', $table); if (!$qid) { $ADODB_FETCH_MODE = $savem; @@ -244,17 +246,16 @@ class ADODB_odbc extends ADOConnection { $rs->Close(); //print_r($arr); $arr2 = array(); - for ($i=0; $i < sizeof($arr); $i++) { + for ($i = 0; $i < sizeof($arr); $i++) { if ($arr[$i][3]) $arr2[] = $arr[$i][3]; } return $arr2; } - - function &MetaTables($ttype=false) + function &MetaTables($ttype = false) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $savem = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; @@ -274,90 +275,91 @@ class ADODB_odbc extends ADOConnection { $arr2 = array(); if ($ttype) { - $isview = strncmp($ttype,'V',1) === 0; + $isview = strncmp($ttype, 'V', 1) === 0; } - for ($i=0; $i < sizeof($arr); $i++) { + for ($i = 0; $i < sizeof($arr); $i++) { if (!$arr[$i][2]) continue; $type = $arr[$i][3]; if ($ttype) { if ($isview) { - if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2]; - } elseif (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2]; - } elseif (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2]; + if (strncmp($type, 'V', 1) === 0) $arr2[] = $arr[$i][2]; + } elseif (strncmp($type, 'SYS', 3) !== 0) $arr2[] = $arr[$i][2]; + } elseif (strncmp($type, 'SYS', 3) !== 0) $arr2[] = $arr[$i][2]; } return $arr2; } -/* -/ SQL data type codes / -#define SQL_UNKNOWN_TYPE 0 -#define SQL_CHAR 1 -#define SQL_NUMERIC 2 -#define SQL_DECIMAL 3 -#define SQL_INTEGER 4 -#define SQL_SMALLINT 5 -#define SQL_FLOAT 6 -#define SQL_REAL 7 -#define SQL_DOUBLE 8 -#if (ODBCVER >= 0x0300) -#define SQL_DATETIME 9 -#endif -#define SQL_VARCHAR 12 - -/ One-parameter shortcuts for date/time data types / -#if (ODBCVER >= 0x0300) -#define SQL_TYPE_DATE 91 -#define SQL_TYPE_TIME 92 -#define SQL_TYPE_TIMESTAMP 93 - -#define SQL_UNICODE (-95) -#define SQL_UNICODE_VARCHAR (-96) -#define SQL_UNICODE_LONGVARCHAR (-97) -*/ + /* + / SQL data type codes / + #define SQL_UNKNOWN_TYPE 0 + #define SQL_CHAR 1 + #define SQL_NUMERIC 2 + #define SQL_DECIMAL 3 + #define SQL_INTEGER 4 + #define SQL_SMALLINT 5 + #define SQL_FLOAT 6 + #define SQL_REAL 7 + #define SQL_DOUBLE 8 + #if (ODBCVER >= 0x0300) + #define SQL_DATETIME 9 + #endif + #define SQL_VARCHAR 12 + + / One-parameter shortcuts for date/time data types / + #if (ODBCVER >= 0x0300) + #define SQL_TYPE_DATE 91 + #define SQL_TYPE_TIME 92 + #define SQL_TYPE_TIMESTAMP 93 + + #define SQL_UNICODE (-95) + #define SQL_UNICODE_VARCHAR (-96) + #define SQL_UNICODE_LONGVARCHAR (-97) + */ function ODBCTypes($t) { switch ((integer)$t) { - case 1: - case 12: - case 0: - case -95: - case -96: - return 'C'; - case -97: - case -1: //text - return 'X'; - case -4: //image - return 'B'; - - case 91: - case 11: - return 'D'; - - case 92: - case 93: - case 9: return 'T'; - case 4: - case 5: - case -6: - return 'I'; - - case -11: // uniqidentifier - return 'R'; - case -7: //bit - return 'L'; - - default: - return 'N'; + case 1: + case 12: + case 0: + case -95: + case -96: + return 'C'; + case -97: + case -1: //text + return 'X'; + case -4: //image + return 'B'; + + case 91: + case 11: + return 'D'; + + case 92: + case 93: + case 9: + return 'T'; + case 4: + case 5: + case -6: + return 'I'; + + case -11: // uniqidentifier + return 'R'; + case -7: //bit + return 'L'; + + default: + return 'N'; } } function &MetaColumns($table) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $table = strtoupper($table); $schema = false; - $this->_findschema($table,$schema); + $this->_findschema($table, $schema); $savem = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; @@ -380,18 +382,18 @@ class ADODB_odbc extends ADOConnection { } $rs->Close(); - $qid = odbc_columns($this->_connectionID,$q,$o,strtoupper($table),'%'); + $qid = odbc_columns($this->_connectionID, $q, $o, strtoupper($table), '%'); } else switch ($this->databaseType) { - case 'access': - case 'vfp': - case 'db2': - $qid = odbc_columns($this->_connectionID); - break; - - default: - $qid = @odbc_columns($this->_connectionID,'%','%',strtoupper($table),'%'); - if (empty($qid)) $qid = odbc_columns($this->_connectionID); - break; + case 'access': + case 'vfp': + case 'db2': + $qid = odbc_columns($this->_connectionID); + break; + + default: + $qid = @odbc_columns($this->_connectionID, '%', '%', strtoupper($table), '%'); + if (empty($qid)) $qid = odbc_columns($this->_connectionID); + break; } if (empty($qid)) return false; @@ -432,7 +434,7 @@ class ADODB_odbc extends ADOConnection { if ($this->databaseType == 'access') $fld->max_length = $rs->fields[6]; else if ($rs->fields[4] <= -95) // UNICODE - $fld->max_length = $rs->fields[7]/2; + $fld->max_length = $rs->fields[7] / 2; else $fld->max_length = $rs->fields[7]; } else @@ -440,7 +442,7 @@ class ADODB_odbc extends ADOConnection { $fld->not_null = !empty($rs->fields[10]); $fld->scale = $rs->fields[8]; $retarr[strtoupper($fld->name)] = $fld; - } elseif (sizeof($retarr)>0) + } elseif (sizeof($retarr) > 0) break; $rs->MoveNext(); } @@ -451,19 +453,19 @@ class ADODB_odbc extends ADOConnection { function Prepare($sql) { - if (! $this->_bindInputArray) return $sql; // no binding - $stmt = odbc_prepare($this->_connectionID,$sql); + if (!$this->_bindInputArray) return $sql; // no binding + $stmt = odbc_prepare($this->_connectionID, $sql); if (!$stmt) { // we don't know whether odbc driver is parsing prepared stmts, so just return sql return $sql; } - return array($sql,$stmt,false); + return array($sql, $stmt, false); } /* returns queryID or false */ - function _query($sql,$inputarr=false) + function _query($sql, $inputarr = false) { - GLOBAL $php_errormsg; + GLOBAL $php_errormsg; $php_errormsg = ''; $this->_error = ''; @@ -471,7 +473,7 @@ class ADODB_odbc extends ADOConnection { if (is_array($sql)) { $stmtid = $sql[1]; } else { - $stmtid = odbc_prepare($this->_connectionID,$sql); + $stmtid = odbc_prepare($this->_connectionID, $sql); if ($stmtid == false) { $this->_errorMsg = $php_errormsg; @@ -479,7 +481,7 @@ class ADODB_odbc extends ADOConnection { } } - if (! odbc_execute($stmtid,$inputarr)) { + if (!odbc_execute($stmtid, $inputarr)) { //@odbc_free_result($stmtid); if ($this->_haserrorfunctions) { $this->_errorMsg = odbc_errormsg(); @@ -499,7 +501,7 @@ class ADODB_odbc extends ADOConnection { return false; } } else - $stmtid = odbc_exec($this->_connectionID,$sql); + $stmtid = odbc_exec($this->_connectionID, $sql); $this->_lastAffectedRows = 0; if ($stmtid) { @@ -508,8 +510,8 @@ class ADODB_odbc extends ADOConnection { $stmtid = true; } else { $this->_lastAffectedRows = 0; - odbc_binmode($stmtid,$this->binmode); - odbc_longreadlen($stmtid,$this->maxblobsize); + odbc_binmode($stmtid, $this->binmode); + odbc_longreadlen($stmtid, $this->maxblobsize); } if ($this->_haserrorfunctions) { @@ -536,9 +538,9 @@ class ADODB_odbc extends ADOConnection { $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); */ - function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') + function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB') { - return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false; + return $this->Execute("UPDATE $table SET $column=? WHERE $where", array($val)) != false; } // returns true or false @@ -560,7 +562,8 @@ class ADODB_odbc extends ADOConnection { Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordSet_odbc extends ADORecordSet { +class ADORecordSet_odbc extends ADORecordSet +{ var $bind = false; var $databaseType = "odbc"; @@ -568,7 +571,7 @@ class ADORecordSet_odbc extends ADORecordSet { var $useFetchArray; var $_has_stupid_odbc_fetch_api_change; - function ADORecordSet_odbc($id,$mode=false) + function ADORecordSet_odbc($id, $mode = false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -588,12 +591,12 @@ class ADORecordSet_odbc extends ADORecordSet { function &FetchField($fieldOffset = -1) { - $off=$fieldOffset+1; // offsets begin at 1 + $off = $fieldOffset + 1; // offsets begin at 1 - $o= new ADOFieldObject(); - $o->name = @odbc_field_name($this->_queryID,$off); - $o->type = @odbc_field_type($this->_queryID,$off); - $o->max_length = @odbc_field_len($this->_queryID,$off); + $o = new ADOFieldObject(); + $o->name = @odbc_field_name($this->_queryID, $off); + $o->type = @odbc_field_type($this->_queryID, $off); + $o->max_length = @odbc_field_len($this->_queryID, $off); if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name); else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name); return $o; @@ -605,18 +608,18 @@ class ADORecordSet_odbc extends ADORecordSet { if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname]; if (!$this->bind) { $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { + for ($i = 0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } function _initrs() { - global $ADODB_COUNTRECS; + global $ADODB_COUNTRECS; $this->_numOfRows = ($ADODB_COUNTRECS) ? @odbc_num_rows($this->_queryID) : -1; $this->_numOfFields = @odbc_num_fields($this->_queryID); // some silly drivers such as db2 as/400 and intersystems cache return _numOfRows = 0 @@ -631,7 +634,7 @@ class ADORecordSet_odbc extends ADORecordSet { } // speed up SelectLimit() by switching to ADODB_FETCH_NUM as ADODB_FETCH_ASSOC is emulated - function &GetArrayLimit($nrows,$offset=-1) + function &GetArrayLimit($nrows, $offset = -1) { if ($offset <= 0) { $rs =& $this->GetArray($nrows); @@ -662,9 +665,9 @@ class ADORecordSet_odbc extends ADORecordSet { $this->_currentRow++; $row = 0; if ($this->_has_stupid_odbc_fetch_api_change) - $rez = @odbc_fetch_into($this->_queryID,$this->fields); + $rez = @odbc_fetch_into($this->_queryID, $this->fields); else - $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields); + $rez = @odbc_fetch_into($this->_queryID, $row, $this->fields); if ($rez) { if ($this->fetchMode & ADODB_FETCH_ASSOC) { $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE); @@ -681,9 +684,9 @@ class ADORecordSet_odbc extends ADORecordSet { { $row = 0; if ($this->_has_stupid_odbc_fetch_api_change) - $rez = @odbc_fetch_into($this->_queryID,$this->fields,$row); + $rez = @odbc_fetch_into($this->_queryID, $this->fields, $row); else - $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields); + $rez = @odbc_fetch_into($this->_queryID, $row, $this->fields); if ($rez) { if ($this->fetchMode & ADODB_FETCH_ASSOC) { diff --git a/lib/WikiDB/adodb/drivers/adodb-odbc_mssql.inc.php b/lib/WikiDB/adodb/drivers/adodb-odbc_mssql.inc.php index 91e930da4..a6b941bdd 100644 --- a/lib/WikiDB/adodb/drivers/adodb-odbc_mssql.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-odbc_mssql.inc.php @@ -13,17 +13,18 @@ Set tabs to 4 for best viewing. */ if (!defined('_ADODB_ODBC_LAYER')) { - include(ADODB_DIR."/drivers/adodb-odbc.inc.php"); + include(ADODB_DIR . "/drivers/adodb-odbc.inc.php"); } -class ADODB_odbc_mssql extends ADODB_odbc { +class ADODB_odbc_mssql extends ADODB_odbc +{ var $databaseType = 'odbc_mssql'; var $fmtDate = "'Y-m-d'"; var $fmtTimeStamp = "'Y-m-d h:i:sA'"; var $_bindInputArray = true; - var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE'))"; + var $metaTablesSQL = "select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE'))"; var $metaColumnsSQL = "select c.name,t.name,c.length from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'"; - var $hasTop = 'top'; // support mssql/interbase SELECT TOP 10 * FROM TABLE + var $hasTop = 'top'; // support mssql/interbase SELECT TOP 10 * FROM TABLE var $sysDate = 'GetDate()'; var $sysTimeStamp = 'GetDate()'; var $leftOuter = '*='; @@ -35,7 +36,7 @@ class ADODB_odbc_mssql extends ADODB_odbc { var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000 var $hasInsertID = true; var $connectStmt = 'SET CONCAT_NULL_YIELDS_NULL OFF'; # When SET CONCAT_NULL_YIELDS_NULL is ON, - # concatenating a null value with a string yields a NULL result + # concatenating a null value with a string yields a NULL result function ADODB_odbc_mssql() { @@ -46,7 +47,7 @@ class ADODB_odbc_mssql extends ADODB_odbc { // crashes php... function ServerInfo() { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; $row = $this->GetRow("execute sp_server_info 2"); @@ -57,31 +58,31 @@ class ADODB_odbc_mssql extends ADODB_odbc { return $arr; } - function IfNull( $field, $ifNull ) + function IfNull($field, $ifNull) { return " ISNULL($field, $ifNull) "; // if MS SQL Server } function _insertid() { - // SCOPE_IDENTITY() - // Returns the last IDENTITY value inserted into an IDENTITY column in - // the same scope. A scope is a module -- a stored procedure, trigger, - // function, or batch. Thus, two statements are in the same scope if - // they are in the same stored procedure, function, or batch. - return $this->GetOne($this->identitySQL); + // SCOPE_IDENTITY() + // Returns the last IDENTITY value inserted into an IDENTITY column in + // the same scope. A scope is a module -- a stored procedure, trigger, + // function, or batch. Thus, two statements are in the same scope if + // they are in the same stored procedure, function, or batch. + return $this->GetOne($this->identitySQL); } - function MetaForeignKeys($table, $owner=false, $upper=false) + function MetaForeignKeys($table, $owner = false, $upper = false) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; $table = $this->qstr(strtoupper($table)); $sql = -"select object_name(constid) as constraint_name, + "select object_name(constid) as constraint_name, col_name(fkeyid, fkey) as column_name, object_name(rkeyid) as referenced_table_name, col_name(rkeyid, rkey) as referenced_column_name @@ -94,16 +95,16 @@ order by constraint_name, referenced_table_name, keyno"; $ADODB_FETCH_MODE = $save; $arr = false; - foreach($constraints as $constr) { + foreach ($constraints as $constr) { //print_r($constr); - $arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3]; + $arr[$constr[0]][$constr[2]][] = $constr[1] . '=' . $constr[3]; } if (!$arr) return false; $arr2 = false; - foreach($arr as $k => $v) { - foreach($v as $a => $b) { + foreach ($arr as $k => $v) { + foreach ($v as $a => $b) { if ($upper) $a = strtoupper($a); $arr2[$a] = $b; } @@ -111,14 +112,15 @@ order by constraint_name, referenced_table_name, keyno"; return $arr2; } - function &MetaTables($ttype=false,$showSchema=false,$mask=false) + function &MetaTables($ttype = false, $showSchema = false, $mask = false) { - if ($mask) {$this->debug=1; + if ($mask) { + $this->debug = 1; $save = $this->metaTablesSQL; $mask = $this->qstr($mask); $this->metaTablesSQL .= " AND name like $mask"; } - $ret =& ADOConnection::MetaTables($ttype,$showSchema); + $ret =& ADOConnection::MetaTables($ttype, $showSchema); if ($mask) { $this->metaTablesSQL = $save; @@ -131,10 +133,10 @@ order by constraint_name, referenced_table_name, keyno"; return ADOConnection::MetaColumns($table); } - function _query($sql,$inputarr) + function _query($sql, $inputarr) { - if (is_string($sql)) $sql = str_replace('||','+',$sql); - return ADODB_odbc::_query($sql,$inputarr); + if (is_string($sql)) $sql = str_replace('||', '+', $sql); + return ADODB_odbc::_query($sql, $inputarr); } // "Stein-Aksel Basma" <basma@accelero.no> @@ -147,77 +149,77 @@ order by constraint_name, referenced_table_name, keyno"; 'PRIMARY KEY' and k.table_name = '$table'"; $a = $this->GetCol($sql); - if ($a && sizeof($a)>0) return $a; + if ($a && sizeof($a) > 0) return $a; return false; } - function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) { if ($nrows > 0 && $offset <= 0) { $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql); - $rs =& $this->Execute($sql,$inputarr); + '/(^\s*select\s+(distinctrow|distinct)?)/i', '\\1 ' . $this->hasTop . " $nrows ", $sql); + $rs =& $this->Execute($sql, $inputarr); } else - $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + $rs =& ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); return $rs; } // Format date column in sql string given an input format that understands Y M D - function SQLDate($fmt, $col=false) + function SQLDate($fmt, $col = false) { if (!$col) $col = $this->sysTimeStamp; $s = ''; $len = strlen($fmt); - for ($i=0; $i < $len; $i++) { + for ($i = 0; $i < $len; $i++) { if ($s) $s .= '+'; $ch = $fmt[$i]; - switch($ch) { - case 'Y': - case 'y': - $s .= "datename(yyyy,$col)"; - break; - case 'M': - $s .= "convert(char(3),$col,0)"; - break; - case 'm': - $s .= "replace(str(month($col),2),' ','0')"; - break; - case 'Q': - case 'q': - $s .= "datename(quarter,$col)"; - break; - case 'D': - case 'd': - $s .= "replace(str(day($col),2),' ','0')"; - break; - case 'h': - $s .= "substring(convert(char(14),$col,0),13,2)"; - break; - - case 'H': - $s .= "replace(str(datepart(hh,$col),2),' ','0')"; - break; - - case 'i': - $s .= "replace(str(datepart(mi,$col),2),' ','0')"; - break; - case 's': - $s .= "replace(str(datepart(ss,$col),2),' ','0')"; - break; - case 'a': - case 'A': - $s .= "substring(convert(char(19),$col,0),18,2)"; - break; - - default: - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); - } - $s .= $this->qstr($ch); - break; + switch ($ch) { + case 'Y': + case 'y': + $s .= "datename(yyyy,$col)"; + break; + case 'M': + $s .= "convert(char(3),$col,0)"; + break; + case 'm': + $s .= "replace(str(month($col),2),' ','0')"; + break; + case 'Q': + case 'q': + $s .= "datename(quarter,$col)"; + break; + case 'D': + case 'd': + $s .= "replace(str(day($col),2),' ','0')"; + break; + case 'h': + $s .= "substring(convert(char(14),$col,0),13,2)"; + break; + + case 'H': + $s .= "replace(str(datepart(hh,$col),2),' ','0')"; + break; + + case 'i': + $s .= "replace(str(datepart(mi,$col),2),' ','0')"; + break; + case 's': + $s .= "replace(str(datepart(ss,$col),2),' ','0')"; + break; + case 'a': + case 'A': + $s .= "substring(convert(char(19),$col,0),18,2)"; + break; + + default: + if ($ch == '\\') { + $i++; + $ch = substr($fmt, $i, 1); + } + $s .= $this->qstr($ch); + break; } } return $s; @@ -225,12 +227,13 @@ order by constraint_name, referenced_table_name, keyno"; } -class ADORecordSet_odbc_mssql extends ADORecordSet_odbc { +class ADORecordSet_odbc_mssql extends ADORecordSet_odbc +{ var $databaseType = 'odbc_mssql'; - function ADORecordSet_odbc_mssql($id,$mode=false) + function ADORecordSet_odbc_mssql($id, $mode = false) { - return $this->ADORecordSet_odbc($id,$mode); + return $this->ADORecordSet_odbc($id, $mode); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-odbc_oracle.inc.php b/lib/WikiDB/adodb/drivers/adodb-odbc_oracle.inc.php index 807e0b01a..26530abae 100644 --- a/lib/WikiDB/adodb/drivers/adodb-odbc_oracle.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-odbc_oracle.inc.php @@ -12,13 +12,14 @@ Set tabs to 4 for best viewing. */ if (!defined('_ADODB_ODBC_LAYER')) { - include(ADODB_DIR."/drivers/adodb-odbc.inc.php"); + include(ADODB_DIR . "/drivers/adodb-odbc.inc.php"); } -class ADODB_odbc_oracle extends ADODB_odbc { +class ADODB_odbc_oracle extends ADODB_odbc +{ var $databaseType = 'odbc_oracle'; - var $replaceQuote = "''"; // string to use to replace quotes - var $concat_operator='||'; + var $replaceQuote = "''"; // string to use to replace quotes + var $concat_operator = '||'; var $fmtDate = "'Y-m-d 00:00:00'"; var $fmtTimeStamp = "'Y-m-d h:i:sA'"; var $metaTablesSQL = 'select table_name from cat'; @@ -40,7 +41,7 @@ class ADODB_odbc_oracle extends ADODB_odbc { if ($rs === false) return false; $arr = $rs->GetArray(); $arr2 = array(); - for ($i=0; $i < sizeof($arr); $i++) { + for ($i = 0; $i < sizeof($arr); $i++) { $arr2[] = $arr[$i][0]; } $rs->Close(); @@ -53,7 +54,7 @@ class ADODB_odbc_oracle extends ADODB_odbc { { if (!empty($this->metaColumnsSQL)) { - $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table))); + $rs = $this->Execute(sprintf($this->metaColumnsSQL, strtoupper($table))); if ($rs === false) return false; $retarr = array(); @@ -77,22 +78,23 @@ class ADODB_odbc_oracle extends ADODB_odbc { // returns true or false function _connect($argDSN, $argUsername, $argPassword, $argDatabasename) { - global $php_errormsg; + global $php_errormsg; $php_errormsg = ''; - $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC ); + $this->_connectionID = odbc_connect($argDSN, $argUsername, $argPassword, SQL_CUR_USE_ODBC); $this->_errorMsg = $php_errormsg; $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'"); //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true); return $this->_connectionID != false; } + // returns true or false function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename) { - global $php_errormsg; + global $php_errormsg; $php_errormsg = ''; - $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC ); + $this->_connectionID = odbc_pconnect($argDSN, $argUsername, $argPassword, SQL_CUR_USE_ODBC); $this->_errorMsg = $php_errormsg; $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'"); @@ -101,12 +103,13 @@ class ADODB_odbc_oracle extends ADODB_odbc { } } -class ADORecordSet_odbc_oracle extends ADORecordSet_odbc { +class ADORecordSet_odbc_oracle extends ADORecordSet_odbc +{ var $databaseType = 'odbc_oracle'; - function ADORecordSet_odbc_oracle($id,$mode=false) + function ADORecordSet_odbc_oracle($id, $mode = false) { - return $this->ADORecordSet_odbc($id,$mode); + return $this->ADORecordSet_odbc($id, $mode); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-odbtp.inc.php b/lib/WikiDB/adodb/drivers/adodb-odbtp.inc.php index 2714d9ba4..627c9e690 100644 --- a/lib/WikiDB/adodb/drivers/adodb-odbtp.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-odbtp.inc.php @@ -9,9 +9,10 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese */ // Code contributed by "stefan bogdan" <sbogdan#rsb.ro> -define("_ADODB_ODBTP_LAYER", 2 ); +define("_ADODB_ODBTP_LAYER", 2); -class ADODB_odbtp extends ADOConnection{ +class ADODB_odbtp extends ADOConnection +{ var $databaseType = "odbtp"; var $dataProvider = "odbtp"; var $fmtDate = "'Y-m-d'"; @@ -36,8 +37,8 @@ class ADODB_odbtp extends ADOConnection{ function ServerInfo() { - return array('description' => @odbtp_get_attr( ODB_ATTR_DBMSNAME, $this->_connectionID), - 'version' => @odbtp_get_attr( ODB_ATTR_DBMSVER, $this->_connectionID)); + return array('description' => @odbtp_get_attr(ODB_ATTR_DBMSNAME, $this->_connectionID), + 'version' => @odbtp_get_attr(ODB_ATTR_DBMSVER, $this->_connectionID)); } function ErrorMsg() @@ -49,42 +50,42 @@ class ADODB_odbtp extends ADOConnection{ function ErrorNo() { if (empty($this->_connectionID)) return @odbtp_last_error_state(); - return @odbtp_last_error_state($this->_connectionID); + return @odbtp_last_error_state($this->_connectionID); } function _insertid() { - // SCOPE_IDENTITY() - // Returns the last IDENTITY value inserted into an IDENTITY column in - // the same scope. A scope is a module -- a stored procedure, trigger, - // function, or batch. Thus, two statements are in the same scope if - // they are in the same stored procedure, function, or batch. - return $this->GetOne($this->identitySQL); + // SCOPE_IDENTITY() + // Returns the last IDENTITY value inserted into an IDENTITY column in + // the same scope. A scope is a module -- a stored procedure, trigger, + // function, or batch. Thus, two statements are in the same scope if + // they are in the same stored procedure, function, or batch. + return $this->GetOne($this->identitySQL); } function _affectedrows() { if ($this->_queryID) { - return @odbtp_affected_rows ($this->_queryID); - } else - return 0; + return @odbtp_affected_rows($this->_queryID); + } else + return 0; } - function CreateSequence($seqname='adodbseq',$start=1) + function CreateSequence($seqname = 'adodbseq', $start = 1) { //verify existence $num = $this->GetOne("select seq_value from adodb_seq"); - $seqtab='adodb_seq'; - if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) { - $path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID ); + $seqtab = 'adodb_seq'; + if ($this->odbc_driver == ODB_DRIVER_FOXPRO) { + $path = @odbtp_get_attr(ODB_ATTR_DATABASENAME, $this->_connectionID); //if using vfp dbc file - if( !strcasecmp(strrchr($path, '.'), '.dbc') ) - $path = substr($path,0,strrpos($path,'\/')); - $seqtab = $path . '/' . $seqtab; + if (!strcasecmp(strrchr($path, '.'), '.dbc')) + $path = substr($path, 0, strrpos($path, '\/')); + $seqtab = $path . '/' . $seqtab; } - if($num == false) { + if ($num == false) { if (empty($this->_genSeqSQL)) return false; - $ok = $this->Execute(sprintf($this->_genSeqSQL ,$seqtab)); + $ok = $this->Execute(sprintf($this->_genSeqSQL, $seqtab)); } $num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seqname'"); if ($num) { @@ -97,28 +98,28 @@ class ADODB_odbtp extends ADOConnection{ function DropSequence($seqname) { if (empty($this->_dropSeqSQL)) return false; - return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); + return $this->Execute(sprintf($this->_dropSeqSQL, $seqname)); } - function GenID($seq='adodbseq',$start=1) + function GenID($seq = 'adodbseq', $start = 1) { - $seqtab='adodb_seq'; - if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) { - $path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID ); + $seqtab = 'adodb_seq'; + if ($this->odbc_driver == ODB_DRIVER_FOXPRO) { + $path = @odbtp_get_attr(ODB_ATTR_DATABASENAME, $this->_connectionID); //if using vfp dbc file - if( !strcasecmp(strrchr($path, '.'), '.dbc') ) - $path = substr($path,0,strrpos($path,'\/')); - $seqtab = $path . '/' . $seqtab; + if (!strcasecmp(strrchr($path, '.'), '.dbc')) + $path = substr($path, 0, strrpos($path, '\/')); + $seqtab = $path . '/' . $seqtab; } $MAXLOOPS = 100; - while (--$MAXLOOPS>=0) { + while (--$MAXLOOPS >= 0) { $num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seq'"); if ($num === false) { //verify if abodb_seq table exist $ok = $this->GetOne("select seq_value from adodb_seq "); - if(!$ok) { + if (!$ok) { //creating the sequence table adodb_seq - $this->Execute(sprintf($this->_genSeqSQL ,$seqtab)); + $this->Execute(sprintf($this->_genSeqSQL, $seqtab)); } $start -= 1; $num = '0'; @@ -126,15 +127,15 @@ class ADODB_odbtp extends ADOConnection{ if (!$ok) return false; } $ok = $this->Execute("update adodb_seq set seq_value=seq_value+1 where seq_name='$seq'"); - if($ok) { + if ($ok) { $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); - } + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType, 'GENID', -32000, "Unable to generate unique id after $MAXLOOPS attempts", $seq, $num); + } return false; } @@ -144,18 +145,17 @@ class ADODB_odbtp extends ADOConnection{ //for access : DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\path_to_access_db\base_test.mdb;UID=root;PWD=; //for mssql : DRIVER={SQL Server};SERVER=myserver;UID=myuid;PWD=mypwd;DATABASE=OdbtpTest; //if uid & pwd can be separate - function _connect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='') + function _connect($HostOrInterface, $UserOrDSN = '', $argPassword = '', $argDatabase = '') { - $this->_connectionID = @odbtp_connect($HostOrInterface,$UserOrDSN,$argPassword,$argDatabase); - if ($this->_connectionID === false) - { - $this->_errorMsg = $this->ErrorMsg() ; + $this->_connectionID = @odbtp_connect($HostOrInterface, $UserOrDSN, $argPassword, $argDatabase); + if ($this->_connectionID === false) { + $this->_errorMsg = $this->ErrorMsg(); return false; } $this->odbc_driver = @odbtp_get_attr(ODB_ATTR_DRIVER, $this->_connectionID); // Set driver specific attributes - switch( $this->odbc_driver ) { + switch ($this->odbc_driver) { case ODB_DRIVER_MSSQL: $this->fmtDate = "'Y-m-d'"; $this->fmtTimeStamp = "'Y-m-d h:i:sA'"; @@ -182,7 +182,7 @@ class ADODB_odbtp extends ADOConnection{ $this->sysTimeStamp = 'NOW'; $this->hasTop = 'top'; $this->hasTransactions = false; - $this->_canPrepareSP = true; // For MS Access only. + $this->_canPrepareSP = true; // For MS Access only. // Can't rebind ODB_CHAR to ODB_WCHAR if row cache enabled. if ($this->_useUnicodeSQL) @@ -195,7 +195,7 @@ class ADODB_odbtp extends ADOConnection{ $this->sysTimeStamp = 'datetime()'; $this->ansiOuter = true; $this->hasTop = 'top'; - $this->hasTransactions = false; + $this->hasTransactions = false; $this->replaceQuote = "'+chr(39)+'"; $this->true = '.T.'; $this->false = '.F.'; @@ -223,20 +223,20 @@ class ADODB_odbtp extends ADOConnection{ $this->identitySQL = 'select @@IDENTITY'; break; default: - if( @odbtp_get_attr(ODB_ATTR_TXNCAPABLE, $this->_connectionID) ) - $this->hasTransactions = true; + if (@odbtp_get_attr(ODB_ATTR_TXNCAPABLE, $this->_connectionID)) + $this->hasTransactions = true; else $this->hasTransactions = false; } - @odbtp_set_attr(ODB_ATTR_FULLCOLINFO, TRUE, $this->_connectionID ); - if ($this->_useUnicodeSQL ) + @odbtp_set_attr(ODB_ATTR_FULLCOLINFO, TRUE, $this->_connectionID); + if ($this->_useUnicodeSQL) @odbtp_set_attr(ODB_ATTR_UNICODESQL, TRUE, $this->_connectionID); return true; } - function _pconnect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='') + function _pconnect($HostOrInterface, $UserOrDSN = '', $argPassword = '', $argDatabase = '') { - return $this->_connect($HostOrInterface, $UserOrDSN, $argPassword, $argDatabase); + return $this->_connect($HostOrInterface, $UserOrDSN, $argPassword, $argDatabase); } function SelectDB($dbName) @@ -248,9 +248,9 @@ class ADODB_odbtp extends ADOConnection{ return true; } - function &MetaTables($ttype='',$showSchema=false,$mask=false) + function &MetaTables($ttype = '', $showSchema = false, $mask = false) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $savem = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; @@ -258,25 +258,25 @@ class ADODB_odbtp extends ADOConnection{ $ADODB_FETCH_MODE = $savem; $arr2 = array(); - for ($i=0; $i < sizeof($arr); $i++) { - if ($arr[$i][3] == 'SYSTEM TABLE' ) continue; + for ($i = 0; $i < sizeof($arr); $i++) { + if ($arr[$i][3] == 'SYSTEM TABLE') continue; if ($arr[$i][2]) - $arr2[] = $showSchema ? $arr[$i][1].'.'.$arr[$i][2] : $arr[$i][2]; + $arr2[] = $showSchema ? $arr[$i][1] . '.' . $arr[$i][2] : $arr[$i][2]; } return $arr2; } - function &MetaColumns($table,$upper=true) + function &MetaColumns($table, $upper = true) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $schema = false; - $this->_findschema($table,$schema); + $this->_findschema($table, $schema); if ($upper) $table = strtoupper($table); $savem = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - $rs = $this->Execute( "||SQLColumns||$schema|$table" ); + $rs = $this->Execute("||SQLColumns||$schema|$table"); $ADODB_FETCH_MODE = $savem; if (!$rs) return false; @@ -289,13 +289,13 @@ class ADODB_odbtp extends ADOConnection{ $fld->type = $rs->fields[5]; $fld->max_length = $rs->fields[6]; $fld->not_null = !empty($rs->fields[9]); - $fld->scale = $rs->fields[7]; - if (!is_null($rs->fields[12])) { - $fld->has_default = true; - $fld->default_value = $rs->fields[12]; + $fld->scale = $rs->fields[7]; + if (!is_null($rs->fields[12])) { + $fld->has_default = true; + $fld->default_value = $rs->fields[12]; } $retarr[strtoupper($fld->name)] = $fld; - } elseif (sizeof($retarr)>0) + } elseif (sizeof($retarr) > 0) break; $rs->MoveNext(); } @@ -304,9 +304,9 @@ class ADODB_odbtp extends ADOConnection{ return $retarr; } - function &MetaPrimaryKeys($table, $owner='') + function &MetaPrimaryKeys($table, $owner = '') { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $savem = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; @@ -315,15 +315,15 @@ class ADODB_odbtp extends ADOConnection{ //print_r($arr); $arr2 = array(); - for ($i=0; $i < sizeof($arr); $i++) { + for ($i = 0; $i < sizeof($arr); $i++) { if ($arr[$i][3]) $arr2[] = $arr[$i][3]; } return $arr2; } - function &MetaForeignKeys($table, $owner='', $upper=false) + function &MetaForeignKeys($table, $owner = '', $upper = false) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $savem = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; @@ -331,16 +331,16 @@ class ADODB_odbtp extends ADOConnection{ $ADODB_FETCH_MODE = $savem; $arr = false; - foreach($constraints as $constr) { + foreach ($constraints as $constr) { //print_r($constr); - $arr[$constr[11]][$constr[2]][] = $constr[7].'='.$constr[3]; + $arr[$constr[11]][$constr[2]][] = $constr[7] . '=' . $constr[3]; } if (!$arr) return false; $arr2 = array(); - foreach($arr as $k => $v) { - foreach($v as $a => $b) { + foreach ($arr as $k => $v) { + foreach ($v as $a => $b) { if ($upper) $a = strtoupper($a); $arr2[$a] = $b; } @@ -354,19 +354,20 @@ class ADODB_odbtp extends ADOConnection{ if ($this->transOff) return true; $this->transCnt += 1; $this->_autocommit = false; - $rs = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS,ODB_TXN_READUNCOMMITTED,$this->_connectionID); - if(!$rs) return false; + $rs = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_READUNCOMMITTED, $this->_connectionID); + if (!$rs) return false; else return true; } - function CommitTrans($ok=true) + function CommitTrans($ok = true) { if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); if ($this->transCnt) $this->transCnt -= 1; $this->_autocommit = true; - if( ($ret = odbtp_commit($this->_connectionID)) ) - $ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off + if (($ret = odbtp_commit($this->_connectionID))) + $ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID); + //set transaction off return $ret; } @@ -375,38 +376,39 @@ class ADODB_odbtp extends ADOConnection{ if ($this->transOff) return true; if ($this->transCnt) $this->transCnt -= 1; $this->_autocommit = true; - if( ($ret = odbtp_rollback($this->_connectionID)) ) - $ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off + if (($ret = odbtp_rollback($this->_connectionID))) + $ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID); + //set transaction off return $ret; } - function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) { // TOP requires ORDER BY for Visual FoxPro - if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) { - if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1'; + if ($this->odbc_driver == ODB_DRIVER_FOXPRO) { + if (!preg_match('/ORDER[ \t\r\n]+BY/is', $sql)) $sql .= ' ORDER BY 1'; } - return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + return ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); } function Prepare($sql) { - if (! $this->_bindInputArray) return $sql; // no binding - $stmt = odbtp_prepare($sql,$this->_connectionID); + if (!$this->_bindInputArray) return $sql; // no binding + $stmt = odbtp_prepare($sql, $this->_connectionID); if (!$stmt) { - // print "Prepare Error for ($sql) ".$this->ErrorMsg()."<br>"; + // print "Prepare Error for ($sql) ".$this->ErrorMsg()."<br>"; return $sql; } - return array($sql,$stmt,false); + return array($sql, $stmt, false); } function PrepareSP($sql) { if (!$this->_canPrepareSP) return $sql; // Can't prepare procedures - $stmt = odbtp_prepare_proc($sql,$this->_connectionID); + $stmt = odbtp_prepare_proc($sql, $this->_connectionID); if (!$stmt) return false; - return array($sql,$stmt); + return array($sql, $stmt); } /* @@ -428,18 +430,17 @@ class ADODB_odbtp extends ADOConnection{ See odbtp_attach_param documentation at http://odbtp.sourceforge.net. */ - function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=0, $type=0) + function Parameter(&$stmt, &$var, $name, $isOutput = false, $maxLen = 0, $type = 0) { - if ( $this->odbc_driver == ODB_DRIVER_JET ) { - $name = '['.$name.']'; - if( !$type && $this->_useUnicodeSQL - && @odbtp_param_bindtype($stmt[1], $name) == ODB_CHAR ) - { + if ($this->odbc_driver == ODB_DRIVER_JET) { + $name = '[' . $name . ']'; + if (!$type && $this->_useUnicodeSQL + && @odbtp_param_bindtype($stmt[1], $name) == ODB_CHAR + ) { $type = ODB_WCHAR; } - } - else { - $name = '@'.$name; + } else { + $name = '@' . $name; } return odbtp_attach_param($stmt[1], $name, $var, $type, $maxLen); } @@ -454,21 +455,21 @@ class ADODB_odbtp extends ADOConnection{ $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); */ - function UpdateBlob($table,$column,$val,$where,$blobtype='image') + function UpdateBlob($table, $column, $val, $where, $blobtype = 'image') { $sql = "UPDATE $table SET $column = ? WHERE $where"; - if( !($stmt = odbtp_prepare($sql, $this->_connectionID)) ) + if (!($stmt = odbtp_prepare($sql, $this->_connectionID))) return false; - if( !odbtp_input( $stmt, 1, ODB_BINARY, 1000000, $blobtype ) ) + if (!odbtp_input($stmt, 1, ODB_BINARY, 1000000, $blobtype)) return false; - if( !odbtp_set( $stmt, 1, $val ) ) + if (!odbtp_set($stmt, 1, $val)) return false; - return odbtp_execute( $stmt ) != false; + return odbtp_execute($stmt) != false; } - function IfNull( $field, $ifNull ) + function IfNull($field, $ifNull) { - switch( $this->odbc_driver ) { + switch ($this->odbc_driver) { case ODB_DRIVER_MSSQL: return " ISNULL($field, $ifNull) "; case ODB_DRIVER_JET: @@ -477,24 +478,24 @@ class ADODB_odbtp extends ADOConnection{ return " CASE WHEN $field is null THEN $ifNull ELSE $field END "; } - function _query($sql,$inputarr=false) + function _query($sql, $inputarr = false) { - if ($inputarr) { + if ($inputarr) { if (is_array($sql)) { $stmtid = $sql[1]; } else { - $stmtid = odbtp_prepare($sql,$this->_connectionID); + $stmtid = odbtp_prepare($sql, $this->_connectionID); if ($stmtid == false) { $this->_errorMsg = $php_errormsg; return false; } } - $num_params = odbtp_num_params( $stmtid ); - for( $param = 1; $param <= $num_params; $param++ ) { - @odbtp_input( $stmtid, $param ); - @odbtp_set( $stmtid, $param, $inputarr[$param-1] ); + $num_params = odbtp_num_params($stmtid); + for ($param = 1; $param <= $num_params; $param++) { + @odbtp_input($stmtid, $param); + @odbtp_set($stmtid, $param, $inputarr[$param - 1]); } - if (! odbtp_execute($stmtid) ) { + if (!odbtp_execute($stmtid)) { return false; } } elseif (is_array($sql)) { @@ -503,11 +504,11 @@ class ADODB_odbtp extends ADOConnection{ return false; } } else { - $stmtid = @odbtp_query($sql,$this->_connectionID); - } + $stmtid = @odbtp_query($sql, $this->_connectionID); + } $this->_lastAffectedRows = 0; if ($stmtid) { - $this->_lastAffectedRows = @odbtp_affected_rows($stmtid); + $this->_lastAffectedRows = @odbtp_affected_rows($stmtid); } return $stmtid; } @@ -520,12 +521,13 @@ class ADODB_odbtp extends ADOConnection{ } } -class ADORecordSet_odbtp extends ADORecordSet { +class ADORecordSet_odbtp extends ADORecordSet +{ var $databaseType = 'odbtp'; var $canSeek = true; - function ADORecordSet_odbtp($queryID,$mode=false) + function ADORecordSet_odbtp($queryID, $mode = false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -544,11 +546,11 @@ class ADORecordSet_odbtp extends ADORecordSet { function &FetchField($fieldOffset = 0) { - $off=$fieldOffset; // offsets begin at 0 - $o= new ADOFieldObject(); - $o->name = @odbtp_field_name($this->_queryID,$off); - $o->type = @odbtp_field_type($this->_queryID,$off); - $o->max_length = @odbtp_field_length($this->_queryID,$off); + $off = $fieldOffset; // offsets begin at 0 + $o = new ADOFieldObject(); + $o->name = @odbtp_field_name($this->_queryID, $off); + $o->type = @odbtp_field_type($this->_queryID, $off); + $o->max_length = @odbtp_field_length($this->_queryID, $off); if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name); else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name); return $o; @@ -565,15 +567,15 @@ class ADORecordSet_odbtp extends ADORecordSet { if (!$this->bind) { $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { - $name = @odbtp_field_name( $this->_queryID, $i ); + for ($i = 0; $i < $this->_numOfFields; $i++) { + $name = @odbtp_field_name($this->_queryID, $i); $this->bind[strtoupper($name)] = $i; } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } - function _fetch_odbtp($type=0) + function _fetch_odbtp($type = 0) { switch ($this->fetchMode) { case ADODB_FETCH_NUM: @@ -597,16 +599,16 @@ class ADORecordSet_odbtp extends ADORecordSet { { if (!$this->_fetch_odbtp(ODB_FETCH_FIRST)) return false; $this->EOF = false; - $this->_currentRow = 0; - return true; + $this->_currentRow = 0; + return true; } function MoveLast() - { + { if (!$this->_fetch_odbtp(ODB_FETCH_LAST)) return false; $this->EOF = false; $this->_currentRow = $this->_numOfRows - 1; - return true; + return true; } function NextRecordSet() diff --git a/lib/WikiDB/adodb/drivers/adodb-odbtp_unicode.inc.php b/lib/WikiDB/adodb/drivers/adodb-odbtp_unicode.inc.php index 20027e3e8..1daf2113d 100644 --- a/lib/WikiDB/adodb/drivers/adodb-odbtp_unicode.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-odbtp_unicode.inc.php @@ -21,10 +21,11 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese */ if (!defined('_ADODB_ODBTP_LAYER')) { - include(ADODB_DIR."/drivers/adodb-odbtp.inc.php"); + include(ADODB_DIR . "/drivers/adodb-odbtp.inc.php"); } -class ADODB_odbtp_unicode extends ADODB_odbtp { +class ADODB_odbtp_unicode extends ADODB_odbtp +{ var $databaseType = "odbtp_unicode"; var $_useUnicodeSQL = true; @@ -34,10 +35,11 @@ class ADODB_odbtp_unicode extends ADODB_odbtp { } } -class ADORecordSet_odbtp_unicode extends ADORecordSet_odbtp { +class ADORecordSet_odbtp_unicode extends ADORecordSet_odbtp +{ var $databaseType = 'odbtp_unicode'; - function ADORecordSet_odbtp_unicode($queryID,$mode=false) + function ADORecordSet_odbtp_unicode($queryID, $mode = false) { $this->ADORecordSet_odbtp($queryID, $mode); } diff --git a/lib/WikiDB/adodb/drivers/adodb-oracle.inc.php b/lib/WikiDB/adodb/drivers/adodb-oracle.inc.php index ea4391926..ba1007aff 100644 --- a/lib/WikiDB/adodb/drivers/adodb-oracle.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-oracle.inc.php @@ -13,10 +13,11 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese */ -class ADODB_oracle extends ADOConnection { +class ADODB_oracle extends ADOConnection +{ var $databaseType = "oracle"; var $replaceQuote = "''"; // string to use to replace quotes - var $concat_operator='||'; + var $concat_operator = '||'; var $_curs; var $_initdate = true; // init date to YYYY-MM-DD var $metaTablesSQL = 'select table_name from cat'; @@ -33,29 +34,29 @@ class ADODB_oracle extends ADOConnection { function DBDate($d) { if (is_string($d)) $d = ADORecordSet::UnixDate($d); - return 'TO_DATE('.adodb_date($this->fmtDate,$d).",'YYYY-MM-DD')"; + return 'TO_DATE(' . adodb_date($this->fmtDate, $d) . ",'YYYY-MM-DD')"; } // format and return date string in database timestamp format function DBTimeStamp($ts) { if (is_string($ts)) $d = ADORecordSet::UnixTimeStamp($ts); - return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')"; + return 'TO_DATE(' . adodb_date($this->fmtTimeStamp, $ts) . ",'RRRR-MM-DD, HH:MI:SS AM')"; } function BeginTrans() { - $this->autoCommit = false; - ora_commitoff($this->_connectionID); - return true; + $this->autoCommit = false; + ora_commitoff($this->_connectionID); + return true; } - function CommitTrans($ok=true) + function CommitTrans($ok = true) { - if (!$ok) return $this->RollbackTrans(); - $ret = ora_commit($this->_connectionID); - ora_commiton($this->_connectionID); - return $ret; + if (!$ok) return $this->RollbackTrans(); + $ret = ora_commit($this->_connectionID); + ora_commiton($this->_connectionID); + return $ret; } function RollbackTrans() @@ -67,9 +68,9 @@ class ADODB_oracle extends ADOConnection { /* there seems to be a bug in the oracle extension -- always returns ORA-00000 - no error */ function ErrorMsg() - { + { $this->_errorMsg = @ora_error($this->_curs); - if (!$this->_errorMsg) $this->_errorMsg = @ora_error($this->_connectionID); + if (!$this->_errorMsg) $this->_errorMsg = @ora_error($this->_connectionID); return $this->_errorMsg; } @@ -79,76 +80,76 @@ class ADODB_oracle extends ADOConnection { if (!$err) return @ora_errorcode($this->_connectionID); } - // returns true or false - function _connect($argHostname, $argUsername, $argPassword, $argDatabasename, $mode=0) - { - // G. Giunta 2003/08/13 - This looks danegrously suspicious: why should we want to set - // the oracle home to the host name of remote DB? + // returns true or false + function _connect($argHostname, $argUsername, $argPassword, $argDatabasename, $mode = 0) + { + // G. Giunta 2003/08/13 - This looks danegrously suspicious: why should we want to set + // the oracle home to the host name of remote DB? // if ($argHostname) putenv("ORACLE_HOME=$argHostname"); - if($argHostname) { // code copied from version submitted for oci8 by Jorma Tuomainen <jorma.tuomainen@ppoy.fi> - if (empty($argDatabasename)) $argDatabasename = $argHostname; - else { - if(strpos($argHostname,":")) { - $argHostinfo=explode(":",$argHostname); - $argHostname=$argHostinfo[0]; - $argHostport=$argHostinfo[1]; - } else { - $argHostport="1521"; - } - - if ($this->connectSID) { - $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname - .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))"; - } else - $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname - .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))"; + if ($argHostname) { // code copied from version submitted for oci8 by Jorma Tuomainen <jorma.tuomainen@ppoy.fi> + if (empty($argDatabasename)) $argDatabasename = $argHostname; + else { + if (strpos($argHostname, ":")) { + $argHostinfo = explode(":", $argHostname); + $argHostname = $argHostinfo[0]; + $argHostport = $argHostinfo[1]; + } else { + $argHostport = "1521"; } + if ($this->connectSID) { + $argDatabasename = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=" . $argHostname + . ")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))"; + } else + $argDatabasename = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=" . $argHostname + . ")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))"; } - if ($argDatabasename) $argUsername .= "@$argDatabasename"; + } - //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>"; - if ($mode = 1) - $this->_connectionID = ora_plogon($argUsername,$argPassword); - else - $this->_connectionID = ora_logon($argUsername,$argPassword); - if ($this->_connectionID === false) return false; - if ($this->autoCommit) ora_commiton($this->_connectionID); - if ($this->_initdate) { - $rs = $this->_query("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'"); - if ($rs) ora_close($rs); - } + if ($argDatabasename) $argUsername .= "@$argDatabasename"; - return true; + //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>"; + if ($mode = 1) + $this->_connectionID = ora_plogon($argUsername, $argPassword); + else + $this->_connectionID = ora_logon($argUsername, $argPassword); + if ($this->_connectionID === false) return false; + if ($this->autoCommit) ora_commiton($this->_connectionID); + if ($this->_initdate) { + $rs = $this->_query("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'"); + if ($rs) ora_close($rs); } - // returns true or false - function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, 1); - } + return true; + } - // returns query ID if successful, otherwise false - function _query($sql,$inputarr=false) - { - $curs = ora_open($this->_connectionID); + // returns true or false + function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, 1); + } - if ($curs === false) return false; - $this->_curs = $curs; - if (!ora_parse($curs,$sql)) return false; - if (ora_exec($curs)) return $curs; + // returns query ID if successful, otherwise false + function _query($sql, $inputarr = false) + { + $curs = ora_open($this->_connectionID); - @ora_close($curs); - return false; - } + if ($curs === false) return false; + $this->_curs = $curs; + if (!ora_parse($curs, $sql)) return false; + if (ora_exec($curs)) return $curs; - // returns true or false - function _close() - { - return @ora_logoff($this->_connectionID); - } + @ora_close($curs); + return false; + } + + // returns true or false + function _close() + { + return @ora_logoff($this->_connectionID); + } } @@ -156,12 +157,13 @@ class ADODB_oracle extends ADOConnection { Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordset_oracle extends ADORecordSet { +class ADORecordset_oracle extends ADORecordSet +{ var $databaseType = "oracle"; var $bind = false; - function ADORecordset_oracle($queryID,$mode=false) + function ADORecordset_oracle($queryID, $mode = false) { if ($mode === false) { @@ -187,61 +189,62 @@ class ADORecordset_oracle extends ADORecordSet { return $this->_queryID; } - /* Returns: an object containing field information. - Get column information in the Recordset object. fetchField() can be used in order to obtain information about - fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by - fetchField() is retrieved. */ + /* Returns: an object containing field information. + Get column information in the Recordset object. fetchField() can be used in order to obtain information about + fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by + fetchField() is retrieved. */ - function FetchField($fieldOffset = -1) - { - $fld = new ADOFieldObject; - $fld->name = ora_columnname($this->_queryID, $fieldOffset); - $fld->type = ora_columntype($this->_queryID, $fieldOffset); - $fld->max_length = ora_columnsize($this->_queryID, $fieldOffset); - return $fld; - } + function FetchField($fieldOffset = -1) + { + $fld = new ADOFieldObject; + $fld->name = ora_columnname($this->_queryID, $fieldOffset); + $fld->type = ora_columntype($this->_queryID, $fieldOffset); + $fld->max_length = ora_columnsize($this->_queryID, $fieldOffset); + return $fld; + } /* Use associative array to get fields array */ function Fields($colname) { if (!$this->bind) { $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { + for ($i = 0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } - function _initrs() - { - $this->_numOfRows = -1; - $this->_numOfFields = @ora_numcols($this->_queryID); - } + function _initrs() + { + $this->_numOfRows = -1; + $this->_numOfFields = @ora_numcols($this->_queryID); + } - function _seek($row) - { - return false; - } + function _seek($row) + { + return false; + } - function _fetch($ignore_fields=false) { + function _fetch($ignore_fields = false) + { if ($this->fetchMode & ADODB_FETCH_ASSOC) - return @ora_fetch_into($this->_queryID,$this->fields,ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC); - else - return @ora_fetch_into($this->_queryID,$this->fields,ORA_FETCHINTO_NULLS); - } + return @ora_fetch_into($this->_queryID, $this->fields, ORA_FETCHINTO_NULLS | ORA_FETCHINTO_ASSOC); + else + return @ora_fetch_into($this->_queryID, $this->fields, ORA_FETCHINTO_NULLS); + } - /* close() only needs to be called if you are worried about using too much memory while your script - is running. All associated result memory for the specified result identifier will automatically be freed. */ + /* close() only needs to be called if you are worried about using too much memory while your script + is running. All associated result memory for the specified result identifier will automatically be freed. */ - function _close() -{ - return @ora_close($this->_queryID); - } + function _close() + { + return @ora_close($this->_queryID); + } - function MetaType($t,$len=-1) + function MetaType($t, $len = -1) { if (is_object($t)) { $fieldobj = $t; @@ -250,30 +253,34 @@ class ADORecordset_oracle extends ADORecordSet { } switch (strtoupper($t)) { - case 'VARCHAR': - case 'VARCHAR2': - case 'CHAR': - case 'VARBINARY': - case 'BINARY': + case 'VARCHAR': + case 'VARCHAR2': + case 'CHAR': + case 'VARBINARY': + case 'BINARY': if ($len <= $this->blobSize) return 'C'; - case 'LONG': - case 'LONG VARCHAR': - case 'CLOB': - return 'X'; - case 'LONG RAW': - case 'LONG VARBINARY': - case 'BLOB': + case 'LONG': + case 'LONG VARCHAR': + case 'CLOB': + return 'X'; + case 'LONG RAW': + case 'LONG VARBINARY': + case 'BLOB': return 'B'; - case 'DATE': return 'D'; + case 'DATE': + return 'D'; - //case 'T': return 'T'; + //case 'T': return 'T'; - case 'BIT': return 'L'; - case 'INT': - case 'SMALLINT': - case 'INTEGER': return 'I'; - default: return 'N'; + case 'BIT': + return 'L'; + case 'INT': + case 'SMALLINT': + case 'INTEGER': + return 'I'; + default: + return 'N'; } } } diff --git a/lib/WikiDB/adodb/drivers/adodb-postgres64.inc.php b/lib/WikiDB/adodb/drivers/adodb-postgres64.inc.php index 611ba703a..2cee87bff 100644 --- a/lib/WikiDB/adodb/drivers/adodb-postgres64.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-postgres64.inc.php @@ -46,17 +46,18 @@ function adodb_addslashes($s) { $len = strlen($s); if ($len == 0) return "''"; - if (strncmp($s,"'",1) === 0 && substr(s,$len-1) == "'") return $s; // already quoted + if (strncmp($s, "'", 1) === 0 && substr(s, $len - 1) == "'") return $s; // already quoted - return "'".addslashes($s)."'"; + return "'" . addslashes($s) . "'"; } -class ADODB_postgres64 extends ADOConnection{ +class ADODB_postgres64 extends ADOConnection +{ var $databaseType = 'postgres64'; var $dataProvider = 'postgres'; var $hasInsertID = true; var $_resultid = false; - var $concat_operator='||'; + var $concat_operator = '||'; var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1"; var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%' union select viewname,'V' from pg_views where viewname not like 'pg\_%'"; @@ -82,11 +83,11 @@ WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'"; var $hasAffectedRows = true; - var $hasLimit = false; // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10 + var $hasLimit = false; // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10 // below suggested by Freek Dijkstra - var $true = 't'; // string that represents TRUE for a database - var $false = 'f'; // string that represents FALSE for a database - var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database + var $true = 't'; // string that represents TRUE for a database + var $false = 'f'; // string that represents FALSE for a database + var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt. var $hasMoveFirst = true; var $hasGenID = true; @@ -94,9 +95,9 @@ WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) var $_genSeqSQL = "CREATE SEQUENCE %s START %s"; var $_dropSeqSQL = "DROP SEQUENCE %s"; var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum"; - var $random = 'random()'; /// random function + var $random = 'random()'; /// random function var $autoRollback = true; // apparently pgsql does not autorollback properly before 4.3.4 - // http://bugs.php.net/bug.php?id=25404 + // http://bugs.php.net/bug.php?id=25404 var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database @@ -110,7 +111,7 @@ WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) function ADODB_postgres64() { - // changes the metaColumnsSQL, adds columns: attnum[6] + // changes the metaColumnsSQL, adds columns: attnum[6] } function ServerInfo() @@ -122,43 +123,44 @@ WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) $this->version = $arr; return $arr; } -/* - function IfNull( $field, $ifNull ) - { - return " NULLIF($field, $ifNull) "; // if PGSQL - } -*/ + + /* + function IfNull( $field, $ifNull ) + { + return " NULLIF($field, $ifNull) "; // if PGSQL + } + */ // get the last id - never tested - function pg_insert_id($tablename,$fieldname) + function pg_insert_id($tablename, $fieldname) { - $result=pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq"); + $result = pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq"); if ($result) { - $arr = @pg_fetch_row($result,0); + $arr = @pg_fetch_row($result, 0); pg_freeresult($result); if (isset($arr[0])) return $arr[0]; } return false; } -/* Warning from http://www.php.net/manual/function.pg-getlastoid.php: -Using a OID as a unique identifier is not generally wise. -Unless you are very careful, you might end up with a tuple having -a different OID if a database must be reloaded. */ + /* Warning from http://www.php.net/manual/function.pg-getlastoid.php: + Using a OID as a unique identifier is not generally wise. + Unless you are very careful, you might end up with a tuple having + a different OID if a database must be reloaded. */ function _insertid() { if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false; - return pg_getlastoid($this->_resultid); + return pg_getlastoid($this->_resultid); } // I get this error with PHP before 4.0.6 - jlim // Warning: This compilation does not support pg_cmdtuples() in d:/inetpub/wwwroot/php/adodb/adodb-postgres.inc.php on line 44 - function _affectedrows() - { - if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false; - return pg_cmdtuples($this->_resultid); - } + function _affectedrows() + { + if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false; + return pg_cmdtuples($this->_resultid); + } - // returns true/false + // returns true/false function BeginTrans() { if ($this->transOff) return true; @@ -166,14 +168,14 @@ a different OID if a database must be reloaded. */ return @pg_Exec($this->_connectionID, "begin"); } - function RowLock($tables,$where) + function RowLock($tables, $where) { if (!$this->transCnt) $this->BeginTrans(); return $this->GetOne("select 1 as ignore from $tables where $where for update"); } // returns true/false. - function CommitTrans($ok=true) + function CommitTrans($ok = true) { if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); @@ -190,7 +192,7 @@ a different OID if a database must be reloaded. */ return @pg_Exec($this->_connectionID, "rollback"); } - function &MetaTables($ttype=false,$showSchema=false,$mask=false) + function &MetaTables($ttype = false, $showSchema = false, $mask = false) { if ($mask) { $save = $this->metaTablesSQL; @@ -199,7 +201,7 @@ a different OID if a database must be reloaded. */ select tablename,'T' from pg_tables where tablename like $mask union select viewname,'V' from pg_views where viewname like $mask"; } - $ret =& ADOConnection::MetaTables($ttype,$showSchema); + $ret =& ADOConnection::MetaTables($ttype, $showSchema); if ($mask) { $this->metaTablesSQL = $save; @@ -229,73 +231,72 @@ select viewname,'V' from pg_views where viewname like $mask"; // Format date column in sql string given an input format that understands Y M D - function SQLDate($fmt, $col=false) + function SQLDate($fmt, $col = false) { if (!$col) $col = $this->sysTimeStamp; - $s = 'TO_CHAR('.$col.",'"; + $s = 'TO_CHAR(' . $col . ",'"; $len = strlen($fmt); - for ($i=0; $i < $len; $i++) { + for ($i = 0; $i < $len; $i++) { $ch = $fmt[$i]; - switch($ch) { - case 'Y': - case 'y': - $s .= 'YYYY'; - break; - case 'Q': - case 'q': - $s .= 'Q'; - break; - - case 'M': - $s .= 'Mon'; - break; - - case 'm': - $s .= 'MM'; - break; - case 'D': - case 'd': - $s .= 'DD'; - break; - - case 'H': - $s.= 'HH24'; - break; - - case 'h': - $s .= 'HH'; - break; - - case 'i': - $s .= 'MI'; - break; - - case 's': - $s .= 'SS'; - break; - - case 'a': - case 'A': - $s .= 'AM'; - break; - - default: - // handle escape characters... - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); - } - if (strpos('-/.:;, ',$ch) !== false) $s .= $ch; - else $s .= '"'.$ch.'"'; + switch ($ch) { + case 'Y': + case 'y': + $s .= 'YYYY'; + break; + case 'Q': + case 'q': + $s .= 'Q'; + break; + + case 'M': + $s .= 'Mon'; + break; + + case 'm': + $s .= 'MM'; + break; + case 'D': + case 'd': + $s .= 'DD'; + break; + + case 'H': + $s .= 'HH24'; + break; + + case 'h': + $s .= 'HH'; + break; + + case 'i': + $s .= 'MI'; + break; + + case 's': + $s .= 'SS'; + break; + + case 'a': + case 'A': + $s .= 'AM'; + break; + + default: + // handle escape characters... + if ($ch == '\\') { + $i++; + $ch = substr($fmt, $i, 1); + } + if (strpos('-/.:;, ', $ch) !== false) $s .= $ch; + else $s .= '"' . $ch . '"'; } } - return $s. "')"; + return $s . "')"; } - /* * Load a Large Object from a file * - the procedure stores the object id in the table and imports the object using @@ -304,12 +305,12 @@ select viewname,'V' from pg_views where viewname like $mask"; * contributed by Mattia Rossi mattia@technologist.com * modified for safe mode by juraj chlebec */ - function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') + function UpdateBlobFile($table, $column, $path, $where, $blobtype = 'BLOB') { - pg_exec ($this->_connectionID, "begin"); + pg_exec($this->_connectionID, "begin"); - $fd = fopen($path,'r'); - $contents = fread($fd,filesize($path)); + $fd = fopen($path, 'r'); + $contents = fread($fd, filesize($path)); fclose($fd); $oid = pg_lo_create($this->_connectionID); @@ -319,7 +320,7 @@ select viewname,'V' from pg_views where viewname like $mask"; // $oid = pg_lo_import ($path); pg_exec($this->_connectionID, "commit"); - $rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype); + $rs = ADOConnection::UpdateBlob($table, $column, $oid, $where, $blobtype); $rez = !empty($rs); return $rez; } @@ -333,19 +334,19 @@ select viewname,'V' from pg_views where viewname like $mask"; * * see http://www.postgresql.org/idocs/index.php?largeobjects.html */ - function BlobDecode( $blob) + function BlobDecode($blob) { if (strlen($blob) > 24) return $blob; - @pg_exec($this->_connectionID,"begin"); - $fd = @pg_lo_open($this->_connectionID,$blob,"r"); + @pg_exec($this->_connectionID, "begin"); + $fd = @pg_lo_open($this->_connectionID, $blob, "r"); if ($fd === false) { - @pg_exec($this->_connectionID,"commit"); + @pg_exec($this->_connectionID, "commit"); return $blob; } $realblob = @pg_loreadall($fd); @pg_loclose($fd); - @pg_exec($this->_connectionID,"commit"); + @pg_exec($this->_connectionID, "commit"); return $realblob; } @@ -361,20 +362,20 @@ select viewname,'V' from pg_views where viewname like $mask"; if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob); /*92=backslash, 0=null, 39=single-quote*/ - $badch = array(chr(92),chr(0),chr(39)); # \ null ' - $fixch = array('\\\\134','\\\\000','\\\\047'); - return adodb_str_replace($badch,$fixch,$blob); + $badch = array(chr(92), chr(0), chr(39)); # \ null ' + $fixch = array('\\\\134', '\\\\000', '\\\\047'); + return adodb_str_replace($badch, $fixch, $blob); // note that there is a pg_escape_bytea function only for php 4.2.0 or later } - function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') + function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB') { // do not use bind params which uses qstr(), as blobencode() already quotes data - return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where"); + return $this->Execute("UPDATE $table SET $column='" . $this->BlobEncode($val) . "'::bytea WHERE $where"); } - function OffsetDate($dayFraction,$date=false) + function OffsetDate($dayFraction, $date = false) { if (!$date) $date = $this->sysDate; return "($date+interval'$dayFraction days')"; @@ -383,12 +384,12 @@ select viewname,'V' from pg_views where viewname like $mask"; // for schema support, pass in the $table param "$schema.$tabname". // converts field names to lowercase, $upper is ignored - function &MetaColumns($table,$upper=true) + function &MetaColumns($table, $upper = true) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $schema = false; - $this->_findschema($table,$schema); + $this->_findschema($table, $schema); $table = strtolower($table); @@ -396,8 +397,8 @@ select viewname,'V' from pg_views where viewname like $mask"; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema)); - else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table)); + if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1, $table, $table, $schema)); + else $rs =& $this->Execute(sprintf($this->metaColumnsSQL, $table, $table)); if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; @@ -411,7 +412,7 @@ select viewname,'V' from pg_views where viewname like $mask"; $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; - $rskey = $this->Execute(sprintf($this->metaKeySQL,($table))); + $rskey = $this->Execute(sprintf($this->metaKeySQL, ($table))); // fetch all result in once for performance. $keys =& $rskey->GetArray(); if (isset($savem)) $this->SetFetchMode($savem); @@ -442,7 +443,7 @@ select viewname,'V' from pg_views where viewname like $mask"; $rsdef->MoveNext(); } } else { - ADOConnection::outp( "==> SQL => " . $sql); + ADOConnection::outp("==> SQL => " . $sql); } unset($rsdef); } @@ -453,7 +454,7 @@ select viewname,'V' from pg_views where viewname like $mask"; $fld->name = $rs->fields[0]; $fld->type = $rs->fields[1]; $fld->max_length = $rs->fields[2]; - if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4; + if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3] - 4; if ($fld->max_length <= 0) $fld->max_length = -1; // dannym @@ -470,7 +471,7 @@ select viewname,'V' from pg_views where viewname like $mask"; // Freek if (is_array($keys)) { - foreach($keys as $key) { + foreach ($keys as $key) { if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true) $fld->primary_key = true; if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true) @@ -488,76 +489,76 @@ select viewname,'V' from pg_views where viewname like $mask"; } - function &MetaIndexes ($table, $primary = FALSE) - { - global $ADODB_FETCH_MODE; + function &MetaIndexes($table, $primary = FALSE) + { + global $ADODB_FETCH_MODE; - $schema = false; - $this->_findschema($table,$schema); + $schema = false; + $this->_findschema($table, $schema); - if ($schema) { // requires pgsql 7.3+ - pg_namespace used. - $sql = ' + if ($schema) { // requires pgsql 7.3+ - pg_namespace used. + $sql = ' SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns" FROM pg_catalog.pg_class c JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid ,pg_namespace n WHERE c2.relname=\'%s\' and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\' AND i.indisprimary=false'; - } else { - $sql = ' + } else { + $sql = ' SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns" FROM pg_catalog.pg_class c JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid WHERE c2.relname=\'%s\''; - } - - if ($primary == FALSE) { - $sql .= ' AND i.indisprimary=false;'; - } + } - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== FALSE) { - $savem = $this->SetFetchMode(FALSE); - } + if ($primary == FALSE) { + $sql .= ' AND i.indisprimary=false;'; + } - $rs = $this->Execute(sprintf($sql,$table,$schema)); + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } - if (isset($savem)) { - $this->SetFetchMode($savem); - } - $ADODB_FETCH_MODE = $save; + $rs = $this->Execute(sprintf($sql, $table, $schema)); - if (!is_object($rs)) { - return FALSE; - } + if (isset($savem)) { + $this->SetFetchMode($savem); + } + $ADODB_FETCH_MODE = $save; - $col_names = $this->MetaColumnNames($table); - $indexes = array(); + if (!is_object($rs)) { + return FALSE; + } - while ($row = $rs->FetchRow()) { - $columns = array(); + $col_names = $this->MetaColumnNames($table); + $indexes = array(); - foreach (explode(' ', $row[2]) as $col) { - $columns[] = $col_names[$col - 1]; - } + while ($row = $rs->FetchRow()) { + $columns = array(); - $indexes[$row[0]] = array( - 'unique' => ($row[1] == 't'), - 'columns' => $columns - ); - } + foreach (explode(' ', $row[2]) as $col) { + $columns[] = $col_names[$col - 1]; + } - return $indexes; + $indexes[$row[0]] = array( + 'unique' => ($row[1] == 't'), + 'columns' => $columns + ); } + return $indexes; + } + // returns true or false // // examples: // $db->Connect("host=host1 user=user1 password=secret port=4341"); // $db->Connect('host1','user1','secret'); - function _connect($str,$user='',$pwd='',$db='',$ctype=0) + function _connect($str, $user = '', $pwd = '', $db = '', $ctype = 0) { if (!function_exists('pg_pconnect')) return false; @@ -569,15 +570,15 @@ WHERE c2.relname=\'%s\''; $pwd = adodb_addslashes($pwd); if (strlen($db) == 0) $db = 'template1'; $db = adodb_addslashes($db); - if ($str) { - $host = explode(":", $str); - if ($host[0]) $str = "host=".adodb_addslashes($host[0]); + if ($str) { + $host = explode(":", $str); + if ($host[0]) $str = "host=" . adodb_addslashes($host[0]); else $str = 'host=localhost'; if (isset($host[1])) $str .= " port=$host[1]"; } - if ($user) $str .= " user=".$user; - if ($pwd) $str .= " password=".$pwd; - if ($db) $str .= " dbname=".$db; + if ($user) $str .= " user=" . $user; + if ($pwd) $str .= " password=" . $pwd; + if ($db) $str .= " dbname=" . $db; } //if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432"; @@ -586,12 +587,12 @@ WHERE c2.relname=\'%s\''; $this->_connectionID = pg_pconnect($str); } else { if ($ctype === -1) { // nconnect, we trick pgsql ext by changing the connection str - static $ncnt; + static $ncnt; if (empty($ncnt)) $ncnt = 1; else $ncnt += 1; - $str .= str_repeat(' ',$ncnt); + $str .= str_repeat(' ', $ncnt); } $this->_connectionID = pg_connect($str); } @@ -602,7 +603,7 @@ WHERE c2.relname=\'%s\''; function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) { - return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,-1); + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName, -1); } // returns true or false @@ -610,34 +611,34 @@ WHERE c2.relname=\'%s\''; // examples: // $db->PConnect("host=host1 user=user1 password=secret port=4341"); // $db->PConnect('host1','user1','secret'); - function _pconnect($str,$user='',$pwd='',$db='') + function _pconnect($str, $user = '', $pwd = '', $db = '') { - return $this->_connect($str,$user,$pwd,$db,1); + return $this->_connect($str, $user, $pwd, $db, 1); } // returns queryID or false - function _query($sql,$inputarr) + function _query($sql, $inputarr) { if ($inputarr) { - /* - It appears that PREPARE/EXECUTE is slower for many queries. + /* + It appears that PREPARE/EXECUTE is slower for many queries. - For query executed 1000 times: - "select id,firstname,lastname from adoxyz - where firstname not like ? and lastname not like ? and id = ?" + For query executed 1000 times: + "select id,firstname,lastname from adoxyz + where firstname not like ? and lastname not like ? and id = ?" - with plan = 1.51861286163 secs - no plan = 1.26903700829 secs + with plan = 1.51861286163 secs + no plan = 1.26903700829 secs - */ - $plan = 'P'.md5($sql); + */ + $plan = 'P' . md5($sql); $execp = ''; - foreach($inputarr as $v) { + foreach ($inputarr as $v) { if ($execp) $execp .= ','; if (is_string($v)) { - if (strncmp($v,"'",1) !== 0) $execp .= $this->qstr($v); + if (strncmp($v, "'", 1) !== 0) $execp .= $this->qstr($v); } else { $execp .= $v; } @@ -646,11 +647,11 @@ WHERE c2.relname=\'%s\''; if ($execp) $exsql = "EXECUTE $plan ($execp)"; else $exsql = "EXECUTE $plan"; - $rez = @pg_exec($this->_connectionID,$exsql); + $rez = @pg_exec($this->_connectionID, $exsql); if (!$rez) { - # Perhaps plan does not exist? Prepare/compile plan. + # Perhaps plan does not exist? Prepare/compile plan. $params = ''; - foreach($inputarr as $v) { + foreach ($inputarr as $v) { if ($params) $params .= ','; if (is_string($v)) { $params .= 'VARCHAR'; @@ -660,25 +661,25 @@ WHERE c2.relname=\'%s\''; $params .= "REAL"; } } - $sqlarr = explode('?',$sql); + $sqlarr = explode('?', $sql); //print_r($sqlarr); $sql = ''; $i = 1; - foreach($sqlarr as $v) { - $sql .= $v.' $'.$i; + foreach ($sqlarr as $v) { + $sql .= $v . ' $' . $i; $i++; } - $s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2); + $s = "PREPARE $plan ($params) AS " . substr($sql, 0, strlen($sql) - 2); //adodb_pr($s); - pg_exec($this->_connectionID,$s); + pg_exec($this->_connectionID, $s); echo $this->ErrorMsg(); } - $rez = pg_exec($this->_connectionID,$exsql); + $rez = pg_exec($this->_connectionID, $exsql); } else { $this->_errorMsg = false; //adodb_backtrace(); - $rez = pg_exec($this->_connectionID,$sql); + $rez = pg_exec($this->_connectionID, $sql); } // check if no data returned, then no need to create real recordset if ($rez && pg_numfields($rez) <= 0) { @@ -736,7 +737,7 @@ WHERE c2.relname=\'%s\''; */ function CharMax() { - return 1000000000; // should be 1 Gb? + return 1000000000; // should be 1 Gb? } /* @@ -753,28 +754,35 @@ WHERE c2.relname=\'%s\''; Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordSet_postgres64 extends ADORecordSet{ +class ADORecordSet_postgres64 extends ADORecordSet +{ var $_blobArr; var $databaseType = "postgres64"; var $canSeek = true; - function ADORecordSet_postgres64($queryID,$mode=false) + + function ADORecordSet_postgres64($queryID, $mode = false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } - switch ($mode) - { - case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break; - case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break; - default: - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break; + switch ($mode) { + case ADODB_FETCH_NUM: + $this->fetchMode = PGSQL_NUM; + break; + case ADODB_FETCH_ASSOC: + $this->fetchMode = PGSQL_ASSOC; + break; + default: + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + $this->fetchMode = PGSQL_BOTH; + break; } $this->ADORecordSet($queryID); } - function &GetRowAssoc($upper=true) + function &GetRowAssoc($upper = true) { if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields; $row =& ADORecordSet::GetRowAssoc($upper); @@ -783,65 +791,65 @@ class ADORecordSet_postgres64 extends ADORecordSet{ function _initrs() { - global $ADODB_COUNTRECS; + global $ADODB_COUNTRECS; $qid = $this->_queryID; - $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($qid):-1; + $this->_numOfRows = ($ADODB_COUNTRECS) ? @pg_numrows($qid) : -1; $this->_numOfFields = @pg_numfields($qid); // cache types for blob decode check - for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { - if (pg_fieldtype($qid,$i) == 'bytea') { - $this->_blobArr[$i] = pg_fieldname($qid,$off); + for ($i = 0, $max = $this->_numOfFields; $i < $max; $i++) { + if (pg_fieldtype($qid, $i) == 'bytea') { + $this->_blobArr[$i] = pg_fieldname($qid, $off); } } } - /* Use associative array to get fields array */ + /* Use associative array to get fields array */ function Fields($colname) { if ($this->fetchMode != PGSQL_NUM) return @$this->fields[$colname]; if (!$this->bind) { $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { + for ($i = 0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } function &FetchField($fieldOffset = 0) { - $off=$fieldOffset; // offsets begin at 0 + $off = $fieldOffset; // offsets begin at 0 - $o= new ADOFieldObject(); - $o->name = @pg_fieldname($this->_queryID,$off); - $o->type = @pg_fieldtype($this->_queryID,$off); - $o->max_length = @pg_fieldsize($this->_queryID,$off); + $o = new ADOFieldObject(); + $o->name = @pg_fieldname($this->_queryID, $off); + $o->type = @pg_fieldtype($this->_queryID, $off); + $o->max_length = @pg_fieldsize($this->_queryID, $off); return $o; } function _seek($row) { - return @pg_fetch_row($this->_queryID,$row); + return @pg_fetch_row($this->_queryID, $row); } function _decode($blob) { - eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";'); + eval('$realblob="' . adodb_str_replace(array('"', '$'), array('\"', '\$'), $blob) . '";'); return $realblob; } function _fixblobs() { if ($this->fetchMode == PGSQL_NUM || $this->fetchMode == PGSQL_BOTH) { - foreach($this->_blobArr as $k => $v) { + foreach ($this->_blobArr as $k => $v) { $this->fields[$k] = ADORecordSet_postgres64::_decode($this->fields[$k]); } } if ($this->fetchMode == PGSQL_ASSOC || $this->fetchMode == PGSQL_BOTH) { - foreach($this->_blobArr as $k => $v) { + foreach ($this->_blobArr as $k => $v) { $this->fields[$v] = ADORecordSet_postgres64::_decode($this->fields[$v]); } } @@ -853,7 +861,7 @@ class ADORecordSet_postgres64 extends ADORecordSet{ if (!$this->EOF) { $this->_currentRow++; if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) { - $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode); + $this->fields = @pg_fetch_array($this->_queryID, $this->_currentRow, $this->fetchMode); if (is_array($this->fields) && $this->fields) { if ($this->fields && isset($this->_blobArr)) $this->_fixblobs(); return true; @@ -871,9 +879,9 @@ class ADORecordSet_postgres64 extends ADORecordSet{ if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0) return false; - $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode); + $this->fields = @pg_fetch_array($this->_queryID, $this->_currentRow, $this->fetchMode); - if ($this->fields && isset($this->_blobArr)) $this->_fixblobs(); + if ($this->fields && isset($this->_blobArr)) $this->_fixblobs(); return (is_array($this->fields)); } @@ -883,7 +891,7 @@ class ADORecordSet_postgres64 extends ADORecordSet{ return @pg_freeresult($this->_queryID); } - function MetaType($t,$len=-1,$fieldobj=false) + function MetaType($t, $len = -1, $fieldobj = false) { if (is_object($t)) { $fieldobj = $t; @@ -891,55 +899,56 @@ class ADORecordSet_postgres64 extends ADORecordSet{ $len = $fieldobj->max_length; } switch (strtoupper($t)) { - case 'MONEY': // stupid, postgres expects money to be a string - case 'INTERVAL': - case 'CHAR': - case 'CHARACTER': - case 'VARCHAR': - case 'NAME': - case 'BPCHAR': - case '_VARCHAR': - if ($len <= $this->blobSize) return 'C'; - - case 'TEXT': - return 'X'; - - case 'IMAGE': // user defined type - case 'BLOB': // user defined type - case 'BIT': // This is a bit string, not a single bit, so don't return 'L' - case 'VARBIT': - case 'BYTEA': - return 'B'; - - case 'BOOL': - case 'BOOLEAN': - return 'L'; - - case 'DATE': - return 'D'; - - case 'TIME': - case 'DATETIME': - case 'TIMESTAMP': - case 'TIMESTAMPTZ': - return 'T'; - - case 'SMALLINT': - case 'BIGINT': - case 'INTEGER': - case 'INT8': - case 'INT4': - case 'INT2': - if (isset($fieldobj) && - empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I'; - - case 'OID': - case 'SERIAL': - return 'R'; - - default: - return 'N'; - } + case 'MONEY': // stupid, postgres expects money to be a string + case 'INTERVAL': + case 'CHAR': + case 'CHARACTER': + case 'VARCHAR': + case 'NAME': + case 'BPCHAR': + case '_VARCHAR': + if ($len <= $this->blobSize) return 'C'; + + case 'TEXT': + return 'X'; + + case 'IMAGE': // user defined type + case 'BLOB': // user defined type + case 'BIT': // This is a bit string, not a single bit, so don't return 'L' + case 'VARBIT': + case 'BYTEA': + return 'B'; + + case 'BOOL': + case 'BOOLEAN': + return 'L'; + + case 'DATE': + return 'D'; + + case 'TIME': + case 'DATETIME': + case 'TIMESTAMP': + case 'TIMESTAMPTZ': + return 'T'; + + case 'SMALLINT': + case 'BIGINT': + case 'INTEGER': + case 'INT8': + case 'INT4': + case 'INT2': + if (isset($fieldobj) && + empty($fieldobj->primary_key) && empty($fieldobj->unique) + ) return 'I'; + + case 'OID': + case 'SERIAL': + return 'R'; + + default: + return 'N'; + } } } diff --git a/lib/WikiDB/adodb/drivers/adodb-postgres7.inc.php b/lib/WikiDB/adodb/drivers/adodb-postgres7.inc.php index 72c2070ed..76b688e30 100644 --- a/lib/WikiDB/adodb/drivers/adodb-postgres7.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-postgres7.inc.php @@ -11,11 +11,12 @@ 01 Dec 2001: dannym added support for default values */ -include_once(ADODB_DIR."/drivers/adodb-postgres64.inc.php"); +include_once(ADODB_DIR . "/drivers/adodb-postgres64.inc.php"); -class ADODB_postgres7 extends ADODB_postgres64 { +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 $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 @@ -26,32 +27,33 @@ class ADODB_postgres7 extends ADODB_postgres64 { // 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 $offset" : ''; - $limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ''; - if ($secs2cache) - $rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr); - else - $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr); + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) + { + $offsetStr = ($offset >= 0) ? " OFFSET $offset" : ''; + $limitStr = ($nrows >= 0) ? " LIMIT $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; } - */ + + /* + function Prepare($sql) + { + $info = $this->ServerInfo(); + if ($info['version']>=7.3) { + return array($sql,false); + } + return $sql; + } + */ // from Edward Jaramilla, improved version - works on pg 7.4 -function MetaForeignKeys($table, $owner=false, $upper=false) -{ - $sql = 'SELECT t.tgargs as args + function MetaForeignKeys($table, $owner = false, $upper = false) + { + $sql = 'SELECT t.tgargs as args FROM pg_trigger t,pg_class c,pg_proc p WHERE @@ -59,30 +61,29 @@ function MetaForeignKeys($table, $owner=false, $upper=false) t.tgrelid = c.oid AND t.tgfoid = p.oid AND p.proname = \'RI_FKey_check_ins\' AND - c.relname = \''.strtolower($table).'\' + c.relname = \'' . strtolower($table) . '\' ORDER BY t.tgrelid'; - $rs = $this->Execute($sql); - - if ($rs && !$rs->EOF) { - $arr =& $rs->GetArray(); - $a = array(); - foreach($arr as $v) - { - $data = explode(chr(0), $v['args']); - if ($upper) { - $a[strtoupper($data[2])][] = strtoupper($data[4].'='.$data[5]); - } else { - $a[$data[2]][] = $data[4].'='.$data[5]; + $rs = $this->Execute($sql); + + if ($rs && !$rs->EOF) { + $arr =& $rs->GetArray(); + $a = array(); + foreach ($arr as $v) { + $data = explode(chr(0), $v['args']); + if ($upper) { + $a[strtoupper($data[2])][] = strtoupper($data[4] . '=' . $data[5]); + } else { + $a[$data[2]][] = $data[4] . '=' . $data[5]; + } } + return $a; } - return $a; + return false; } - return false; -} - function xMetaForeignKeys($table, $owner=false, $upper=false) + function xMetaForeignKeys($table, $owner = false, $upper = false) { $sql = ' @@ -96,28 +97,27 @@ SELECT t.tgargs as args AND t.tgconstrrelid=c2.oid AND t.tgfoid=f.oid AND f.proname ~ \'^RI_FKey_check_ins\' - AND t.tgargs like \'$1\\\000'.strtolower($table).'%\' + AND t.tgargs like \'$1\\\000' . strtolower($table) . '%\' ORDER BY t.tgrelid'; $rs = $this->Execute($sql); if ($rs && !$rs->EOF) { $arr =& $rs->GetArray(); $a = array(); - foreach($arr as $v) { + foreach ($arr as $v) { $data = explode(chr(0), $v['args']); if ($upper) { - $a[] = array(strtoupper($data[2]) => strtoupper($data[4].'='.$data[5])); + $a[] = array(strtoupper($data[2]) => strtoupper($data[4] . '=' . $data[5])); } else { - $a[] = array($data[2] => $data[4].'='.$data[5]); + $a[] = array($data[2] => $data[4] . '=' . $data[5]); } } return $a; - } - else return false; + } else return false; } - // this is a set of functions for managing client encoding - very important if the encodings + // 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 @@ -153,22 +153,23 @@ SELECT t.tgargs as args Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordSet_postgres7 extends ADORecordSet_postgres64{ +class ADORecordSet_postgres7 extends ADORecordSet_postgres64 +{ var $databaseType = "postgres7"; - function ADORecordSet_postgres7($queryID,$mode=false) + function ADORecordSet_postgres7($queryID, $mode = false) { - $this->ADORecordSet_postgres64($queryID,$mode); + $this->ADORecordSet_postgres64($queryID, $mode); } - // 10% speedup to move MoveNext to child class + // 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); + $this->fields = @pg_fetch_array($this->_queryID, $this->_currentRow, $this->fetchMode); if (is_array($this->fields)) { if ($this->fields && isset($this->_blobArr)) $this->_fixblobs(); diff --git a/lib/WikiDB/adodb/drivers/adodb-proxy.inc.php b/lib/WikiDB/adodb/drivers/adodb-proxy.inc.php index 173e87983..67cfdc7ae 100644 --- a/lib/WikiDB/adodb/drivers/adodb-proxy.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-proxy.inc.php @@ -9,20 +9,25 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese Synonym for csv driver. */ -if (! defined("_ADODB_PROXY_LAYER")) { - define("_ADODB_PROXY_LAYER", 1 ); - include(ADODB_DIR."/drivers/adodb-csv.inc.php"); +if (!defined("_ADODB_PROXY_LAYER")) { + define("_ADODB_PROXY_LAYER", 1); + include(ADODB_DIR . "/drivers/adodb-csv.inc.php"); - class ADODB_proxy extends ADODB_csv { + class ADODB_proxy extends ADODB_csv + { var $databaseType = 'proxy'; var $databaseProvider = 'csv'; } - class ADORecordset_proxy extends ADORecordset_csv { - var $databaseType = "proxy"; - function ADORecordset_proxy($id,$mode=false) + class ADORecordset_proxy extends ADORecordset_csv + { + var $databaseType = "proxy"; + + function ADORecordset_proxy($id, $mode = false) { - $this->ADORecordset($id,$mode); + $this->ADORecordset($id, $mode); } - }; + } + + ; } // define diff --git a/lib/WikiDB/adodb/drivers/adodb-sapdb.inc.php b/lib/WikiDB/adodb/drivers/adodb-sapdb.inc.php index cbdefd202..951d5d968 100644 --- a/lib/WikiDB/adodb/drivers/adodb-sapdb.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-sapdb.inc.php @@ -13,49 +13,53 @@ Set tabs to 4 for best viewing. */ if (!defined('_ADODB_ODBC_LAYER')) { - include(ADODB_DIR."/drivers/adodb-odbc.inc.php"); + include(ADODB_DIR . "/drivers/adodb-odbc.inc.php"); } -if (!defined('ADODB_SAPDB')){ -define('ADODB_SAPDB',1); - -class ADODB_SAPDB extends ADODB_odbc { - var $databaseType = "sapdb"; - var $concat_operator = '||'; - var $sysDate = 'DATE'; - var $sysTimeStamp = 'TIMESTAMP'; - var $fmtDate = "\\D\\A\\T\\E('Y-m-d')"; /// used by DBDate() as the default date format used by the database - var $fmtTimeStamp = "\\T\\I\\M\\E\\S\\T\\A\\M\\P('Y-m-d','H:i:s')"; /// used by DBTimeStamp as the default timestamp fmt. - - function ADODB_SAPDB() +if (!defined('ADODB_SAPDB')) { + define('ADODB_SAPDB', 1); + + class ADODB_SAPDB extends ADODB_odbc { - //if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC; - $this->ADODB_odbc(); - } + var $databaseType = "sapdb"; + var $concat_operator = '||'; + var $sysDate = 'DATE'; + var $sysTimeStamp = 'TIMESTAMP'; + var $fmtDate = "\\D\\A\\T\\E('Y-m-d')"; /// used by DBDate() as the default date format used by the database + var $fmtTimeStamp = "\\T\\I\\M\\E\\S\\T\\A\\M\\P('Y-m-d','H:i:s')"; /// used by DBTimeStamp as the default timestamp fmt. - /* - SelectLimit implementation problems: + function ADODB_SAPDB() + { + //if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC; + $this->ADODB_odbc(); + } - The following will return random 10 rows as order by performed after "WHERE rowno<10" - which is not ideal... + /* + SelectLimit implementation problems: - select * from table where rowno < 10 order by 1 + The following will return random 10 rows as order by performed after "WHERE rowno<10" + which is not ideal... - This means that we have to use the adoconnection base class SelectLimit when - there is an "order by". + select * from table where rowno < 10 order by 1 - See http://listserv.sap.com/pipermail/sapdb.general/2002-January/010405.html - */ + This means that we have to use the adoconnection base class SelectLimit when + there is an "order by". -}; + See http://listserv.sap.com/pipermail/sapdb.general/2002-January/010405.html + */ -class ADORecordSet_sapdb extends ADORecordSet_odbc { + } - var $databaseType = "sapdb"; + ; - function ADORecordSet_sapdb($id,$mode=false) + class ADORecordSet_sapdb extends ADORecordSet_odbc { - $this->ADORecordSet_odbc($id,$mode); + + var $databaseType = "sapdb"; + + function ADORecordSet_sapdb($id, $mode = false) + { + $this->ADORecordSet_odbc($id, $mode); + } } -} } //define diff --git a/lib/WikiDB/adodb/drivers/adodb-sqlanywhere.inc.php b/lib/WikiDB/adodb/drivers/adodb-sqlanywhere.inc.php index e52a131c8..4752d0f0f 100644 --- a/lib/WikiDB/adodb/drivers/adodb-sqlanywhere.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-sqlanywhere.inc.php @@ -42,122 +42,133 @@ Set tabs to 4 for best viewing. */ if (!defined('_ADODB_ODBC_LAYER')) { - include(ADODB_DIR."/drivers/adodb-odbc.inc.php"); + include(ADODB_DIR . "/drivers/adodb-odbc.inc.php"); } -if (!defined('ADODB_SYBASE_SQLANYWHERE')){ +if (!defined('ADODB_SYBASE_SQLANYWHERE')) { - define('ADODB_SYBASE_SQLANYWHERE',1); + define('ADODB_SYBASE_SQLANYWHERE', 1); - class ADODB_sqlanywhere extends ADODB_odbc { - var $databaseType = "sqlanywhere"; - var $hasInsertID = true; - - function ADODB_sqlanywhere() + class ADODB_sqlanywhere extends ADODB_odbc { - $this->ADODB_odbc(); + var $databaseType = "sqlanywhere"; + var $hasInsertID = true; + + function ADODB_sqlanywhere() + { + $this->ADODB_odbc(); + } + + function _insertid() + { + return $this->GetOne('select @@identity'); + } + + function create_blobvar($blobVarName) + { + $this->Execute("create variable $blobVarName long binary"); + return; + } + + function drop_blobvar($blobVarName) + { + $this->Execute("drop variable $blobVarName"); + return; + } + + function load_blobvar_from_file($blobVarName, $filename) + { + $chunk_size = 1000; + + $fd = fopen($filename, "rb"); + + $integer_chunks = (integer)filesize($filename) / $chunk_size; + $modulus = filesize($filename) % $chunk_size; + if ($modulus != 0) { + $integer_chunks += 1; + } + + for ($loop = 1; $loop <= $integer_chunks; $loop++) { + $contents = fread($fd, $chunk_size); + $contents = bin2hex($contents); + + $hexstring = ''; + + for ($loop2 = 0; $loop2 < strlen($contents); $loop2 += 2) { + $hexstring .= '\x' . substr($contents, $loop2, 2); + } + + $hexstring = $this->qstr($hexstring); + + $this->Execute("set $blobVarName = $blobVarName || " . $hexstring); + } + + fclose($fd); + return; + } + + function load_blobvar_from_var($blobVarName, &$varName) + { + $chunk_size = 1000; + + $integer_chunks = (integer)strlen($varName) / $chunk_size; + $modulus = strlen($varName) % $chunk_size; + if ($modulus != 0) { + $integer_chunks += 1; + } + + for ($loop = 1; $loop <= $integer_chunks; $loop++) { + $contents = substr($varName, (($loop - 1) * $chunk_size), $chunk_size); + $contents = bin2hex($contents); + + $hexstring = ''; + + for ($loop2 = 0; $loop2 < strlen($contents); $loop2 += 2) { + $hexstring .= '\x' . substr($contents, $loop2, 2); + } + + $hexstring = $this->qstr($hexstring); + + $this->Execute("set $blobVarName = $blobVarName || " . $hexstring); + } + + return; + } + + /* + Insert a null into the blob field of the table first. + Then use UpdateBlob to store the blob. + + Usage: + + $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); + $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); + */ + function UpdateBlob($table, $column, &$val, $where, $blobtype = 'BLOB') + { + $blobVarName = 'hold_blob'; + $this->create_blobvar($blobVarName); + $this->load_blobvar_from_var($blobVarName, $val); + $this->Execute("UPDATE $table SET $column=$blobVarName WHERE $where"); + $this->drop_blobvar($blobVarName); + return true; + } } - function _insertid() { - return $this->GetOne('select @@identity'); - } - - function create_blobvar($blobVarName) { - $this->Execute("create variable $blobVarName long binary"); - return; - } - - function drop_blobvar($blobVarName) { - $this->Execute("drop variable $blobVarName"); - return; - } - - function load_blobvar_from_file($blobVarName, $filename) { - $chunk_size = 1000; - - $fd = fopen ($filename, "rb"); - - $integer_chunks = (integer)filesize($filename) / $chunk_size; - $modulus = filesize($filename) % $chunk_size; - if ($modulus != 0){ - $integer_chunks += 1; - } - - for($loop=1;$loop<=$integer_chunks;$loop++){ - $contents = fread ($fd, $chunk_size); - $contents = bin2hex($contents); - - $hexstring = ''; - - for($loop2=0;$loop2<strlen($contents);$loop2+=2){ - $hexstring .= '\x' . substr($contents,$loop2,2); - } - - $hexstring = $this->qstr($hexstring); - - $this->Execute("set $blobVarName = $blobVarName || " . $hexstring); - } - - fclose ($fd); - return; - } + ; //class - function load_blobvar_from_var($blobVarName, &$varName) { - $chunk_size = 1000; - - $integer_chunks = (integer)strlen($varName) / $chunk_size; - $modulus = strlen($varName) % $chunk_size; - if ($modulus != 0){ - $integer_chunks += 1; - } - - for($loop=1;$loop<=$integer_chunks;$loop++){ - $contents = substr ($varName, (($loop - 1) * $chunk_size), $chunk_size); - $contents = bin2hex($contents); - - $hexstring = ''; - - for($loop2=0;$loop2<strlen($contents);$loop2+=2){ - $hexstring .= '\x' . substr($contents,$loop2,2); - } - - $hexstring = $this->qstr($hexstring); - - $this->Execute("set $blobVarName = $blobVarName || " . $hexstring); - } - - return; - } - - /* - Insert a null into the blob field of the table first. - Then use UpdateBlob to store the blob. - - Usage: - - $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); - $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); - */ - function UpdateBlob($table,$column,&$val,$where,$blobtype='BLOB') - { - $blobVarName = 'hold_blob'; - $this->create_blobvar($blobVarName); - $this->load_blobvar_from_var($blobVarName, $val); - $this->Execute("UPDATE $table SET $column=$blobVarName WHERE $where"); - $this->drop_blobvar($blobVarName); - return true; - } - }; //class + class ADORecordSet_sqlanywhere extends ADORecordSet_odbc + { - class ADORecordSet_sqlanywhere extends ADORecordSet_odbc { + var $databaseType = "sqlanywhere"; - var $databaseType = "sqlanywhere"; + function ADORecordSet_sqlanywhere($id, $mode = false) + { + $this->ADORecordSet_odbc($id, $mode); + } - function ADORecordSet_sqlanywhere($id,$mode=false) - { - $this->ADORecordSet_odbc($id,$mode); - } + } - }; //class + ; //class } //define diff --git a/lib/WikiDB/adodb/drivers/adodb-sqlite.inc.php b/lib/WikiDB/adodb/drivers/adodb-sqlite.inc.php index ba7281cca..d163b4526 100644 --- a/lib/WikiDB/adodb/drivers/adodb-sqlite.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-sqlite.inc.php @@ -15,14 +15,15 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese 2. Rename the file, remove the .txt prefix. */ -class ADODB_sqlite extends ADOConnection { +class ADODB_sqlite extends ADOConnection +{ var $databaseType = "sqlite"; var $replaceQuote = "''"; // string to use to replace quotes - var $concat_operator='||'; + 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 $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')"; @@ -32,14 +33,14 @@ class ADODB_sqlite extends ADOConnection { { } -/* - function __get($name) - { - switch($name) { - case 'sysDate': return "'".date($this->fmtDate)."'"; - case 'sysTimeStamp' : return "'".date($this->sysTimeStamp)."'"; - } - }*/ + /* + function __get($name) + { + switch($name) { + case 'sysDate': return "'".date($this->fmtDate)."'"; + case 'sysTimeStamp' : return "'".date($this->sysTimeStamp)."'"; + } + }*/ function ServerInfo() { @@ -51,18 +52,18 @@ class ADODB_sqlite extends ADOConnection { function BeginTrans() { - if ($this->transOff) return true; - $ret = $this->Execute("BEGIN TRANSACTION"); - $this->transCnt += 1; - return true; + if ($this->transOff) return true; + $ret = $this->Execute("BEGIN TRANSACTION"); + $this->transCnt += 1; + return true; } - function CommitTrans($ok=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; + if ($this->transCnt > 0) $this->transCnt -= 1; return !empty($ret); } @@ -70,7 +71,7 @@ class ADODB_sqlite extends ADOConnection { { if ($this->transOff) return true; $ret = $this->Execute("ROLLBACK"); - if ($this->transCnt>0)$this->transCnt -= 1; + if ($this->transCnt > 0) $this->transCnt -= 1; return !empty($ret); } @@ -85,7 +86,7 @@ class ADODB_sqlite extends ADOConnection { } function ErrorMsg() - { + { if ($this->_logsql) return $this->_errorMsg; return ($this->_errorNo) ? sqlite_error_string($this->_errorNo) : ''; } @@ -95,7 +96,7 @@ class ADODB_sqlite extends ADOConnection { return $this->_errorNo; } - function SQLDate($fmt, $col=false) + function SQLDate($fmt, $col = false) { $fmt = $this->qstr($fmt); return ($col) ? "adodb_date2($fmt,$col)" : "adodb_date($fmt)"; @@ -103,12 +104,12 @@ class ADODB_sqlite extends ADOConnection { function &MetaColumns($tab) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $rs = $this->Execute("select * from $tab limit 1"); if (!$rs) return false; $arr = array(); - for ($i=0,$max=$rs->_numOfFields; $i < $max; $i++) { + for ($i = 0, $max = $rs->_numOfFields; $i < $max; $i++) { $fld =& $rs->FetchField($i); if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] =& $fld; else $arr[strtoupper($fld->name)] =& $fld; @@ -146,9 +147,9 @@ class ADODB_sqlite extends ADOConnection { } // returns query ID if successful, otherwise false - function _query($sql,$inputarr=false) + function _query($sql, $inputarr = false) { - $rez = sqlite_query($sql,$this->_connectionID); + $rez = sqlite_query($sql, $this->_connectionID); if (!$rez) { $this->_errorNo = sqlite_last_error($this->_connectionID); } @@ -156,14 +157,14 @@ class ADODB_sqlite extends ADOConnection { return $rez; } - function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) + 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); + $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; } @@ -176,16 +177,16 @@ class ADODB_sqlite extends ADOConnection { */ var $_genSeqSQL = "create table %s (id integer)"; - function GenID($seq='adodbseq',$start=1) + 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) { + while (--$MAXLOOPS >= 0) { $num = $this->GetOne("select id from $seq"); if ($num === false) { - $this->Execute(sprintf($this->_genSeqSQL ,$seq)); + $this->Execute(sprintf($this->_genSeqSQL, $seq)); $start -= 1; $num = '0'; $ok = $this->Execute("insert into $seq values($start)"); @@ -200,25 +201,26 @@ class ADODB_sqlite extends ADOConnection { } } if ($fn = $this->raiseErrorFn) { - $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num); + $fn($this->databaseType, 'GENID', -32000, "Unable to generate unique id after $MAXLOOPS attempts", $seq, $num); } return false; } - function CreateSequence($seqname='adodbseq',$start=1) + function CreateSequence($seqname = 'adodbseq', $start = 1) { if (empty($this->_genSeqSQL)) return false; - $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); + $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)); + return $this->Execute(sprintf($this->_dropSeqSQL, $seqname)); } // returns true or false @@ -234,22 +236,29 @@ class ADODB_sqlite extends ADOConnection { Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordset_sqlite extends ADORecordSet { +class ADORecordset_sqlite extends ADORecordSet +{ var $databaseType = "sqlite"; var $bind = false; - function ADORecordset_sqlite($queryID,$mode=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; + 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->_queryID = $queryID; @@ -279,34 +288,34 @@ class ADORecordset_sqlite extends ADORecordSet { return $fld; } - function _initrs() - { + 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++) { + for ($i = 0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } - function _seek($row) - { - return sqlite_seek($this->_queryID, $row); - } + function _seek($row) + { + return sqlite_seek($this->_queryID, $row); + } - function _fetch($ignore_fields=false) + function _fetch($ignore_fields = false) { - $this->fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode); + $this->fields = @sqlite_fetch_array($this->_queryID, $this->fetchMode); return !empty($this->fields); } diff --git a/lib/WikiDB/adodb/drivers/adodb-sybase.inc.php b/lib/WikiDB/adodb/drivers/adodb-sybase.inc.php index 7e2511533..578acbf5c 100644 --- a/lib/WikiDB/adodb/drivers/adodb-sybase.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-sybase.inc.php @@ -15,7 +15,8 @@ V4.22 15 Apr 2004 (c) 2000-2004 John Lim. All rights reserved. Date patch by Toni 15 Feb 2002 */ -class ADODB_sybase extends ADOConnection { +class ADODB_sybase extends ADOConnection +{ var $databaseType = "sybase"; //var $dataProvider = 'sybase'; var $replaceQuote = "''"; // string to use to replace quotes @@ -23,7 +24,7 @@ class ADODB_sybase extends ADOConnection { var $fmtTimeStamp = "'Y-m-d H:i:s'"; var $hasInsertID = true; var $hasAffectedRows = true; - var $metaTablesSQL="select name from sysobjects where type='U' or type='V'"; + var $metaTablesSQL = "select name from sysobjects where type='U' or type='V'"; // see http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8 var $metaColumnsSQL = "SELECT c.column_name, c.column_type, c.width FROM syscolumn c, systable t WHERE t.table_name='%s' AND c.table_id=t.table_id AND t.table_type='BASE'"; /* @@ -46,10 +47,11 @@ class ADODB_sybase extends ADOConnection { { return $this->GetOne('select @@identity'); } - // might require begintrans -- committrans + + // might require begintrans -- committrans function _affectedrows() { - return $this->GetOne('select @@rowcount'); + return $this->GetOne('select @@rowcount'); } function BeginTrans() @@ -62,7 +64,7 @@ class ADODB_sybase extends ADOConnection { return true; } - function CommitTrans($ok=true) + function CommitTrans($ok = true) { if ($this->transOff) return true; @@ -82,20 +84,20 @@ class ADODB_sybase extends ADOConnection { } // http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4 - function RowLock($tables,$where) + function RowLock($tables, $where) { if (!$this->_hastrans) $this->BeginTrans(); - $tables = str_replace(',',' HOLDLOCK,',$tables); + $tables = str_replace(',', ' HOLDLOCK,', $tables); return $this->GetOne("select top 1 null as ignore from $tables HOLDLOCK where $where"); } - function SelectDB($dbName) { + function SelectDB($dbName) + { $this->databaseName = $dbName; if ($this->_connectionID) { return @sybase_select_db($dbName); - } - else return false; + } else return false; } /* Returns: the last error message from previous database operation @@ -113,45 +115,46 @@ class ADODB_sybase extends ADOConnection { { if (!function_exists('sybase_connect')) return false; - $this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword); + $this->_connectionID = sybase_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 (!function_exists('sybase_connect')) return false; - $this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword); + $this->_connectionID = sybase_pconnect($argHostname, $argUsername, $argPassword); if ($this->_connectionID === false) return false; if ($argDatabasename) return $this->SelectDB($argDatabasename); return true; } // returns query ID if successful, otherwise false - function _query($sql,$inputarr) + function _query($sql, $inputarr) { - global $ADODB_COUNTRECS; + global $ADODB_COUNTRECS; if ($ADODB_COUNTRECS == false && ADODB_PHPVER >= 0x4300) - return sybase_unbuffered_query($sql,$this->_connectionID); + return sybase_unbuffered_query($sql, $this->_connectionID); else - return sybase_query($sql,$this->_connectionID); + return sybase_query($sql, $this->_connectionID); } // See http://www.isug.com/Sybase_FAQ/ASE/section6.2.html#6.2.12 - function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) { - if ($secs2cache > 0) {// we do not cache rowcount, so we have to load entire recordset - $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + if ($secs2cache > 0) { // we do not cache rowcount, so we have to load entire recordset + $rs =& ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); return $rs; } $cnt = ($nrows > 0) ? $nrows : 0; if ($offset > 0 && $cnt) $cnt += $offset; $this->Execute("set rowcount $cnt"); - $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + $rs =& ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); $this->Execute("set rowcount 0"); return $rs; @@ -177,60 +180,60 @@ class ADODB_sybase extends ADOConnection { # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=16756?target=%25N%15_12018_START_RESTART_N%25 # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version // Format date column in sql string given an input format that understands Y M D - function SQLDate($fmt, $col=false) + function SQLDate($fmt, $col = false) { if (!$col) $col = $this->sysTimeStamp; $s = ''; $len = strlen($fmt); - for ($i=0; $i < $len; $i++) { + for ($i = 0; $i < $len; $i++) { if ($s) $s .= '+'; $ch = $fmt[$i]; - switch($ch) { - case 'Y': - case 'y': - $s .= "datename(yy,$col)"; - break; - case 'M': - $s .= "convert(char(3),$col,0)"; - break; - case 'm': - $s .= "replace(str(month($col),2),' ','0')"; - break; - case 'Q': - case 'q': - $s .= "datename(qq,$col)"; - break; - case 'D': - case 'd': - $s .= "replace(str(datepart(dd,$col),2),' ','0')"; - break; - case 'h': - $s .= "substring(convert(char(14),$col,0),13,2)"; - break; - - case 'H': - $s .= "replace(str(datepart(hh,$col),2),' ','0')"; - break; - - case 'i': - $s .= "replace(str(datepart(mi,$col),2),' ','0')"; - break; - case 's': - $s .= "replace(str(datepart(ss,$col),2),' ','0')"; - break; - case 'a': - case 'A': - $s .= "substring(convert(char(19),$col,0),18,2)"; - break; - - default: - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); - } - $s .= $this->qstr($ch); - break; + switch ($ch) { + case 'Y': + case 'y': + $s .= "datename(yy,$col)"; + break; + case 'M': + $s .= "convert(char(3),$col,0)"; + break; + case 'm': + $s .= "replace(str(month($col),2),' ','0')"; + break; + case 'Q': + case 'q': + $s .= "datename(qq,$col)"; + break; + case 'D': + case 'd': + $s .= "replace(str(datepart(dd,$col),2),' ','0')"; + break; + case 'h': + $s .= "substring(convert(char(14),$col,0),13,2)"; + break; + + case 'H': + $s .= "replace(str(datepart(hh,$col),2),' ','0')"; + break; + + case 'i': + $s .= "replace(str(datepart(mi,$col),2),' ','0')"; + break; + case 's': + $s .= "replace(str(datepart(ss,$col),2),' ','0')"; + break; + case 'a': + case 'A': + $s .= "substring(convert(char(19),$col,0),18,2)"; + break; + + default: + if ($ch == '\\') { + $i++; + $ch = substr($fmt, $i, 1); + } + $s .= $this->qstr($ch); + break; } } return $s; @@ -242,14 +245,14 @@ class ADODB_sybase extends ADOConnection { function MetaPrimaryKeys($table) { $sql = "SELECT c.column_name " . - "FROM syscolumn c, systable t " . - "WHERE t.table_name='$table' AND c.table_id=t.table_id " . - "AND t.table_type='BASE' " . - "AND c.pkey = 'Y' " . - "ORDER BY c.column_id"; + "FROM syscolumn c, systable t " . + "WHERE t.table_name='$table' AND c.table_id=t.table_id " . + "AND t.table_type='BASE' " . + "AND c.pkey = 'Y' " . + "ORDER BY c.column_id"; $a = $this->GetCol($sql); - if ($a && sizeof($a)>0) return $a; + if ($a && sizeof($a) > 0) return $a; return false; } } @@ -259,17 +262,18 @@ class ADODB_sybase extends ADOConnection { --------------------------------------------------------------------------------------*/ global $ADODB_sybase_mths; $ADODB_sybase_mths = array( - 'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6, - 'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12); + 'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6, + 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' => 10, 'NOV' => 11, 'DEC' => 12); -class ADORecordset_sybase extends ADORecordSet { +class ADORecordset_sybase extends ADORecordSet +{ var $databaseType = "sybase"; var $canSeek = true; // _mths works only in non-localised system - var $_mths = array('JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12); + var $_mths = array('JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6, 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' => 10, 'NOV' => 11, 'DEC' => 12); - function ADORecordset_sybase($id,$mode=false) + function ADORecordset_sybase($id, $mode = false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -277,7 +281,7 @@ class ADORecordset_sybase extends ADORecordSet { } if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC; else $this->fetchMode = $mode; - return $this->ADORecordSet($id,$mode); + return $this->ADORecordSet($id, $mode); } /* Returns: an object containing field information. @@ -288,8 +292,7 @@ class ADORecordset_sybase extends ADORecordSet { { if ($fieldOffset != -1) { $o = @sybase_fetch_field($this->_queryID, $fieldOffset); - } - else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ + } else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ $o = @sybase_fetch_field($this->_queryID); } // older versions of PHP did not support type, only numeric @@ -299,8 +302,8 @@ class ADORecordset_sybase extends ADORecordSet { function _initrs() { - global $ADODB_COUNTRECS; - $this->_numOfRows = ($ADODB_COUNTRECS)? @sybase_num_rows($this->_queryID):-1; + global $ADODB_COUNTRECS; + $this->_numOfRows = ($ADODB_COUNTRECS) ? @sybase_num_rows($this->_queryID) : -1; $this->_numOfFields = @sybase_num_fields($this->_queryID); } @@ -309,7 +312,7 @@ class ADORecordset_sybase extends ADORecordSet { return @sybase_data_seek($this->_queryID, $row); } - function _fetch($ignore_fields=false) + function _fetch($ignore_fields = false) { if ($this->fetchMode == ADODB_FETCH_NUM) { $this->fields = @sybase_fetch_row($this->_queryID); @@ -320,10 +323,10 @@ class ADORecordset_sybase extends ADORecordSet { return true; } return false; - } else { + } else { $this->fields = @sybase_fetch_array($this->_queryID); } - if ( is_array($this->fields)) { + if (is_array($this->fields)) { return true; } @@ -332,7 +335,8 @@ class ADORecordset_sybase extends ADORecordSet { /* close() only needs to be called if you are worried about using too much memory while your script is running. All associated result memory for the specified result identifier will automatically be freed. */ - function _close() { + function _close() + { return @sybase_free_result($this->_queryID); } @@ -348,54 +352,57 @@ class ADORecordset_sybase extends ADORecordSet { } } -class ADORecordSet_array_sybase extends ADORecordSet_array { - function ADORecordSet_array_sybase($id=-1) +class ADORecordSet_array_sybase extends ADORecordSet_array +{ + function ADORecordSet_array_sybase($id = -1) { $this->ADORecordSet_array($id); } - // sybase/mssql uses a default date like Dec 30 2000 12:00AM + // sybase/mssql uses a default date like Dec 30 2000 12:00AM function UnixDate($v) { - global $ADODB_sybase_mths; + global $ADODB_sybase_mths; //Dec 30 2000 12:00AM - if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})" - ,$v, $rr)) return parent::UnixDate($v); + if (!ereg("([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})" + , $v, $rr) + ) return parent::UnixDate($v); if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; - $themth = substr(strtoupper($rr[1]),0,3); + $themth = substr(strtoupper($rr[1]), 0, 3); $themth = $ADODB_sybase_mths[$themth]; if ($themth <= 0) return false; // h-m-s-MM-DD-YY - return mktime(0,0,0,$themth,$rr[2],$rr[3]); + return mktime(0, 0, 0, $themth, $rr[2], $rr[3]); } function UnixTimeStamp($v) { - global $ADODB_sybase_mths; + global $ADODB_sybase_mths; //11.02.2001 Toni Tunkkari toni.tunkkari@finebyte.com //Changed [0-9] to [0-9 ] in day conversion - if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})" - ,$v, $rr)) return parent::UnixTimeStamp($v); + if (!ereg("([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})" + , $v, $rr) + ) return parent::UnixTimeStamp($v); if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; - $themth = substr(strtoupper($rr[1]),0,3); + $themth = substr(strtoupper($rr[1]), 0, 3); $themth = $ADODB_sybase_mths[$themth]; if ($themth <= 0) return false; switch (strtoupper($rr[6])) { - case 'P': - if ($rr[4]<12) $rr[4] += 12; - break; - case 'A': - if ($rr[4]==12) $rr[4] = 0; - break; - default: - break; + case 'P': + if ($rr[4] < 12) $rr[4] += 12; + break; + case 'A': + if ($rr[4] == 12) $rr[4] = 0; + break; + default: + break; } // h-m-s-MM-DD-YY - return mktime($rr[4],$rr[5],0,$themth,$rr[2],$rr[3]); + return mktime($rr[4], $rr[5], 0, $themth, $rr[2], $rr[3]); } } diff --git a/lib/WikiDB/adodb/drivers/adodb-vfp.inc.php b/lib/WikiDB/adodb/drivers/adodb-vfp.inc.php index 6e05ccfe4..650682281 100644 --- a/lib/WikiDB/adodb/drivers/adodb-vfp.inc.php +++ b/lib/WikiDB/adodb/drivers/adodb-vfp.inc.php @@ -12,87 +12,99 @@ Set tabs to 4 for best viewing. */ if (!defined('_ADODB_ODBC_LAYER')) { - include(ADODB_DIR."/drivers/adodb-odbc.inc.php"); + include(ADODB_DIR . "/drivers/adodb-odbc.inc.php"); } -if (!defined('ADODB_VFP')){ -define('ADODB_VFP',1); -class ADODB_vfp extends ADODB_odbc { - var $databaseType = "vfp"; - var $fmtDate = "{^Y-m-d}"; - var $fmtTimeStamp = "{^Y-m-d, h:i:sA}"; - var $replaceQuote = "'+chr(39)+'" ; - var $true = '.T.'; - var $false = '.F.'; - var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE - var $upperCase = 'upper'; - var $_bindInputArray = false; // strangely enough, setting to true does not work reliably - var $sysTimeStamp = 'datetime()'; - var $sysDate = 'date()'; - var $ansiOuter = true; - var $hasTransactions = false; - var $curmode = SQL_CUR_USE_ODBC ; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L - - function ADODB_vfp() +if (!defined('ADODB_VFP')) { + define('ADODB_VFP', 1); + class ADODB_vfp extends ADODB_odbc { - $this->ADODB_odbc(); - } - - function Time() - { - return time(); - } - - function BeginTrans() { return false;} - - // quote string to be sent back to database - function qstr($s,$nofixquotes=false) - { - if (!$nofixquotes) return "'".str_replace("\r\n","'+chr(13)+'",str_replace("'",$this->replaceQuote,$s))."'"; - return "'".$s."'"; - } + var $databaseType = "vfp"; + var $fmtDate = "{^Y-m-d}"; + var $fmtTimeStamp = "{^Y-m-d, h:i:sA}"; + var $replaceQuote = "'+chr(39)+'"; + var $true = '.T.'; + var $false = '.F.'; + var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE + var $upperCase = 'upper'; + var $_bindInputArray = false; // strangely enough, setting to true does not work reliably + var $sysTimeStamp = 'datetime()'; + var $sysDate = 'date()'; + var $ansiOuter = true; + var $hasTransactions = false; + var $curmode = SQL_CUR_USE_ODBC; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L + + function ADODB_vfp() + { + $this->ADODB_odbc(); + } - // TOP requires ORDER BY for VFP - function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) - { - $this->hasTop = preg_match('/ORDER[ \t\r\n]+BY/is',$sql) ? 'top' : false; - return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); - } + function Time() + { + return time(); + } -}; + function BeginTrans() + { + return false; + } -class ADORecordSet_vfp extends ADORecordSet_odbc { + // quote string to be sent back to database + function qstr($s, $nofixquotes = false) + { + if (!$nofixquotes) return "'" . str_replace("\r\n", "'+chr(13)+'", str_replace("'", $this->replaceQuote, $s)) . "'"; + return "'" . $s . "'"; + } - var $databaseType = "vfp"; + // TOP requires ORDER BY for VFP + function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) + { + $this->hasTop = preg_match('/ORDER[ \t\r\n]+BY/is', $sql) ? 'top' : false; + return ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); + } - function ADORecordSet_vfp($id,$mode=false) - { - return $this->ADORecordSet_odbc($id,$mode); } - function MetaType($t,$len=-1) - { - if (is_object($t)) { - $fieldobj = $t; - $t = $fieldobj->type; - $len = $fieldobj->max_length; - } - switch (strtoupper($t)) { - case 'C': - if ($len <= $this->blobSize) return 'C'; - case 'M': - return 'X'; - - case 'D': return 'D'; + ; - case 'T': return 'T'; + class ADORecordSet_vfp extends ADORecordSet_odbc + { - case 'L': return 'L'; + var $databaseType = "vfp"; - case 'I': return 'I'; + function ADORecordSet_vfp($id, $mode = false) + { + return $this->ADORecordSet_odbc($id, $mode); + } - default: return 'N'; + function MetaType($t, $len = -1) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } + switch (strtoupper($t)) { + case 'C': + if ($len <= $this->blobSize) return 'C'; + case 'M': + return 'X'; + + case 'D': + return 'D'; + + case 'T': + return 'T'; + + case 'L': + return 'L'; + + case 'I': + return 'I'; + + default: + return 'N'; + } } } -} } //define diff --git a/lib/WikiDB/adodb/readme.htm b/lib/WikiDB/adodb/readme.htm index 7e4544049..4ebe63611 100644 --- a/lib/WikiDB/adodb/readme.htm +++ b/lib/WikiDB/adodb/readme.htm @@ -1,32 +1,43 @@ <html> <head> -<title>ADODB Manual - - - + ADODB Manual + + +

    ADOdb Library for PHP

    -

    ADOdb is a suite of database libraries that allow you to connect to multiple - databases in a portable manner. Download from http://php.weblogs.com/adodb.

    -
    • The ADOdb documentation has moved to docs-adodb.htm. - This allows you to query, update and insert records using a portable API.
    • -
    • The ADOdb data dictionary docs are at docs-datadict.htm. - This allows you to create database tables and indexes in a portable manner.
    • -
    • The ADOdb database performance monitoring docs are at docs-perf.htm. - This allows you to perform health checks, tune and monitor your database.
    • -
    • The ADOdb database-backed session docs are at docs-session.htm.
    • -
    • The ADOdb Date Time Library documentation to support dates outside the 32-bit range, at adodb_date_time_library.
    • + +

      ADOdb is a suite of database libraries that allow you to connect to multiple + databases in a portable manner. Download from http://php.weblogs.com/adodb.

      +
        +
      • The ADOdb documentation has moved to docs-adodb.htm. + This allows you to query, update and insert records using a portable API. +
      • +
      • The ADOdb data dictionary docs are at docs-datadict.htm. + This allows you to create database tables and indexes in a portable manner. +
      • +
      • The ADOdb database performance monitoring docs are at docs-perf.htm. + This allows you to perform health checks, tune and monitor your database. +
      • +
      • The ADOdb database-backed session docs are at docs-session.htm. +
      • +
      • The ADOdb Date Time Library documentation to support dates outside the 32-bit range, at adodb_date_time_library. +

      Installation

      Make sure you are running PHP4.0.4 or later. Unpack all the files into a directory accessible by your webserver.

      -To test, try modifying some of the tutorial examples. Make sure you customize the connection settings correctly. You can debug using: + To test, try modifying some of the tutorial examples. Make sure you customize the connection settings correctly. You + can debug using:

       <?php
       include('adodb/adodb.inc.php');
      @@ -41,30 +52,34 @@ print "</pre>";
       ?>
       

      How are people using ADOdb

      -Here are some examples of how people are using ADOdb (for a much longer list, -visit http://php.weblogs.com/adodb-cool-applications): +Here are some examples of how people are using ADOdb (for a much longer list, +visit http://php.weblogs.com/adodb-cool-applications):
        -
      • PhpLens is a commercial data grid component that allows - both cool Web designers and serious unshaved programmers to develop and - maintain databases on the Web easily. Developed by the author of ADOdb. -
      • -
      • PHAkt: PHP Extension for DreamWeaver Ultradev allows - you to script PHP in the popular Web page editor. Database handling provided - by ADOdb.
      • -
      • Analysis Console for Intrusion Databases (ACID): PHP-based - analysis engine to search and process a database of security incidents - generated by security-related software such as IDSes and firewalls (e.g. - Snort, ipchains). By Roman Danyliw.
      • -
      • PostNuke is a very popular free content management system - and weblog system. It offers full CSS support, HTML 4.01 transitional - compliance throughout, an advanced blocks system, and is fully multi-lingual - enabled.
      • -
      • EasyPublish CMS is another free content management system - for managing information and integrated modules on your internet, intranet- - and extranet-sites. From Norway.
      • -
      • NOLA is a full featured accounting, inventory, and job - tracking application. It is licensed under the GPL, and developed by Noguska. -
      • +
      • PhpLens is a commercial data grid component that allows + both cool Web designers and serious unshaved programmers to develop and + maintain databases on the Web easily. Developed by the author of ADOdb. +
      • +
      • PHAkt: PHP Extension for DreamWeaver Ultradev allows + you to script PHP in the popular Web page editor. Database handling provided + by ADOdb. +
      • +
      • Analysis Console for Intrusion Databases (ACID): PHP-based + analysis engine to search and process a database of security incidents + generated by security-related software such as IDSes and firewalls (e.g. + Snort, ipchains). By Roman Danyliw. +
      • +
      • PostNuke is a very popular free content management system + and weblog system. It offers full CSS support, HTML 4.01 transitional + compliance throughout, an advanced blocks system, and is fully multi-lingual + enabled. +
      • +
      • EasyPublish CMS is another free content management system + for managing information and integrated modules on your internet, intranet- + and extranet-sites. From Norway. +
      • +
      • NOLA is a full featured accounting, inventory, and job + tracking application. It is licensed under the GPL, and developed by Noguska. +
      diff --git a/lib/WikiDB/backend.php b/lib/WikiDB/backend.php index b5c9fb817..5eb885ba1 100644 --- a/lib/WikiDB/backend.php +++ b/lib/WikiDB/backend.php @@ -86,7 +86,8 @@ class WikiDB_backend * don't think we need this...) * */ - function get_pagedata($pagename) { + function get_pagedata($pagename) + { trigger_error("virtual", E_USER_ERROR); } @@ -113,7 +114,8 @@ class WikiDB_backend * @param $pagename string Page name. * @param $newdata hash New meta-data. */ - function update_pagedata($pagename, $newdata) { + function update_pagedata($pagename, $newdata) + { trigger_error("virtual", E_USER_ERROR); } @@ -124,7 +126,8 @@ class WikiDB_backend * @return int The latest version number for the page. Returns zero if * no versions of a page exist. */ - function get_latest_version($pagename) { + function get_latest_version($pagename) + { trigger_error("virtual", E_USER_ERROR); } @@ -136,7 +139,8 @@ class WikiDB_backend * @return int The version number of the version in the database which * immediately preceeds $version. */ - function get_previous_version($pagename, $version) { + function get_previous_version($pagename, $version) + { trigger_error("virtual", E_USER_ERROR); } @@ -165,7 +169,8 @@ class WikiDB_backend * For description of other version meta-data see WikiDB_PageRevision::get(). * @see WikiDB_PageRevision::get */ - function get_versiondata($pagename, $version, $want_content = false) { + function get_versiondata($pagename, $version, $want_content = false) + { trigger_error("virtual", E_USER_ERROR); } @@ -178,19 +183,20 @@ class WikiDB_backend * i.e save_page('') and DELETE nonempty id * Can be undone and is seen in RecentChanges. */ - function delete_page($pagename) { + function delete_page($pagename) + { $mtime = time(); $user =& $GLOBALS['request']->_user; $vdata = array('author' => $user->getId(), - 'author_id' => $user->getAuthenticatedId(), - 'mtime' => $mtime); + 'author_id' => $user->getAuthenticatedId(), + 'mtime' => $mtime); $this->lock(); // critical section: $version = $this->get_latest_version($pagename); - $this->set_versiondata($pagename, $version+1, $vdata); + $this->set_versiondata($pagename, $version + 1, $vdata); $this->set_links($pagename, false); // links are purged. // SQL needs to invalidate the non_empty id - if (! WIKIDB_NOCACHE_MARKUP) { + if (!WIKIDB_NOCACHE_MARKUP) { // need the hits, perms and LOCKED, otherwise you can reset the perm // by action=remove and re-create it with default perms $pagedata = $this->get_pagedata($pagename); @@ -204,7 +210,8 @@ class WikiDB_backend * Delete page (and all its revisions) from the database. * */ - function purge_page($pagename) { + function purge_page($pagename) + { trigger_error("virtual", E_USER_ERROR); } @@ -220,7 +227,8 @@ class WikiDB_backend * @param $pagename string Page name. * @param $version integer Version to delete. */ - function delete_versiondata($pagename, $version) { + function delete_versiondata($pagename, $version) + { trigger_error("virtual", E_USER_ERROR); } @@ -236,7 +244,8 @@ class WikiDB_backend * * @see get_versiondata */ - function set_versiondata($pagename, $version, $data) { + function set_versiondata($pagename, $version, $data) + { trigger_error("virtual", E_USER_ERROR); } @@ -252,7 +261,8 @@ class WikiDB_backend * @param $newdata hash New revision metadata. * @see set_versiondata, get_versiondata */ - function update_versiondata($pagename, $version, $newdata) { + function update_versiondata($pagename, $version, $newdata) + { $data = $this->get_versiondata($pagename, $version, true); if (!$data) { assert($data); @@ -274,7 +284,8 @@ class WikiDB_backend * * @param $links array List of page(names) which page links to. */ - function set_links($pagename, $links) { + function set_links($pagename, $links) + { trigger_error("virtual", E_USER_ERROR); } @@ -287,8 +298,9 @@ class WikiDB_backend * FIXME: array or iterator? * @return object A WikiDB_backend_iterator. */ - function get_links($pagename, $reversed, $include_empty=false, - $sortby='', $limit='', $exclude='') { + function get_links($pagename, $reversed, $include_empty = false, + $sortby = '', $limit = '', $exclude = '') + { //FIXME: implement simple (but slow) link finder. die("FIXME get_links"); } @@ -299,7 +311,8 @@ class WikiDB_backend * @param $pagename string The page name. * @return object A WikiDB_backend_iterator. */ - function get_all_revisions($pagename) { + function get_all_revisions($pagename) + { include_once 'lib/WikiDB/backend/dumb/AllRevisionsIter.php'; return new WikiDB_backend_dumb_AllRevisionsIter($this, $pagename); } @@ -323,7 +336,8 @@ class WikiDB_backend * * @return object A WikiDB_backend_iterator. */ - function get_all_pages($include_defaulted, $orderby=false, $limit='', $exclude='') { + function get_all_pages($include_defaulted, $orderby = false, $limit = '', $exclude = '') + { trigger_error("virtual", E_USER_ERROR); } @@ -345,8 +359,8 @@ class WikiDB_backend * * @see WikiDB::titleSearch */ - function text_search($search, $fulltext=false, $sortby='', - $limit='', $exclude='') + function text_search($search, $fulltext = false, $sortby = '', + $limit = '', $exclude = '') { // This method implements a simple linear search // through all the pages in the database. @@ -357,8 +371,8 @@ class WikiDB_backend // ignore $limit $pages = $this->get_all_pages(false, $sortby, false, $exclude); return new WikiDB_backend_dumb_TextSearchIter($this, $pages, $search, $fulltext, - array('limit' => $limit, - 'exclude' => $exclude)); + array('limit' => $limit, + 'exclude' => $exclude)); } /** @@ -373,7 +387,8 @@ class WikiDB_backend * @return object A WikiDB_backend_iterator. * @see WikiDB::linkSearch */ - function link_search( $pages, $linkvalue, $linktype, $relation=false, $options=array() ) { + function link_search($pages, $linkvalue, $linktype, $relation = false, $options = array()) + { include_once 'lib/WikiDB/backend/dumb/LinkSearchIter.php'; $pageiter = $this->text_search($pages); return new WikiDB_backend_dumb_LinkSearchIter($this, $pageiter, $linkvalue, $linktype, $relation, $options); @@ -389,7 +404,8 @@ class WikiDB_backend * @param integer $limit No more than this many pages * @return object A WikiDB_backend_iterator. */ - function most_popular($limit, $sortby='-hits') { + function most_popular($limit, $sortby = '-hits') + { // This is method fetches all pages, then // sorts them by hit count. // (Not very efficient.) @@ -410,7 +426,8 @@ class WikiDB_backend * @return object A WikiDB_backend_iterator. * @see WikiDB::mostRecent */ - function most_recent($params) { + function most_recent($params) + { // This method is very inefficient and searches through // all pages for the most recent changes. // @@ -421,9 +438,10 @@ class WikiDB_backend return new WikiDB_backend_dumb_MostRecentIter($this, $pages, $params); } - function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') { + function wanted_pages($exclude_from = '', $exclude = '', $sortby = '', $limit = '') + { include_once 'lib/WikiDB/backend/dumb/WantedPagesIter.php'; - $allpages = $this->get_all_pages(true,false,false,$exclude_from); + $allpages = $this->get_all_pages(true, false, false, $exclude_from); return new WikiDB_backend_dumb_WantedPagesIter($this, $allpages, $exclude, $sortby, $limit); } @@ -439,7 +457,8 @@ class WikiDB_backend * * All backends should support write locking. */ - function lock($write_lock = true) { + function lock($write_lock = true) + { } /** @@ -449,14 +468,16 @@ class WikiDB_backend * unlock() is called as many times as lock() has been. If $force is * set to true, the the database is unconditionally unlocked. */ - function unlock($force = false) { + function unlock($force = false) + { } /** * Close database. */ - function close () { + function close() + { } /** @@ -464,13 +485,15 @@ class WikiDB_backend * * This should flush all unwritten data to the filesystem. */ - function sync() { + function sync() + { } /** * Optimize the database. */ - function optimize() { + function optimize() + { } /** @@ -484,7 +507,8 @@ class WikiDB_backend * * @return boolean True iff database is in a consistent state. */ - function check($args=false) { + function check($args = false) + { } /** @@ -496,31 +520,33 @@ class WikiDB_backend * * @return boolean True iff successful. */ - function rebuild($args=false) { - global $request; - $dbh = $request->getDbh(); + function rebuild($args = false) + { + global $request; + $dbh = $request->getDbh(); $iter = $dbh->getAllPages(false); while ($page = $iter->next()) { - $current = $page->getCurrentRevision(true); - $pagename = $page->getName(); - $meta = $current->_data; - $version = $current->getVersion(); - $content =& $meta['%content']; - $formatted = new TransformedText($page, $content, $current->getMetaData()); - $type = $formatted->getType(); - $meta['pagetype'] = $type->getName(); - $links = $formatted->getWikiPageLinks(); // linkto => relation - $this->lock(array('version','page','recent','link','nonempty')); - $this->set_versiondata($pagename, $version, $meta); - $this->set_links($pagename, $links); - $this->unlock(array('version','page','recent','link','nonempty')); + $current = $page->getCurrentRevision(true); + $pagename = $page->getName(); + $meta = $current->_data; + $version = $current->getVersion(); + $content =& $meta['%content']; + $formatted = new TransformedText($page, $content, $current->getMetaData()); + $type = $formatted->getType(); + $meta['pagetype'] = $type->getName(); + $links = $formatted->getWikiPageLinks(); // linkto => relation + $this->lock(array('version', 'page', 'recent', 'link', 'nonempty')); + $this->set_versiondata($pagename, $version, $meta); + $this->set_links($pagename, $links); + $this->unlock(array('version', 'page', 'recent', 'link', 'nonempty')); } } - function _parse_searchwords($search) { + function _parse_searchwords($search) + { $search = strtolower(trim($search)); if (!$search) - return array(array(),array()); + return array(array(), array()); $words = preg_split('/\s+/', $search); $exclude = array(); @@ -540,15 +566,15 @@ class WikiDB_backend * Usage: * list($offset,$count) = $this->limit($args['limit']); */ - function limit($limit) { + function limit($limit) + { if (strstr($limit, ',')) { list($from, $limit) = explode(',', $limit); if ((!empty($from) && !is_numeric($from)) or (!empty($limit) && !is_numeric($limit))) { return $this->error(_("Illegal 'limit' argument: must be numeric")); } return array($from, $limit); - } - else { + } else { if (!empty($limit) && !is_numeric($limit)) { return $this->error(_("Illegal 'limit' argument: must be numeric")); } @@ -567,7 +593,8 @@ class WikiDB_backend * Duplicate the PageList function here to avoid loading the whole * PageList.php, and it forces the backend specific sortable_columns() */ - function sortby ($column, $action, $sortable_columns=false) { + function sortby($column, $action, $sortable_columns = false) + { if (empty($column)) return ''; //support multiple comma-delimited sortby args: "+hits,+pagename" if (strstr($column, ',')) { @@ -578,16 +605,18 @@ class WikiDB_backend else $result[] = $this->sortby($col, $action); } - return join(",",$result); + return join(",", $result); } - if (substr($column,0,1) == '+') { - $order = '+'; $column = substr($column,1); - } elseif (substr($column,0,1) == '-') { - $order = '-'; $column = substr($column,1); + if (substr($column, 0, 1) == '+') { + $order = '+'; + $column = substr($column, 1); + } elseif (substr($column, 0, 1) == '-') { + $order = '-'; + $column = substr($column, 1); } // default order: +pagename, -mtime, -hits if (empty($order)) - if (in_array($column,array('mtime','hits'))) + if (in_array($column, array('mtime', 'hits'))) $order = '-'; else $order = '+'; @@ -598,8 +627,8 @@ class WikiDB_backend return $order . $column; } elseif ($action == 'check') { return (!empty($this->_sortby[$column]) or - ($GLOBALS['request']->getArg('sortby') and - strstr($GLOBALS['request']->getArg('sortby'),$column))); + ($GLOBALS['request']->getArg('sortby') and + strstr($GLOBALS['request']->getArg('sortby'), $column))); } elseif ($action == 'db') { // native sort possible? if (!empty($this) and !$sortable_columns) @@ -613,51 +642,64 @@ class WikiDB_backend return ''; } - function sortable_columns() { - return array('pagename'/*,'mtime','author_id','author'*/); + function sortable_columns() + { + return array('pagename' /*,'mtime','author_id','author'*/); } // adds surrounding quotes - function quote ($s) { return "'".$s."'"; } + function quote($s) + { + return "'" . $s . "'"; + } + // no surrounding quotes because we know it's a string - function qstr ($s) { return $s; } + function qstr($s) + { + return $s; + } - function isSQL () { - return in_array(DATABASE_TYPE, array('SQL','ADODB','PDO')); + function isSQL() + { + return in_array(DATABASE_TYPE, array('SQL', 'ADODB', 'PDO')); } - function backendType() { + function backendType() + { return DATABASE_TYPE; } - function write_accesslog(&$entry) { + function write_accesslog(&$entry) + { global $request; if (!$this->isSQL()) return; $dbh = &$this->_dbh; $log_tbl = $entry->_accesslog->logtable; // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales $dbh->query("INSERT INTO $log_tbl" - . " (time_stamp,remote_host,remote_user,request_method,request_line,request_args," - . "request_uri,request_time,status,bytes_sent,referer,agent,request_duration)" - . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", - array( - // Problem: date formats are backend specific. Either use unixtime as %d (long), - // or the native timestamp format. - $entry->time, - $entry->host, - $entry->user, - $entry->request_method, - $entry->request, - $entry->request_args, - $entry->request_uri, - $entry->_ncsa_time($entry->time), - $entry->status, - (int)$entry->size, - $entry->referer, - $entry->user_agent, - $entry->duration)); - } -}; + . " (time_stamp,remote_host,remote_user,request_method,request_line,request_args," + . "request_uri,request_time,status,bytes_sent,referer,agent,request_duration)" + . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", + array( + // Problem: date formats are backend specific. Either use unixtime as %d (long), + // or the native timestamp format. + $entry->time, + $entry->host, + $entry->user, + $entry->request_method, + $entry->request, + $entry->request_args, + $entry->request_uri, + $entry->_ncsa_time($entry->time), + $entry->status, + (int)$entry->size, + $entry->referer, + $entry->user_agent, + $entry->duration)); + } +} + +; /** * Iterator returned by backend methods which (possibly) return @@ -687,18 +729,21 @@ class WikiDB_backend_iterator * * If this is a link iterator, the 'pagename' is mandatory, 'linkrelation' is optional. */ - function next() { + function next() + { trigger_error("virtual", E_USER_ERROR); } - function count() { + function count() + { if (!empty($this->_pages)) - return count($this->_pages); - else - return 0; + return count($this->_pages); + else + return 0; } - function asArray() { + function asArray() + { if (!empty($this->_pages)) { reset($this->_pages); return $this->_pages; @@ -715,57 +760,90 @@ class WikiDB_backend_iterator * Some backends limit the result set itself (dba, file, flatfile), * Some SQL based leave it to WikiDB/PageList - deferred filtering in the iterator. */ - function limit() { + function limit() + { return empty($this->_options['limit']) ? 0 : $this->_options['limit']; } /** * Release resources held by this iterator. */ - function free() { + function free() + { } -}; +} + +; /** * search baseclass, pcre-specific */ class WikiDB_backend_search { - function WikiDB_backend_search($search, &$dbh) { + function WikiDB_backend_search($search, &$dbh) + { $this->_dbh = $dbh; $this->_case_exact = $search->_case_exact; - $this->_stoplist =& $search->_stoplist; + $this->_stoplist =& $search->_stoplist; $this->stoplisted = array(); } - function _quote($word) { + + function _quote($word) + { return preg_quote($word, "/"); } + //TODO: use word anchors - function EXACT($word) { return "^".$this->_quote($word)."$"; } - function STARTS_WITH($word) { return "^".$this->_quote($word); } - function ENDS_WITH($word) { return $this->_quote($word)."$"; } - function WORD($word) { return $this->_quote($word); } - function REGEX($word) { return $word; } + function EXACT($word) + { + return "^" . $this->_quote($word) . "$"; + } + + function STARTS_WITH($word) + { + return "^" . $this->_quote($word); + } + + function ENDS_WITH($word) + { + return $this->_quote($word) . "$"; + } + + function WORD($word) + { + return $this->_quote($word); + } + + function REGEX($word) + { + return $word; + } + //TESTME - function _pagename_match_clause($node) { + function _pagename_match_clause($node) + { $method = $node->op; $word = $this->$method($node->word); - return "preg_match(\"/\".$word.\"/\"".($this->_case_exact ? "i":"").")"; + return "preg_match(\"/\".$word.\"/\"" . ($this->_case_exact ? "i" : "") . ")"; } + /* Eliminate stoplist words. * Keep a list of Stoplisted words to inform the poor user. */ - function isStoplisted ($node) { + function isStoplisted($node) + { // check only on WORD or EXACT fulltext search if ($node->op != 'WORD' and $node->op != 'EXACT') return false; - if (preg_match("/^".$this->_stoplist."$/i", $node->word)) { + if (preg_match("/^" . $this->_stoplist . "$/i", $node->word)) { array_push($this->stoplisted, $node->word); return true; } return false; } - function getStoplisted($word) { + + function getStoplisted($word) + { return $this->stoplisted; } } @@ -775,27 +853,30 @@ class WikiDB_backend_search */ class WikiDB_backend_search_sql extends WikiDB_backend_search { - function _pagename_match_clause($node) { + function _pagename_match_clause($node) + { // word already quoted by TextSearchQuery_node_word::_sql_quote() $word = $node->sql(); if ($word == '%') // ALL shortcut return "1=1"; else return ($this->_case_exact - ? "pagename LIKE '$word'" - : "LOWER(pagename) LIKE '$word'"); + ? "pagename LIKE '$word'" + : "LOWER(pagename) LIKE '$word'"); } - function _fulltext_match_clause($node) { + + function _fulltext_match_clause($node) + { // force word-style %word% for fulltext search $word = '%' . $node->_sql_quote($node->word) . '%'; // eliminate stoplist words if ($this->isStoplisted($node)) - return "1=1"; // and (pagename or 1) => and 1 + return "1=1"; // and (pagename or 1) => and 1 else return $this->_pagename_match_clause($node) // probably convert this MATCH AGAINST or SUBSTR/POSITION without wildcards . ($this->_case_exact ? " OR content LIKE '$word'" - : " OR LOWER(content) LIKE '$word'"); + : " OR LOWER(content) LIKE '$word'"); } } diff --git a/lib/WikiDB/backend/ADODB.php b/lib/WikiDB/backend/ADODB.php index 54b447cf7..6f8ec60a3 100644 --- a/lib/WikiDB/backend/ADODB.php +++ b/lib/WikiDB/backend/ADODB.php @@ -46,7 +46,6 @@ * unneeded features included: paging, monitoring and sessions, and much more drivers. * No locking (which PearDB supports in some backends), and sequences are very * bad compared to PearDB. - * Old Comments, by Lawrence Akka: * 1) ADODB's GetRow() is slightly different from that in PEAR. It does not * accept a fetchmode parameter @@ -69,10 +68,11 @@ include_once 'lib/WikiDB/adodb/adodb-errorhandler.inc.php'; require_once 'lib/WikiDB/adodb/adodb.inc.php'; class WikiDB_backend_ADODB -extends WikiDB_backend + extends WikiDB_backend { - function WikiDB_backend_ADODB ($dbparams) { + function WikiDB_backend_ADODB($dbparams) + { $parsed = parseDSN($dbparams['dsn']); $this->_dbparams = $dbparams; $this->_parsedDSN =& $parsed; @@ -85,14 +85,14 @@ extends WikiDB_backend // persistent is defined as DSN option, or with a config value. // phptype://username:password@hostspec/database?persistent=false - //FIXME: how to catch connection errors for dbamin_user? + //FIXME: how to catch connection errors for dbamin_user? if (!empty($parsed['persistent']) or DATABASE_PERSISTENT) - $conn = $this->_dbh->PConnect($parsed['hostspec'],$parsed['username'], - $parsed['password'], $parsed['database']); + $conn = $this->_dbh->PConnect($parsed['hostspec'], $parsed['username'], + $parsed['password'], $parsed['database']); else - $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'], - $parsed['password'], $parsed['database']); - if (!$conn) return; + $conn = $this->_dbh->Connect($parsed['hostspec'], $parsed['username'], + $parsed['password'], $parsed['database']); + if (!$conn) return; // Since 1.3.10 we use the faster ADODB_FETCH_NUM, // with some ASSOC based recordsets. @@ -102,11 +102,11 @@ extends WikiDB_backend $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : ''; $this->_table_names - = array('page_tbl' => $prefix . 'page', - 'version_tbl' => $prefix . 'version', - 'link_tbl' => $prefix . 'link', - 'recent_tbl' => $prefix . 'recent', - 'nonempty_tbl' => $prefix . 'nonempty'); + = array('page_tbl' => $prefix . 'page', + 'version_tbl' => $prefix . 'version', + 'link_tbl' => $prefix . 'link', + 'recent_tbl' => $prefix . 'recent', + 'nonempty_tbl' => $prefix . 'nonempty'); $page_tbl = $this->_table_names['page_tbl']; $version_tbl = $this->_table_names['version_tbl']; $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, " @@ -121,27 +121,28 @@ extends WikiDB_backend 'versiondata'); $this->_expressions - = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)", - 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)", - 'maxversion' => "MAX(version)", - 'notempty' => "<>''", - 'iscontent' => "$version_tbl.content<>''"); + = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)", + 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)", + 'maxversion' => "MAX(version)", + 'notempty' => "<>''", + 'iscontent' => "$version_tbl.content<>''"); $this->_lock_count = 0; } /** * Close database connection. */ - function close () { + function close() + { if (!$this->_dbh) return; if ($this->_lock_count) { trigger_error("WARNING: database still locked " . - '(lock_count = $this->_lock_count)' . "\n
      ", - E_USER_WARNING); + '(lock_count = $this->_lock_count)' . "\n
      ", + E_USER_WARNING); } // $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops. - $this->unlock(false,'force'); + $this->unlock(false, 'force'); $this->_dbh->close(); $this->_dbh = false; @@ -150,69 +151,76 @@ extends WikiDB_backend /* * Fast test for wikipage. */ - function is_wiki_page($pagename) { + function is_wiki_page($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); $row = $dbh->GetRow(sprintf("SELECT $page_tbl.id AS id" - . " FROM $nonempty_tbl, $page_tbl" - . " WHERE $nonempty_tbl.id=$page_tbl.id" - . " AND pagename=%s", - $dbh->qstr($pagename))); + . " FROM $nonempty_tbl, $page_tbl" + . " WHERE $nonempty_tbl.id=$page_tbl.id" + . " AND pagename=%s", + $dbh->qstr($pagename))); return $row ? $row[0] : false; } - function get_all_pagenames() { + function get_all_pagenames() + { $dbh = &$this->_dbh; extract($this->_table_names); $result = $dbh->Execute("SELECT pagename" - . " FROM $nonempty_tbl, $page_tbl" - . " WHERE $nonempty_tbl.id=$page_tbl.id"); + . " FROM $nonempty_tbl, $page_tbl" + . " WHERE $nonempty_tbl.id=$page_tbl.id"); return $result->GetArray(); } /* * filter (nonempty pages) currently ignored */ - function numPages($filter=false, $exclude='') { + function numPages($filter = false, $exclude = '') + { $dbh = &$this->_dbh; extract($this->_table_names); $result = $dbh->getRow("SELECT count(*)" - . " FROM $nonempty_tbl, $page_tbl" - . " WHERE $nonempty_tbl.id=$page_tbl.id"); + . " FROM $nonempty_tbl, $page_tbl" + . " WHERE $nonempty_tbl.id=$page_tbl.id"); return $result[0]; } - function increaseHitCount($pagename) { + function increaseHitCount($pagename) + { $dbh = &$this->_dbh; // Hits is the only thing we can update in a fast manner. // Note that this will fail silently if the page does not // have a record in the page table. Since it's just the // hit count, who cares? $dbh->Execute(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename=%s", - $this->_table_names['page_tbl'], - $dbh->qstr($pagename))); + $this->_table_names['page_tbl'], + $dbh->qstr($pagename))); return; } /** * Read page information from database. */ - function get_pagedata($pagename) { + function get_pagedata($pagename) + { $dbh = &$this->_dbh; $row = $dbh->GetRow(sprintf("SELECT id,pagename,hits,pagedata FROM %s WHERE pagename=%s", - $this->_table_names['page_tbl'], - $dbh->qstr($pagename))); + $this->_table_names['page_tbl'], + $dbh->qstr($pagename))); return $row ? $this->_extract_page_data($row[3], $row[2]) : false; } - function _extract_page_data($data, $hits) { + function _extract_page_data($data, $hits) + { if (empty($data)) return array('hits' => $hits); else return array_merge(array('hits' => $hits), $this->_unserialize($data)); } - function update_pagedata($pagename, $newdata) { + function update_pagedata($pagename, $newdata) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; @@ -222,12 +230,12 @@ extends WikiDB_backend // have a record in the page table. Since it's just the // hit count, who cares? $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s", - $newdata['hits'], $dbh->qstr($pagename))); + $newdata['hits'], $dbh->qstr($pagename))); return; } $where = sprintf("pagename=%s", $dbh->qstr($pagename)); - $dbh->BeginTrans( ); - $dbh->RowLock($page_tbl,$where); + $dbh->BeginTrans(); + $dbh->RowLock($page_tbl, $where); $data = $this->get_pagedata($pagename); if (!$data) { @@ -247,36 +255,40 @@ extends WikiDB_backend $data[$key] = $val; } if ($dbh->Execute("UPDATE $page_tbl" - . " SET hits=?, pagedata=?" - . " WHERE pagename=?", - array($hits, $this->_serialize($data), $pagename))) { - $dbh->CommitTrans( ); + . " SET hits=?, pagedata=?" + . " WHERE pagename=?", + array($hits, $this->_serialize($data), $pagename)) + ) { + $dbh->CommitTrans(); return true; } else { - $dbh->RollbackTrans( ); + $dbh->RollbackTrans(); return false; } } - function get_cached_html($pagename) { + function get_cached_html($pagename) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; $row = $dbh->GetRow(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename=%s", - $dbh->qstr($pagename))); + $dbh->qstr($pagename))); return $row ? $row[0] : false; } - function set_cached_html($pagename, $data) { + function set_cached_html($pagename, $data) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; if (empty($data)) $data = ''; $rs = $dbh->Execute("UPDATE $page_tbl" - . " SET cached_html=?" - . " WHERE pagename=?", - array($data, $pagename)); + . " SET cached_html=?" + . " WHERE pagename=?", + array($data, $pagename)); } - function _get_pageid($pagename, $create_if_missing = false) { + function _get_pageid($pagename, $create_if_missing = false) + { // check id_cache global $request; @@ -286,38 +298,38 @@ extends WikiDB_backend return $cache[$pagename]; } } - // attributes play this game. + // attributes play this game. if ($pagename === '') return 0; $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s", - $dbh->qstr($pagename)); - if (! $create_if_missing ) { + $dbh->qstr($pagename)); + if (!$create_if_missing) { $row = $dbh->GetRow($query); return $row ? $row[0] : false; } $row = $dbh->GetRow($query); - if (! $row ) { - //TODO: Does the DBM has subselects? Then we can do it with select max(id)+1 - // $this->lock(array('page')); - $dbh->BeginTrans( ); - $dbh->CommitLock($page_tbl); + if (!$row) { + //TODO: Does the DBM has subselects? Then we can do it with select max(id)+1 + // $this->lock(array('page')); + $dbh->BeginTrans(); + $dbh->CommitLock($page_tbl); if (0 and $dbh->hasGenID) { // requires create permissions - $id = $dbh->GenID($page_tbl."_id"); + $id = $dbh->GenID($page_tbl . "_id"); } else { // Better generic version than with adodb::genID $row = $dbh->GetRow("SELECT MAX(id) FROM $page_tbl"); $id = $row[0] + 1; } - $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl" + $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl" . " (id,pagename,hits)" . " VALUES (%d,%s,0)", - $id, $dbh->qstr($pagename))); - if ($rs) $dbh->CommitTrans( ); - else $dbh->RollbackTrans( ); - // $this->unlock(array('page')); + $id, $dbh->qstr($pagename))); + if ($rs) $dbh->CommitTrans(); + else $dbh->RollbackTrans(); + // $this->unlock(array('page')); } else { $id = $row[0]; } @@ -325,30 +337,32 @@ extends WikiDB_backend return $id; } - function get_latest_version($pagename) { + function get_latest_version($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); $row = $dbh->GetRow(sprintf("SELECT latestversion" - . " FROM $page_tbl, $recent_tbl" - . " WHERE $page_tbl.id=$recent_tbl.id" - . " AND pagename=%s", - $dbh->qstr($pagename))); + . " FROM $page_tbl, $recent_tbl" + . " WHERE $page_tbl.id=$recent_tbl.id" + . " AND pagename=%s", + $dbh->qstr($pagename))); return $row ? (int)$row[0] : false; } - function get_previous_version($pagename, $version) { + function get_previous_version($pagename, $version) + { $dbh = &$this->_dbh; extract($this->_table_names); // Use SELECTLIMIT for maximum portability $rs = $dbh->SelectLimit(sprintf("SELECT version" - . " FROM $version_tbl, $page_tbl" - . " WHERE $version_tbl.id=$page_tbl.id" - . " AND pagename=%s" - . " AND version < %d" - . " ORDER BY version DESC", - $dbh->qstr($pagename), - $version), - 1); + . " FROM $version_tbl, $page_tbl" + . " WHERE $version_tbl.id=$page_tbl.id" + . " AND pagename=%s" + . " AND version < %d" + . " ORDER BY version DESC", + $dbh->qstr($pagename), + $version), + 1); return $rs->fields ? (int)$rs->fields[0] : false; } @@ -360,7 +374,8 @@ extends WikiDB_backend * @return hash The version data, or false if specified version does not * exist. */ - function get_versiondata($pagename, $version, $want_content = false) { + function get_versiondata($pagename, $version, $want_content = false) + { $dbh = &$this->_dbh; extract($this->_table_names); extract($this->_expressions); @@ -379,22 +394,23 @@ extends WikiDB_backend . "$version_tbl.versiondata as versiondata"; } $row = $dbh->GetRow(sprintf("SELECT $fields" - . " FROM $page_tbl, $version_tbl" - . " WHERE $page_tbl.id=$version_tbl.id" - . " AND pagename=%s" - . " AND version=%d", - $dbh->qstr($pagename), $version)); + . " FROM $page_tbl, $version_tbl" + . " WHERE $page_tbl.id=$version_tbl.id" + . " AND pagename=%s" + . " AND version=%d", + $dbh->qstr($pagename), $version)); return $row ? $this->_extract_version_data_num($row, $want_content) : false; } - function _extract_version_data_num($row, $want_content) { + function _extract_version_data_num($row, $want_content) + { if (!$row) return false; //$id &= $row[0]; //$pagename &= $row[1]; $data = empty($row[8]) ? array() : $this->_unserialize($row[8]); - $data['mtime'] = $row[5]; + $data['mtime'] = $row[5]; $data['is_minor_edit'] = !empty($row[6]); if ($want_content) { $data['%content'] = $row[7]; @@ -407,7 +423,8 @@ extends WikiDB_backend return $data; } - function _extract_version_data_assoc($row) { + function _extract_version_data_assoc($row) + { if (!$row) return false; @@ -418,8 +435,7 @@ extends WikiDB_backend if (isset($content)) $data['%content'] = $content; elseif ($have_content) - $data['%content'] = true; - else + $data['%content'] = true; else $data['%content'] = ''; if (!empty($pagedata)) { // hmm, $pagedata = is already extracted by WikiDB_backend_ADODB_iter @@ -432,52 +448,54 @@ extends WikiDB_backend /** * Create a new revision of a page. */ - function set_versiondata($pagename, $version, $data) { + function set_versiondata($pagename, $version, $data) + { $dbh = &$this->_dbh; $version_tbl = $this->_table_names['version_tbl']; - $minor_edit = (int) !empty($data['is_minor_edit']); + $minor_edit = (int)!empty($data['is_minor_edit']); unset($data['is_minor_edit']); $mtime = (int)$data['mtime']; unset($data['mtime']); assert(!empty($mtime)); - @$content = (string) $data['%content']; + @$content = (string)$data['%content']; unset($data['%content']); unset($data['%pagedata']); - $this->lock(array('page','recent','version','nonempty')); - $dbh->BeginTrans( ); + $this->lock(array('page', 'recent', 'version', 'nonempty')); + $dbh->BeginTrans(); $dbh->CommitLock($version_tbl); $id = $this->_get_pageid($pagename, true); $backend_type = $this->backendType(); - $dbh->Execute(sprintf("DELETE FROM $version_tbl" - . " WHERE id=%d AND version=%d", - $id, $version)); - $rs = $dbh->Execute("INSERT INTO $version_tbl" + $dbh->Execute(sprintf("DELETE FROM $version_tbl" + . " WHERE id=%d AND version=%d", + $id, $version)); + $rs = $dbh->Execute("INSERT INTO $version_tbl" . " (id,version,mtime,minor_edit,content,versiondata)" . " VALUES(?,?,?,?,?,?)", - array($id, $version, $mtime, $minor_edit, - $content, $this->_serialize($data))); + array($id, $version, $mtime, $minor_edit, + $content, $this->_serialize($data))); $this->_update_recent_table($id); $this->_update_nonempty_table($id); - if ($rs) $dbh->CommitTrans( ); - else $dbh->RollbackTrans( ); - $this->unlock(array('page','recent','version','nonempty')); + if ($rs) $dbh->CommitTrans(); + else $dbh->RollbackTrans(); + $this->unlock(array('page', 'recent', 'version', 'nonempty')); } /** * Delete an old revision of a page. */ - function delete_versiondata($pagename, $version) { + function delete_versiondata($pagename, $version) + { $dbh = &$this->_dbh; extract($this->_table_names); $this->lock(array('version')); - if ( ($id = $this->_get_pageid($pagename)) ) { + if (($id = $this->_get_pageid($pagename))) { $dbh->Execute("DELETE FROM $version_tbl" - . " WHERE id=$id AND version=$version"); + . " WHERE id=$id AND version=$version"); $this->_update_recent_table($id); // This shouldn't be needed (as long as the latestversion // never gets deleted.) But, let's be safe. @@ -495,54 +513,55 @@ extends WikiDB_backend * so that get_latest_version returns id+1 and get_previous_version returns prev id * and page->exists returns false. */ - function delete_page($pagename) { + function delete_page($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); $dbh->BeginTrans(); $dbh->CommitLock($recent_tbl); if (($id = $this->_get_pageid($pagename, false)) === false) { - $dbh->RollbackTrans( ); + $dbh->RollbackTrans(); return false; } $mtime = time(); $user =& $GLOBALS['request']->_user; $meta = array('author' => $user->getId(), - 'author_id' => $user->getAuthenticatedId(), - 'mtime' => $mtime); - $this->lock(array('version','recent','nonempty','page','link')); + 'author_id' => $user->getAuthenticatedId(), + 'mtime' => $mtime); + $this->lock(array('version', 'recent', 'nonempty', 'page', 'link')); $version = $this->get_latest_version($pagename); if ($dbh->Execute("UPDATE $recent_tbl SET latestversion=latestversion+1," - . "latestmajor=latestversion+1,latestminor=NULL WHERE id=$id") + . "latestmajor=latestversion+1,latestminor=NULL WHERE id=$id") and $dbh->Execute("INSERT INTO $version_tbl" - . " (id,version,mtime,minor_edit,content,versiondata)" - . " VALUES(?,?,?,?,?,?)", - array($id, $version+1, $mtime, 0, - '', $this->_serialize($meta))) - and $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id") - and $this->set_links($pagename, false) + . " (id,version,mtime,minor_edit,content,versiondata)" + . " VALUES(?,?,?,?,?,?)", + array($id, $version + 1, $mtime, 0, + '', $this->_serialize($meta))) + and $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id") + and $this->set_links($pagename, false) // need to keep perms and LOCKED, otherwise you can reset the perm // by action=remove and re-create it with default perms // keep hits but delete meta-data //and $dbh->Execute("UPDATE $page_tbl SET pagedata='' WHERE id=$id") - ) - { - $this->unlock(array('version','recent','nonempty','page','link')); - $dbh->CommitTrans( ); + ) { + $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link')); + $dbh->CommitTrans(); return true; } else { - $this->unlock(array('version','recent','nonempty','page','link')); - $dbh->RollbackTrans( ); + $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link')); + $dbh->RollbackTrans(); return false; } } - function purge_page($pagename) { + function purge_page($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); - $this->lock(array('version','recent','nonempty','page','link')); - if ( ($id = $this->_get_pageid($pagename, false)) ) { + $this->lock(array('version', 'recent', 'nonempty', 'page', 'link')); + if (($id = $this->_get_pageid($pagename, false))) { $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id"); $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id"); $dbh->Execute("DELETE FROM $version_tbl WHERE id=$id"); @@ -553,15 +572,14 @@ extends WikiDB_backend // altogether. $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id"); $result = 0; - } - else { + } else { $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id"); $result = 1; } } else { $result = -1; // already purged or not existing } - $this->unlock(array('version','recent','nonempty','page','link')); + $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link')); return $result; } @@ -575,7 +593,8 @@ extends WikiDB_backend * Update link table. * on DEBUG: delete old, deleted links from page */ - function set_links($pagename, $links) { + function set_links($pagename, $links) + { // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE. $dbh = &$this->_dbh; @@ -585,8 +604,8 @@ extends WikiDB_backend $pageid = $this->_get_pageid($pagename, true); $oldlinks = $dbh->getAssoc("SELECT $link_tbl.linkto as id, page.pagename FROM $link_tbl" - ." JOIN page ON ($link_tbl.linkto = page.id)" - ." WHERE linkfrom=$pageid"); + . " JOIN page ON ($link_tbl.linkto = page.id)" + . " WHERE linkfrom=$pageid"); // Delete current links, $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid"); // and insert new links. Faster than checking for all single links @@ -611,10 +630,10 @@ extends WikiDB_backend assert($linkid); if ($relation) { $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto, relation)" - . " VALUES ($pageid, $linkid, $relation)"); + . " VALUES ($pageid, $linkid, $relation)"); } else { $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)" - . " VALUES ($pageid, $linkid)"); + . " VALUES ($pageid, $linkid)"); } if ($oldlinks and array_key_exists($linkid, $oldlinks)) { // This was also in the previous page @@ -629,18 +648,17 @@ extends WikiDB_backend foreach ($oldlinks as $id => $name) { // ...check if the page is empty and has no version $result = $dbh->getRow("SELECT $page_tbl.id FROM $page_tbl" - . " LEFT JOIN $nonempty_tbl USING (id) " - . " LEFT JOIN $version_tbl USING (id)" - . " WHERE $nonempty_tbl.id is NULL" - . " AND $version_tbl.id is NULL" - . " AND $page_tbl.id=$id"); + . " LEFT JOIN $nonempty_tbl USING (id) " + . " LEFT JOIN $version_tbl USING (id)" + . " WHERE $nonempty_tbl.id is NULL" + . " AND $version_tbl.id is NULL" + . " AND $page_tbl.id=$id"); $linkto = $dbh->getRow("SELECT linkfrom FROM $link_tbl WHERE linkto=$id"); - if ($result and empty($linkto)) - { + if ($result and empty($linkto)) { trigger_error("delete empty and non-referenced link $name ($id)", E_USER_NOTICE); $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id"); // may fail - $dbh->Execute("DELETE FROM $link_tbl WHERE linkto=$id"); - $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link + $dbh->Execute("DELETE FROM $link_tbl WHERE linkto=$id"); + $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link } } } @@ -651,7 +669,8 @@ extends WikiDB_backend /* get all oldlinks in hash => id, relation check for all new links */ - function set_links1($pagename, $links) { + function set_links1($pagename, $links) + { $dbh = &$this->_dbh; extract($this->_table_names); @@ -660,9 +679,9 @@ extends WikiDB_backend $pageid = $this->_get_pageid($pagename, true); $oldlinks = $dbh->getAssoc("SELECT $link_tbl.linkto as linkto, $link_tbl.relation, page.pagename" - ." FROM $link_tbl" - ." JOIN page ON ($link_tbl.linkto = page.id)" - ." WHERE linkfrom=$pageid"); + . " FROM $link_tbl" + . " JOIN page ON ($link_tbl.linkto = page.id)" + . " WHERE linkfrom=$pageid"); /* old new * X => [1,0 2,0 1,1] X => [1,1 3,0] * => delete 1,0 2,0 + insert 3,0 @@ -693,15 +712,15 @@ extends WikiDB_backend } } } - if (! $skip ) { + if (!$skip) { if ($update) { } if ($relation) { $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto, relation)" - . " VALUES ($pageid, $linkid, $relation)"); + . " VALUES ($pageid, $linkid, $relation)"); } else { $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)" - . " VALUES ($pageid, $linkid)"); + . " VALUES ($pageid, $linkid)"); } } @@ -718,15 +737,15 @@ extends WikiDB_backend foreach ($oldlinks as $id => $name) { // ...check if the page is empty and has no version if ($dbh->getRow("SELECT $page_tbl.id FROM $page_tbl" - . " LEFT JOIN $nonempty_tbl USING (id) " - . " LEFT JOIN $version_tbl USING (id)" - . " WHERE $nonempty_tbl.id is NULL" - . " AND $version_tbl.id is NULL" - . " AND $page_tbl.id=$id")) - { - trigger_error("delete empty and non-referenced link $name ($id)", E_USER_NOTICE); - $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link - $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id"); // may fail + . " LEFT JOIN $nonempty_tbl USING (id) " + . " LEFT JOIN $version_tbl USING (id)" + . " WHERE $nonempty_tbl.id is NULL" + . " AND $version_tbl.id is NULL" + . " AND $page_tbl.id=$id") + ) { + trigger_error("delete empty and non-referenced link $name ($id)", E_USER_NOTICE); + $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link + $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id"); // may fail } } } @@ -746,23 +765,23 @@ extends WikiDB_backend * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next * if (isset($next['linkrelation'])) */ - function get_links($pagename, $reversed=true, $include_empty=false, - $sortby='', $limit='', $exclude='', + function get_links($pagename, $reversed = true, $include_empty = false, + $sortby = '', $limit = '', $exclude = '', $want_relations = false) { $dbh = &$this->_dbh; extract($this->_table_names); if ($reversed) - list($have,$want) = array('linkee', 'linker'); + list($have, $want) = array('linkee', 'linker'); else - list($have,$want) = array('linker', 'linkee'); + list($have, $want) = array('linker', 'linkee'); $orderby = $this->sortby($sortby, 'db', array('pagename')); if ($orderby) $orderby = " ORDER BY $want." . $orderby; if ($exclude) // array of pagenames - $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND $want.pagename NOT IN " . $this->_sql_set($exclude); else - $exclude=''; + $exclude = ''; $qpagename = $dbh->qstr($pagename); // removed ref to FETCH_MODE in next line @@ -778,14 +797,14 @@ extends WikiDB_backend //. " GROUP BY $want.id" . $exclude . $orderby; -/* - echo "SELECT linkee.id AS id, linkee.pagename AS pagename, related.pagename as linkrelation FROM link, page linkee, page linker JOIN page related ON (link.relation=related.id) WHERE linkfrom=linker.id AND linkto=linkee.id AND linker.pagename='SanDiego'" | mysql phpwiki -id pagename linkrelation -2268 California located_in -*/ + /* + echo "SELECT linkee.id AS id, linkee.pagename AS pagename, related.pagename as linkrelation FROM link, page linkee, page linker JOIN page related ON (link.relation=related.id) WHERE linkfrom=linker.id AND linkto=linkee.id AND linker.pagename='SanDiego'" | mysql phpwiki + id pagename linkrelation + 2268 California located_in + */ if ($limit) { // extract from,count from limit - list($offset,$count) = $this->limit($limit); + list($offset, $count) = $this->limit($limit); $result = $dbh->SelectLimit($sql, $count, $offset); } else { $result = $dbh->Execute($sql); @@ -799,7 +818,8 @@ id pagename linkrelation /** * Find if a page links to another page */ - function exists_link($pagename, $link, $reversed=false) { + function exists_link($pagename, $link, $reversed = false) + { $dbh = &$this->_dbh; extract($this->_table_names); @@ -810,27 +830,28 @@ id pagename linkrelation $qpagename = $dbh->qstr($pagename); $qlink = $dbh->qstr($link); $row = $dbh->GetRow("SELECT CASE WHEN $want.pagename=$qlink THEN 1 ELSE 0 END" - . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl" - . " WHERE linkfrom=linker.id AND linkto=linkee.id" - . " AND $have.pagename=$qpagename" - . " AND $want.pagename=$qlink"); + . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl" + . " WHERE linkfrom=linker.id AND linkto=linkee.id" + . " AND $have.pagename=$qpagename" + . " AND $want.pagename=$qlink"); return $row[0]; } /* * */ - function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') { + function get_all_pages($include_empty = false, $sortby = '', $limit = '', $exclude = '') + { $dbh = &$this->_dbh; extract($this->_table_names); $orderby = $this->sortby($sortby, 'db'); if ($orderby) $orderby = ' ORDER BY ' . $orderby; $and = ''; - if ($exclude) {// array of pagenames + if ($exclude) { // array of pagenames $and = ' AND '; - $exclude = " $page_tbl.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " $page_tbl.pagename NOT IN " . $this->_sql_set($exclude); } else { - $exclude=''; + $exclude = ''; } //$dbh->SetFetchMode(ADODB_FETCH_ASSOC); @@ -838,13 +859,12 @@ id pagename linkrelation if ($include_empty) { $sql = "SELECT " . $this->page_tbl_fields - ." FROM $page_tbl, $recent_tbl, $version_tbl" + . " FROM $page_tbl, $recent_tbl, $version_tbl" . " WHERE $page_tbl.id=$recent_tbl.id" . " AND $page_tbl.id=$version_tbl.id AND latestversion=version" . " $and$exclude" . $orderby; - } - else { + } else { $sql = "SELECT " . $this->page_tbl_fields . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl" @@ -872,7 +892,7 @@ id pagename linkrelation } if ($limit) { // extract from,count from limit - list($offset,$count) = $this->limit($limit); + list($offset, $count) = $this->limit($limit); $result = $dbh->SelectLimit($sql, $count, $offset); } else { $result = $dbh->Execute($sql); @@ -884,8 +904,8 @@ id pagename linkrelation /** * Title and fulltext search. */ - function text_search($search, $fullsearch=false, - $sortby='', $limit='', $exclude='') + function text_search($search, $fullsearch = false, + $sortby = '', $limit = '', $exclude = '') { $dbh = &$this->_dbh; extract($this->_table_names); @@ -907,7 +927,7 @@ id pagename linkrelation $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields; $field_list = array_merge($field_list, array('pagedata'), - $this->version_tbl_field_list); + $this->version_tbl_field_list); $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause"); } else { $callback = new WikiMethodCb($searchobj, "_pagename_match_clause"); @@ -920,7 +940,7 @@ id pagename linkrelation . $orderby; if ($limit) { // extract from,count from limit - list($offset,$count) = $this->limit($limit); + list($offset, $count) = $this->limit($limit); $result = $dbh->SelectLimit($sql, $count, $offset); } else { $result = $dbh->Execute($sql); @@ -937,22 +957,24 @@ id pagename linkrelation * This is only for already resolved wildcards: * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2')); */ - function _sql_set(&$pagenames) { + function _sql_set(&$pagenames) + { $s = '('; foreach ($pagenames as $p) { - $s .= ($this->_dbh->qstr($p).","); + $s .= ($this->_dbh->qstr($p) . ","); } - return substr($s,0,-1).")"; + return substr($s, 0, -1) . ")"; } /** * Find highest or lowest hit counts. */ - function most_popular($limit=20, $sortby='-hits') { + function most_popular($limit = 20, $sortby = '-hits') + { $dbh = &$this->_dbh; extract($this->_table_names); $order = "DESC"; - if ($limit < 0){ + if ($limit < 0) { $order = "ASC"; $limit = -$limit; $where = ""; @@ -960,7 +982,7 @@ id pagename linkrelation $where = " AND hits > 0"; } if ($sortby != '-hits') { - if ($order = $this->sortby($sortby, 'db')) $orderby = " ORDER BY " . $order; + if ($order = $this->sortby($sortby, 'db')) $orderby = " ORDER BY " . $order; else $orderby = ""; } else $orderby = " ORDER BY hits $order"; @@ -972,7 +994,7 @@ id pagename linkrelation . $orderby; if ($limit) { // extract from,count from limit - list($offset,$count) = $this->limit($limit); + list($offset, $count) = $this->limit($limit); $result = $dbh->SelectLimit($sql, $count, $offset); } else { $result = $dbh->Execute($sql); @@ -983,7 +1005,8 @@ id pagename linkrelation /** * Find recent changes. */ - function most_recent($params) { + function most_recent($params) + { $limit = 0; $since = 0; $include_minor_revisions = false; @@ -1006,13 +1029,11 @@ id pagename linkrelation if ($exclude_major_revisions) { // Include only minor revisions $pick[] = "minor_edit <> 0"; - } - elseif (!$include_minor_revisions) { + } elseif (!$include_minor_revisions) { // Include only major revisions $pick[] = "minor_edit = 0"; } - } - else { + } else { $table = "$page_tbl, $recent_tbl"; $join_clause = "$page_tbl.id=$recent_tbl.id"; $table .= ", $version_tbl"; @@ -1021,18 +1042,16 @@ id pagename linkrelation if ($exclude_major_revisions) { // Include only most recent minor revision $pick[] = 'version=latestminor'; - } - elseif (!$include_minor_revisions) { + } elseif (!$include_minor_revisions) { // Include only most recent major revision $pick[] = 'version=latestmajor'; - } - else { + } else { // Include only the latest revision (whether major or minor). - $pick[] ='version=latestversion'; + $pick[] = 'version=latestversion'; } } $order = "DESC"; - if($limit < 0){ + if ($limit < 0) { $order = "ASC"; $limit = -$limit; } @@ -1047,7 +1066,7 @@ id pagename linkrelation // FIXME: use SQL_BUFFER_RESULT for mysql? if ($limit) { // extract from,count from limit - list($offset,$count) = $this->limit($limit); + list($offset, $count) = $this->limit($limit); $result = $dbh->SelectLimit($sql, $count, $offset); } else { $result = $dbh->Execute($sql); @@ -1060,16 +1079,17 @@ id pagename linkrelation /** * Find referenced empty pages. */ - function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') { + function wanted_pages($exclude_from = '', $exclude = '', $sortby = '', $limit = '') + { $dbh = &$this->_dbh; extract($this->_table_names); - if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom'))) + if ($orderby = $this->sortby($sortby, 'db', array('pagename', 'wantedfrom'))) $orderby = 'ORDER BY ' . $orderby; if ($exclude_from) // array of pagenames - $exclude_from = " AND pp.pagename NOT IN ".$this->_sql_set($exclude_from); + $exclude_from = " AND pp.pagename NOT IN " . $this->_sql_set($exclude_from); if ($exclude) // array of pagenames - $exclude = " AND p.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND p.pagename NOT IN " . $this->_sql_set($exclude); /* all empty pages, independent of linkstatus: @@ -1081,32 +1101,33 @@ id pagename linkrelation */ $sql = "SELECT p.pagename, pp.pagename as wantedfrom" . " FROM $page_tbl p, $link_tbl linked" - . " LEFT JOIN $page_tbl pp ON (linked.linkto = pp.id)" - . " LEFT JOIN $nonempty_tbl ne ON (linked.linkto = ne.id)" + . " LEFT JOIN $page_tbl pp ON (linked.linkto = pp.id)" + . " LEFT JOIN $nonempty_tbl ne ON (linked.linkto = ne.id)" . " WHERE ne.id is NULL" - . " AND (p.id = linked.linkfrom)" + . " AND (p.id = linked.linkfrom)" . $exclude_from . $exclude . $orderby; if ($limit) { // extract from,count from limit - list($offset,$count) = $this->limit($limit); + list($offset, $count) = $this->limit($limit); $result = $dbh->SelectLimit($sql, $count, $offset); } else { $result = $dbh->Execute($sql); } - return new WikiDB_backend_ADODB_iter($this, $result, array('pagename','wantedfrom')); + return new WikiDB_backend_ADODB_iter($this, $result, array('pagename', 'wantedfrom')); } /** * Rename page in the database. */ - function rename_page($pagename, $to) { + function rename_page($pagename, $to) + { $dbh = &$this->_dbh; extract($this->_table_names); - $this->lock(array('page','version','recent','nonempty','link')); - if ( ($id = $this->_get_pageid($pagename, false)) ) { + $this->lock(array('page', 'version', 'recent', 'nonempty', 'link')); + if (($id = $this->_get_pageid($pagename, false))) { if ($new = $this->_get_pageid($to, false)) { // Cludge Alert! // This page does not exist (already verified before), but exists in the page table. @@ -1120,13 +1141,14 @@ id pagename linkrelation $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new"); } $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id", - $dbh->qstr($to))); + $dbh->qstr($to))); } $this->unlock(array('page')); return $id; } - function _update_recent_table($pageid = false) { + function _update_recent_table($pageid = false) + { $dbh = &$this->_dbh; extract($this->_table_names); extract($this->_expressions); @@ -1135,28 +1157,29 @@ id pagename linkrelation // optimize: mysql can do this with one REPLACE INTO. $backend_type = $this->backendType(); - if (substr($backend_type,0,5) == 'mysql') { + if (substr($backend_type, 0, 5) == 'mysql') { $dbh->Execute("REPLACE INTO $recent_tbl" - . " (id, latestversion, latestmajor, latestminor)" - . " SELECT id, $maxversion, $maxmajor, $maxminor" - . " FROM $version_tbl" - . ( $pageid ? " WHERE id=$pageid" : "") - . " GROUP BY id" ); + . " (id, latestversion, latestmajor, latestminor)" + . " SELECT id, $maxversion, $maxmajor, $maxminor" + . " FROM $version_tbl" + . ($pageid ? " WHERE id=$pageid" : "") + . " GROUP BY id"); } else { $this->lock(array('recent')); $dbh->Execute("DELETE FROM $recent_tbl" - . ( $pageid ? " WHERE id=$pageid" : "")); - $dbh->Execute( "INSERT INTO $recent_tbl" - . " (id, latestversion, latestmajor, latestminor)" - . " SELECT id, $maxversion, $maxmajor, $maxminor" - . " FROM $version_tbl" - . ( $pageid ? " WHERE id=$pageid" : "") - . " GROUP BY id" ); + . ($pageid ? " WHERE id=$pageid" : "")); + $dbh->Execute("INSERT INTO $recent_tbl" + . " (id, latestversion, latestmajor, latestminor)" + . " SELECT id, $maxversion, $maxmajor, $maxminor" + . " FROM $version_tbl" + . ($pageid ? " WHERE id=$pageid" : "") + . " GROUP BY id"); $this->unlock(array('recent')); } } - function _update_nonempty_table($pageid = false) { + function _update_nonempty_table($pageid = false) + { $dbh = &$this->_dbh; extract($this->_table_names); extract($this->_expressions); @@ -1166,16 +1189,16 @@ id pagename linkrelation extract($this->_expressions); $this->lock(array('nonempty')); $dbh->Execute("DELETE FROM $nonempty_tbl" - . ( $pageid ? " WHERE id=$pageid" : "")); + . ($pageid ? " WHERE id=$pageid" : "")); $dbh->Execute("INSERT INTO $nonempty_tbl (id)" - . " SELECT $recent_tbl.id" - . " FROM $recent_tbl, $version_tbl" - . " WHERE $recent_tbl.id=$version_tbl.id" - . " AND version=latestversion" - // We have some specifics here (Oracle) - //. " AND content<>''" - . " AND content $notempty" // On Oracle not just "<>''" - . ( $pageid ? " AND $recent_tbl.id=$pageid" : "")); + . " SELECT $recent_tbl.id" + . " FROM $recent_tbl, $version_tbl" + . " WHERE $recent_tbl.id=$version_tbl.id" + . " AND version=latestversion" + // We have some specifics here (Oracle) + //. " AND content<>''" + . " AND content $notempty" // On Oracle not just "<>''" + . ($pageid ? " AND $recent_tbl.id=$pageid" : "")); $this->unlock(array('nonempty')); } @@ -1187,8 +1210,9 @@ id pagename linkrelation * * @access protected */ - function lock($tables, $write_lock = true) { - $this->_dbh->StartTrans(); + function lock($tables, $write_lock = true) + { + $this->_dbh->StartTrans(); if ($this->_lock_count++ == 0) { $this->_current_lock = $tables; $this->_lock_tables($tables, $write_lock); @@ -1198,7 +1222,8 @@ id pagename linkrelation /** * Overridden by non-transaction safe backends. */ - function _lock_tables($tables, $write_lock) { + function _lock_tables($tables, $write_lock) + { return $this->_current_lock; } @@ -1212,7 +1237,8 @@ id pagename linkrelation * * @see _lock_database */ - function unlock($tables = false, $force = false) { + function unlock($tables = false, $force = false) + { if ($this->_lock_count == 0) { $this->_current_lock = false; return; @@ -1222,20 +1248,22 @@ id pagename linkrelation $this->_current_lock = false; $this->_lock_count = 0; } - $this->_dbh->CompleteTrans(! $force); + $this->_dbh->CompleteTrans(!$force); } /** * overridden by non-transaction safe backends */ - function _unlock_tables($tables, $write_lock=false) { + function _unlock_tables($tables, $write_lock = false) + { return; } /** * Serialize data */ - function _serialize($data) { + function _serialize($data) + { if (empty($data)) return ''; assert(is_array($data)); @@ -1245,37 +1273,47 @@ id pagename linkrelation /** * Unserialize data */ - function _unserialize($data) { + function _unserialize($data) + { return empty($data) ? array() : unserialize($data); } /* some variables and functions for DB backend abstraction (action=upgrade) */ - function database () { + function database() + { return $this->_dbh->database; } - function backendType() { + + function backendType() + { return $this->_dbh->databaseType; } - function connection() { + + function connection() + { return $this->_dbh->_connectionID; } - function getRow($query) { + + function getRow($query) + { return $this->_dbh->getRow($query); } - function listOfTables() { + function listOfTables() + { return $this->_dbh->MetaTables(); } // other database needs another connection and other privileges. - function listOfFields($database, $table) { + function listOfFields($database, $table) + { $field_list = array(); $old_db = $this->database(); if ($database != $old_db) { $conn = $this->_dbh->Connect($this->_parsedDSN['hostspec'], - DBADMIN_USER ? DBADMIN_USER : $this->_parsedDSN['username'], - DBADMIN_PASSWD ? DBADMIN_PASSWD : $this->_parsedDSN['password'], - $database); + DBADMIN_USER ? DBADMIN_USER : $this->_parsedDSN['username'], + DBADMIN_PASSWD ? DBADMIN_PASSWD : $this->_parsedDSN['password'], + $database); } foreach ($this->_dbh->MetaColumns($table, false) as $field) { $field_list[] = $field->name; @@ -1283,19 +1321,22 @@ id pagename linkrelation if ($database != $old_db) { $this->_dbh->close(); $conn = $this->_dbh->Connect($this->_parsedDSN['hostspec'], - $this->_parsedDSN['username'], - $this->_parsedDSN['password'], - $old_db); + $this->_parsedDSN['username'], + $this->_parsedDSN['password'], + $old_db); } return $field_list; } -}; +} + +; class WikiDB_backend_ADODB_generic_iter -extends WikiDB_backend_iterator + extends WikiDB_backend_iterator { - function WikiDB_backend_ADODB_generic_iter($backend, $query_result, $field_list = NULL) { + function WikiDB_backend_ADODB_generic_iter($backend, $query_result, $field_list = NULL) + { $this->_backend = &$backend; $this->_result = $query_result; @@ -1304,7 +1345,7 @@ extends WikiDB_backend_iterator // WikiLens is using the iterator behind the scene $field_list = array(); $fields = $query_result->FieldCount(); - for ($i = 0; $i < $fields ; $i++) { + for ($i = 0; $i < $fields; $i++) { $field_info = $query_result->FetchField($i); array_push($field_list, $field_info->name); } @@ -1313,7 +1354,8 @@ extends WikiDB_backend_iterator $this->_fields = $field_list; } - function count() { + function count() + { if (!$this->_result) { return false; } @@ -1322,7 +1364,8 @@ extends WikiDB_backend_iterator return $count; } - function next() { + function next() + { $result = &$this->_result; $backend = &$this->_backend; if (!$result || $result->EOF) { @@ -1342,19 +1385,23 @@ extends WikiDB_backend_iterator return $rec_assoc; } - function reset () { + function reset() + { if ($this->_result) { $this->_result->MoveFirst(); } } - function asArray () { + + function asArray() + { $result = array(); while ($page = $this->next()) $result[] = $page; return $result; } - function free () { + function free() + { if ($this->_result) { /* call mysql_free_result($this->_queryID) */ $this->_result->Close(); @@ -1364,9 +1411,10 @@ extends WikiDB_backend_iterator } class WikiDB_backend_ADODB_iter -extends WikiDB_backend_ADODB_generic_iter + extends WikiDB_backend_ADODB_generic_iter { - function next() { + function next() + { $result = &$this->_result; $backend = &$this->_backend; if (!$result || $result->EOF) { @@ -1403,162 +1451,162 @@ class WikiDB_backend_ADODB_search extends WikiDB_backend_search_sql // Following function taken from Pear::DB (prev. from adodb-pear.inc.php). // Eventually, change index.php to provide the relevant information // directly? - /** - * Parse a data source name. - * - * Additional keys can be added by appending a URI query string to the - * end of the DSN. - * - * The format of the supplied DSN is in its fullest form: - * - * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true - * - * - * Most variations are allowed: - * - * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644 - * phptype://username:password@hostspec/database_name - * phptype://username:password@hostspec - * phptype://username@hostspec - * phptype://hostspec/database - * phptype://hostspec - * phptype(dbsyntax) - * phptype - * - * - * @param string $dsn Data Source Name to be parsed - * - * @return array an associative array with the following keys: - * + phptype: Database backend used in PHP (mysql, odbc etc.) - * + dbsyntax: Database used with regards to SQL syntax etc. - * + protocol: Communication protocol to use (tcp, unix etc.) - * + hostspec: Host specification (hostname[:port]) - * + database: Database to use on the DBMS server - * + username: User name for login - * + password: Password for login - * - * @author Tomas V.V.Cox - */ - function parseDSN($dsn) - { - $parsed = array( - 'phptype' => false, - 'dbsyntax' => false, - 'username' => false, - 'password' => false, - 'protocol' => false, - 'hostspec' => false, - 'port' => false, - 'socket' => false, - 'database' => false, - ); - - if (is_array($dsn)) { - $dsn = array_merge($parsed, $dsn); - if (!$dsn['dbsyntax']) { - $dsn['dbsyntax'] = $dsn['phptype']; - } - return $dsn; +/** + * Parse a data source name. + * + * Additional keys can be added by appending a URI query string to the + * end of the DSN. + * + * The format of the supplied DSN is in its fullest form: + * + * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true + * + * + * Most variations are allowed: + * + * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644 + * phptype://username:password@hostspec/database_name + * phptype://username:password@hostspec + * phptype://username@hostspec + * phptype://hostspec/database + * phptype://hostspec + * phptype(dbsyntax) + * phptype + * + * + * @param string $dsn Data Source Name to be parsed + * + * @return array an associative array with the following keys: + * + phptype: Database backend used in PHP (mysql, odbc etc.) + * + dbsyntax: Database used with regards to SQL syntax etc. + * + protocol: Communication protocol to use (tcp, unix etc.) + * + hostspec: Host specification (hostname[:port]) + * + database: Database to use on the DBMS server + * + username: User name for login + * + password: Password for login + * + * @author Tomas V.V.Cox + */ +function parseDSN($dsn) +{ + $parsed = array( + 'phptype' => false, + 'dbsyntax' => false, + 'username' => false, + 'password' => false, + 'protocol' => false, + 'hostspec' => false, + 'port' => false, + 'socket' => false, + 'database' => false, + ); + + if (is_array($dsn)) { + $dsn = array_merge($parsed, $dsn); + if (!$dsn['dbsyntax']) { + $dsn['dbsyntax'] = $dsn['phptype']; } + return $dsn; + } - // Find phptype and dbsyntax - if (($pos = strpos($dsn, '://')) !== false) { - $str = substr($dsn, 0, $pos); - $dsn = substr($dsn, $pos + 3); - } else { - $str = $dsn; - $dsn = null; - } + // Find phptype and dbsyntax + if (($pos = strpos($dsn, '://')) !== false) { + $str = substr($dsn, 0, $pos); + $dsn = substr($dsn, $pos + 3); + } else { + $str = $dsn; + $dsn = null; + } - // Get phptype and dbsyntax - // $str => phptype(dbsyntax) - if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) { - $parsed['phptype'] = $arr[1]; - $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2]; - } else { - $parsed['phptype'] = $str; - $parsed['dbsyntax'] = $str; - } + // Get phptype and dbsyntax + // $str => phptype(dbsyntax) + if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) { + $parsed['phptype'] = $arr[1]; + $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2]; + } else { + $parsed['phptype'] = $str; + $parsed['dbsyntax'] = $str; + } - if (!count($dsn)) { - return $parsed; - } + if (!count($dsn)) { + return $parsed; + } - // Get (if found): username and password - // $dsn => username:password@protocol+hostspec/database - if (($at = strrpos($dsn,'@')) !== false) { - $str = substr($dsn, 0, $at); - $dsn = substr($dsn, $at + 1); - if (($pos = strpos($str, ':')) !== false) { - $parsed['username'] = rawurldecode(substr($str, 0, $pos)); - $parsed['password'] = rawurldecode(substr($str, $pos + 1)); - } else { - $parsed['username'] = rawurldecode($str); - } + // Get (if found): username and password + // $dsn => username:password@protocol+hostspec/database + if (($at = strrpos($dsn, '@')) !== false) { + $str = substr($dsn, 0, $at); + $dsn = substr($dsn, $at + 1); + if (($pos = strpos($str, ':')) !== false) { + $parsed['username'] = rawurldecode(substr($str, 0, $pos)); + $parsed['password'] = rawurldecode(substr($str, $pos + 1)); + } else { + $parsed['username'] = rawurldecode($str); } + } - // Find protocol and hostspec + // Find protocol and hostspec - // $dsn => proto(proto_opts)/database - if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) { - $proto = $match[1]; - $proto_opts = $match[2] ? $match[2] : false; - $dsn = $match[3]; + // $dsn => proto(proto_opts)/database + if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) { + $proto = $match[1]; + $proto_opts = $match[2] ? $match[2] : false; + $dsn = $match[3]; // $dsn => protocol+hostspec/database (old format) + } else { + if (strpos($dsn, '+') !== false) { + list($proto, $dsn) = explode('+', $dsn, 2); + } + if (strpos($dsn, '/') !== false) { + list($proto_opts, $dsn) = explode('/', $dsn, 2); } else { - if (strpos($dsn, '+') !== false) { - list($proto, $dsn) = explode('+', $dsn, 2); - } - if (strpos($dsn, '/') !== false) { - list($proto_opts, $dsn) = explode('/', $dsn, 2); - } else { - $proto_opts = $dsn; - $dsn = null; - } + $proto_opts = $dsn; + $dsn = null; } + } - // process the different protocol options - $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp'; - $proto_opts = rawurldecode($proto_opts); - if ($parsed['protocol'] == 'tcp') { - if (strpos($proto_opts, ':') !== false) { - list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts); - } else { - $parsed['hostspec'] = $proto_opts; - } - } elseif ($parsed['protocol'] == 'unix') { - $parsed['socket'] = $proto_opts; + // process the different protocol options + $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp'; + $proto_opts = rawurldecode($proto_opts); + if ($parsed['protocol'] == 'tcp') { + if (strpos($proto_opts, ':') !== false) { + list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts); + } else { + $parsed['hostspec'] = $proto_opts; } + } elseif ($parsed['protocol'] == 'unix') { + $parsed['socket'] = $proto_opts; + } - // Get dabase if any - // $dsn => database - if ($dsn) { - // /database - if (($pos = strpos($dsn, '?')) === false) { - $parsed['database'] = $dsn; + // Get dabase if any + // $dsn => database + if ($dsn) { + // /database + if (($pos = strpos($dsn, '?')) === false) { + $parsed['database'] = $dsn; // /database?param1=value1¶m2=value2 - } else { - $parsed['database'] = substr($dsn, 0, $pos); - $dsn = substr($dsn, $pos + 1); - if (strpos($dsn, '&') !== false) { - $opts = explode('&', $dsn); - } else { // database?param1=value1 - $opts = array($dsn); - } - foreach ($opts as $opt) { - list($key, $value) = explode('=', $opt); - if (!isset($parsed[$key])) { - // don't allow params overwrite - $parsed[$key] = rawurldecode($value); - } + } else { + $parsed['database'] = substr($dsn, 0, $pos); + $dsn = substr($dsn, $pos + 1); + if (strpos($dsn, '&') !== false) { + $opts = explode('&', $dsn); + } else { // database?param1=value1 + $opts = array($dsn); + } + foreach ($opts as $opt) { + list($key, $value) = explode('=', $opt); + if (!isset($parsed[$key])) { + // don't allow params overwrite + $parsed[$key] = rawurldecode($value); } } } - - return $parsed; } + return $parsed; +} + // Local Variables: // mode: php // tab-width: 8 diff --git a/lib/WikiDB/backend/ADODB_mssql.php b/lib/WikiDB/backend/ADODB_mssql.php index 3706aa316..499b5ba58 100644 --- a/lib/WikiDB/backend/ADODB_mssql.php +++ b/lib/WikiDB/backend/ADODB_mssql.php @@ -7,14 +7,15 @@ require_once 'lib/WikiDB/backend/ADODB.php'; class WikiDB_backend_ADODB_mssql -extends WikiDB_backend_ADODB + extends WikiDB_backend_ADODB { /** * Constructor. */ - function WikiDB_backend_ADODB_mssql($dbparams) { + function WikiDB_backend_ADODB_mssql($dbparams) + { // Lowercase Assoc arrays - define('ADODB_ASSOC_CASE',0); + define('ADODB_ASSOC_CASE', 0); // Backend constructor $this->WikiDB_backend_ADODB($dbparams); @@ -30,7 +31,8 @@ extends WikiDB_backend_ADODB /** * Pack tables. */ - function optimize() { + function optimize() + { // Do nothing here -- Leave that for the DB // Cost Based Optimizer tuning vary from version to version return 1; @@ -43,11 +45,12 @@ extends WikiDB_backend_ADODB * understand phpWiki locking ;-) * */ - function _lock_tables($tables, $write_lock = true) { + function _lock_tables($tables, $write_lock = true) + { if (!$tables) return; $dbh = &$this->_dbh; - if($write_lock) { + if ($write_lock) { // Next line is default behaviour, so just skip it // $dbh->Execute("SET TRANSACTION READ WRITE"); foreach ($tables as $table) { @@ -65,31 +68,35 @@ extends WikiDB_backend_ADODB /** * Release the locks. */ - function _unlock_tables($tables) { + function _unlock_tables($tables) + { $dbh = &$this->_dbh; $dbh->Execute("COMMIT WORK"); } // Search callabcks // Page name - function _sql_match_clause($word) { + function _sql_match_clause($word) + { $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); $word = $this->_dbh->qstr("%$word%"); return "LOWER(pagename) LIKE $word"; } // Fulltext -- case sensitive :-\ - function _fullsearch_sql_match_clause($word) { + function _fullsearch_sql_match_clause($word) + { $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); $wordq = $this->_dbh->qstr("%$word%"); return "LOWER(pagename) LIKE $wordq " - . "OR CHARINDEX(content, '$word') > 0"; + . "OR CHARINDEX(content, '$word') > 0"; } /** * Serialize data */ - function _serialize($data) { + function _serialize($data) + { if (empty($data)) return ''; assert(is_array($data)); @@ -99,11 +106,14 @@ extends WikiDB_backend_ADODB /** * Unserialize data */ - function _unserialize($data) { + function _unserialize($data) + { return empty($data) ? array() : unserialize(stripslashes($data)); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/backend/ADODB_mssqlnative.php b/lib/WikiDB/backend/ADODB_mssqlnative.php index 9410b6539..0e8463c68 100644 --- a/lib/WikiDB/backend/ADODB_mssqlnative.php +++ b/lib/WikiDB/backend/ADODB_mssqlnative.php @@ -6,14 +6,15 @@ require_once 'lib/WikiDB/backend/ADODB.php'; class WikiDB_backend_ADODB_mssqlnative -extends WikiDB_backend_ADODB + extends WikiDB_backend_ADODB { /** * Constructor. */ - function WikiDB_backend_ADODB_mssqlnative($dbparams) { + function WikiDB_backend_ADODB_mssqlnative($dbparams) + { // Lowercase Assoc arrays - define('ADODB_ASSOC_CASE',0); + define('ADODB_ASSOC_CASE', 0); // Backend constructor $this->WikiDB_backend_ADODB($dbparams); @@ -30,7 +31,8 @@ extends WikiDB_backend_ADODB /** * Pack tables. */ - function optimize() { + function optimize() + { // Do nothing here -- Leave that for the DB // Cost Based Optimizer tuning vary from version to version return 1; @@ -38,24 +40,27 @@ extends WikiDB_backend_ADODB // Search callabcks // Page name - function _sql_match_clause($word) { + function _sql_match_clause($word) + { $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); $word = $this->_dbh->qstr("%$word%"); return "LOWER(pagename) LIKE $word"; } // Fulltext -- case sensitive :-\ - function _fullsearch_sql_match_clause($word) { + function _fullsearch_sql_match_clause($word) + { $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); $wordq = $this->_dbh->qstr("%$word%"); return "LOWER(pagename) LIKE $wordq " - . "OR CHARINDEX(content, '$word') > 0"; + . "OR CHARINDEX(content, '$word') > 0"; } /** * Serialize data */ - function _serialize($data) { + function _serialize($data) + { if (empty($data)) return ''; assert(is_array($data)); @@ -65,7 +70,8 @@ extends WikiDB_backend_ADODB /** * Unserialize data */ - function _unserialize($data) { + function _unserialize($data) + { return empty($data) ? array() : unserialize(stripslashes($data)); } @@ -73,7 +79,8 @@ extends WikiDB_backend_ADODB * Update link table. * on DEBUG: delete old, deleted links from page */ - function set_links($pagename, $links) { + function set_links($pagename, $links) + { // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE. $dbh = &$this->_dbh; @@ -83,8 +90,8 @@ extends WikiDB_backend_ADODB $pageid = $this->_get_pageid($pagename, true); $oldlinks = $dbh->getAssoc("SELECT $link_tbl.linkto as id, page.pagename FROM $link_tbl" - ." JOIN page ON ($link_tbl.linkto = page.id)" - ." WHERE linkfrom=$pageid"); + . " JOIN page ON ($link_tbl.linkto = page.id)" + . " WHERE linkfrom=$pageid"); // Delete current links, $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid"); // and insert new links. Faster than checking for all single links @@ -109,10 +116,10 @@ extends WikiDB_backend_ADODB assert($linkid); if ($relation) { $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto, relation)" - . " VALUES ($pageid, $linkid, $relation)"); + . " VALUES ($pageid, $linkid, $relation)"); } else { $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)" - . " VALUES ($pageid, $linkid)"); + . " VALUES ($pageid, $linkid)"); } if ($oldlinks and array_key_exists($linkid, $oldlinks)) { // This was also in the previous page @@ -126,19 +133,19 @@ extends WikiDB_backend_ADODB // trigger_error("purge page table: delete all non-referenced pages...", E_USER_NOTICE); foreach ($oldlinks as $id => $name) { // ...check if the page is empty and has no version - if($id != '') { + if ($id != '') { $result = $dbh->getRow("SELECT $page_tbl.id FROM $page_tbl" - . " LEFT JOIN $nonempty_tbl ON ($nonempty_tbl.id = $page_tbl.id)"//'"id" is not a recognized table hints option' - . " LEFT JOIN $version_tbl ON ($version_tbl.id = $page_tbl.id)"//'"id" is not a recognized table hints option' - . " WHERE $nonempty_tbl.id is NULL" - . " AND $version_tbl.id is NULL" - . " AND $page_tbl.id=$id"); + . " LEFT JOIN $nonempty_tbl ON ($nonempty_tbl.id = $page_tbl.id)" //'"id" is not a recognized table hints option' + . " LEFT JOIN $version_tbl ON ($version_tbl.id = $page_tbl.id)" //'"id" is not a recognized table hints option' + . " WHERE $nonempty_tbl.id is NULL" + . " AND $version_tbl.id is NULL" + . " AND $page_tbl.id=$id"); $linkto = $dbh->getRow("SELECT linkfrom FROM $link_tbl WHERE linkto=$id"); if ($result and empty($linkto)) { trigger_error("delete empty and non-referenced link $name ($id)", E_USER_NOTICE); $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id"); // may fail $dbh->Execute("DELETE FROM $link_tbl WHERE linkto=$id"); - $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link + $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link } } } @@ -150,7 +157,8 @@ extends WikiDB_backend_ADODB /* get all oldlinks in hash => id, relation check for all new links */ - function set_links1($pagename, $links) { + function set_links1($pagename, $links) + { $dbh = &$this->_dbh; extract($this->_table_names); @@ -159,9 +167,9 @@ extends WikiDB_backend_ADODB $pageid = $this->_get_pageid($pagename, true); $oldlinks = $dbh->getAssoc("SELECT $link_tbl.linkto as linkto, $link_tbl.relation, page.pagename" - ." FROM $link_tbl" - ." JOIN page ON ($link_tbl.linkto = page.id)" - ." WHERE linkfrom=$pageid"); + . " FROM $link_tbl" + . " JOIN page ON ($link_tbl.linkto = page.id)" + . " WHERE linkfrom=$pageid"); /* old new * X => [1,0 2,0 1,1] X => [1,1 3,0] * => delete 1,0 2,0 + insert 3,0 @@ -192,15 +200,15 @@ extends WikiDB_backend_ADODB } } } - if (! $skip ) { + if (!$skip) { if ($update) { } if ($relation) { $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto, relation)" - . " VALUES ($pageid, $linkid, $relation)"); + . " VALUES ($pageid, $linkid, $relation)"); } else { $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)" - . " VALUES ($pageid, $linkid)"); + . " VALUES ($pageid, $linkid)"); } } @@ -216,16 +224,16 @@ extends WikiDB_backend_ADODB // trigger_error("purge page table: delete all non-referenced pages...", E_USER_NOTICE); foreach ($oldlinks as $id => $name) { // ...check if the page is empty and has no version - if($id != '') { + if ($id != '') { if ($dbh->getRow("SELECT $page_tbl.id FROM $page_tbl" - . " LEFT JOIN $nonempty_tbl ON ($nonempty_tbl.id = $page_tbl.id)"//'"id" is not a recognized table hints option' - . " LEFT JOIN $version_tbl ON ($version_tbl.id = $page_tbl.id)"//'"id" is not a recognized table hints option' - . " WHERE $nonempty_tbl.id is NULL" - . " AND $version_tbl.id is NULL" - . " AND $page_tbl.id=$id")) - { + . " LEFT JOIN $nonempty_tbl ON ($nonempty_tbl.id = $page_tbl.id)" //'"id" is not a recognized table hints option' + . " LEFT JOIN $version_tbl ON ($version_tbl.id = $page_tbl.id)" //'"id" is not a recognized table hints option' + . " WHERE $nonempty_tbl.id is NULL" + . " AND $version_tbl.id is NULL" + . " AND $page_tbl.id=$id") + ) { trigger_error("delete empty and non-referenced link $name ($id)", E_USER_NOTICE); - $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link + $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id"); // may fail } } @@ -235,7 +243,9 @@ extends WikiDB_backend_ADODB return true; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/backend/ADODB_mysql.php b/lib/WikiDB/backend/ADODB_mysql.php index bd525d1b2..4825406c5 100644 --- a/lib/WikiDB/backend/ADODB_mysql.php +++ b/lib/WikiDB/backend/ADODB_mysql.php @@ -15,8 +15,8 @@ require_once 'lib/WikiDB/backend/ADODB.php'; * * See also http://use.perl.org/~Smylers/journal/34246 for strict mode and warnings. */ -define('DO_APP_LOCK',true); -define('DO_FULL_LOCK',false); +define('DO_APP_LOCK', true); +define('DO_FULL_LOCK', false); /** * WikiDB layer for ADODB-mysql, called by lib/WikiDB/ADODB.php. @@ -27,18 +27,19 @@ define('DO_FULL_LOCK',false); * @author: Lawrence Akka, Reini Urban */ class WikiDB_backend_ADODB_mysql -extends WikiDB_backend_ADODB + extends WikiDB_backend_ADODB { /** * Constructor. */ - function WikiDB_backend_ADODB_mysql($dbparams) { + function WikiDB_backend_ADODB_mysql($dbparams) + { $this->WikiDB_backend_ADODB($dbparams); if (!$this->_dbh->_connectionID) return; $this->_serverinfo = $this->_dbh->ServerInfo(); if (!empty($this->_serverinfo['version'])) { - $arr = explode('.',$this->_serverinfo['version']); + $arr = explode('.', $this->_serverinfo['version']); $this->_serverinfo['version'] = (string)(($arr[0] * 100) + $arr[1]) . "." . (integer)$arr[2]; } if ($this->_serverinfo['version'] < 323.0) { @@ -51,11 +52,11 @@ extends WikiDB_backend_ADODB if ($this->_serverinfo['version'] > 401.0) { global $charset; $aliases = array('iso-8859-1' => 'latin1', - 'utf-8' => 'utf8'); + 'utf-8' => 'utf8'); //http://dev.mysql.com/doc/mysql/en/charset-connection.html if (isset($aliases[strtolower($charset)])) { // mysql needs special unusual names and doesn't resolve aliases - mysql_query("SET NAMES '". $aliases[$charset] . "'"); + mysql_query("SET NAMES '" . $aliases[$charset] . "'"); } else { mysql_query("SET NAMES '$charset'"); } @@ -65,25 +66,27 @@ extends WikiDB_backend_ADODB /** * Kill timed out processes. ( so far only called on about every 50-th save. ) */ - function _timeout() { + function _timeout() + { if (empty($this->_dbparams['timeout'])) return; - $result = mysql_query("SHOW processlist"); - while ($row = mysql_fetch_array($result)) { - if ($row["db"] == $this->_dsn['database'] - and $row["User"] == $this->_dsn['username'] - and $row["Time"] > $this->_dbparams['timeout'] - and $row["Command"] == "Sleep") - { + $result = mysql_query("SHOW processlist"); + while ($row = mysql_fetch_array($result)) { + if ($row["db"] == $this->_dsn['database'] + and $row["User"] == $this->_dsn['username'] + and $row["Time"] > $this->_dbparams['timeout'] + and $row["Command"] == "Sleep" + ) { $process_id = $row["Id"]; mysql_query("KILL $process_id"); + } } } - } /** * Pack tables. */ - function optimize() { + function optimize() + { $dbh = &$this->_dbh; $this->_timeout(); foreach ($this->_table_names as $table) { @@ -100,14 +103,15 @@ extends WikiDB_backend_ADODB * New: which tables as params, * support nested locks via app locks */ - function _lock_tables($tables, $write_lock = true) { + function _lock_tables($tables, $write_lock = true) + { if (!$tables) return; if (DO_APP_LOCK) { - $lock = join('-',$tables); + $lock = join('-', $tables); $result = $this->_dbh->GetRow("SELECT GET_LOCK('$lock',10)"); if (!$result or $result[0] == 0) { - trigger_error( "WARNING: Couldn't obtain application lock " . $lock . "\n
      ", - E_USER_WARNING); + trigger_error("WARNING: Couldn't obtain application lock " . $lock . "\n
      ", + E_USER_WARNING); return; } } @@ -125,13 +129,14 @@ extends WikiDB_backend_ADODB * Release the locks. * Support nested locks */ - function _unlock_tables($tables) { + function _unlock_tables($tables) + { if (!$tables) { $this->_dbh->Execute("UNLOCK TABLES"); return; } if (DO_APP_LOCK) { - $lock = join('-',$tables); + $lock = join('-', $tables); $result = $this->_dbh->Execute("SELECT RELEASE_LOCK('$lock')"); } if (DO_FULL_LOCK) { @@ -140,7 +145,8 @@ extends WikiDB_backend_ADODB } } - function increaseHitCount($pagename) { + function increaseHitCount($pagename) + { $dbh = &$this->_dbh; // Hits is the only thing we can update in a fast manner. // Note that this will fail silently if the page does not @@ -148,14 +154,15 @@ extends WikiDB_backend_ADODB // hit count, who cares? // LIMIT since 3.23 $dbh->Execute(sprintf("UPDATE LOW_PRIORITY %s SET hits=hits+1 WHERE pagename=%s %s", - $this->_table_names['page_tbl'], - $dbh->qstr($pagename), - ($this->_serverinfo['version'] >= 323.0) ? "LIMIT 1": "") - ); + $this->_table_names['page_tbl'], + $dbh->qstr($pagename), + ($this->_serverinfo['version'] >= 323.0) ? "LIMIT 1" : "") + ); return; } - function _get_pageid($pagename, $create_if_missing = false) { + function _get_pageid($pagename, $create_if_missing = false) + { // check id_cache global $request; @@ -166,25 +173,25 @@ extends WikiDB_backend_ADODB } } - // attributes play this game. + // attributes play this game. if ($pagename === '') return 0; $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s", - $dbh->qstr($pagename)); - if (! $create_if_missing ) { + $dbh->qstr($pagename)); + if (!$create_if_missing) { $row = $dbh->GetRow($query); return $row ? $row[0] : false; } $row = $dbh->GetRow($query); - if (! $row ) { - // have auto-incrementing, atomic version - $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl" + if (!$row) { + // have auto-incrementing, atomic version + $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl" . " (id,pagename)" . " VALUES(NULL,%s)", - $dbh->qstr($pagename))); - $id = $dbh->_insertid(); + $dbh->qstr($pagename))); + $id = $dbh->_insertid(); } else { $id = $row[0]; } @@ -195,41 +202,44 @@ extends WikiDB_backend_ADODB /** * Create a new revision of a page. */ - function set_versiondata($pagename, $version, $data) { + function set_versiondata($pagename, $version, $data) + { $dbh = &$this->_dbh; $version_tbl = $this->_table_names['version_tbl']; - $minor_edit = (int) !empty($data['is_minor_edit']); + $minor_edit = (int)!empty($data['is_minor_edit']); unset($data['is_minor_edit']); $mtime = (int)$data['mtime']; unset($data['mtime']); assert(!empty($mtime)); - @$content = (string) $data['%content']; + @$content = (string)$data['%content']; unset($data['%content']); unset($data['%pagedata']); - $this->lock(array('page','recent','version','nonempty')); - $dbh->BeginTrans( ); + $this->lock(array('page', 'recent', 'version', 'nonempty')); + $dbh->BeginTrans(); $dbh->CommitLock($version_tbl); $id = $this->_get_pageid($pagename, true); $backend_type = $this->backendType(); // optimize: mysql can do this with one REPLACE INTO. - $rs = $dbh->Execute(sprintf("REPLACE INTO $version_tbl" - . " (id,version,mtime,minor_edit,content,versiondata)" - . " VALUES(%d,%d,%d,%d,%s,%s)", - $id, $version, $mtime, $minor_edit, - $dbh->qstr($content), - $dbh->qstr($this->_serialize($data)))); + $rs = $dbh->Execute(sprintf("REPLACE INTO $version_tbl" + . " (id,version,mtime,minor_edit,content,versiondata)" + . " VALUES(%d,%d,%d,%d,%s,%s)", + $id, $version, $mtime, $minor_edit, + $dbh->qstr($content), + $dbh->qstr($this->_serialize($data)))); $this->_update_recent_table($id); $this->_update_nonempty_table($id); - if ($rs) $dbh->CommitTrans( ); - else $dbh->RollbackTrans( ); - $this->unlock(array('page','recent','version','nonempty')); + if ($rs) $dbh->CommitTrans(); + else $dbh->RollbackTrans(); + $this->unlock(array('page', 'recent', 'version', 'nonempty')); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/backend/ADODB_oci8po.php b/lib/WikiDB/backend/ADODB_oci8po.php index 6d56d1f80..0581e5971 100644 --- a/lib/WikiDB/backend/ADODB_oci8po.php +++ b/lib/WikiDB/backend/ADODB_oci8po.php @@ -8,16 +8,17 @@ require_once 'lib/WikiDB/backend/ADODB.php'; class WikiDB_backend_ADODB_oci8po -extends WikiDB_backend_ADODB + extends WikiDB_backend_ADODB { var $_prefix; /** * Constructor. */ - function WikiDB_backend_ADODB_oci8po($dbparams) { + function WikiDB_backend_ADODB_oci8po($dbparams) + { // Lowercase Assoc arrays - define('ADODB_ASSOC_CASE',0); + define('ADODB_ASSOC_CASE', 0); // Backend constructor $this->WikiDB_backend_ADODB($dbparams); @@ -33,7 +34,8 @@ extends WikiDB_backend_ADODB /** * Pack tables. */ - function optimize() { + function optimize() + { // Do nothing here -- Leave that for the DBA // Cost Based Optimizer tuning vary from version to version return 1; @@ -46,11 +48,12 @@ extends WikiDB_backend_ADODB * understand phpWiki locking ;-) * */ - function _lock_tables($tables, $write_lock = true) { - if (!$tables) return; + function _lock_tables($tables, $write_lock = true) + { + if (!$tables) return; $dbh = &$this->_dbh; - if($write_lock) { + if ($write_lock) { // Next line is default behaviour, so just skip it // $dbh->Execute("SET TRANSACTION READ WRITE"); foreach ($tables as $table) { @@ -68,7 +71,8 @@ extends WikiDB_backend_ADODB /** * Release the locks. */ - function _unlock_tables($tables) { + function _unlock_tables($tables) + { $dbh = &$this->_dbh; $dbh->Execute("COMMIT WORK"); } @@ -99,7 +103,8 @@ extends WikiDB_backend_ADODB /** * Serialize data */ - function _serialize($data) { + function _serialize($data) + { if (empty($data)) return ''; assert(is_array($data)); @@ -109,59 +114,64 @@ extends WikiDB_backend_ADODB /** * Unserialize data */ - function _unserialize($data) { + function _unserialize($data) + { if (empty($data)) return array(); $d = $this->_dbh->BlobDecode($data); - if(! is_string($d)) { - print_r($d); + if (!is_string($d)) { + print_r($d); } return unserialize($this->_dbh->BlobDecode($data)); } - function write_accesslog(&$entry) { + function write_accesslog(&$entry) + { global $request; $dbh = &$this->_dbh; $log_tbl = $entry->_accesslog->logtable; $dbh->query("INSERT INTO $log_tbl" - . " (time_stamp,remote_host,remote_user,request_method,request_line,request_uri," - . "request_args,request_time,status,bytes_sent,referer,agent,request_duration)" - . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", - array( - // Problem: date formats are backend specific. Either use unixtime as %d (long), - // or the native timestamp format. - date('d-M-Y H:i:s', $entry->time), - $entry->host, - $entry->user, - $entry->request_method, - $entry->request, - $entry->request_uri, - $entry->request_args, - $entry->_ncsa_time($entry->time), - $entry->status, - $entry->size, - $entry->referer, - $entry->user_agent, - $entry->duration)); + . " (time_stamp,remote_host,remote_user,request_method,request_line,request_uri," + . "request_args,request_time,status,bytes_sent,referer,agent,request_duration)" + . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", + array( + // Problem: date formats are backend specific. Either use unixtime as %d (long), + // or the native timestamp format. + date('d-M-Y H:i:s', $entry->time), + $entry->host, + $entry->user, + $entry->request_method, + $entry->request, + $entry->request_uri, + $entry->request_args, + $entry->_ncsa_time($entry->time), + $entry->status, + $entry->size, + $entry->referer, + $entry->user_agent, + $entry->duration)); } -}; +} + +; class WikiDB_backend_ADODB_oci8_search -extends WikiDB_backend_ADODB_search + extends WikiDB_backend_ADODB_search { // If we want case insensitive search, one need to create a Context // Index on the CLOB. While it is very efficient, it requires the // Intermedia Text option, so let's stick to the 'simple' thing // Note that this does only an exact fulltext search, not using MATCH or LIKE. - function _fulltext_match_clause($node) { + function _fulltext_match_clause($node) + { if ($this->isStoplisted($node)) return "1=1"; $page = $node->sql(); $exactword = $node->_sql_quote($node->word); return ($this->_case_exact - ? "pagename LIKE '$page' OR DBMS_LOB.INSTR(content, '$exactword') > 0" - : "LOWER(pagename) LIKE '$page' OR DBMS_LOB.INSTR(content, '$exactword') > 0"); + ? "pagename LIKE '$page' OR DBMS_LOB.INSTR(content, '$exactword') > 0" + : "LOWER(pagename) LIKE '$page' OR DBMS_LOB.INSTR(content, '$exactword') > 0"); } } diff --git a/lib/WikiDB/backend/ADODB_postgres7.php b/lib/WikiDB/backend/ADODB_postgres7.php index 350a1a083..f9059312e 100644 --- a/lib/WikiDB/backend/ADODB_postgres7.php +++ b/lib/WikiDB/backend/ADODB_postgres7.php @@ -2,9 +2,9 @@ require_once 'lib/WikiDB/backend/ADODB.php'; -if (!defined("USE_BYTEA")) // see schemas/psql-initialize.sql +if (!defined("USE_BYTEA")) // see schemas/psql-initialize.sql define("USE_BYTEA", true); // only BYTEA is binary safe - //define("USE_BYTEA", false); +//define("USE_BYTEA", false); /** * WikiDB layer for ADODB-postgres (7 or 8), called by lib/WikiDB/ADODB.php. @@ -15,21 +15,22 @@ if (!defined("USE_BYTEA")) // see schemas/psql-initialize.sql * @author: Reini Urban */ class WikiDB_backend_ADODB_postgres7 -extends WikiDB_backend_ADODB + extends WikiDB_backend_ADODB { /** * Constructor. */ - function WikiDB_backend_ADODB_postgres7($dbparams) { + function WikiDB_backend_ADODB_postgres7($dbparams) + { $this->WikiDB_backend_ADODB($dbparams); if (!$this->_dbh->_connectionID) return; $this->_serverinfo = $this->_dbh->ServerInfo(); if (!empty($this->_serverinfo['version'])) { - $arr = explode('.',$this->_serverinfo['version']); + $arr = explode('.', $this->_serverinfo['version']); $this->_serverinfo['version'] = (string)(($arr[0] * 100) + $arr[1]); - if (!empty($arr[2])) - $this->_serverinfo['version'] .= ("." . (integer)$arr[2]); + if (!empty($arr[2])) + $this->_serverinfo['version'] .= ("." . (integer)$arr[2]); } } @@ -37,8 +38,9 @@ extends WikiDB_backend_ADODB * Pack tables. * NOTE: Only the table owner can do this. Either fix the schema or setup autovacuum. */ - function optimize() { - return 0; // if the wikiuser is not the table owner + function optimize() + { + return 0; // if the wikiuser is not the table owner foreach ($this->_table_names as $table) { $this->_dbh->Execute("VACUUM ANALYZE $table"); @@ -47,49 +49,53 @@ extends WikiDB_backend_ADODB } // just for blobs. the rest is escaped with qstr() - function _quote($s) { - if (USE_BYTEA) - return $this->_dbh->BlobEncode($s); + function _quote($s) + { + if (USE_BYTEA) + return $this->_dbh->BlobEncode($s); return base64_encode($s); } // just for blobs, which might be base64_encoded - function _unquote($s) { - if (USE_BYTEA) { - //if function_exists('pg_unescape_bytea') - //return pg_unescape_bytea($s); - // TODO: already unescaped by ADORecordSet_postgres64::_decode? - return $s; - } + function _unquote($s) + { + if (USE_BYTEA) { + //if function_exists('pg_unescape_bytea') + //return pg_unescape_bytea($s); + // TODO: already unescaped by ADORecordSet_postgres64::_decode? + return $s; + } return base64_decode($s); } - function get_cached_html($pagename) { + function get_cached_html($pagename) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; - $data = $dbh->GetOne(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename=%s", - $dbh->qstr($pagename))); + $data = $dbh->GetOne(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename=%s", + $dbh->qstr($pagename))); if ($data) return $this->_unquote($data); else return ''; } - function set_cached_html($pagename, $data) { + function set_cached_html($pagename, $data) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; - if (USE_BYTEA) { - $dbh->UpdateBlob($page_tbl,'cached_html',$data,"pagename=".$dbh->qstr($pagename)); - /* - $dbh->Execute(sprintf("UPDATE $page_tbl" - . " SET cached_html='%s'" - . " WHERE pagename=%s", - $this->_quote($data), - $dbh->qstr($pagename))); - */ - } else { - $dbh->Execute("UPDATE $page_tbl" - . " SET cached_html=?" - . " WHERE pagename=?", - array($this->_quote($data), $pagename)); + if (USE_BYTEA) { + $dbh->UpdateBlob($page_tbl, 'cached_html', $data, "pagename=" . $dbh->qstr($pagename)); + /* + $dbh->Execute(sprintf("UPDATE $page_tbl" + . " SET cached_html='%s'" + . " WHERE pagename=%s", + $this->_quote($data), + $dbh->qstr($pagename))); + */ + } else { + $dbh->Execute("UPDATE $page_tbl" + . " SET cached_html=?" + . " WHERE pagename=?", + array($this->_quote($data), $pagename)); } } @@ -97,7 +103,8 @@ extends WikiDB_backend_ADODB * Lock all tables we might use. * postgresql has proper transactions so we dont need table locks. */ - function _lock_tables($tables, $write_lock = true) { + function _lock_tables($tables, $write_lock = true) + { ; } @@ -105,14 +112,16 @@ extends WikiDB_backend_ADODB * Unlock all tables. * postgresql has proper transactions so we dont need table locks. */ - function _unlock_tables($tables, $write_lock=false) { + function _unlock_tables($tables, $write_lock = false) + { ; } /** * Serialize data */ - function _serialize($data) { + function _serialize($data) + { if (empty($data)) return ''; assert(is_array($data)); @@ -122,31 +131,35 @@ extends WikiDB_backend_ADODB /** * Unserialize data */ - function _unserialize($data) { + function _unserialize($data) + { if (empty($data)) return array(); // Base64 encoded data does not contain colons. // (only alphanumerics and '+' and '/'.) - if (substr($data,0,2) == 'a:') + if (substr($data, 0, 2) == 'a:') return unserialize($data); return unserialize($this->_unquote($data)); } -}; +} + +; class WikiDB_backend_ADODB_postgres7_search -extends WikiDB_backend_ADODB_search + extends WikiDB_backend_ADODB_search { - function _pagename_match_clause($node) { + function _pagename_match_clause($node) + { $word = $node->sql(); if ($node->op == 'REGEX') { // posix regex extensions return ($this->_case_exact - ? "pagename ~* '$word'" - : "pagename ~ '$word'"); + ? "pagename ~* '$word'" + : "pagename ~ '$word'"); } else { return ($this->_case_exact - ? "pagename LIKE '$word'" - : "pagename ILIKE '$word'"); + ? "pagename LIKE '$word'" + : "pagename ILIKE '$word'"); } } diff --git a/lib/WikiDB/backend/ADODB_sqlite.php b/lib/WikiDB/backend/ADODB_sqlite.php index f0f9aa4e3..1758ebbbc 100644 --- a/lib/WikiDB/backend/ADODB_sqlite.php +++ b/lib/WikiDB/backend/ADODB_sqlite.php @@ -9,14 +9,15 @@ require_once 'lib/WikiDB/backend/ADODB.php'; * @author: Reini Urban */ class WikiDB_backend_ADODB_sqlite -extends WikiDB_backend_ADODB + extends WikiDB_backend_ADODB { /** * Constructor. */ - function WikiDB_backend_ADODB_sqlite($dbparams) { + function WikiDB_backend_ADODB_sqlite($dbparams) + { $parsed = parseDSN($dbparams['dsn']); - if (! file_exists($parsed['database'])) { + if (!file_exists($parsed['database'])) { // creating the empty database $db = $parsed['database']; $schema = FindFile("schemas/sqlite-initialize.sql"); @@ -26,34 +27,37 @@ extends WikiDB_backend_ADODB $this->WikiDB_backend_ADODB($dbparams); } - function _get_pageid($pagename, $create_if_missing = false) { + function _get_pageid($pagename, $create_if_missing = false) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s", - $dbh->qstr($pagename)); - if (! $create_if_missing ) { + $dbh->qstr($pagename)); + if (!$create_if_missing) { $row = $dbh->GetRow($query); return $row ? $row[0] : false; } - // attributes play this game. + // attributes play this game. if ($pagename === '') return 0; $row = $dbh->GetRow($query); - if (! $row ) { + if (!$row) { // atomic version // TODO: we have auto-increment since sqlite-2.3.4 // http://www.sqlite.org/faq.html#q1 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl" - . " (id,pagename)" - . " VALUES((SELECT max(id) FROM $page_tbl)+1, %s)", - $dbh->qstr($pagename))); + . " (id,pagename)" + . " VALUES((SELECT max(id) FROM $page_tbl)+1, %s)", + $dbh->qstr($pagename))); $id = $dbh->_insertid(); } else { $id = $row[0]; } return $id; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/backend/PDO.php b/lib/WikiDB/backend/PDO.php index 0add51bea..196e0d030 100644 --- a/lib/WikiDB/backend/PDO.php +++ b/lib/WikiDB/backend/PDO.php @@ -27,10 +27,11 @@ require_once 'lib/WikiDB/backend.php'; class WikiDB_backend_PDO -extends WikiDB_backend + extends WikiDB_backend { - function WikiDB_backend_PDO ($dbparams) { + function WikiDB_backend_PDO($dbparams) + { $this->_dbparams = $dbparams; if (strstr($dbparams['dsn'], "://")) { // pear DB syntax $parsed = parseDSN($dbparams['dsn']); @@ -48,9 +49,9 @@ extends WikiDB_backend $dbparams['dsn'] = $driver . ":"; $this->_dbh->database = $parsed['database']; // mysql needs to map database=>dbname, hostspec=>host. TODO for the others. - $dsnmap = array('mysql' => array('database'=>'dbname', 'hostspec' => 'host') - ); - foreach (array('protocol','hostspec','port','socket','database') as $option) { + $dsnmap = array('mysql' => array('database' => 'dbname', 'hostspec' => 'host') + ); + foreach (array('protocol', 'hostspec', 'port', 'socket', 'database') as $option) { if (!empty($parsed[$option])) { $optionname = (isset($dsnmap[$driver][$option]) and !isset($parsed[$optionname])) ? $dsnmap[$driver][$option] @@ -85,22 +86,21 @@ extends WikiDB_backend if (!loadPhpExtension("pdo_$driver")) { echo $GLOBALS['php_errormsg'], "
      \n"; trigger_error(sprintf("dl() problem: Required extension '%s' could not be loaded!", - "pdo_$driver"), - E_USER_WARNING); + "pdo_$driver"), + E_USER_WARNING); } // persistent is defined as DSN option, or with a config value. // phptype://username:password@hostspec/database?persistent=false $this->_dbh = new PDO($dbparams['dsn'], - $this->_parsedDSN['username'], - $this->_parsedDSN['password'], - array(PDO_ATTR_AUTOCOMMIT => true, - PDO_ATTR_TIMEOUT => DATABASE_TIMEOUT, - PDO_ATTR_PERSISTENT => !empty($parsed['persistent']) - or DATABASE_PERSISTENT - )); - } - catch (PDOException $e) { + $this->_parsedDSN['username'], + $this->_parsedDSN['password'], + array(PDO_ATTR_AUTOCOMMIT => true, + PDO_ATTR_TIMEOUT => DATABASE_TIMEOUT, + PDO_ATTR_PERSISTENT => !empty($parsed['persistent']) + or DATABASE_PERSISTENT + )); + } catch (PDOException $e) { echo "
      \nCan't connect to database: %s" . $e->getMessage(); if (DEBUG & _DEBUG_VERBOSE or DEBUG & _DEBUG_SQL) { echo "
      \nDSN: '", $dbparams['dsn'], "'"; @@ -109,7 +109,7 @@ extends WikiDB_backend } if (isset($dbparams['_tryroot_from_upgrade'])) trigger_error(sprintf("Can't connect to database: %s", $e->getMessage()), - E_USER_WARNING); + E_USER_WARNING); else exit(); } @@ -124,8 +124,7 @@ extends WikiDB_backend $this->_hasTransactions = true; try { $this->_dbh->beginTransaction(); - } - catch (PDOException $e) { + } catch (PDOException $e) { $this->_hasTransactions = false; } $sth = $this->_dbh->prepare("SELECT version()"); @@ -135,11 +134,11 @@ extends WikiDB_backend $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : ''; $this->_table_names - = array('page_tbl' => $prefix . 'page', - 'version_tbl' => $prefix . 'version', - 'link_tbl' => $prefix . 'link', - 'recent_tbl' => $prefix . 'recent', - 'nonempty_tbl' => $prefix . 'nonempty'); + = array('page_tbl' => $prefix . 'page', + 'version_tbl' => $prefix . 'version', + 'link_tbl' => $prefix . 'link', + 'recent_tbl' => $prefix . 'recent', + 'nonempty_tbl' => $prefix . 'nonempty'); $page_tbl = $this->_table_names['page_tbl']; $version_tbl = $this->_table_names['version_tbl']; $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, " @@ -153,33 +152,42 @@ extends WikiDB_backend 'versiondata'); $this->_expressions - = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)", - 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)", - 'maxversion' => "MAX(version)", - 'notempty' => "<>''", - 'iscontent' => "$version_tbl.content<>''"); + = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)", + 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)", + 'maxversion' => "MAX(version)", + 'notempty' => "<>''", + 'iscontent' => "$version_tbl.content<>''"); $this->_lock_count = 0; } - function beginTransaction() { + function beginTransaction() + { if ($this->_hasTransactions) $this->_dbh->beginTransaction(); } - function commit() { + + function commit() + { if ($this->_hasTransactions) $this->_dbh->commit(); } - function rollback() { + + function rollback() + { if ($this->_hasTransactions) $this->_dbh->rollback(); } + /* no result */ - function query($sql) { + function query($sql) + { $sth = $this->_dbh->prepare($sql); return $sth->execute(); } + /* with one result row */ - function getRow($sql) { + function getRow($sql) + { $sth = $this->_dbh->prepare($sql); if ($sth->execute()) return $sth->fetch(PDO_FETCH_BOTH); @@ -190,13 +198,14 @@ extends WikiDB_backend /** * Close database connection. */ - function close () { + function close() + { if (!$this->_dbh) return; if ($this->_lock_count) { trigger_error("WARNING: database still locked " . - '(lock_count = $this->_lock_count)' . "\n
      ", - E_USER_WARNING); + '(lock_count = $this->_lock_count)' . "\n
      ", + E_USER_WARNING); } $this->unlock(false, 'force'); @@ -206,13 +215,14 @@ extends WikiDB_backend /* * Fast test for wikipage. */ - function is_wiki_page($pagename) { + function is_wiki_page($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); $sth = $dbh->prepare("SELECT $page_tbl.id AS id" - . " FROM $nonempty_tbl, $page_tbl" - . " WHERE $nonempty_tbl.id=$page_tbl.id" - . " AND pagename=?"); + . " FROM $nonempty_tbl, $page_tbl" + . " WHERE $nonempty_tbl.id=$page_tbl.id" + . " AND pagename=?"); $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100); if ($sth->execute()) return $sth->fetchSingle(); @@ -220,31 +230,34 @@ extends WikiDB_backend return false; } - function get_all_pagenames() { + function get_all_pagenames() + { $dbh = &$this->_dbh; extract($this->_table_names); $sth = $dbh->exec("SELECT pagename" - . " FROM $nonempty_tbl, $page_tbl" - . " WHERE $nonempty_tbl.id=$page_tbl.id" - . " LIMIT 1"); + . " FROM $nonempty_tbl, $page_tbl" + . " WHERE $nonempty_tbl.id=$page_tbl.id" + . " LIMIT 1"); return $sth->fetchAll(PDO_FETCH_NUM); } - function numPages($filter=false, $exclude='') { + function numPages($filter = false, $exclude = '') + { $dbh = &$this->_dbh; extract($this->_table_names); $sth = $dbh->exec("SELECT count(*)" - . " FROM $nonempty_tbl, $page_tbl" - . " WHERE $nonempty_tbl.id=$page_tbl.id"); + . " FROM $nonempty_tbl, $page_tbl" + . " WHERE $nonempty_tbl.id=$page_tbl.id"); return $sth->fetchSingle(); } - function increaseHitCount($pagename) { + function increaseHitCount($pagename) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; $sth = $dbh->prepare("UPDATE $page_tbl SET hits=hits+1" - . " WHERE pagename=?" - . " LIMIT 1"); + . " WHERE pagename=?" + . " LIMIT 1"); $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100); $sth->execute(); } @@ -252,25 +265,28 @@ extends WikiDB_backend /** * Read page information from database. */ - function get_pagedata($pagename) { + function get_pagedata($pagename) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; $sth = $dbh->prepare("SELECT id,pagename,hits,pagedata FROM $page_tbl" - ." WHERE pagename=? LIMIT 1"); + . " WHERE pagename=? LIMIT 1"); $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100); $sth->execute(); $row = $sth->fetch(PDO_FETCH_NUM); return $row ? $this->_extract_page_data($row[3], $row[2]) : false; } - function _extract_page_data($data, $hits) { + function _extract_page_data($data, $hits) + { if (empty($data)) return array('hits' => $hits); else return array_merge(array('hits' => $hits), $this->_unserialize($data)); } - function update_pagedata($pagename, $newdata) { + function update_pagedata($pagename, $newdata) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; @@ -304,9 +320,9 @@ extends WikiDB_backend $data[$key] = $val; } $sth = $dbh->prepare("UPDATE $page_tbl" - . " SET hits=?, pagedata=?" - . " WHERE pagename=?" - . " LIMIT 1"); + . " SET hits=?, pagedata=?" + . " WHERE pagename=?" + . " LIMIT 1"); $sth->bindParam(1, $hits, PDO_PARAM_INT); $sth->bindParam(2, $this->_serialize($data), PDO_PARAM_LOB); $sth->bindParam(3, $pagename, PDO_PARAM_STR, 100); @@ -319,7 +335,8 @@ extends WikiDB_backend } } - function get_cached_html($pagename) { + function get_cached_html($pagename) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; $sth = $dbh->prepare("SELECT cached_html FROM $page_tbl WHERE pagename=? LIMIT 1"); @@ -328,20 +345,22 @@ extends WikiDB_backend return $sth->fetchSingle(PDO_FETCH_NUM); } - function set_cached_html($pagename, $data) { + function set_cached_html($pagename, $data) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; if (empty($data)) $data = ''; $sth = $dbh->prepare("UPDATE $page_tbl" - . " SET cached_html=?" - . " WHERE pagename=?" - . " LIMIT 1"); + . " SET cached_html=?" + . " WHERE pagename=?" + . " LIMIT 1"); $sth->bindParam(1, $data, PDO_PARAM_STR); $sth->bindParam(2, $pagename, PDO_PARAM_STR, 100); $sth->execute(); } - function _get_pageid($pagename, $create_if_missing = false) { + function _get_pageid($pagename, $create_if_missing = false) + { // check id_cache global $request; $cache =& $request->_dbi->_cache->_id_cache; @@ -351,7 +370,7 @@ extends WikiDB_backend } } - // attributes play this game. + // attributes play this game. if ($pagename === '') return 0; $dbh = &$this->_dbh; @@ -359,16 +378,16 @@ extends WikiDB_backend $sth = $dbh->prepare("SELECT id FROM $page_tbl WHERE pagename=? LIMIT 1"); $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100); $id = $sth->fetchSingle(); - if (! $create_if_missing ) { + if (!$create_if_missing) { return $id; } - if (! $id ) { + if (!$id) { //mysql, mysqli or mysqlt - if (substr($dbh->databaseType,0,5) == 'mysql') { + if (substr($dbh->databaseType, 0, 5) == 'mysql') { // have auto-incrementing, atomic version $sth = $dbh->prepare("INSERT INTO $page_tbl" - . " (id,pagename)" - . " VALUES (NULL,?)"); + . " (id,pagename)" + . " VALUES (NULL,?)"); $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100); $sth->execute(); $id = $dbh->lastInsertId(); @@ -378,8 +397,8 @@ extends WikiDB_backend $sth->execute(); $id = $sth->fetchSingle(); $sth = $dbh->prepare("INSERT INTO $page_tbl" - . " (id,pagename,hits)" - . " VALUES (?,?,0)"); + . " (id,pagename,hits)" + . " VALUES (?,?,0)"); $id++; $sth->bindParam(1, $id, PDO_PARAM_INT); $sth->bindParam(2, $pagename, PDO_PARAM_STR, 100); @@ -393,29 +412,31 @@ extends WikiDB_backend return $id; } - function get_latest_version($pagename) { + function get_latest_version($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); $sth = $dbh->prepare("SELECT latestversion" - . " FROM $page_tbl, $recent_tbl" - . " WHERE $page_tbl.id=$recent_tbl.id" - . " AND pagename=?" - . " LIMIT 1"); + . " FROM $page_tbl, $recent_tbl" + . " WHERE $page_tbl.id=$recent_tbl.id" + . " AND pagename=?" + . " LIMIT 1"); $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100); $sth->execute(); return $sth->fetchSingle(); } - function get_previous_version($pagename, $version) { + function get_previous_version($pagename, $version) + { $dbh = &$this->_dbh; extract($this->_table_names); $sth = $dbh->prepare("SELECT version" - . " FROM $version_tbl, $page_tbl" - . " WHERE $version_tbl.id=$page_tbl.id" - . " AND pagename=?" - . " AND version < ?" - . " ORDER BY version DESC" - . " LIMIT 1"); + . " FROM $version_tbl, $page_tbl" + . " WHERE $version_tbl.id=$page_tbl.id" + . " AND pagename=?" + . " AND version < ?" + . " ORDER BY version DESC" + . " LIMIT 1"); $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100); $sth->bindParam(2, $version, PDO_PARAM_INT); $sth->execute(); @@ -430,7 +451,8 @@ extends WikiDB_backend * @return hash The version data, or false if specified version does not * exist. */ - function get_versiondata($pagename, $version, $want_content = false) { + function get_versiondata($pagename, $version, $want_content = false) + { $dbh = &$this->_dbh; extract($this->_table_names); extract($this->_expressions); @@ -449,11 +471,11 @@ extends WikiDB_backend . "$version_tbl.versiondata as versiondata"; } $sth = $dbh->prepare("SELECT $fields" - . " FROM $page_tbl, $version_tbl" - . " WHERE $page_tbl.id=$version_tbl.id" - . " AND pagename=?" - . " AND version=?" - . " LIMIT 1"); + . " FROM $page_tbl, $version_tbl" + . " WHERE $page_tbl.id=$version_tbl.id" + . " AND pagename=?" + . " AND version=?" + . " LIMIT 1"); $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100); $sth->bindParam(2, $version, PDO_PARAM_INT); $sth->execute(); @@ -461,14 +483,15 @@ extends WikiDB_backend return $row ? $this->_extract_version_data_num($row, $want_content) : false; } - function _extract_version_data_num($row, $want_content) { + function _extract_version_data_num($row, $want_content) + { if (!$row) return false; //$id &= $row[0]; //$pagename &= $row[1]; $data = empty($row[8]) ? array() : $this->_unserialize($row[8]); - $data['mtime'] = $row[5]; + $data['mtime'] = $row[5]; $data['is_minor_edit'] = !empty($row[6]); if ($want_content) { $data['%content'] = $row[7]; @@ -481,7 +504,8 @@ extends WikiDB_backend return $data; } - function _extract_version_data_assoc($row) { + function _extract_version_data_assoc($row) + { if (!$row) return false; @@ -492,8 +516,7 @@ extends WikiDB_backend if (isset($content)) $data['%content'] = $content; elseif ($have_content) - $data['%content'] = true; - else + $data['%content'] = true; else $data['%content'] = ''; if (!empty($pagedata)) { $data['%pagedata'] = $this->_extract_page_data($pagedata, $hits); @@ -504,30 +527,31 @@ extends WikiDB_backend /** * Create a new revision of a page. */ - function set_versiondata($pagename, $version, $data) { + function set_versiondata($pagename, $version, $data) + { $dbh = &$this->_dbh; $version_tbl = $this->_table_names['version_tbl']; - $minor_edit = (int) !empty($data['is_minor_edit']); + $minor_edit = (int)!empty($data['is_minor_edit']); unset($data['is_minor_edit']); $mtime = (int)$data['mtime']; unset($data['mtime']); assert(!empty($mtime)); - @$content = (string) $data['%content']; + @$content = (string)$data['%content']; unset($data['%content']); unset($data['%pagedata']); - $this->lock(array('page','recent','version','nonempty')); + $this->lock(array('page', 'recent', 'version', 'nonempty')); $this->beginTransaction(); $id = $this->_get_pageid($pagename, true); $backend_type = $this->backendType(); // optimize: mysql can do this with one REPLACE INTO. - if (substr($backend_type,0,5) == 'mysql') { + if (substr($backend_type, 0, 5) == 'mysql') { $sth = $dbh->prepare("REPLACE INTO $version_tbl" - . " (id,version,mtime,minor_edit,content,versiondata)" - . " VALUES(?,?,?,?,?,?)"); + . " (id,version,mtime,minor_edit,content,versiondata)" + . " VALUES(?,?,?,?,?,?)"); $sth->bindParam(1, $id, PDO_PARAM_INT); $sth->bindParam(2, $version, PDO_PARAM_INT); $sth->bindParam(3, $mtime, PDO_PARAM_INT); @@ -537,13 +561,13 @@ extends WikiDB_backend $rs = $sth->execute(); } else { $sth = $dbh->prepare("DELETE FROM $version_tbl" - . " WHERE id=? AND version=?"); + . " WHERE id=? AND version=?"); $sth->bindParam(1, $id, PDO_PARAM_INT); $sth->bindParam(2, $version, PDO_PARAM_INT); $sth->execute(); $sth = $dbh->prepare("INSERT INTO $version_tbl" - . " (id,version,mtime,minor_edit,content,versiondata)" - . " VALUES(?,?,?,?,?,?)"); + . " (id,version,mtime,minor_edit,content,versiondata)" + . " VALUES(?,?,?,?,?,?)"); $sth->bindParam(1, $id, PDO_PARAM_INT); $sth->bindParam(2, $version, PDO_PARAM_INT); $sth->bindParam(3, $mtime, PDO_PARAM_INT); @@ -554,22 +578,23 @@ extends WikiDB_backend } $this->_update_recent_table($id); $this->_update_nonempty_table($id); - if ($rs) $this->commit( ); - else $this->rollBack( ); - $this->unlock(array('page','recent','version','nonempty')); + if ($rs) $this->commit(); + else $this->rollBack(); + $this->unlock(array('page', 'recent', 'version', 'nonempty')); } /** * Delete an old revision of a page. */ - function delete_versiondata($pagename, $version) { + function delete_versiondata($pagename, $version) + { $dbh = &$this->_dbh; extract($this->_table_names); $this->lock(array('version')); - if ( ($id = $this->_get_pageid($pagename)) ) { + if (($id = $this->_get_pageid($pagename))) { $dbh->query("DELETE FROM $version_tbl" - . " WHERE id=$id AND version=$version"); + . " WHERE id=$id AND version=$version"); $this->_update_recent_table($id); // This shouldn't be needed (as long as the latestversion // never gets deleted.) But, let's be safe. @@ -587,29 +612,30 @@ extends WikiDB_backend * so that get_latest_version returns id+1 and get_previous_version returns prev id * and page->exists returns false. */ - function delete_page($pagename) { + function delete_page($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); $this->beginTransaction(); //$dbh->CommitLock($recent_tbl); if (($id = $this->_get_pageid($pagename, false)) === false) { - $this->rollback( ); + $this->rollback(); return false; } $mtime = time(); $user =& $GLOBALS['request']->_user; $meta = array('author' => $user->getId(), - 'author_id' => $user->getAuthenticatedId(), - 'mtime' => $mtime); - $this->lock(array('version','recent','nonempty','page','link')); + 'author_id' => $user->getAuthenticatedId(), + 'mtime' => $mtime); + $this->lock(array('version', 'recent', 'nonempty', 'page', 'link')); $version = $this->get_latest_version($pagename); if ($dbh->query("UPDATE $recent_tbl SET latestversion=latestversion+1," - . "latestmajor=latestversion+1,latestminor=NULL WHERE id=$id")) - { + . "latestmajor=latestversion+1,latestminor=NULL WHERE id=$id") + ) { $insert = $dbh->prepare("INSERT INTO $version_tbl" - . " (id,version,mtime,minor_edit,content,versiondata)" - . " VALUES(?,?,?,?,?,?)"); + . " (id,version,mtime,minor_edit,content,versiondata)" + . " VALUES(?,?,?,?,?,?)"); $insert->bindParam(1, $id, PDO_PARAM_INT); $insert->bindParam(2, $version + 1, PDO_PARAM_INT); $insert->bindParam(3, $mtime, PDO_PARAM_INT); @@ -618,28 +644,30 @@ extends WikiDB_backend $insert->bindParam(6, $this->_serialize($meta), PDO_PARAM_STR, 100); if ($insert->execute() and $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id") - and $this->set_links($pagename, false)) { - // need to keep perms and LOCKED, otherwise you can reset the perm - // by action=remove and re-create it with default perms - // keep hits but delete meta-data - //and $dbh->Execute("UPDATE $page_tbl SET pagedata='' WHERE id=$id") - $this->unlock(array('version','recent','nonempty','page','link')); + and $this->set_links($pagename, false) + ) { + // need to keep perms and LOCKED, otherwise you can reset the perm + // by action=remove and re-create it with default perms + // keep hits but delete meta-data + //and $dbh->Execute("UPDATE $page_tbl SET pagedata='' WHERE id=$id") + $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link')); $this->commit(); return true; } } else { - $this->unlock(array('version','recent','nonempty','page','link')); + $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link')); $this->rollBack(); return false; } } - function purge_page($pagename) { + function purge_page($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); - $this->lock(array('version','recent','nonempty','page','link')); - if ( ($id = $this->_get_pageid($pagename, false)) ) { + $this->lock(array('version', 'recent', 'nonempty', 'page', 'link')); + if (($id = $this->_get_pageid($pagename, false))) { $dbh->query("DELETE FROM $version_tbl WHERE id=$id"); $dbh->query("DELETE FROM $recent_tbl WHERE id=$id"); $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id"); @@ -651,15 +679,14 @@ extends WikiDB_backend // altogether. $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id"); $result = 0; - } - else { + } else { $dbh->query("DELETE FROM $page_tbl WHERE id=$id"); $result = 1; } } else { $result = -1; // already purged or not existing } - $this->unlock(array('version','recent','nonempty','page','link')); + $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link')); return $result; } @@ -669,7 +696,8 @@ extends WikiDB_backend //function update_versiondata($pagename, $version, $data) { //} - function set_links($pagename, $links) { + function set_links($pagename, $links) + { // Update link table. // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE. @@ -688,24 +716,24 @@ extends WikiDB_backend $linkid = $this->_get_pageid($link, true); assert($linkid); $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)" - . " VALUES ($pageid, $linkid)"); + . " VALUES ($pageid, $linkid)"); } } elseif (DEBUG) { // purge page table: delete all non-referenced pages // for all previously linked pages... - $sth = $dbh->prepare("SELECT $link_tbl.linkto as id FROM $link_tbl". - " WHERE linkfrom=$pageid"); + $sth = $dbh->prepare("SELECT $link_tbl.linkto as id FROM $link_tbl" . + " WHERE linkfrom=$pageid"); $sth->execute(); foreach ($sth->fetchAll(PDO_FETCH_NUM) as $id) { // ...check if the page is empty and has no version $sth1 = $dbh->prepare("SELECT $page_tbl.id FROM $page_tbl" - . " LEFT JOIN $nonempty_tbl USING (id) " - . " LEFT JOIN $version_tbl USING (id)" - . " WHERE ISNULL($nonempty_tbl.id) AND" - . " ISNULL($version_tbl.id) AND $page_tbl.id=$id"); + . " LEFT JOIN $nonempty_tbl USING (id) " + . " LEFT JOIN $version_tbl USING (id)" + . " WHERE ISNULL($nonempty_tbl.id) AND" + . " ISNULL($version_tbl.id) AND $page_tbl.id=$id"); $sth1->execute(); if ($sth1->fetchSingle()) { - $dbh->query("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link + $dbh->query("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link $dbh->query("DELETE FROM $recent_tbl WHERE id=$id"); // may fail } } @@ -722,34 +750,35 @@ extends WikiDB_backend * (linkExistingWikiWord or linkUnknownWikiWord) * This is called on every page header GleanDescription, so we can store all the existing links. */ - function get_links($pagename, $reversed=true, $include_empty=false, - $sortby='', $limit='', $exclude='') { + function get_links($pagename, $reversed = true, $include_empty = false, + $sortby = '', $limit = '', $exclude = '') + { $dbh = &$this->_dbh; extract($this->_table_names); if ($reversed) - list($have,$want) = array('linkee', 'linker'); + list($have, $want) = array('linkee', 'linker'); else - list($have,$want) = array('linker', 'linkee'); + list($have, $want) = array('linker', 'linkee'); $orderby = $this->sortby($sortby, 'db', array('pagename')); if ($orderby) $orderby = " ORDER BY $want." . $orderby; if ($exclude) // array of pagenames - $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND $want.pagename NOT IN " . $this->_sql_set($exclude); else - $exclude=''; + $exclude = ''; $limit = $this->_limit_sql($limit); $sth = $dbh->prepare("SELECT $want.id AS id, $want.pagename AS pagename," - . " $want.hits AS hits" - . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee" - . (!$include_empty ? ", $nonempty_tbl" : '') - . " WHERE linkfrom=linker.id AND linkto=linkee.id" - . " AND $have.pagename=?" - . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "") - //. " GROUP BY $want.id" - . $exclude - . $orderby - . $limit); + . " $want.hits AS hits" + . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee" + . (!$include_empty ? ", $nonempty_tbl" : '') + . " WHERE linkfrom=linker.id AND linkto=linkee.id" + . " AND $have.pagename=?" + . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "") + //. " GROUP BY $want.id" + . $exclude + . $orderby + . $limit); $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100); $sth->execute(); $result = $sth->fetch(PDO_FETCH_BOTH); @@ -759,7 +788,8 @@ extends WikiDB_backend /** * Find if a page links to another page */ - function exists_link($pagename, $link, $reversed=false) { + function exists_link($pagename, $link, $reversed = false) + { $dbh = &$this->_dbh; extract($this->_table_names); @@ -768,38 +798,38 @@ extends WikiDB_backend else list($have, $want) = array('linker', 'linkee'); $sth = $dbh->prepare("SELECT CASE WHEN $want.pagename THEN 1 ELSE 0 END" - . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl" - . " WHERE linkfrom=linker.id AND linkto=linkee.id" - . " AND $have.pagename=?" - . " AND $want.pagename=?"); + . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl" + . " WHERE linkfrom=linker.id AND linkto=linkee.id" + . " AND $have.pagename=?" + . " AND $want.pagename=?"); $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100); $sth->bindParam(2, $link, PDO_PARAM_STR, 100); $sth->execute(); return $sth->fetchSingle(); } - function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') { + function get_all_pages($include_empty = false, $sortby = '', $limit = '', $exclude = '') + { $dbh = &$this->_dbh; extract($this->_table_names); $orderby = $this->sortby($sortby, 'db'); if ($orderby) $orderby = ' ORDER BY ' . $orderby; if ($exclude) // array of pagenames - $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND $page_tbl.pagename NOT IN " . $this->_sql_set($exclude); else - $exclude=''; + $exclude = ''; $limit = $this->_limit_sql($limit); if (strstr($orderby, 'mtime ')) { // was ' mtime' if ($include_empty) { $sql = "SELECT " . $this->page_tbl_fields - ." FROM $page_tbl, $recent_tbl, $version_tbl" + . " FROM $page_tbl, $recent_tbl, $version_tbl" . " WHERE $page_tbl.id=$recent_tbl.id" . " AND $page_tbl.id=$version_tbl.id AND latestversion=version" . $exclude . $orderby; - } - else { + } else { $sql = "SELECT " . $this->page_tbl_fields . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl" @@ -834,7 +864,8 @@ extends WikiDB_backend /** * Title search. */ - function text_search($search, $fullsearch=false, $sortby='', $limit='', $exclude='') { + function text_search($search, $fullsearch = false, $sortby = '', $limit = '', $exclude = '') + { $dbh = &$this->_dbh; extract($this->_table_names); $orderby = $this->sortby($sortby, 'db'); @@ -863,10 +894,10 @@ extends WikiDB_backend $search_clause = $search->makeSqlClauseObj($callback); $sth = $dbh->prepare("SELECT $fields FROM $table" - . " WHERE $join_clause" - . " AND ($search_clause)" - . $orderby - . $limit); + . " WHERE $join_clause" + . " AND ($search_clause)" + . $orderby + . $limit); $sth->execute(); $result = $sth->fetch(PDO_FETCH_NUM); $iter = new WikiDB_backend_PDO_iter($this, $result, $field_list); @@ -880,22 +911,24 @@ extends WikiDB_backend * This is only for already resolved wildcards: * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2')); */ - function _sql_set(&$pagenames) { + function _sql_set(&$pagenames) + { $s = '('; foreach ($pagenames as $p) { - $s .= ($this->_dbh->qstr($p).","); + $s .= ($this->_dbh->qstr($p) . ","); } - return substr($s,0,-1).")"; + return substr($s, 0, -1) . ")"; } /** * Find highest or lowest hit counts. */ - function most_popular($limit=20, $sortby='-hits') { + function most_popular($limit = 20, $sortby = '-hits') + { $dbh = &$this->_dbh; extract($this->_table_names); $order = "DESC"; - if ($limit < 0){ + if ($limit < 0) { $order = "ASC"; $limit = -$limit; $where = ""; @@ -903,7 +936,7 @@ extends WikiDB_backend $where = " AND hits > 0"; } if ($sortby != '-hits') { - if ($order = $this->sortby($sortby, 'db')) $orderby = " ORDER BY " . $order; + if ($order = $this->sortby($sortby, 'db')) $orderby = " ORDER BY " . $order; else $orderby = ""; } else $orderby = " ORDER BY hits $order"; @@ -926,7 +959,8 @@ extends WikiDB_backend /** * Find recent changes. */ - function most_recent($params) { + function most_recent($params) + { $limit = 0; $since = 0; $include_minor_revisions = false; @@ -949,13 +983,11 @@ extends WikiDB_backend if ($exclude_major_revisions) { // Include only minor revisions $pick[] = "minor_edit <> 0"; - } - elseif (!$include_minor_revisions) { + } elseif (!$include_minor_revisions) { // Include only major revisions $pick[] = "minor_edit = 0"; } - } - else { + } else { $table = "$page_tbl, $recent_tbl"; $join_clause = "$page_tbl.id=$recent_tbl.id"; $table .= ", $version_tbl"; @@ -964,18 +996,16 @@ extends WikiDB_backend if ($exclude_major_revisions) { // Include only most recent minor revision $pick[] = 'version=latestminor'; - } - elseif (!$include_minor_revisions) { + } elseif (!$include_minor_revisions) { // Include only most recent major revision $pick[] = 'version=latestmajor'; - } - else { + } else { // Include only the latest revision (whether major or minor). - $pick[] ='version=latestversion'; + $pick[] = 'version=latestversion'; } } $order = "DESC"; - if($limit < 0){ + if ($limit < 0) { $order = "ASC"; $limit = -$limit; } @@ -1001,16 +1031,17 @@ extends WikiDB_backend /** * Find referenced empty pages. */ - function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') { + function wanted_pages($exclude_from = '', $exclude = '', $sortby = '', $limit = '') + { $dbh = &$this->_dbh; extract($this->_table_names); - if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom'))) + if ($orderby = $this->sortby($sortby, 'db', array('pagename', 'wantedfrom'))) $orderby = 'ORDER BY ' . $orderby; if ($exclude_from) // array of pagenames - $exclude_from = " AND linked.pagename NOT IN ".$this->_sql_set($exclude_from); + $exclude_from = " AND linked.pagename NOT IN " . $this->_sql_set($exclude_from); if ($exclude) // array of pagenames - $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND $page_tbl.pagename NOT IN " . $this->_sql_set($exclude); /* all empty pages, independent of linkstatus: @@ -1025,7 +1056,7 @@ extends WikiDB_backend . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id" . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id" . " WHERE ne.id is NULL" - . " AND p.id = linked.linkfrom" + . " AND p.id = linked.linkfrom" . $exclude_from . $exclude . $orderby; @@ -1036,18 +1067,19 @@ extends WikiDB_backend } $sth->execute(); $result = $sth->fetch(PDO_FETCH_NUM); - return new WikiDB_backend_PDO_iter($this, $result, array('pagename','wantedfrom')); + return new WikiDB_backend_PDO_iter($this, $result, array('pagename', 'wantedfrom')); } /** * Rename page in the database. */ - function rename_page($pagename, $to) { + function rename_page($pagename, $to) + { $dbh = &$this->_dbh; extract($this->_table_names); - $this->lock(array('page','version','recent','nonempty','link')); - if ( ($id = $this->_get_pageid($pagename, false)) ) { + $this->lock(array('page', 'version', 'recent', 'nonempty', 'link')); + if (($id = $this->_get_pageid($pagename, false))) { if ($new = $this->_get_pageid($to, false)) { // Cludge Alert! // This page does not exist (already verified before), but exists in the page table. @@ -1069,7 +1101,8 @@ extends WikiDB_backend return $id; } - function _update_recent_table($pageid = false) { + function _update_recent_table($pageid = false) + { $dbh = &$this->_dbh; extract($this->_table_names); extract($this->_expressions); @@ -1078,31 +1111,32 @@ extends WikiDB_backend // optimize: mysql can do this with one REPLACE INTO. $backend_type = $this->backendType(); - if (substr($backend_type,0,5) == 'mysql') { + if (substr($backend_type, 0, 5) == 'mysql') { $sth = $dbh->prepare("REPLACE INTO $recent_tbl" - . " (id, latestversion, latestmajor, latestminor)" - . " SELECT id, $maxversion, $maxmajor, $maxminor" - . " FROM $version_tbl" - . ( $pageid ? " WHERE id=$pageid" : "") - . " GROUP BY id" ); + . " (id, latestversion, latestmajor, latestminor)" + . " SELECT id, $maxversion, $maxmajor, $maxminor" + . " FROM $version_tbl" + . ($pageid ? " WHERE id=$pageid" : "") + . " GROUP BY id"); $sth->execute(); } else { $this->lock(array('recent')); $sth = $dbh->prepare("DELETE FROM $recent_tbl" - . ( $pageid ? " WHERE id=$pageid" : "")); + . ($pageid ? " WHERE id=$pageid" : "")); $sth->execute(); - $sth = $dbh->prepare( "INSERT INTO $recent_tbl" - . " (id, latestversion, latestmajor, latestminor)" - . " SELECT id, $maxversion, $maxmajor, $maxminor" - . " FROM $version_tbl" - . ( $pageid ? " WHERE id=$pageid" : "") - . " GROUP BY id" ); + $sth = $dbh->prepare("INSERT INTO $recent_tbl" + . " (id, latestversion, latestmajor, latestminor)" + . " SELECT id, $maxversion, $maxmajor, $maxminor" + . " FROM $version_tbl" + . ($pageid ? " WHERE id=$pageid" : "") + . " GROUP BY id"); $sth->execute(); $this->unlock(array('recent')); } } - function _update_nonempty_table($pageid = false) { + function _update_nonempty_table($pageid = false) + { $dbh = &$this->_dbh; extract($this->_table_names); extract($this->_expressions); @@ -1112,16 +1146,16 @@ extends WikiDB_backend extract($this->_expressions); $this->lock(array('nonempty')); $dbh->query("DELETE FROM $nonempty_tbl" - . ( $pageid ? " WHERE id=$pageid" : "")); + . ($pageid ? " WHERE id=$pageid" : "")); $dbh->query("INSERT INTO $nonempty_tbl (id)" - . " SELECT $recent_tbl.id" - . " FROM $recent_tbl, $version_tbl" - . " WHERE $recent_tbl.id=$version_tbl.id" - . " AND version=latestversion" - // We have some specifics here (Oracle) - //. " AND content<>''" - . " AND content $notempty" - . ( $pageid ? " AND $recent_tbl.id=$pageid" : "")); + . " SELECT $recent_tbl.id" + . " FROM $recent_tbl, $version_tbl" + . " WHERE $recent_tbl.id=$version_tbl.id" + . " AND version=latestversion" + // We have some specifics here (Oracle) + //. " AND content<>''" + . " AND content $notempty" + . ($pageid ? " AND $recent_tbl.id=$pageid" : "")); $this->unlock(array('nonempty')); } @@ -1133,7 +1167,8 @@ extends WikiDB_backend * * @access protected */ - function lock($tables, $write_lock = true) { + function lock($tables, $write_lock = true) + { if ($this->_lock_count++ == 0) { $this->_current_lock = $tables; if (!$this->_hasTransactions) @@ -1144,7 +1179,8 @@ extends WikiDB_backend /** * Overridden by non-transaction safe backends. */ - function _lock_tables($tables, $write_lock) { + function _lock_tables($tables, $write_lock) + { $lock_type = $write_lock ? "WRITE" : "READ"; foreach ($this->_table_names as $key => $table) { $locks[] = "$table $lock_type"; @@ -1162,7 +1198,8 @@ extends WikiDB_backend * * @see _lock_database */ - function unlock($tables = false, $force = false) { + function unlock($tables = false, $force = false) + { if ($this->_lock_count == 0) { $this->_current_lock = false; return; @@ -1178,14 +1215,16 @@ extends WikiDB_backend /** * overridden by non-transaction safe backends */ - function _unlock_tables($tables) { + function _unlock_tables($tables) + { $this->_dbh->query("UNLOCK TABLES"); } /** * Serialize data */ - function _serialize($data) { + function _serialize($data) + { if (empty($data)) return ''; assert(is_array($data)); @@ -1195,26 +1234,36 @@ extends WikiDB_backend /** * Unserialize data */ - function _unserialize($data) { + function _unserialize($data) + { return empty($data) ? array() : unserialize($data); } /* some variables and functions for DB backend abstraction (action=upgrade) */ - function database () { + function database() + { return $this->_dbh->database; } - function backendType() { + + function backendType() + { return $this->_dbh->databaseType; } - function connection() { + + function connection() + { trigger_error("PDO: connectionID unsupported", E_USER_ERROR); return false; } - function listOfTables() { + + function listOfTables() + { trigger_error("PDO: virtual listOfTables", E_USER_ERROR); return array(); } - function listOfFields($database, $table) { + + function listOfFields($database, $table) + { trigger_error("PDO: virtual listOfFields", E_USER_ERROR); return array(); } @@ -1236,7 +1285,8 @@ extends WikiDB_backend BETWEEN $offset AND $last ORDER BY $pk $asc_desc */ - function _limit_sql($limit = false) { + function _limit_sql($limit = false) + { if ($limit) { list($offset, $count) = $this->limit($limit); if ($offset) { @@ -1249,14 +1299,15 @@ extends WikiDB_backend return $limit; } - function write_accesslog(&$entry) { + function write_accesslog(&$entry) + { global $request; $dbh = &$this->_dbh; $log_tbl = $entry->_accesslog->logtable; $dbh->prepare("INSERT INTO $log_tbl" - . " (time_stamp,remote_host,remote_user,request_method,request_line,request_args," - . "request_file,request_uri,request_time,status,bytes_sent,referer,agent,request_duration)" - . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); + . " (time_stamp,remote_host,remote_user,request_method,request_line,request_args," + . "request_file,request_uri,request_time,status,bytes_sent,referer,agent,request_duration)" + . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); // Either use unixtime as %d (long), or the native timestamp format. $sth->bindParam(1, $entry->time, PDO_PARAM_INT); $sth->bindParam(2, $entry->host, PDO_PARAM_STR, 100); @@ -1267,25 +1318,29 @@ extends WikiDB_backend $sth->bindParam(7, $entry->request_uri, PDO_PARAM_STR, 255); $sth->bindParam(8, $entry->_ncsa_time($entry->time), PDO_PARAM_STR, 28); $sth->bindParam(9, $entry->time, PDO_PARAM_INT); - $sth->bindParam(10,$entry->status, PDO_PARAM_INT); - $sth->bindParam(11,$entry->size, PDO_PARAM_INT); - $sth->bindParam(12,$entry->referer, PDO_PARAM_STR, 255); - $sth->bindParam(13,$entry->user_agent, PDO_PARAM_STR, 255); - $sth->bindParam(14,$entry->duration, PDO_PARAM_FLOAT); + $sth->bindParam(10, $entry->status, PDO_PARAM_INT); + $sth->bindParam(11, $entry->size, PDO_PARAM_INT); + $sth->bindParam(12, $entry->referer, PDO_PARAM_STR, 255); + $sth->bindParam(13, $entry->user_agent, PDO_PARAM_STR, 255); + $sth->bindParam(14, $entry->duration, PDO_PARAM_FLOAT); $sth->execute(); } -}; +} + +; class WikiDB_backend_PDO_generic_iter -extends WikiDB_backend_iterator + extends WikiDB_backend_iterator { - function WikiDB_backend_PDO_generic_iter($backend, $query_result, $field_list = NULL) { + function WikiDB_backend_PDO_generic_iter($backend, $query_result, $field_list = NULL) + { $this->_backend = &$backend; $this->_result = $query_result; //$this->_fields = $field_list; } - function count() { + function count() + { if (!is_object($this->_result)) { return false; } @@ -1293,7 +1348,8 @@ extends WikiDB_backend_iterator return $count; } - function next() { + function next() + { $result = &$this->_result; if (!is_object($result)) { return false; @@ -1301,7 +1357,8 @@ extends WikiDB_backend_iterator return $result->fetch(PDO_FETCH_BOTH); } - function free () { + function free() + { if ($this->_result) { unset($this->_result); } @@ -1309,9 +1366,10 @@ extends WikiDB_backend_iterator } class WikiDB_backend_PDO_iter -extends WikiDB_backend_PDO_generic_iter + extends WikiDB_backend_PDO_generic_iter { - function next() { + function next() + { $result = &$this->_result; if (!is_object($result)) { return false; @@ -1328,167 +1386,169 @@ extends WikiDB_backend_PDO_generic_iter } } -class WikiDB_backend_PDO_search extends WikiDB_backend_search_sql {} +class WikiDB_backend_PDO_search extends WikiDB_backend_search_sql +{ +} // Following function taken from Pear::DB (prev. from adodb-pear.inc.php). // Eventually, change index.php to provide the relevant information // directly? - /** - * Parse a data source name. - * - * Additional keys can be added by appending a URI query string to the - * end of the DSN. - * - * The format of the supplied DSN is in its fullest form: - * - * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true - * - * - * Most variations are allowed: - * - * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644 - * phptype://username:password@hostspec/database_name - * phptype://username:password@hostspec - * phptype://username@hostspec - * phptype://hostspec/database - * phptype://hostspec - * phptype(dbsyntax) - * phptype - * - * - * @param string $dsn Data Source Name to be parsed - * - * @return array an associative array with the following keys: - * + phptype: Database backend used in PHP (mysql, odbc etc.) - * + dbsyntax: Database used with regards to SQL syntax etc. (ignored with PDO) - * + protocol: Communication protocol to use (tcp, unix, pipe etc.) - * + hostspec: Host specification (hostname[:port]) - * + database: Database to use on the DBMS server - * + username: User name for login - * + password: Password for login - * - * @author Tomas V.V.Cox - */ - function parseDSN($dsn) - { - $parsed = array( - 'phptype' => false, - 'dbsyntax' => false, - 'username' => false, - 'password' => false, - 'protocol' => false, - 'hostspec' => false, - 'port' => false, - 'socket' => false, - 'database' => false, - ); - - if (is_array($dsn)) { - $dsn = array_merge($parsed, $dsn); - if (!$dsn['dbsyntax']) { - $dsn['dbsyntax'] = $dsn['phptype']; - } - return $dsn; +/** + * Parse a data source name. + * + * Additional keys can be added by appending a URI query string to the + * end of the DSN. + * + * The format of the supplied DSN is in its fullest form: + * + * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true + * + * + * Most variations are allowed: + * + * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644 + * phptype://username:password@hostspec/database_name + * phptype://username:password@hostspec + * phptype://username@hostspec + * phptype://hostspec/database + * phptype://hostspec + * phptype(dbsyntax) + * phptype + * + * + * @param string $dsn Data Source Name to be parsed + * + * @return array an associative array with the following keys: + * + phptype: Database backend used in PHP (mysql, odbc etc.) + * + dbsyntax: Database used with regards to SQL syntax etc. (ignored with PDO) + * + protocol: Communication protocol to use (tcp, unix, pipe etc.) + * + hostspec: Host specification (hostname[:port]) + * + database: Database to use on the DBMS server + * + username: User name for login + * + password: Password for login + * + * @author Tomas V.V.Cox + */ +function parseDSN($dsn) +{ + $parsed = array( + 'phptype' => false, + 'dbsyntax' => false, + 'username' => false, + 'password' => false, + 'protocol' => false, + 'hostspec' => false, + 'port' => false, + 'socket' => false, + 'database' => false, + ); + + if (is_array($dsn)) { + $dsn = array_merge($parsed, $dsn); + if (!$dsn['dbsyntax']) { + $dsn['dbsyntax'] = $dsn['phptype']; } + return $dsn; + } - // Find phptype and dbsyntax - if (($pos = strpos($dsn, '://')) !== false) { - $str = substr($dsn, 0, $pos); - $dsn = substr($dsn, $pos + 3); - } else { - $str = $dsn; - $dsn = null; - } + // Find phptype and dbsyntax + if (($pos = strpos($dsn, '://')) !== false) { + $str = substr($dsn, 0, $pos); + $dsn = substr($dsn, $pos + 3); + } else { + $str = $dsn; + $dsn = null; + } - // Get phptype and dbsyntax - // $str => phptype(dbsyntax) - if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) { - $parsed['phptype'] = $arr[1]; - $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2]; - } else { - $parsed['phptype'] = $str; - $parsed['dbsyntax'] = $str; - } + // Get phptype and dbsyntax + // $str => phptype(dbsyntax) + if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) { + $parsed['phptype'] = $arr[1]; + $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2]; + } else { + $parsed['phptype'] = $str; + $parsed['dbsyntax'] = $str; + } - if (!count($dsn)) { - return $parsed; - } + if (!count($dsn)) { + return $parsed; + } - // Get (if found): username and password - // $dsn => username:password@protocol+hostspec/database - if (($at = strrpos($dsn,'@')) !== false) { - $str = substr($dsn, 0, $at); - $dsn = substr($dsn, $at + 1); - if (($pos = strpos($str, ':')) !== false) { - $parsed['username'] = rawurldecode(substr($str, 0, $pos)); - $parsed['password'] = rawurldecode(substr($str, $pos + 1)); - } else { - $parsed['username'] = rawurldecode($str); - } + // Get (if found): username and password + // $dsn => username:password@protocol+hostspec/database + if (($at = strrpos($dsn, '@')) !== false) { + $str = substr($dsn, 0, $at); + $dsn = substr($dsn, $at + 1); + if (($pos = strpos($str, ':')) !== false) { + $parsed['username'] = rawurldecode(substr($str, 0, $pos)); + $parsed['password'] = rawurldecode(substr($str, $pos + 1)); + } else { + $parsed['username'] = rawurldecode($str); } + } - // Find protocol and hostspec + // Find protocol and hostspec - // $dsn => proto(proto_opts)/database - if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) { - $proto = $match[1]; - $proto_opts = $match[2] ? $match[2] : false; - $dsn = $match[3]; + // $dsn => proto(proto_opts)/database + if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) { + $proto = $match[1]; + $proto_opts = $match[2] ? $match[2] : false; + $dsn = $match[3]; // $dsn => protocol+hostspec/database (old format) + } else { + if (strpos($dsn, '+') !== false) { + list($proto, $dsn) = explode('+', $dsn, 2); + } + if (strpos($dsn, '/') !== false) { + list($proto_opts, $dsn) = explode('/', $dsn, 2); } else { - if (strpos($dsn, '+') !== false) { - list($proto, $dsn) = explode('+', $dsn, 2); - } - if (strpos($dsn, '/') !== false) { - list($proto_opts, $dsn) = explode('/', $dsn, 2); - } else { - $proto_opts = $dsn; - $dsn = null; - } + $proto_opts = $dsn; + $dsn = null; } + } - // process the different protocol options - $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp'; - $proto_opts = rawurldecode($proto_opts); - if ($parsed['protocol'] == 'tcp') { - if (strpos($proto_opts, ':') !== false) { - list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts); - } else { - $parsed['hostspec'] = $proto_opts; - } - } elseif ($parsed['protocol'] == 'unix') { - $parsed['socket'] = $proto_opts; + // process the different protocol options + $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp'; + $proto_opts = rawurldecode($proto_opts); + if ($parsed['protocol'] == 'tcp') { + if (strpos($proto_opts, ':') !== false) { + list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts); + } else { + $parsed['hostspec'] = $proto_opts; } + } elseif ($parsed['protocol'] == 'unix') { + $parsed['socket'] = $proto_opts; + } - // Get dabase if any - // $dsn => database - if ($dsn) { - // /database - if (($pos = strpos($dsn, '?')) === false) { - $parsed['database'] = $dsn; + // Get dabase if any + // $dsn => database + if ($dsn) { + // /database + if (($pos = strpos($dsn, '?')) === false) { + $parsed['database'] = $dsn; // /database?param1=value1¶m2=value2 - } else { - $parsed['database'] = substr($dsn, 0, $pos); - $dsn = substr($dsn, $pos + 1); - if (strpos($dsn, '&') !== false) { - $opts = explode('&', $dsn); - } else { // database?param1=value1 - $opts = array($dsn); - } - foreach ($opts as $opt) { - list($key, $value) = explode('=', $opt); - if (!isset($parsed[$key])) { - // don't allow params overwrite - $parsed[$key] = rawurldecode($value); - } + } else { + $parsed['database'] = substr($dsn, 0, $pos); + $dsn = substr($dsn, $pos + 1); + if (strpos($dsn, '&') !== false) { + $opts = explode('&', $dsn); + } else { // database?param1=value1 + $opts = array($dsn); + } + foreach ($opts as $opt) { + list($key, $value) = explode('=', $opt); + if (!isset($parsed[$key])) { + // don't allow params overwrite + $parsed[$key] = rawurldecode($value); } } } - - return $parsed; } + return $parsed; +} + // Local Variables: // mode: php // tab-width: 8 diff --git a/lib/WikiDB/backend/PDO_mysql.php b/lib/WikiDB/backend/PDO_mysql.php index 9dc8f2ede..613782741 100644 --- a/lib/WikiDB/backend/PDO_mysql.php +++ b/lib/WikiDB/backend/PDO_mysql.php @@ -26,9 +26,10 @@ require_once 'lib/WikiDB/backend/PDO.php'; class WikiDB_backend_PDO_mysql -extends WikiDB_backend_PDO + extends WikiDB_backend_PDO { - function WikiDB_backend_PDO_mysql($dbparams) { + function WikiDB_backend_PDO_mysql($dbparams) + { $this->WikiDB_backend_PDO($dbparams); @@ -45,44 +46,47 @@ extends WikiDB_backend_PDO if ($this->_serverinfo['version'] > 401.0) { global $charset; $aliases = array('iso-8859-1' => 'latin1', - 'utf-8' => 'utf8'); + 'utf-8' => 'utf8'); //http://dev.mysql.com/doc/mysql/en/charset-connection.html if (isset($aliases[strtolower($charset)])) { // mysql needs special unusual names and doesn't resolve aliases - mysql_query("SET NAMES '". $aliases[$charset] . "'"); + mysql_query("SET NAMES '" . $aliases[$charset] . "'"); } else { mysql_query("SET NAMES '$charset'"); } } } - function backendType() { + function backendType() + { return 'mysql'; } /** * Kill timed out processes. ( so far only called on about every 50-th save. ) */ - function _timeout() { + function _timeout() + { if (empty($this->_dbparams['timeout'])) return; - $sth = $this->_dbh->prepare("SHOW processlist"); + $sth = $this->_dbh->prepare("SHOW processlist"); if ($sth->execute()) - while ($row = $sth->fetch(PDO_FETCH_ASSOC)) { - if ($row["db"] == $this->_dsn['database'] - and $row["User"] == $this->_dsn['username'] - and $row["Time"] > $this->_dbparams['timeout'] - and $row["Command"] == "Sleep") - { - $process_id = $row["Id"]; - $this->query("KILL $process_id"); - } - } + while ($row = $sth->fetch(PDO_FETCH_ASSOC)) { + if ($row["db"] == $this->_dsn['database'] + and $row["User"] == $this->_dsn['username'] + and $row["Time"] > $this->_dbparams['timeout'] + and $row["Command"] == "Sleep" + ) { + $process_id = $row["Id"]; + $this->query("KILL $process_id"); + } + } } /** * Pack tables. */ - function optimize() { + function optimize() + { $dbh = &$this->_dbh; $this->_timeout(); foreach ($this->_table_names as $table) { @@ -91,25 +95,28 @@ extends WikiDB_backend_PDO return 1; } - function listOfTables() { + function listOfTables() + { $sth = $this->_dbh->prepare("SHOW TABLES"); $sth->execute(); $tables = array(); - while ($row = $sth->fetch(PDO_FETCH_NUM)) { $tables[] = $row[0]; } + while ($row = $sth->fetch(PDO_FETCH_NUM)) { + $tables[] = $row[0]; + } return $tables; } - function listOfFields($database, $table) { + function listOfFields($database, $table) + { $old_db = $this->database(); if ($database != $old_db) { try { - $dsn = preg_replace("/dbname=\w+;/", "dbname=".$database, $this->_dsn); - $dsn = preg_replace("/database=\w+;/", "database=".$database, $dsn); + $dsn = preg_replace("/dbname=\w+;/", "dbname=" . $database, $this->_dsn); + $dsn = preg_replace("/database=\w+;/", "database=" . $database, $dsn); $conn = new PDO($dsn, - DBADMIN_USER ? DBADMIN_USER : $this->_parsedDSN['username'], - DBADMIN_PASSWD ? DBADMIN_PASSWD : $this->_parsedDSN['password']); - } - catch (PDOException $e) { + DBADMIN_USER ? DBADMIN_USER : $this->_parsedDSN['username'], + DBADMIN_PASSWD ? DBADMIN_PASSWD : $this->_parsedDSN['password']); + } catch (PDOException $e) { echo "
      \nDB Connection failed: " . $e->getMessage(); echo "
      \nDSN: '", $this->_dsn, "'"; echo "
      \n_parsedDSN: '", print_r($this->_parsedDSN), "'"; @@ -134,7 +141,8 @@ extends WikiDB_backend_PDO * offset specific syntax within mysql * convert from,count to SQL "LIMIT $offset, $count" */ - function _limit_sql($limit = false) { + function _limit_sql($limit = false) + { if ($limit) { list($offset, $count) = $this->limit($limit); if ($offset) diff --git a/lib/WikiDB/backend/PDO_oci8.php b/lib/WikiDB/backend/PDO_oci8.php index b68636cbd..a310b6b9a 100644 --- a/lib/WikiDB/backend/PDO_oci8.php +++ b/lib/WikiDB/backend/PDO_oci8.php @@ -26,10 +26,11 @@ require_once 'lib/WikiDB/backend/PDO.php'; class WikiDB_backend_PDO_oci8 -extends WikiDB_backend_PDO + extends WikiDB_backend_PDO { - function optimize() { + function optimize() + { // Do nothing here -- Leave that for the DBA // Cost Based Optimizer tuning vary from version to version return 1; @@ -38,7 +39,8 @@ extends WikiDB_backend_PDO /** * Lock all tables we might use. */ - function _lock_tables($write_lock=true) { + function _lock_tables($write_lock = true) + { $dbh = &$this->_dbh; // Not sure if we really need to lock tables here, the Oracle row @@ -56,17 +58,20 @@ extends WikiDB_backend_PDO } } - function backendType() { + function backendType() + { return 'oci8'; } - function write_accesslog(&$entry) { + + function write_accesslog(&$entry) + { global $request; $dbh = &$this->_dbh; $log_tbl = $entry->_accesslog->logtable; $sth = $dbh->prepare("INSERT INTO $log_tbl" - . " (time_stamp,remote_host,remote_user,request_method,request_line,request_args," - . "request_file,request_uri,request_time,status,bytes_sent,referer,agent,request_duration)" - . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); + . " (time_stamp,remote_host,remote_user,request_method,request_line,request_args," + . "request_file,request_uri,request_time,status,bytes_sent,referer,agent,request_duration)" + . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); // Either use unixtime as %d (long), or the native timestamp format. $sth->bindParam(1, date('d-M-Y H:i:s', $entry->time)); $sth->bindParam(2, $entry->host, PDO_PARAM_STR, 100); @@ -77,11 +82,11 @@ extends WikiDB_backend_PDO $sth->bindParam(7, $entry->request_uri, PDO_PARAM_STR, 255); $sth->bindParam(8, $entry->_ncsa_time($entry->time), PDO_PARAM_STR, 28); $sth->bindParam(9, $entry->time, PDO_PARAM_INT); - $sth->bindParam(10,$entry->status, PDO_PARAM_INT); - $sth->bindParam(11,$entry->size, PDO_PARAM_INT); - $sth->bindParam(12,$entry->referer, PDO_PARAM_STR, 255); - $sth->bindParam(13,$entry->user_agent, PDO_PARAM_STR, 255); - $sth->bindParam(14,$entry->duration, PDO_PARAM_FLOAT); + $sth->bindParam(10, $entry->status, PDO_PARAM_INT); + $sth->bindParam(11, $entry->size, PDO_PARAM_INT); + $sth->bindParam(12, $entry->referer, PDO_PARAM_STR, 255); + $sth->bindParam(13, $entry->user_agent, PDO_PARAM_STR, 255); + $sth->bindParam(14, $entry->duration, PDO_PARAM_FLOAT); $sth->execute(); } } diff --git a/lib/WikiDB/backend/PDO_pgsql.php b/lib/WikiDB/backend/PDO_pgsql.php index e64198210..661e179b1 100644 --- a/lib/WikiDB/backend/PDO_pgsql.php +++ b/lib/WikiDB/backend/PDO_pgsql.php @@ -26,13 +26,14 @@ require_once 'lib/WikiDB/backend/PDO.php'; class WikiDB_backend_PDO_pgsql -extends WikiDB_backend_PDO + extends WikiDB_backend_PDO { /* * convert from,count to SQL "LIMIT $count OFFSET $from" */ - function _limit_sql($limit = false) { + function _limit_sql($limit = false) + { if ($limit) { list($offset, $count) = $this->limit($limit); if ($offset) @@ -44,7 +45,8 @@ extends WikiDB_backend_PDO return $limit; } - function backendType() { + function backendType() + { return 'pgsql'; } } diff --git a/lib/WikiDB/backend/PearDB.php b/lib/WikiDB/backend/PearDB.php index a5efd07cf..1784d6d5a 100644 --- a/lib/WikiDB/backend/PearDB.php +++ b/lib/WikiDB/backend/PearDB.php @@ -5,11 +5,12 @@ require_once 'lib/WikiDB/backend.php'; //require_once('lib/ErrorManager.php'); class WikiDB_backend_PearDB -extends WikiDB_backend + extends WikiDB_backend { var $_dbh; - function WikiDB_backend_PearDB ($dbparams) { + function WikiDB_backend_PearDB($dbparams) + { // Find and include PEAR's DB.php. maybe we should force our private version again... // if DB would have exported its version number, it would be easier. @require_once('DB/common.php'); // Either our local pear copy or the system one @@ -19,7 +20,7 @@ extends WikiDB_backend // which is invalid for "select version()" if (!in_array($name, get_class_methods("DB_common"))) { $finder = new FileFinder; - $dir = dirname(__FILE__)."/../../pear"; + $dir = dirname(__FILE__) . "/../../pear"; $finder->_prepend_to_include_path($dir); include_once("$dir/DB/common.php"); // use our version instead. if (!in_array($name, get_class_methods("DB_common"))) { @@ -29,7 +30,7 @@ extends WikiDB_backend include_once("$dir/DB.php"); } } else { - include_once 'DB.php'; + include_once 'DB.php'; } // Install filter to handle bogus error notices from buggy DB.php's. @@ -42,61 +43,62 @@ extends WikiDB_backend // Open connection to database $this->_dsn = $dbparams['dsn']; - $this->_dbparams = $dbparams; + $this->_dbparams = $dbparams; $this->_lock_count = 0; // persistent is usually a DSN option: we override it with a config value. // phptype://username:password@hostspec/database?persistent=false $dboptions = array('persistent' => DATABASE_PERSISTENT, - 'debug' => 2); + 'debug' => 2); //if (preg_match('/^pgsql/', $this->_dsn)) $dboptions['persistent'] = false; $this->_dbh = DB::connect($this->_dsn, $dboptions); $dbh = &$this->_dbh; if (DB::isError($dbh)) { trigger_error(sprintf("Can't connect to database: %s", - $this->_pear_error_message($dbh)), - isset($dbparams['_tryroot_from_upgrade']) // hack! - ? E_USER_WARNING : E_USER_ERROR); + $this->_pear_error_message($dbh)), + isset($dbparams['_tryroot_from_upgrade']) // hack! + ? E_USER_WARNING : E_USER_ERROR); if (isset($dbparams['_tryroot_from_upgrade'])) return; } $dbh->setErrorHandling(PEAR_ERROR_CALLBACK, - array($this, '_pear_error_callback')); + array($this, '_pear_error_callback')); $dbh->setFetchMode(DB_FETCHMODE_ASSOC); $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : ''; $this->_table_names - = array('page_tbl' => $prefix . 'page', - 'version_tbl' => $prefix . 'version', - 'link_tbl' => $prefix . 'link', - 'recent_tbl' => $prefix . 'recent', - 'nonempty_tbl' => $prefix . 'nonempty'); + = array('page_tbl' => $prefix . 'page', + 'version_tbl' => $prefix . 'version', + 'link_tbl' => $prefix . 'link', + 'recent_tbl' => $prefix . 'recent', + 'nonempty_tbl' => $prefix . 'nonempty'); $page_tbl = $this->_table_names['page_tbl']; $version_tbl = $this->_table_names['version_tbl']; $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, $page_tbl.hits AS hits"; - $this->version_tbl_fields = "$version_tbl.version AS version, $version_tbl.mtime AS mtime, ". + $this->version_tbl_fields = "$version_tbl.version AS version, $version_tbl.mtime AS mtime, " . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, $version_tbl.versiondata AS versiondata"; $this->_expressions - = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)", - 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)", - 'maxversion' => "MAX(version)", - 'notempty' => "<>''", - 'iscontent' => "content<>''"); + = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)", + 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)", + 'maxversion' => "MAX(version)", + 'notempty' => "<>''", + 'iscontent' => "content<>''"); } /** * Close database connection. */ - function close () { + function close() + { if (!$this->_dbh) return; if ($this->_lock_count) { - trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n
      ", - E_USER_WARNING); + trigger_error("WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n
      ", + E_USER_WARNING); } - $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops. + $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops. $this->unlock('force'); $this->_dbh->disconnect(); @@ -109,68 +111,74 @@ extends WikiDB_backend /* * Test fast wikipage. */ - function is_wiki_page($pagename) { + function is_wiki_page($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); return $dbh->getOne(sprintf("SELECT $page_tbl.id as id" - . " FROM $nonempty_tbl, $page_tbl" - . " WHERE $nonempty_tbl.id=$page_tbl.id" - . " AND pagename='%s'", - $dbh->escapeSimple($pagename))); + . " FROM $nonempty_tbl, $page_tbl" + . " WHERE $nonempty_tbl.id=$page_tbl.id" + . " AND pagename='%s'", + $dbh->escapeSimple($pagename))); } - function get_all_pagenames() { + function get_all_pagenames() + { $dbh = &$this->_dbh; extract($this->_table_names); return $dbh->getCol("SELECT pagename" - . " FROM $nonempty_tbl, $page_tbl" - . " WHERE $nonempty_tbl.id=$page_tbl.id"); + . " FROM $nonempty_tbl, $page_tbl" + . " WHERE $nonempty_tbl.id=$page_tbl.id"); } - function numPages($filter=false, $exclude='') { + function numPages($filter = false, $exclude = '') + { $dbh = &$this->_dbh; extract($this->_table_names); return $dbh->getOne("SELECT count(*)" - . " FROM $nonempty_tbl, $page_tbl" - . " WHERE $nonempty_tbl.id=$page_tbl.id"); + . " FROM $nonempty_tbl, $page_tbl" + . " WHERE $nonempty_tbl.id=$page_tbl.id"); } - function increaseHitCount($pagename) { + function increaseHitCount($pagename) + { $dbh = &$this->_dbh; // Hits is the only thing we can update in a fast manner. // Note that this will fail silently if the page does not // have a record in the page table. Since it's just the // hit count, who cares? $dbh->query(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename='%s'", - $this->_table_names['page_tbl'], - $dbh->escapeSimple($pagename))); + $this->_table_names['page_tbl'], + $dbh->escapeSimple($pagename))); return; } /** * Read page information from database. */ - function get_pagedata($pagename) { + function get_pagedata($pagename) + { $dbh = &$this->_dbh; //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE); $result = $dbh->getRow(sprintf("SELECT hits,pagedata FROM %s WHERE pagename='%s'", - $this->_table_names['page_tbl'], - $dbh->escapeSimple($pagename)), - DB_FETCHMODE_ASSOC); + $this->_table_names['page_tbl'], + $dbh->escapeSimple($pagename)), + DB_FETCHMODE_ASSOC); return $result ? $this->_extract_page_data($result) : false; } - function _extract_page_data($data) { + function _extract_page_data($data) + { if (empty($data)) return array(); - elseif (empty($data['pagedata'])) return $data; - else { + elseif (empty($data['pagedata'])) return $data; else { $data = array_merge($data, $this->_unserialize($data['pagedata'])); unset($data['pagedata']); return $data; } } - function update_pagedata($pagename, $newdata) { + function update_pagedata($pagename, $newdata) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; @@ -180,7 +188,7 @@ extends WikiDB_backend // have a record in the page table. Since it's just the // hit count, who cares? $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'", - $newdata['hits'], $dbh->escapeSimple($pagename))); + $newdata['hits'], $dbh->escapeSimple($pagename))); return; } @@ -214,29 +222,32 @@ extends WikiDB_backend $dbh->escapeSimple($pagename))); */ $dbh->query("UPDATE $page_tbl" - . " SET hits=?, pagedata=?" - . " WHERE pagename=?", - array($hits, $this->_serialize($data), $pagename)); + . " SET hits=?, pagedata=?" + . " WHERE pagename=?", + array($hits, $this->_serialize($data), $pagename)); $this->unlock(array($page_tbl)); } - function get_cached_html($pagename) { + function get_cached_html($pagename) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; return $dbh->GetOne(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename='%s'", - $dbh->escapeSimple($pagename))); + $dbh->escapeSimple($pagename))); } - function set_cached_html($pagename, $data) { + function set_cached_html($pagename, $data) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; $dbh->query("UPDATE $page_tbl" - . " SET cached_html=?" - . " WHERE pagename=?", - array($data, $pagename)); + . " SET cached_html=?" + . " WHERE pagename=?", + array($data, $pagename)); } - function _get_pageid($pagename, $create_if_missing = false) { + function _get_pageid($pagename, $create_if_missing = false) + { // check id_cache global $request; @@ -247,14 +258,14 @@ extends WikiDB_backend } } - // attributes play this game. + // attributes play this game. if ($pagename === '') return 0; $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'", - $dbh->escapeSimple($pagename)); + $dbh->escapeSimple($pagename)); if (!$create_if_missing) return $dbh->getOne($query); @@ -267,41 +278,43 @@ extends WikiDB_backend // requires createSequence and on mysql lock the interim table ->getSequenceName //$id = $dbh->nextId($page_tbl . "_id"); $dbh->query(sprintf("INSERT INTO $page_tbl" - . " (id,pagename,hits)" - . " VALUES (%d,'%s',0)", - $id, $dbh->escapeSimple($pagename))); + . " (id,pagename,hits)" + . " VALUES (%d,'%s',0)", + $id, $dbh->escapeSimple($pagename))); $this->unlock(array($page_tbl)); } return $id; } - function get_latest_version($pagename) { + function get_latest_version($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); return (int)$dbh->getOne(sprintf("SELECT latestversion" - . " FROM $page_tbl, $recent_tbl" - . " WHERE $page_tbl.id=$recent_tbl.id" - . " AND pagename='%s'", - $dbh->escapeSimple($pagename))); + . " FROM $page_tbl, $recent_tbl" + . " WHERE $page_tbl.id=$recent_tbl.id" + . " AND pagename='%s'", + $dbh->escapeSimple($pagename))); } - function get_previous_version($pagename, $version) { + function get_previous_version($pagename, $version) + { $dbh = &$this->_dbh; extract($this->_table_names); return (int)$dbh->getOne(sprintf("SELECT version" - . " FROM $version_tbl, $page_tbl" - . " WHERE $version_tbl.id=$page_tbl.id" - . " AND pagename='%s'" - . " AND version < %d" - . " ORDER BY version DESC", - /* Non portable and useless anyway with getOne - . " LIMIT 1", - */ - $dbh->escapeSimple($pagename), - $version)); + . " FROM $version_tbl, $page_tbl" + . " WHERE $version_tbl.id=$page_tbl.id" + . " AND pagename='%s'" + . " AND version < %d" + . " ORDER BY version DESC", + /* Non portable and useless anyway with getOne + . " LIMIT 1", + */ + $dbh->escapeSimple($pagename), + $version)); } /** @@ -312,7 +325,8 @@ extends WikiDB_backend * @return hash The version data, or false if specified version does not * exist. */ - function get_versiondata($pagename, $version, $want_content = false) { + function get_versiondata($pagename, $version, $want_content = false) + { $dbh = &$this->_dbh; extract($this->_table_names); extract($this->_expressions); @@ -326,25 +340,25 @@ extends WikiDB_backend $fields = $this->page_tbl_fields . ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields; - } - else { + } else { $fields = $this->page_tbl_fields . "," . "mtime, minor_edit, versiondata," . "$iscontent AS have_content"; } $result = $dbh->getRow(sprintf("SELECT $fields" - . " FROM $page_tbl, $version_tbl" - . " WHERE $page_tbl.id=$version_tbl.id" - . " AND pagename='%s'" - . " AND version=%d", - $dbh->escapeSimple($pagename), $version), - DB_FETCHMODE_ASSOC); + . " FROM $page_tbl, $version_tbl" + . " WHERE $page_tbl.id=$version_tbl.id" + . " AND pagename='%s'" + . " AND version=%d", + $dbh->escapeSimple($pagename), $version), + DB_FETCHMODE_ASSOC); return $this->_extract_version_data($result); } - function _extract_version_data($query_result) { + function _extract_version_data($query_result) + { if (!$query_result) return false; @@ -363,8 +377,7 @@ extends WikiDB_backend if (isset($query_result['content'])) $data['%content'] = $query_result['content']; elseif ($query_result['have_content']) - $data['%content'] = true; - else + $data['%content'] = true; else $data['%content'] = ''; // FIXME: this is ugly. @@ -382,11 +395,12 @@ extends WikiDB_backend /** * Create a new revision of a page. */ - function set_versiondata($pagename, $version, $data) { + function set_versiondata($pagename, $version, $data) + { $dbh = &$this->_dbh; $version_tbl = $this->_table_names['version_tbl']; - $minor_edit = (int) !empty($data['is_minor_edit']); + $minor_edit = (int)!empty($data['is_minor_edit']); unset($data['is_minor_edit']); $mtime = (int)$data['mtime']; @@ -402,14 +416,14 @@ extends WikiDB_backend $id = $this->_get_pageid($pagename, true); $dbh->query(sprintf("DELETE FROM $version_tbl" - . " WHERE id=%d AND version=%d", - $id, $version)); + . " WHERE id=%d AND version=%d", + $id, $version)); // generic slow PearDB bind eh quoting. $dbh->query("INSERT INTO $version_tbl" - . " (id,version,mtime,minor_edit,content,versiondata)" - . " VALUES(?, ?, ?, ?, ?, ?)", - array($id, $version, $mtime, $minor_edit, $content, - $this->_serialize($data))); + . " (id,version,mtime,minor_edit,content,versiondata)" + . " VALUES(?, ?, ?, ?, ?, ?)", + array($id, $version, $mtime, $minor_edit, $content, + $this->_serialize($data))); $this->_update_recent_table($id); $this->_update_nonempty_table($id); @@ -420,14 +434,15 @@ extends WikiDB_backend /** * Delete an old revision of a page. */ - function delete_versiondata($pagename, $version) { + function delete_versiondata($pagename, $version) + { $dbh = &$this->_dbh; extract($this->_table_names); $this->lock(); - if ( ($id = $this->_get_pageid($pagename)) ) { + if (($id = $this->_get_pageid($pagename))) { $dbh->query("DELETE FROM $version_tbl" - . " WHERE id=$id AND version=$version"); + . " WHERE id=$id AND version=$version"); $this->_update_recent_table($id); // This shouldn't be needed (as long as the latestversion @@ -464,12 +479,13 @@ extends WikiDB_backend * Delete page completely from the database. * I'm not sure if this is what we want. Maybe just delete the revisions */ - function purge_page($pagename) { + function purge_page($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); $this->lock(); - if ( ($id = $this->_get_pageid($pagename, false)) ) { + if (($id = $this->_get_pageid($pagename, false))) { $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id"); $dbh->query("DELETE FROM $recent_tbl WHERE id=$id"); $dbh->query("DELETE FROM $version_tbl WHERE id=$id"); @@ -480,8 +496,7 @@ extends WikiDB_backend // altogether. $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id"); $result = 0; - } - else { + } else { $dbh->query("DELETE FROM $page_tbl WHERE id=$id"); $result = 1; } @@ -500,7 +515,8 @@ extends WikiDB_backend //function update_versiondata($pagename, $version, $data) { //} - function set_links($pagename, $links) { + function set_links($pagename, $links) + { // Update link table. // FIXME: optimize: mysql can do this all in one big INSERT. @@ -511,8 +527,8 @@ extends WikiDB_backend $pageid = $this->_get_pageid($pagename, true); $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid"); - if ($links) { - $linkseen = array(); + if ($links) { + $linkseen = array(); foreach ($links as $link) { $linkto = $link['linkto']; if ($linkto === "") { // ignore attributes @@ -528,17 +544,17 @@ extends WikiDB_backend if (!$relation) $linkseen[$linkto] = true; $linkid = $this->_get_pageid($linkto, true); - if (!$linkid) { - echo("No link for $linkto on page $pagename"); - //printSimpleTrace(debug_backtrace()); - trigger_error("No link for $linkto on page $pagename"); + if (!$linkid) { + echo("No link for $linkto on page $pagename"); + //printSimpleTrace(debug_backtrace()); + trigger_error("No link for $linkto on page $pagename"); } assert($linkid); $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto, relation)" - . " VALUES ($pageid, $linkid, $relation)"); + . " VALUES ($pageid, $linkid, $relation)"); } - unset($linkseen); - } + unset($linkseen); + } $this->unlock(); } @@ -549,23 +565,23 @@ extends WikiDB_backend * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next * if (isset($next['linkrelation'])) */ - function get_links($pagename, $reversed=true, $include_empty=false, - $sortby='', $limit='', $exclude='', + function get_links($pagename, $reversed = true, $include_empty = false, + $sortby = '', $limit = '', $exclude = '', $want_relations = false) { $dbh = &$this->_dbh; extract($this->_table_names); if ($reversed) - list($have,$want) = array('linkee', 'linker'); + list($have, $want) = array('linkee', 'linker'); else - list($have,$want) = array('linker', 'linkee'); + list($have, $want) = array('linker', 'linkee'); $orderby = $this->sortby($sortby, 'db', array('pagename')); if ($orderby) $orderby = " ORDER BY $want." . $orderby; if ($exclude) // array of pagenames - $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND $want.pagename NOT IN " . $this->_sql_set($exclude); else - $exclude=''; + $exclude = ''; $qpagename = $dbh->escapeSimple($pagename); $sql = "SELECT $want.id AS id, $want.pagename AS pagename, " @@ -582,7 +598,7 @@ extends WikiDB_backend . $orderby; if ($limit) { // extract from,count from limit - list($from,$count) = $this->limit($limit); + list($from, $count) = $this->limit($limit); $result = $dbh->limitQuery($sql, $from, $count); } else { $result = $dbh->query($sql); @@ -594,7 +610,8 @@ extends WikiDB_backend /** * Find if a page links to another page */ - function exists_link($pagename, $link, $reversed=false) { + function exists_link($pagename, $link, $reversed = false) + { $dbh = &$this->_dbh; extract($this->_table_names); @@ -605,22 +622,23 @@ extends WikiDB_backend $qpagename = $dbh->escapeSimple($pagename); $qlink = $dbh->escapeSimple($link); $row = $dbh->GetRow("SELECT CASE WHEN $want.pagename='$qlink' THEN 1 ELSE 0 END as result" - . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl" - . " WHERE linkfrom=linker.id AND linkto=linkee.id" - . " AND $have.pagename='$qpagename'" - . " AND $want.pagename='$qlink'"); + . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl" + . " WHERE linkfrom=linker.id AND linkto=linkee.id" + . " AND $have.pagename='$qpagename'" + . " AND $want.pagename='$qlink'"); return $row['result']; } - function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') { + function get_all_pages($include_empty = false, $sortby = '', $limit = '', $exclude = '') + { $dbh = &$this->_dbh; extract($this->_table_names); $orderby = $this->sortby($sortby, 'db'); if ($orderby) $orderby = ' ORDER BY ' . $orderby; if ($exclude) // array of pagenames - $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND $page_tbl.pagename NOT IN " . $this->_sql_set($exclude); else - $exclude=''; + $exclude = ''; if (strstr($orderby, 'mtime ')) { // multiple columns possible if ($include_empty) { @@ -631,8 +649,7 @@ extends WikiDB_backend . " AND $page_tbl.id=$version_tbl.id AND latestversion=version" . $exclude . $orderby; - } - else { + } else { $sql = "SELECT " . $this->page_tbl_fields . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl" @@ -646,11 +663,10 @@ extends WikiDB_backend if ($include_empty) { $sql = "SELECT " . $this->page_tbl_fields - ." FROM $page_tbl" + . " FROM $page_tbl" . ($exclude ? " WHERE $exclude" : '') . $orderby; - } - else { + } else { $sql = "SELECT " . $this->page_tbl_fields . " FROM $nonempty_tbl, $page_tbl" @@ -661,7 +677,7 @@ extends WikiDB_backend } if ($limit && $orderby) { // extract from,count from limit - list($from,$count) = $this->limit($limit); + list($from, $count) = $this->limit($limit); $result = $dbh->limitQuery($sql, $from, $count); $options = array('limit_by_db' => 1); } else { @@ -675,8 +691,8 @@ extends WikiDB_backend * Title search. * Todo: exclude */ - function text_search($search, $fulltext=false, $sortby='', $limit='', - $exclude='') + function text_search($search, $fulltext = false, $sortby = '', $limit = '', + $exclude = '') { $dbh = &$this->_dbh; extract($this->_table_names); @@ -684,7 +700,7 @@ extends WikiDB_backend if ($orderby) $orderby = ' ORDER BY ' . $orderby; //else " ORDER BY rank($field, to_tsquery('$searchon')) DESC"; - $searchclass = get_class($this)."_search"; + $searchclass = get_class($this) . "_search"; // no need to define it everywhere and then fallback. memory! if (!class_exists($searchclass)) $searchclass = "WikiDB_backend_PearDB_search"; @@ -712,12 +728,12 @@ extends WikiDB_backend . " WHERE $join_clause" . " AND ($search_clause)" . $orderby; - if ($limit) { - list($from, $count) = $this->limit($limit); - $result = $dbh->limitQuery($sql, $from, $count); - } else { - $result = $dbh->query($sql); - } + if ($limit) { + list($from, $count) = $this->limit($limit); + $result = $dbh->limitQuery($sql, $from, $count); + } else { + $result = $dbh->query($sql); + } $iter = new WikiDB_backend_PearDB_iter($this, $result); $iter->stoplisted = @$searchobj->stoplisted; @@ -726,7 +742,8 @@ extends WikiDB_backend //Todo: check if the better Mysql MATCH operator is supported, // (ranked search) and also google like expressions. - function _sql_match_clause($word) { + function _sql_match_clause($word) + { $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); $word = $this->_dbh->escapeSimple($word); //$page_tbl = $this->_table_names['page_tbl']; @@ -735,19 +752,25 @@ extends WikiDB_backend // http://bugs.mysql.com/bug.php?id=1491 return "LOWER(pagename) LIKE '%$word%'"; } - function _sql_casematch_clause($word) { + + function _sql_casematch_clause($word) + { $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); $word = $this->_dbh->escapeSimple($word); return "pagename LIKE '%$word%'"; } - function _fullsearch_sql_match_clause($word) { + + function _fullsearch_sql_match_clause($word) + { $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); $word = $this->_dbh->escapeSimple($word); //$page_tbl = $this->_table_names['page_tbl']; //Mysql 4.1.1 has a bug which fails here if word is lowercased. return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'"; } - function _fullsearch_sql_casematch_clause($word) { + + function _fullsearch_sql_casematch_clause($word) + { $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); $word = $this->_dbh->escapeSimple($word); return "pagename LIKE '%$word%' OR content LIKE '%$word%'"; @@ -756,10 +779,11 @@ extends WikiDB_backend /** * Find highest or lowest hit counts. */ - function most_popular($limit=20, $sortby='-hits') { + function most_popular($limit = 20, $sortby = '-hits') + { $dbh = &$this->_dbh; extract($this->_table_names); - if ($limit < 0){ + if ($limit < 0) { $order = "hits ASC"; $limit = -$limit; $where = ""; @@ -781,12 +805,12 @@ extends WikiDB_backend . " WHERE $nonempty_tbl.id=$page_tbl.id" . $where . $orderby; - if ($limit) { - list($from, $count) = $this->limit($limit); - $result = $dbh->limitQuery($sql, $from, $count); - } else { - $result = $dbh->query($sql); - } + if ($limit) { + list($from, $count) = $this->limit($limit); + $result = $dbh->limitQuery($sql, $from, $count); + } else { + $result = $dbh->query($sql); + } return new WikiDB_backend_PearDB_iter($this, $result); } @@ -794,7 +818,8 @@ extends WikiDB_backend /** * Find recent changes. */ - function most_recent($params) { + function most_recent($params) + { $limit = 0; $since = 0; $include_minor_revisions = false; @@ -815,15 +840,13 @@ extends WikiDB_backend $join_clause = "$page_tbl.id=$version_tbl.id"; if ($exclude_major_revisions) { - // Include only minor revisions + // Include only minor revisions $pick[] = "minor_edit <> 0"; - } - elseif (!$include_minor_revisions) { - // Include only major revisions + } elseif (!$include_minor_revisions) { + // Include only major revisions $pick[] = "minor_edit = 0"; } - } - else { + } else { $table = "$page_tbl, $recent_tbl"; $join_clause = "$page_tbl.id=$recent_tbl.id"; $table .= ", $version_tbl"; @@ -832,18 +855,16 @@ extends WikiDB_backend if ($exclude_major_revisions) { // Include only most recent minor revision $pick[] = 'version=latestminor'; - } - elseif (!$include_minor_revisions) { + } elseif (!$include_minor_revisions) { // Include only most recent major revision $pick[] = 'version=latestmajor'; - } - else { + } else { // Include only the latest revision (whether major or minor). - $pick[] ='version=latestversion'; + $pick[] = 'version=latestversion'; } } $order = "DESC"; - if($limit < 0){ + if ($limit < 0) { $order = "ASC"; $limit = -$limit; } @@ -854,13 +875,13 @@ extends WikiDB_backend // FIXME: use SQL_BUFFER_RESULT for mysql? $sql = "SELECT " - . $this->page_tbl_fields . ", " . $this->version_tbl_fields - . " FROM $table" - . " WHERE $where_clause" - . " ORDER BY mtime $order"; + . $this->page_tbl_fields . ", " . $this->version_tbl_fields + . " FROM $table" + . " WHERE $where_clause" + . " ORDER BY mtime $order"; if ($limit) { - list($from, $count) = $this->limit($limit); - $result = $dbh->limitQuery($sql, $from, $count); + list($from, $count) = $this->limit($limit); + $result = $dbh->limitQuery($sql, $from, $count); } else { $result = $dbh->query($sql); } @@ -870,22 +891,23 @@ extends WikiDB_backend /** * Find referenced empty pages. */ - function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') { + function wanted_pages($exclude_from = '', $exclude = '', $sortby = '', $limit = '') + { $dbh = &$this->_dbh; extract($this->_table_names); - if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom'))) + if ($orderby = $this->sortby($sortby, 'db', array('pagename', 'wantedfrom'))) $orderby = 'ORDER BY ' . $orderby; if ($exclude_from) // array of pagenames - $exclude_from = " AND pp.pagename NOT IN ".$this->_sql_set($exclude_from); + $exclude_from = " AND pp.pagename NOT IN " . $this->_sql_set($exclude_from); if ($exclude) // array of pagenames - $exclude = " AND p.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND p.pagename NOT IN " . $this->_sql_set($exclude); $sql = "SELECT p.pagename, pp.pagename AS wantedfrom" . " FROM $page_tbl p, $link_tbl linked" - . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id" - . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id" + . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id" + . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id" . " WHERE ne.id IS NULL" - . " AND p.id = linked.linkfrom" + . " AND p.id = linked.linkfrom" . $exclude_from . $exclude . $orderby; @@ -899,23 +921,25 @@ extends WikiDB_backend return new WikiDB_backend_PearDB_generic_iter($this, $result); } - function _sql_set(&$pagenames) { + function _sql_set(&$pagenames) + { $s = '('; foreach ($pagenames as $p) { - $s .= ("'".$this->_dbh->escapeSimple($p)."',"); + $s .= ("'" . $this->_dbh->escapeSimple($p) . "',"); } - return substr($s,0,-1).")"; + return substr($s, 0, -1) . ")"; } /** * Rename page in the database. */ - function rename_page ($pagename, $to) { + function rename_page($pagename, $to) + { $dbh = &$this->_dbh; extract($this->_table_names); $this->lock(); - if (($id = $this->_get_pageid($pagename, false)) ) { + if (($id = $this->_get_pageid($pagename, false))) { if ($new = $this->_get_pageid($to, false)) { // Cludge Alert! // This page does not exist (already verified before), but exists in the page table. @@ -929,13 +953,14 @@ extends WikiDB_backend $dbh->query("DELETE FROM $page_tbl WHERE id=$new"); } $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id", - $dbh->escapeSimple($to))); + $dbh->escapeSimple($to))); } $this->unlock(); return $id; } - function _update_recent_table($pageid = false) { + function _update_recent_table($pageid = false) + { $dbh = &$this->_dbh; extract($this->_table_names); extract($this->_expressions); @@ -944,17 +969,18 @@ extends WikiDB_backend $this->lock(); $dbh->query("DELETE FROM $recent_tbl" - . ( $pageid ? " WHERE id=$pageid" : "")); - $dbh->query( "INSERT INTO $recent_tbl" - . " (id, latestversion, latestmajor, latestminor)" - . " SELECT id, $maxversion, $maxmajor, $maxminor" - . " FROM $version_tbl" - . ( $pageid ? " WHERE id=$pageid" : "") - . " GROUP BY id" ); + . ($pageid ? " WHERE id=$pageid" : "")); + $dbh->query("INSERT INTO $recent_tbl" + . " (id, latestversion, latestmajor, latestminor)" + . " SELECT id, $maxversion, $maxmajor, $maxminor" + . " FROM $version_tbl" + . ($pageid ? " WHERE id=$pageid" : "") + . " GROUP BY id"); $this->unlock(); } - function _update_nonempty_table($pageid = false) { + function _update_nonempty_table($pageid = false) + { $dbh = &$this->_dbh; extract($this->_table_names); @@ -963,16 +989,16 @@ extends WikiDB_backend extract($this->_expressions); $this->lock(); $dbh->query("DELETE FROM $nonempty_tbl" - . ( $pageid ? " WHERE id=$pageid" : "")); + . ($pageid ? " WHERE id=$pageid" : "")); $dbh->query("INSERT INTO $nonempty_tbl (id)" - . " SELECT $recent_tbl.id" - . " FROM $recent_tbl, $version_tbl" - . " WHERE $recent_tbl.id=$version_tbl.id" - . " AND version=latestversion" - // We have some specifics here (Oracle) - //. " AND content<>''" - . " AND content $notempty" - . ( $pageid ? " AND $recent_tbl.id=$pageid" : "")); + . " SELECT $recent_tbl.id" + . " FROM $recent_tbl, $version_tbl" + . " WHERE $recent_tbl.id=$version_tbl.id" + . " AND version=latestversion" + // We have some specifics here (Oracle) + //. " AND content<>''" + . " AND content $notempty" + . ($pageid ? " AND $recent_tbl.id=$pageid" : "")); $this->unlock(); } @@ -985,7 +1011,8 @@ extends WikiDB_backend * * @access protected */ - function lock($tables = false, $write_lock = true) { + function lock($tables = false, $write_lock = true) + { if ($this->_lock_count++ == 0) $this->_lock_tables($write_lock); } @@ -993,7 +1020,8 @@ extends WikiDB_backend /** * Actually lock the required tables. */ - function _lock_tables($write_lock) { + function _lock_tables($write_lock) + { trigger_error("virtual", E_USER_ERROR); } @@ -1007,7 +1035,8 @@ extends WikiDB_backend * * @see _lock_database */ - function unlock($tables = false, $force = false) { + function unlock($tables = false, $force = false) + { if ($this->_lock_count == 0) return; if (--$this->_lock_count <= 0 || $force) { @@ -1019,7 +1048,8 @@ extends WikiDB_backend /** * Actually unlock the required tables. */ - function _unlock_tables($write_lock) { + function _unlock_tables($write_lock) + { trigger_error("virtual", E_USER_ERROR); } @@ -1027,7 +1057,8 @@ extends WikiDB_backend /** * Serialize data */ - function _serialize($data) { + function _serialize($data) + { if (empty($data)) return ''; assert(is_array($data)); @@ -1037,7 +1068,8 @@ extends WikiDB_backend /** * Unserialize data */ - function _unserialize($data) { + function _unserialize($data) + { return empty($data) ? array() : unserialize($data); } @@ -1048,11 +1080,12 @@ extends WikiDB_backend * * @param A PEAR_error object. */ - function _pear_error_callback($error) { + function _pear_error_callback($error) + { if ($this->_is_false_error($error)) return; - $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops. + $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops. $this->close(); trigger_error($this->_pear_error_message($error), E_USER_ERROR); } @@ -1068,20 +1101,22 @@ extends WikiDB_backend * @access private * @return bool True iff error is not really an error. */ - function _is_false_error($error) { + function _is_false_error($error) + { if ($error->getCode() != DB_ERROR) return false; $query = $this->_dbh->last_query; - if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE' - . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) { + if (!preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE' + . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query) + ) { // Last query was not of the sort which doesn't return any data. //" <--kludge for brain-dead syntax coloring return false; } - if (! in_array('ismanip', get_class_methods('DB'))) { + if (!in_array('ismanip', get_class_methods('DB'))) { // Pear shipped with PHP 4.0.4pl1 (and before, presumably) // does not have the DB::isManip method. return true; @@ -1096,15 +1131,16 @@ extends WikiDB_backend return true; } - function _pear_error_message($error) { + function _pear_error_message($error) + { $class = get_class($this); $message = "$class: fatal database error\n" - . "\t" . $error->getMessage() . "\n" - . "\t(" . $error->getDebugInfo() . ")\n"; + . "\t" . $error->getMessage() . "\n" + . "\t(" . $error->getDebugInfo() . ")\n"; // Prevent password from being exposed during a connection error $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs', - '\\1:XXXXXXXX', $this->_dsn); + '\\1:XXXXXXXX', $this->_dsn); return str_replace($this->_dsn, $safe_dsn, $message); } @@ -1117,39 +1153,50 @@ extends WikiDB_backend * @see _is_false_error, ErrorManager * @access private */ - function _pear_notice_filter($err) { - return ( $err->isNotice() - && preg_match('|DB[/\\\\]common.php$|', $err->errfile) - && $err->errline == 126 - && preg_match('/Undefined offset: +0\b/', $err->errstr) ); + function _pear_notice_filter($err) + { + return ($err->isNotice() + && preg_match('|DB[/\\\\]common.php$|', $err->errfile) + && $err->errline == 126 + && preg_match('/Undefined offset: +0\b/', $err->errstr)); } /* some variables and functions for DB backend abstraction (action=upgrade) */ - function database () { + function database() + { return $this->_dbh->dsn['database']; } - function backendType() { + + function backendType() + { return $this->_dbh->phptype; } - function connection() { + + function connection() + { return $this->_dbh->connection; } - function getRow($query) { + + function getRow($query) + { return $this->_dbh->getRow($query); } - function listOfTables() { + function listOfTables() + { return $this->_dbh->getListOf('tables'); } - function listOfFields($database,$table) { + + function listOfFields($database, $table) + { if ($this->backendType() == 'mysql') { $fields = array(); assert(!empty($database)); assert(!empty($table)); - $result = mysql_list_fields($database, $table, $this->_dbh->connection) or - trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING); - if (!$result) return array(); - $columns = mysql_num_fields($result); + $result = mysql_list_fields($database, $table, $this->_dbh->connection) or + trigger_error(__FILE__ . ':' . __LINE__ . ' ' . mysql_error(), E_USER_WARNING); + if (!$result) return array(); + $columns = mysql_num_fields($result); for ($i = 0; $i < $columns; $i++) { $fields[] = mysql_field_name($result, $i); } @@ -1161,7 +1208,9 @@ extends WikiDB_backend return false; } } -}; +} + +; /** * This class is a generic iterator. @@ -1176,9 +1225,10 @@ extends WikiDB_backend * @author: Dan Frankowski */ class WikiDB_backend_PearDB_generic_iter -extends WikiDB_backend_iterator + extends WikiDB_backend_iterator { - function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) { + function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) + { if (DB::isError($query_result)) { // This shouldn't happen, I thought. $backend->_pear_error_callback($query_result); @@ -1189,13 +1239,15 @@ extends WikiDB_backend_iterator $this->_options = $field_list; } - function count() { + function count() + { if (!$this->_result) return false; return $this->_result->numRows(); } - function next() { + function next() + { if (!$this->_result) return false; @@ -1208,20 +1260,23 @@ extends WikiDB_backend_iterator return $record; } - function reset () { + function reset() + { if ($this->_result) { $this->_result->MoveFirst(); } } - function free () { + function free() + { if ($this->_result) { $this->_result->free(); $this->_result = false; } } - function asArray () { + function asArray() + { $result = array(); while ($page = $this->next()) $result[] = $page; @@ -1230,10 +1285,11 @@ extends WikiDB_backend_iterator } class WikiDB_backend_PearDB_iter -extends WikiDB_backend_PearDB_generic_iter + extends WikiDB_backend_PearDB_generic_iter { - function next() { + function next() + { $backend = &$this->_backend; if (!$this->_result) return false; @@ -1246,7 +1302,7 @@ extends WikiDB_backend_PearDB_generic_iter $pagedata = $backend->_extract_page_data($record); $rec = array('pagename' => $record['pagename'], - 'pagedata' => $pagedata); + 'pagedata' => $pagedata); if (!empty($record['version'])) { $rec['versiondata'] = $backend->_extract_version_data($record); diff --git a/lib/WikiDB/backend/PearDB_ffpgsql.php b/lib/WikiDB/backend/PearDB_ffpgsql.php index 2159dca69..2c7ba2d03 100644 --- a/lib/WikiDB/backend/PearDB_ffpgsql.php +++ b/lib/WikiDB/backend/PearDB_ffpgsql.php @@ -47,46 +47,51 @@ require_once 'lib/ErrorManager.php'; require_once 'lib/WikiDB/backend/PearDB_pgsql.php'; class WikiDB_backend_PearDB_ffpgsql -extends WikiDB_backend_PearDB_pgsql + extends WikiDB_backend_PearDB_pgsql { - function WikiDB_backend_PearDB_ffpgsql($dbparams) { + function WikiDB_backend_PearDB_ffpgsql($dbparams) + { $dbparams['dsn'] = str_replace('ffpgsql:', 'pgsql:', $dbparams['dsn']); parent::WikiDB_backend_PearDB_pgsql($dbparams); - $p = strlen(PAGE_PREFIX)+1; + $p = strlen(PAGE_PREFIX) + 1; $page_tbl = $this->_table_names['page_tbl']; $this->page_tbl_fields = "$page_tbl.id AS id, substring($page_tbl.pagename from $p) AS pagename, $page_tbl.hits AS hits"; pg_set_client_encoding("iso-8859-1"); } - function get_all_pagenames() { + function get_all_pagenames() + { $dbh = &$this->_dbh; extract($this->_table_names); $pat = PAGE_PREFIX; - $p = strlen($pat)+1; + $p = strlen($pat) + 1; return $dbh->getCol("SELECT substring(pagename from $p)" - . " FROM $nonempty_tbl, $page_tbl" - . " WHERE $nonempty_tbl.id=$page_tbl.id" - . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'"); + . " FROM $nonempty_tbl, $page_tbl" + . " WHERE $nonempty_tbl.id=$page_tbl.id" + . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'"); } - function numPages($filter=false, $exclude='') { + function numPages($filter = false, $exclude = '') + { $dbh = &$this->_dbh; extract($this->_table_names); $pat = PAGE_PREFIX; - $p = strlen($pat)+1; + $p = strlen($pat) + 1; return $dbh->getOne("SELECT count(*)" - . " FROM $nonempty_tbl, $page_tbl" - . " WHERE $nonempty_tbl.id=$page_tbl.id" - . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'"); + . " FROM $nonempty_tbl, $page_tbl" + . " WHERE $nonempty_tbl.id=$page_tbl.id" + . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'"); } - function get_pagedata($pagename) { - return parent::get_pagedata(PAGE_PREFIX.$pagename); + function get_pagedata($pagename) + { + return parent::get_pagedata(PAGE_PREFIX . $pagename); } - function update_pagedata($pagename, $newdata) { + function update_pagedata($pagename, $newdata) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; @@ -95,9 +100,9 @@ extends WikiDB_backend_PearDB_pgsql // Note that this will fail silently if the page does not // have a record in the page table. Since it's just the // hit count, who cares? - $pagename = PAGE_PREFIX.$pagename; + $pagename = PAGE_PREFIX . $pagename; $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'", - $newdata['hits'], $dbh->escapeSimple($pagename))); + $newdata['hits'], $dbh->escapeSimple($pagename))); return; } @@ -109,10 +114,10 @@ extends WikiDB_backend_PearDB_pgsql } if (isset($data['hits'])) { - $hits = (int)$data['hits']; - unset($data['hits']); + $hits = (int)$data['hits']; + unset($data['hits']); } else { - $hits = 0; + $hits = 0; } foreach ($newdata as $key => $val) { @@ -134,23 +139,26 @@ extends WikiDB_backend_PearDB_pgsql $dbh->escapeSimple($this->_serialize($data)), $dbh->escapeSimple($pagename))); */ - $pagename = PAGE_PREFIX.$pagename; + $pagename = PAGE_PREFIX . $pagename; $dbh->query("UPDATE $page_tbl" - . " SET hits=?, pagedata=?" - . " WHERE pagename=?", - array($hits, $this->_serialize($data), $pagename)); + . " SET hits=?, pagedata=?" + . " WHERE pagename=?", + array($hits, $this->_serialize($data), $pagename)); $this->unlock(array($page_tbl)); } - function get_latest_version($pagename) { - return parent::get_latest_version(PAGE_PREFIX.$pagename); + function get_latest_version($pagename) + { + return parent::get_latest_version(PAGE_PREFIX . $pagename); } - function get_previous_version($pagename, $version) { - return parent::get_previous_version(PAGE_PREFIX.$pagename, $version); + function get_previous_version($pagename, $version) + { + return parent::get_previous_version(PAGE_PREFIX . $pagename, $version); } - function get_versiondata($pagename, $version, $want_content = false) { + function get_versiondata($pagename, $version, $want_content = false) + { $dbh = &$this->_dbh; extract($this->_table_names); extract($this->_expressions); @@ -164,34 +172,36 @@ extends WikiDB_backend_PearDB_pgsql $fields = $this->page_tbl_fields . ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields; - } - else { + } else { $fields = $this->page_tbl_fields . "," . "mtime, minor_edit, versiondata," . "$iscontent AS have_content"; } - $pagename = PAGE_PREFIX.$pagename; + $pagename = PAGE_PREFIX . $pagename; $result = $dbh->getRow(sprintf("SELECT $fields" - . " FROM $page_tbl, $version_tbl" - . " WHERE $page_tbl.id=$version_tbl.id" - . " AND pagename='%s'" - . " AND version=%d", - $dbh->escapeSimple($pagename), $version), - DB_FETCHMODE_ASSOC); + . " FROM $page_tbl, $version_tbl" + . " WHERE $page_tbl.id=$version_tbl.id" + . " AND pagename='%s'" + . " AND version=%d", + $dbh->escapeSimple($pagename), $version), + DB_FETCHMODE_ASSOC); return $this->_extract_version_data($result); } - function get_cached_html($pagename) { - return parent::get_cached_html(PAGE_PREFIX.$pagename); + function get_cached_html($pagename) + { + return parent::get_cached_html(PAGE_PREFIX . $pagename); } - function set_cached_html($pagename, $data) { - return parent::set_cached_html(PAGE_PREFIX.$pagename, $data); + function set_cached_html($pagename, $data) + { + return parent::set_cached_html(PAGE_PREFIX . $pagename, $data); } - function _get_pageid($pagename, $create_if_missing = false) { + function _get_pageid($pagename, $create_if_missing = false) + { // check id_cache global $request; @@ -202,15 +212,15 @@ extends WikiDB_backend_PearDB_pgsql } } - // attributes play this game. + // attributes play this game. if ($pagename === '') return 0; $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; - $pagename = PAGE_PREFIX.$pagename; + $pagename = PAGE_PREFIX . $pagename; $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'", - $dbh->escapeSimple($pagename)); + $dbh->escapeSimple($pagename)); if (!$create_if_missing) return $dbh->getOne($query); @@ -223,20 +233,21 @@ extends WikiDB_backend_PearDB_pgsql // requires createSequence and on mysql lock the interim table ->getSequenceName //$id = $dbh->nextId($page_tbl . "_id"); $dbh->query(sprintf("INSERT INTO $page_tbl" - . " (id,pagename,hits)" - . " VALUES (%d,'%s',0)", - $id, $dbh->escapeSimple($pagename))); + . " (id,pagename,hits)" + . " VALUES (%d,'%s',0)", + $id, $dbh->escapeSimple($pagename))); $this->unlock(array($page_tbl)); } return $id; } - function purge_page($pagename) { + function purge_page($pagename) + { $dbh = &$this->_dbh; extract($this->_table_names); $this->lock(); - if ( ($id = $this->_get_pageid($pagename, false)) ) { + if (($id = $this->_get_pageid($pagename, false))) { $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id"); $dbh->query("DELETE FROM $recent_tbl WHERE id=$id"); $dbh->query("DELETE FROM $version_tbl WHERE id=$id"); @@ -247,8 +258,7 @@ extends WikiDB_backend_PearDB_pgsql // altogether. $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id"); $result = 0; - } - else { + } else { $dbh->query("DELETE FROM $page_tbl WHERE id=$id"); $result = 1; } @@ -259,26 +269,26 @@ extends WikiDB_backend_PearDB_pgsql return $result; } - function get_links($pagename, $reversed=true, $include_empty=false, - $sortby='', $limit='', $exclude='', + function get_links($pagename, $reversed = true, $include_empty = false, + $sortby = '', $limit = '', $exclude = '', $want_relations = false) { $dbh = &$this->_dbh; extract($this->_table_names); if ($reversed) - list($have,$want) = array('linkee', 'linker'); + list($have, $want) = array('linkee', 'linker'); else - list($have,$want) = array('linker', 'linkee'); + list($have, $want) = array('linker', 'linkee'); $orderby = $this->sortby($sortby, 'db', array('pagename')); if ($orderby) $orderby = " ORDER BY $want." . $orderby; if ($exclude) // array of pagenames - $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND $want.pagename NOT IN " . $this->_sql_set($exclude); else - $exclude=''; + $exclude = ''; $pat = PAGE_PREFIX; - $p = strlen($pat)+1; + $p = strlen($pat) + 1; $qpagename = $dbh->escapeSimple($pagename); // MeV+APe 2007-11-14 @@ -298,7 +308,7 @@ extends WikiDB_backend_PearDB_pgsql . $orderby; if ($limit) { // extract from,count from limit - list($from,$count) = $this->limit($limit); + list($from, $count) = $this->limit($limit); $result = $dbh->limitQuery($sql, $from, $count); } else { $result = $dbh->query($sql); @@ -307,19 +317,20 @@ extends WikiDB_backend_PearDB_pgsql return new WikiDB_backend_PearDB_iter($this, $result); } - function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') { + function get_all_pages($include_empty = false, $sortby = '', $limit = '', $exclude = '') + { $dbh = &$this->_dbh; extract($this->_table_names); $pat = PAGE_PREFIX; - $p = strlen($pat)+1; + $p = strlen($pat) + 1; $orderby = $this->sortby($sortby, 'db'); if ($orderby) $orderby = ' ORDER BY ' . $orderby; if ($exclude) // array of pagenames - $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND $page_tbl.pagename NOT IN " . $this->_sql_set($exclude); else - $exclude=''; + $exclude = ''; if (strstr($orderby, 'mtime ')) { // multiple columns possible if ($include_empty) { @@ -331,8 +342,7 @@ extends WikiDB_backend_PearDB_pgsql . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'" . $exclude . $orderby; - } - else { + } else { $sql = "SELECT " . $this->page_tbl_fields . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl" @@ -350,10 +360,9 @@ extends WikiDB_backend_PearDB_pgsql . " FROM $page_tbl" . ($exclude ? " WHERE $exclude" : '') . ($exclude ? " AND " : " WHERE ") - . " substring($page_tbl.pagename from 0 for $p) = '$pat'" + . " substring($page_tbl.pagename from 0 for $p) = '$pat'" . $orderby; - } - else { + } else { $sql = "SELECT " . $this->page_tbl_fields . " FROM $nonempty_tbl, $page_tbl" @@ -365,7 +374,7 @@ extends WikiDB_backend_PearDB_pgsql } if ($limit && $orderby) { // extract from,count from limit - list($from,$count) = $this->limit($limit); + list($from, $count) = $this->limit($limit); $result = $dbh->limitQuery($sql, $from, $count); $options = array('limit_by_db' => 1); } else { @@ -375,12 +384,13 @@ extends WikiDB_backend_PearDB_pgsql return new WikiDB_backend_PearDB_iter($this, $result, $options); } - function most_popular($limit=20, $sortby='-hits') { + function most_popular($limit = 20, $sortby = '-hits') + { $dbh = &$this->_dbh; extract($this->_table_names); $pat = PAGE_PREFIX; - $p = strlen($pat)+1; - if ($limit < 0){ + $p = strlen($pat) + 1; + if ($limit < 0) { $order = "hits ASC"; $limit = -$limit; $where = ""; @@ -403,17 +413,18 @@ extends WikiDB_backend_PearDB_pgsql . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'" . $where . $orderby; - if ($limit) { - list($from, $count) = $this->limit($limit); - $result = $dbh->limitQuery($sql, $from, $count); - } else { - $result = $dbh->query($sql); - } + if ($limit) { + list($from, $count) = $this->limit($limit); + $result = $dbh->limitQuery($sql, $from, $count); + } else { + $result = $dbh->query($sql); + } return new WikiDB_backend_PearDB_iter($this, $result); } - function most_recent($params) { + function most_recent($params) + { $limit = 0; $since = 0; $include_minor_revisions = false; @@ -434,15 +445,13 @@ extends WikiDB_backend_PearDB_pgsql $join_clause = "$page_tbl.id=$version_tbl.id"; if ($exclude_major_revisions) { - // Include only minor revisions + // Include only minor revisions $pick[] = "minor_edit <> 0"; - } - elseif (!$include_minor_revisions) { - // Include only major revisions + } elseif (!$include_minor_revisions) { + // Include only major revisions $pick[] = "minor_edit = 0"; } - } - else { + } else { $table = "$page_tbl, $recent_tbl"; $join_clause = "$page_tbl.id=$recent_tbl.id"; $table .= ", $version_tbl"; @@ -451,18 +460,16 @@ extends WikiDB_backend_PearDB_pgsql if ($exclude_major_revisions) { // Include only most recent minor revision $pick[] = 'version=latestminor'; - } - elseif (!$include_minor_revisions) { + } elseif (!$include_minor_revisions) { // Include only most recent major revision $pick[] = 'version=latestmajor'; - } - else { + } else { // Include only the latest revision (whether major or minor). - $pick[] ='version=latestversion'; + $pick[] = 'version=latestversion'; } } $order = "DESC"; - if($limit < 0){ + if ($limit < 0) { $order = "ASC"; $limit = -$limit; } @@ -472,46 +479,47 @@ extends WikiDB_backend_PearDB_pgsql $where_clause .= " AND " . join(" AND ", $pick); $pat = PAGE_PREFIX; - $p = strlen($pat)+1; + $p = strlen($pat) + 1; // FIXME: use SQL_BUFFER_RESULT for mysql? $sql = "SELECT " - . $this->page_tbl_fields . ", " . $this->version_tbl_fields - . " FROM $table" - . " WHERE $where_clause" - . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'" - . " ORDER BY mtime $order"; + . $this->page_tbl_fields . ", " . $this->version_tbl_fields + . " FROM $table" + . " WHERE $where_clause" + . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'" + . " ORDER BY mtime $order"; if ($limit) { - list($from, $count) = $this->limit($limit); - $result = $dbh->limitQuery($sql, $from, $count); + list($from, $count) = $this->limit($limit); + $result = $dbh->limitQuery($sql, $from, $count); } else { $result = $dbh->query($sql); } return new WikiDB_backend_PearDB_iter($this, $result); } - function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') { + function wanted_pages($exclude_from = '', $exclude = '', $sortby = '', $limit = '') + { $dbh = &$this->_dbh; extract($this->_table_names); $pat = PAGE_PREFIX; - $p = strlen($pat)+1; - if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom'))) + $p = strlen($pat) + 1; + if ($orderby = $this->sortby($sortby, 'db', array('pagename', 'wantedfrom'))) $orderby = 'ORDER BY ' . $orderby; if ($exclude_from) // array of pagenames - $exclude_from = " AND pp.pagename NOT IN ".$this->_sql_set($exclude_from); + $exclude_from = " AND pp.pagename NOT IN " . $this->_sql_set($exclude_from); if ($exclude) // array of pagenames - $exclude = " AND p.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND p.pagename NOT IN " . $this->_sql_set($exclude); - $p = strlen(PAGE_PREFIX)+1; + $p = strlen(PAGE_PREFIX) + 1; $sql = "SELECT substring(p.pagename from $p) AS wantedfrom, substring(pp.pagename from $p) AS pagename" . " FROM $page_tbl p, $link_tbl linked" - . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id" - . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id" + . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id" + . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id" . " WHERE ne.id IS NULL" - . " AND p.id = linked.linkfrom" - . " AND substring(p.pagename from 0 for $p) = '$pat'" - . " AND substring(pp.pagename from 0 for $p) = '$pat'" + . " AND p.id = linked.linkfrom" + . " AND substring(p.pagename from 0 for $p) = '$pat'" + . " AND substring(pp.pagename from 0 for $p) = '$pat'" . $exclude_from . $exclude . $orderby; @@ -525,12 +533,13 @@ extends WikiDB_backend_PearDB_pgsql return new WikiDB_backend_PearDB_generic_iter($this, $result); } - function rename_page ($pagename, $to) { + function rename_page($pagename, $to) + { $dbh = &$this->_dbh; extract($this->_table_names); $this->lock(); - if (($id = $this->_get_pageid($pagename, false)) ) { + if (($id = $this->_get_pageid($pagename, false))) { if ($new = $this->_get_pageid($to, false)) { // Cludge Alert! // This page does not exist (already verified before), but exists in the page table. @@ -544,21 +553,24 @@ extends WikiDB_backend_PearDB_pgsql $dbh->query("DELETE FROM $page_tbl WHERE id=$new"); } $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id", - $dbh->escapeSimple(PAGE_PREFIX.$to))); + $dbh->escapeSimple(PAGE_PREFIX . $to))); } $this->unlock(); return $id; } - function is_wiki_page($pagename) { - return parent::is_wiki_page(PAGE_PREFIX.$pagename); + function is_wiki_page($pagename) + { + return parent::is_wiki_page(PAGE_PREFIX . $pagename); } - function increaseHitCount($pagename) { - return parent::increaseHitCount(PAGE_PREFIX.$pagename); + function increaseHitCount($pagename) + { + return parent::increaseHitCount(PAGE_PREFIX . $pagename); } - function _serialize($data) { + function _serialize($data) + { return WikiDB_backend_PearDB::_serialize($data); } @@ -566,24 +578,25 @@ extends WikiDB_backend_PearDB_pgsql * Pack tables. * NOTE: Disable vacuum, wikiuser is not the table owner */ - function optimize() { + function optimize() + { return 0; } /** * Title search. */ - function text_search($search, $fulltext=false, $sortby='', $limit='', - $exclude='') + function text_search($search, $fulltext = false, $sortby = '', $limit = '', + $exclude = '') { $dbh = &$this->_dbh; extract($this->_table_names); $pat = PAGE_PREFIX; - $len = strlen($pat)+1; + $len = strlen($pat) + 1; $orderby = $this->sortby($sortby, 'db'); if ($sortby and $orderby) $orderby = ' ORDER BY ' . $orderby; - $searchclass = get_class($this)."_search"; + $searchclass = get_class($this) . "_search"; // no need to define it everywhere and then fallback. memory! if (!class_exists($searchclass)) $searchclass = "WikiDB_backend_PearDB_search"; @@ -601,7 +614,7 @@ extends WikiDB_backend_PearDB_pgsql $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version"; $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields; - // TODO: title still ignored, need better rank and subselect + // TODO: title still ignored, need better rank and subselect $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause"); $search_string = $search->makeTsearch2SqlClauseObj($callback); $search_string = str_replace('%', '', $search_string); @@ -609,7 +622,7 @@ extends WikiDB_backend_PearDB_pgsql $search_clause .= "idxFTI @@ to_tsquery('$search_string')"; if (!$orderby) - $orderby = " ORDER BY ts_rank(idxFTI, to_tsquery('$search_string')) DESC"; + $orderby = " ORDER BY ts_rank(idxFTI, to_tsquery('$search_string')) DESC"; } else { $callback = new WikiMethodCb($searchobj, "_pagename_match_clause"); $search_clause = "substring(plugin_wiki_page.pagename from 0 for $len) = '$pat') AND ("; @@ -620,54 +633,58 @@ extends WikiDB_backend_PearDB_pgsql . " WHERE $join_clause" . " AND ($search_clause)" . $orderby; - if ($limit) { - list($from, $count) = $this->limit($limit); - $result = $dbh->limitQuery($sql, $from, $count); - } else { - $result = $dbh->query($sql); - } + if ($limit) { + list($from, $count) = $this->limit($limit); + $result = $dbh->limitQuery($sql, $from, $count); + } else { + $result = $dbh->query($sql); + } $iter = new WikiDB_backend_PearDB_iter($this, $result); $iter->stoplisted = @$searchobj->stoplisted; return $iter; } - function exists_link($pagename, $link, $reversed=false) { - $dbh = &$this->_dbh; - extract($this->_table_names); - - if ($reversed) - list($have, $want) = array('linkee', 'linker'); - else - list($have, $want) = array('linker', 'linkee'); - $qpagename = $dbh->escapeSimple($pagename); - $qlink = $dbh->escapeSimple($link); - $row = $dbh->GetRow("SELECT $want.pagename as result" - . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl" - . " WHERE linkfrom=linker.id AND linkto=linkee.id" - . " AND $have.pagename='$qpagename'" - . " AND $want.pagename='$qlink'" - . " LIMIT 1"); - return $row['result'] ? 1 : 0; - } -}; + function exists_link($pagename, $link, $reversed = false) + { + $dbh = &$this->_dbh; + extract($this->_table_names); + + if ($reversed) + list($have, $want) = array('linkee', 'linker'); + else + list($have, $want) = array('linker', 'linkee'); + $qpagename = $dbh->escapeSimple($pagename); + $qlink = $dbh->escapeSimple($link); + $row = $dbh->GetRow("SELECT $want.pagename as result" + . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl" + . " WHERE linkfrom=linker.id AND linkto=linkee.id" + . " AND $have.pagename='$qpagename'" + . " AND $want.pagename='$qlink'" + . " LIMIT 1"); + return $row['result'] ? 1 : 0; + } +} + +; class WikiDB_backend_PearDB_ffpgsql_search -extends WikiDB_backend_PearDB_pgsql_search + extends WikiDB_backend_PearDB_pgsql_search { - function _pagename_match_clause($node) { + function _pagename_match_clause($node) + { $word = $node->sql(); // @alu: use _quote maybe instead of direct pg_escape_string $word = pg_escape_string($word); - $len = strlen(PAGE_PREFIX)+1; + $len = strlen(PAGE_PREFIX) + 1; if ($node->op == 'REGEX') { // posix regex extensions return ($this->_case_exact - ? "substring(pagename from $len) ~* '$word'" - : "substring(pagename from $len) ~ '$word'"); + ? "substring(pagename from $len) ~* '$word'" + : "substring(pagename from $len) ~ '$word'"); } else { return ($this->_case_exact - ? "substring(pagename from $len) LIKE '$word'" - : "substring(pagename from $len) ILIKE '$word'"); + ? "substring(pagename from $len) LIKE '$word'" + : "substring(pagename from $len) ILIKE '$word'"); } } @@ -686,7 +703,8 @@ extends WikiDB_backend_PearDB_pgsql_search The full-text index will still be used, and the regex will be used to prune the results afterwards. */ - function _fulltext_match_clause($node) { + function _fulltext_match_clause($node) + { $word = strtolower($node->word); // $word = str_replace(" ", "&", $word); // phrase fix diff --git a/lib/WikiDB/backend/PearDB_mysql.php b/lib/WikiDB/backend/PearDB_mysql.php index 56cec063b..0c0597108 100644 --- a/lib/WikiDB/backend/PearDB_mysql.php +++ b/lib/WikiDB/backend/PearDB_mysql.php @@ -7,20 +7,21 @@ require_once 'lib/WikiDB/backend/PearDB.php'; // The slowest function overall is mysql_connect with [680ms] // 2nd is db_mysql::simpleQuery with [257ms] class WikiDB_backend_PearDB_mysql -extends WikiDB_backend_PearDB + extends WikiDB_backend_PearDB { /** * Constructor. */ - function WikiDB_backend_PearDB_mysql($dbparams) { + function WikiDB_backend_PearDB_mysql($dbparams) + { $this->WikiDB_backend_PearDB($dbparams); if (DB::isError($this->_dbh)) return; //$this->_serverinfo = $this->_dbh->ServerInfo(); $row = $this->_dbh->GetOne("SELECT version()"); if (!DB::isError($row) and !empty($row)) { - $arr = explode('.',$row); + $arr = explode('.', $row); $this->_serverinfo['version'] = (string)(($arr[0] * 100) + $arr[1]) . - "." . (integer)$arr[2]; + "." . (integer)$arr[2]; if ($this->_serverinfo['version'] < 323.0) { // Older MySQL's don't have CASE WHEN ... END $this->_expressions['maxmajor'] = "MAX(IF(minor_edit=0,version,0))"; @@ -30,11 +31,11 @@ extends WikiDB_backend_PearDB if ($this->_serverinfo['version'] > 401.0) { global $charset; $aliases = array('iso-8859-1' => 'latin1', - 'utf-8' => 'utf8'); + 'utf-8' => 'utf8'); //http://dev.mysql.com/doc/mysql/en/charset-connection.html if (isset($aliases[strtolower($charset)])) { // mysql needs special unusual names and doesn't resolve aliases - mysql_query("SET NAMES '". $aliases[strtolower($charset)] . "'"); + mysql_query("SET NAMES '" . $aliases[strtolower($charset)] . "'"); } else { mysql_query("SET NAMES '$charset'"); } @@ -45,36 +46,38 @@ extends WikiDB_backend_PearDB /** * Kill timed out processes. ( so far only called on about every 50-th save. ) */ - function _timeout() { + function _timeout() + { if (empty($this->_dbparams['timeout'])) return; - $result = mysql_query("SHOW processlist"); - while ($row = mysql_fetch_array($result)) { - if ($row["db"] == $this->_dbh->dsn['database'] - and $row["User"] == $this->_dbh->dsn['username'] - and $row["Time"] > $this->_dbparams['timeout'] - and $row["Command"] == "Sleep") - { + $result = mysql_query("SHOW processlist"); + while ($row = mysql_fetch_array($result)) { + if ($row["db"] == $this->_dbh->dsn['database'] + and $row["User"] == $this->_dbh->dsn['username'] + and $row["Time"] > $this->_dbparams['timeout'] + and $row["Command"] == "Sleep" + ) { $process_id = $row["Id"]; mysql_query("KILL $process_id"); + } } } - } /** * Create a new revision of a page. */ - function set_versiondata($pagename, $version, $data) { + function set_versiondata($pagename, $version, $data) + { $dbh = &$this->_dbh; $version_tbl = $this->_table_names['version_tbl']; - $minor_edit = (int) !empty($data['is_minor_edit']); + $minor_edit = (int)!empty($data['is_minor_edit']); unset($data['is_minor_edit']); $mtime = (int)$data['mtime']; unset($data['mtime']); assert(!empty($mtime)); - @$content = (string) $data['%content']; + @$content = (string)$data['%content']; unset($data['%content']); unset($data['%pagedata']); @@ -83,19 +86,20 @@ extends WikiDB_backend_PearDB // requires PRIMARY KEY (id,version)! // VALUES supported since mysql-3.22.5 $dbh->query(sprintf("REPLACE INTO $version_tbl" - . " (id,version,mtime,minor_edit,content,versiondata)" - . " VALUES(%d,%d,%d,%d,'%s','%s')", - $id, $version, $mtime, $minor_edit, - $dbh->escapeSimple($content), - $dbh->escapeSimple($this->_serialize($data)) - )); + . " (id,version,mtime,minor_edit,content,versiondata)" + . " VALUES(%d,%d,%d,%d,'%s','%s')", + $id, $version, $mtime, $minor_edit, + $dbh->escapeSimple($content), + $dbh->escapeSimple($this->_serialize($data)) + )); // real binding (prepare,execute) only since mysqli + PHP5 $this->_update_recent_table($id); $this->_update_nonempty_table($id); $this->unlock(); } - function _update_recent_table($pageid = false) { + function _update_recent_table($pageid = false) + { $dbh = &$this->_dbh; extract($this->_table_names); extract($this->_expressions); @@ -106,31 +110,32 @@ extends WikiDB_backend_PearDB // supported in every (?) mysql version // requires PRIMARY KEY (id)! $dbh->query("REPLACE INTO $recent_tbl" - . " (id, latestversion, latestmajor, latestminor)" - . " SELECT id, $maxversion, $maxmajor, $maxminor" - . " FROM $version_tbl" - . ( $pageid ? " WHERE id=$pageid" : "") - . " GROUP BY id" ); + . " (id, latestversion, latestmajor, latestminor)" + . " SELECT id, $maxversion, $maxmajor, $maxminor" + . " FROM $version_tbl" + . ($pageid ? " WHERE id=$pageid" : "") + . " GROUP BY id"); } /* ISNULL is mysql specific */ - function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') { + function wanted_pages($exclude_from = '', $exclude = '', $sortby = '', $limit = '') + { $dbh = &$this->_dbh; extract($this->_table_names); - if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom'))) + if ($orderby = $this->sortby($sortby, 'db', array('pagename', 'wantedfrom'))) $orderby = 'ORDER BY ' . $orderby; if ($exclude_from) // array of pagenames - $exclude_from = " AND pp.pagename NOT IN ".$this->_sql_set($exclude_from); + $exclude_from = " AND pp.pagename NOT IN " . $this->_sql_set($exclude_from); if ($exclude) // array of pagenames - $exclude = " AND p.pagename NOT IN ".$this->_sql_set($exclude); + $exclude = " AND p.pagename NOT IN " . $this->_sql_set($exclude); $sql = "SELECT p.pagename, pp.pagename as wantedfrom" . " FROM $page_tbl p, $link_tbl linked" . " LEFT JOIN $page_tbl pp ON (linked.linkto = pp.id)" . " LEFT JOIN $nonempty_tbl ne ON (linked.linkto = ne.id)" . " WHERE ISNULL(ne.id)" - . " AND p.id = linked.linkfrom" + . " AND p.id = linked.linkfrom" . $exclude_from . $exclude . $orderby; @@ -166,9 +171,10 @@ extends WikiDB_backend_PearDB /** * Pack tables. */ - function optimize() { + function optimize() + { $dbh = &$this->_dbh; - $this->_timeout(); + $this->_timeout(); foreach ($this->_table_names as $table) { $dbh->query("OPTIMIZE TABLE $table"); } @@ -178,7 +184,8 @@ extends WikiDB_backend_PearDB /** * Lock tables. */ - function _lock_tables($write_lock = true) { + function _lock_tables($write_lock = true) + { $lock_type = $write_lock ? "WRITE" : "READ"; foreach ($this->_table_names as $table) { $tables[] = "$table $lock_type"; @@ -189,11 +196,13 @@ extends WikiDB_backend_PearDB /** * Release all locks. */ - function _unlock_tables() { + function _unlock_tables() + { $this->_dbh->query("UNLOCK TABLES"); } - function increaseHitCount($pagename) { + function increaseHitCount($pagename) + { $dbh = &$this->_dbh; // Hits is the only thing we can update in a fast manner. // Note that this will fail silently if the page does not @@ -201,25 +210,28 @@ extends WikiDB_backend_PearDB // hit count, who cares? // LIMIT since 3.23 $dbh->query(sprintf("UPDATE LOW_PRIORITY %s SET hits=hits+1 WHERE pagename='%s' %s", - $this->_table_names['page_tbl'], - $dbh->escapeSimple($pagename), - ($this->_serverinfo['version'] >= 323.0) ? "LIMIT 1": "")); + $this->_table_names['page_tbl'], + $dbh->escapeSimple($pagename), + ($this->_serverinfo['version'] >= 323.0) ? "LIMIT 1" : "")); return; } -}; +} + +; class WikiDB_backend_PearDB_mysql_search -extends WikiDB_backend_PearDB_search + extends WikiDB_backend_PearDB_search { - function _pagename_match_clause($node) { + function _pagename_match_clause($node) + { $word = $node->sql(); if ($node->op == 'REGEX') { // posix regex extensions return "pagename REGEXP '$word'"; } else { return ($this->_case_exact - ? "pagename LIKE '$word'" - : "LOWER(pagename) LIKE '$word'"); + ? "pagename LIKE '$word'" + : "LOWER(pagename) LIKE '$word'"); } } } diff --git a/lib/WikiDB/backend/PearDB_oci8.php b/lib/WikiDB/backend/PearDB_oci8.php index 5a526fe72..1404bc740 100644 --- a/lib/WikiDB/backend/PearDB_oci8.php +++ b/lib/WikiDB/backend/PearDB_oci8.php @@ -8,12 +8,13 @@ require_once 'lib/WikiDB/backend/PearDB_pgsql.php'; class WikiDB_backend_PearDB_oci8 -extends WikiDB_backend_PearDB_pgsql + extends WikiDB_backend_PearDB_pgsql { /** * Constructor */ - function WikiDB_backend_PearDB_oci8($dbparams) { + function WikiDB_backend_PearDB_oci8($dbparams) + { // Backend constructor $this->WikiDB_backend_PearDB($dbparams); if (DB::isError($this->_dbh)) return; @@ -36,7 +37,8 @@ extends WikiDB_backend_PearDB_pgsql /** * Pack tables. */ - function optimize() { + function optimize() + { // Do nothing here -- Leave that for the DBA // Cost Based Optimizer tuning vary from version to version return 1; @@ -45,7 +47,8 @@ extends WikiDB_backend_PearDB_pgsql /** * Lock all tables we might use. */ - function _lock_tables($write_lock=true) { + function _lock_tables($write_lock = true) + { $dbh = &$this->_dbh; // Not sure if we really need to lock tables here, the Oracle row @@ -63,58 +66,64 @@ extends WikiDB_backend_PearDB_pgsql } } - function _quote($s) { + function _quote($s) + { return base64_encode($s); } - function _unquote($s) { + function _unquote($s) + { return base64_decode($s); } - function write_accesslog(&$entry) { + function write_accesslog(&$entry) + { global $request; $dbh = &$this->_dbh; $log_tbl = $entry->_accesslog->logtable; // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales $dbh->query("INSERT INTO $log_tbl" - . " (time_stamp,remote_host,remote_user,request_method,request_line,request_uri," - . "request_args,request_time,status,bytes_sent,referer,agent,request_duration)" - . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", - array( - // Problem: date formats are backend specific. Either use unixtime as %d (long), - // or the native timestamp format. - date('d-M-Y H:i:s', $entry->time), - $entry->host, - $entry->user, - $entry->request_method, - $entry->request, - $entry->request_uri, - $entry->request_args, - $entry->_ncsa_time($entry->time), - $entry->status, - $entry->size, - $entry->referer, - $entry->user_agent, - $entry->duration)); + . " (time_stamp,remote_host,remote_user,request_method,request_line,request_uri," + . "request_args,request_time,status,bytes_sent,referer,agent,request_duration)" + . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", + array( + // Problem: date formats are backend specific. Either use unixtime as %d (long), + // or the native timestamp format. + date('d-M-Y H:i:s', $entry->time), + $entry->host, + $entry->user, + $entry->request_method, + $entry->request, + $entry->request_uri, + $entry->request_args, + $entry->_ncsa_time($entry->time), + $entry->status, + $entry->size, + $entry->referer, + $entry->user_agent, + $entry->duration)); } -}; +} + +; class WikiDB_backend_PearDB_oci8_search -extends WikiDB_backend_PearDB_search + extends WikiDB_backend_PearDB_search { // If we want case insensitive search, one need to create a Context // Index on the CLOB. While it is very efficient, it requires the // Intermedia Text option, so let's stick to the 'simple' thing // Note that this does only an exact fulltext search, not using MATCH or LIKE. - function _fulltext_match_clause($node) { + function _fulltext_match_clause($node) + { if ($this->isStoplisted($node)) return "1=1"; $page = $node->sql(); $exactword = $node->_sql_quote($node->word); return ($this->_case_exact - ? "pagename LIKE '$page' OR DBMS_LOB.INSTR(content, '$exactword') > 0" - : "LOWER(pagename) LIKE '$page' OR DBMS_LOB.INSTR(content, '$exactword') > 0"); + ? "pagename LIKE '$page' OR DBMS_LOB.INSTR(content, '$exactword') > 0" + : "LOWER(pagename) LIKE '$page' OR DBMS_LOB.INSTR(content, '$exactword') > 0"); } } diff --git a/lib/WikiDB/backend/PearDB_pgsql.php b/lib/WikiDB/backend/PearDB_pgsql.php index c5b00a3f1..2371b909c 100644 --- a/lib/WikiDB/backend/PearDB_pgsql.php +++ b/lib/WikiDB/backend/PearDB_pgsql.php @@ -5,7 +5,7 @@ require_once 'lib/WikiDB/backend/PearDB.php'; if (!defined("USE_BYTEA")) // see schemas/psql-initialize.sql define("USE_BYTEA", true); - //define("USE_BYTEA", false); +//define("USE_BYTEA", false); /* Since 1.3.12 changed to use: @@ -15,9 +15,10 @@ Since 1.3.12 changed to use: */ class WikiDB_backend_PearDB_pgsql -extends WikiDB_backend_PearDB + extends WikiDB_backend_PearDB { - function WikiDB_backend_PearDB_pgsql($dbparams) { + function WikiDB_backend_PearDB_pgsql($dbparams) + { // The pgsql handler of (at least my version of) the PEAR::DB // library generates three warnings when a database is opened: // @@ -30,15 +31,17 @@ extends WikiDB_backend_PearDB // not consequential.) global $ErrorManager; - $ErrorManager->pushErrorHandler(new WikiMethodCb($this,'_pgsql_open_error')); + $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pgsql_open_error')); $this->WikiDB_backend_PearDB($dbparams); $ErrorManager->popErrorHandler(); } - function _pgsql_open_error($error) { + function _pgsql_open_error($error) + { if (preg_match('/^Undefined\s+index:\s+(options|tty|port)/', - $error->errstr)) - return true; // Ignore error + $error->errstr) + ) + return true; // Ignore error return false; } @@ -46,8 +49,9 @@ extends WikiDB_backend_PearDB * Pack tables. * NOTE: Only the table owner can do this. Either fix the schema or setup autovacuum. */ - function optimize() { - return 0; // if the wikiuser is not the table owner + function optimize() + { + return 0; // if the wikiuser is not the table owner foreach ($this->_table_names as $table) { $this->_dbh->query("VACUUM ANALYZE $table"); @@ -55,66 +59,71 @@ extends WikiDB_backend_PearDB return 1; } - function _quote($s) { + function _quote($s) + { if (USE_BYTEA) return pg_escape_bytea($s); - if (function_exists('pg_escape_string')) - return pg_escape_string($s); - else - return base64_encode($s); + if (function_exists('pg_escape_string')) + return pg_escape_string($s); + else + return base64_encode($s); } - function _unquote($s) { + function _unquote($s) + { if (USE_BYTEA) return pg_unescape_bytea($s); - if (function_exists('pg_escape_string')) - return $s; - else - return base64_decode($s); + if (function_exists('pg_escape_string')) + return $s; + else + return base64_decode($s); } // Until the binary escape problems on pear pgsql are solved */ - function get_cached_html($pagename) { + function get_cached_html($pagename) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; $data = $dbh->GetOne(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename='%s'", - $dbh->escapeSimple($pagename))); + $dbh->escapeSimple($pagename))); if ($data) return $this->_unquote($data); else return ''; } - function set_cached_html($pagename, $data) { + function set_cached_html($pagename, $data) + { $dbh = &$this->_dbh; $page_tbl = $this->_table_names['page_tbl']; if (USE_BYTEA) $sth = $dbh->query(sprintf("UPDATE $page_tbl" - . " SET cached_html='%s'" - . " WHERE pagename='%s'", - $this->_quote($data), - $dbh->escapeSimple($pagename))); + . " SET cached_html='%s'" + . " WHERE pagename='%s'", + $this->_quote($data), + $dbh->escapeSimple($pagename))); else $sth = $dbh->query("UPDATE $page_tbl" - . " SET cached_html=?" - . " WHERE pagename=?", - // PearDB does NOT use pg_escape_string()! Oh dear. - array($this->_quote($data), $pagename)); + . " SET cached_html=?" + . " WHERE pagename=?", + // PearDB does NOT use pg_escape_string()! Oh dear. + array($this->_quote($data), $pagename)); } /** * Create a new revision of a page. */ - function _todo_set_versiondata($pagename, $version, $data) { + function _todo_set_versiondata($pagename, $version, $data) + { $dbh = &$this->_dbh; $version_tbl = $this->_table_names['version_tbl']; - $minor_edit = (int) !empty($data['is_minor_edit']); + $minor_edit = (int)!empty($data['is_minor_edit']); unset($data['is_minor_edit']); $mtime = (int)$data['mtime']; unset($data['mtime']); assert(!empty($mtime)); - @$content = (string) $data['%content']; + @$content = (string)$data['%content']; unset($data['%content']); unset($data['%pagedata']); @@ -122,10 +131,10 @@ extends WikiDB_backend_PearDB $id = $this->_get_pageid($pagename, true); $dbh->query(sprintf("DELETE FROM version WHERE id=%d AND version=%d", $id, $version)); $dbh->query(sprintf("INSERT INTO version (id,version,mtime,minor_edit,content,versiondata)" . - " VALUES (%d, %d, %d, %d, '%s', '%s')", - $id, $version, $mtime, $minor_edit, - $this->_quote($content), - $this->_serialize($data))); + " VALUES (%d, %d, %d, %d, '%s', '%s')", + $id, $version, $mtime, $minor_edit, + $this->_quote($content), + $this->_serialize($data))); // TODO: This function does not work yet $dbh->query(sprintf("SELECT update_recent (%d, %d)", $id, $version)); $this->unlock(); @@ -134,7 +143,8 @@ extends WikiDB_backend_PearDB /** * Delete an old revision of a page. */ - function _todo_delete_versiondata($pagename, $version) { + function _todo_delete_versiondata($pagename, $version) + { $dbh = &$this->_dbh; // TODO: This function was removed $dbh->query(sprintf("SELECT delete_versiondata (%d, %d)", $id, $version)); @@ -143,12 +153,13 @@ extends WikiDB_backend_PearDB /** * Rename page in the database. */ - function _todo_rename_page ($pagename, $to) { + function _todo_rename_page($pagename, $to) + { $dbh = &$this->_dbh; extract($this->_table_names); $this->lock(); - if (($id = $this->_get_pageid($pagename, false)) ) { + if (($id = $this->_get_pageid($pagename, false))) { if ($new = $this->_get_pageid($to, false)) { // Cludge Alert! // This page does not exist (already verified before), but exists in the page table. @@ -156,7 +167,7 @@ extends WikiDB_backend_PearDB $dbh->query("SELECT prepare_rename_page($id, $new)"); } $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id", - $dbh->escapeSimple($to))); + $dbh->escapeSimple($to))); } $this->unlock(); return $id; @@ -165,21 +176,24 @@ extends WikiDB_backend_PearDB /** * Lock all tables we might use. */ - function _lock_tables($write_lock=true) { + function _lock_tables($write_lock = true) + { $this->_dbh->query("BEGIN"); } /** * Unlock all tables. */ - function _unlock_tables() { + function _unlock_tables() + { $this->_dbh->query("COMMIT"); } /** * Serialize data */ - function _serialize($data) { + function _serialize($data) + { if (empty($data)) return ''; assert(is_array($data)); @@ -189,12 +203,13 @@ extends WikiDB_backend_PearDB /** * Unserialize data */ - function _unserialize($data) { + function _unserialize($data) + { if (empty($data)) return array(); // Base64 encoded data does not contain colons. // (only alphanumerics and '+' and '/'.) - if (substr($data,0,2) == 'a:') + if (substr($data, 0, 2) == 'a:') return unserialize($data); return unserialize($this->_unquote($data)); } @@ -202,15 +217,15 @@ extends WikiDB_backend_PearDB /** * Title search. */ - function text_search($search, $fulltext=false, $sortby='', $limit='', - $exclude='') + function text_search($search, $fulltext = false, $sortby = '', $limit = '', + $exclude = '') { $dbh = &$this->_dbh; extract($this->_table_names); $orderby = $this->sortby($sortby, 'db'); if ($sortby and $orderby) $orderby = ' ORDER BY ' . $orderby; - $searchclass = get_class($this)."_search"; + $searchclass = get_class($this) . "_search"; // no need to define it everywhere and then fallback. memory! if (!class_exists($searchclass)) $searchclass = "WikiDB_backend_PearDB_search"; @@ -228,13 +243,13 @@ extends WikiDB_backend_PearDB $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version"; $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields; - // TODO: title still ignored, need better rank and subselect + // TODO: title still ignored, need better rank and subselect $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause"); $search_string = $search->makeTsearch2SqlClauseObj($callback); - $search_string = str_replace(array("%"," "), array("","&"), $search_string); + $search_string = str_replace(array("%", " "), array("", "&"), $search_string); $search_clause = "idxFTI @@ to_tsquery('$search_string')"; if (!$orderby) - $orderby = " ORDER BY rank(idxFTI, to_tsquery('$search_string')) DESC"; + $orderby = " ORDER BY rank(idxFTI, to_tsquery('$search_string')) DESC"; } else { $callback = new WikiMethodCb($searchobj, "_pagename_match_clause"); $search_clause = $search->makeSqlClauseObj($callback); @@ -244,33 +259,36 @@ extends WikiDB_backend_PearDB . " WHERE $join_clause" . " AND ($search_clause)" . $orderby; - if ($limit) { - list($from, $count) = $this->limit($limit); - $result = $dbh->limitQuery($sql, $from, $count); - } else { - $result = $dbh->query($sql); - } + if ($limit) { + list($from, $count) = $this->limit($limit); + $result = $dbh->limitQuery($sql, $from, $count); + } else { + $result = $dbh->query($sql); + } $iter = new WikiDB_backend_PearDB_iter($this, $result); $iter->stoplisted = @$searchobj->stoplisted; return $iter; } -}; +} + +; class WikiDB_backend_PearDB_pgsql_search -extends WikiDB_backend_PearDB_search + extends WikiDB_backend_PearDB_search { - function _pagename_match_clause($node) { + function _pagename_match_clause($node) + { $word = $node->sql(); if ($node->op == 'REGEX') { // posix regex extensions return ($this->_case_exact - ? "pagename ~* '$word'" - : "pagename ~ '$word'"); + ? "pagename ~* '$word'" + : "pagename ~ '$word'"); } else { return ($this->_case_exact - ? "pagename LIKE '$word'" - : "pagename ILIKE '$word'"); + ? "pagename LIKE '$word'" + : "pagename ILIKE '$word'"); } } @@ -306,7 +324,8 @@ select * from stat('select idxfti from version') order by ndoc desc, nentry desc The full-text index will still be used, and the regex will be used to prune the results afterwards. */ - function _fulltext_match_clause($node) { + function _fulltext_match_clause($node) + { $word = strtolower($node->word); $word = str_replace(" ", "&", $word); // phrase fix return $word; diff --git a/lib/WikiDB/backend/PearDB_sqlite.php b/lib/WikiDB/backend/PearDB_sqlite.php index 298c39690..669699bd1 100644 --- a/lib/WikiDB/backend/PearDB_sqlite.php +++ b/lib/WikiDB/backend/PearDB_sqlite.php @@ -20,33 +20,37 @@ require_once 'lib/WikiDB/backend/PearDB.php'; */ class WikiDB_backend_PearDB_sqlite -extends WikiDB_backend_PearDB + extends WikiDB_backend_PearDB { /** * Pack tables. */ - function optimize() { - // NOP + function optimize() + { + // NOP } /** * Lock tables. */ - function _lock_tables($write_lock = true) { - // NOP - SQLite does all locking automatically + function _lock_tables($write_lock = true) + { + // NOP - SQLite does all locking automatically } /** * Release all locks. */ - function _unlock_tables() { - // NOP + function _unlock_tables() + { + // NOP } /** * Serialize data */ - function _serialize($data) { + function _serialize($data) + { if (empty($data)) return ''; assert(is_array($data)); @@ -56,12 +60,13 @@ extends WikiDB_backend_PearDB /** * Unserialize data */ - function _unserialize($data) { + function _unserialize($data) + { if (empty($data)) return array(); // Base64 encoded data does not contain colons. // (only alphanumerics and '+' and '/'.) - if (substr($data,0,2) == 'a:') + if (substr($data, 0, 2) == 'a:') return unserialize($data); return unserialize(base64_decode($data)); } @@ -80,16 +85,19 @@ extends WikiDB_backend_PearDB } */ - function _table_exists (&$dblink, $table) { - $sql = "SELECT count(name) FROM sqlite_master WHERE ((type = 'table') and (name = '$table'))"; - if ($res = sqlite_query ($dblink, $sql)) { - return sqlite_fetch_single($res) > 0; - } else { - return false; // or throw exception - } - } + function _table_exists(&$dblink, $table) + { + $sql = "SELECT count(name) FROM sqlite_master WHERE ((type = 'table') and (name = '$table'))"; + if ($res = sqlite_query($dblink, $sql)) { + return sqlite_fetch_single($res) > 0; + } else { + return false; // or throw exception + } + } + +} -}; +; // Local Variables: // mode: php diff --git a/lib/WikiDB/backend/cvs.php b/lib/WikiDB/backend/cvs.php index 6d5fafbb1..2ca52ccab 100644 --- a/lib/WikiDB/backend/cvs.php +++ b/lib/WikiDB/backend/cvs.php @@ -16,28 +16,28 @@ require_once 'lib/ErrorManager.php'; * Constants used by the CVS backend **/ // these are the parameters defined in db_params -define( 'CVS_DOC_DIR', 'doc_dir' ); -define( 'CVS_REPOSITORY', 'repository' ); -define( 'CVS_CHECK_FOR_REPOSITORY', 'check_for_repository' ); -define( 'CVS_DEBUG_FILE', 'debug_file' ); -define( 'CVS_PAGE_SOURCE', 'pgsrc' ); -define( 'CVS_MODULE_NAME', 'module_name' ); +define('CVS_DOC_DIR', 'doc_dir'); +define('CVS_REPOSITORY', 'repository'); +define('CVS_CHECK_FOR_REPOSITORY', 'check_for_repository'); +define('CVS_DEBUG_FILE', 'debug_file'); +define('CVS_PAGE_SOURCE', 'pgsrc'); +define('CVS_MODULE_NAME', 'module_name'); // these are the things that are defined in the page hash // CMD == Cvs Meta Data -define( 'CMD_LAST_MODIFIED', 'lastmodified' ); -define( 'CMD_CONTENT', '%content'); -define( 'CMD_CREATED', 'created'); -define( 'CMD_VERSION', 'version'); -define( 'CMD_AUTHOR', 'author'); -define( 'CMD_LINK_ATT', '_links_' ); +define('CMD_LAST_MODIFIED', 'lastmodified'); +define('CMD_CONTENT', '%content'); +define('CMD_CREATED', 'created'); +define('CMD_VERSION', 'version'); +define('CMD_AUTHOR', 'author'); +define('CMD_LINK_ATT', '_links_'); // file names used to store specific information -define( 'CVS_MP_FILE', '.most_popular' ); -define( 'CVS_MR_FILE', '.most_recent' ); +define('CVS_MP_FILE', '.most_popular'); +define('CVS_MR_FILE', '.most_recent'); class WikiDB_backend_cvs -extends WikiDB_backend + extends WikiDB_backend { var $_docDir; var $_repository; @@ -72,67 +72,68 @@ extends WikiDB_backend * repository or assumed to exist. If on the other hand the parameter * already exists, then it is not overwritten. */ - function WikiDB_backend_cvs( $dbparam ) + function WikiDB_backend_cvs($dbparam) { // setup all the instance values. $this->_docDir = $dbparam{CVS_DOC_DIR}; $this->_repository = $dbparam{CVS_REPOSITORY}; - if ( ! $dbparam{CVS_MODULE_NAME} ) { - $this->_module_name = basename( $this->_docDir ); + if (!$dbparam{CVS_MODULE_NAME}) { + $this->_module_name = basename($this->_docDir); $dbparam{CVS_MODULE_NAME} = $this->_module_name; } else { $this->_module_name = $dbparam{CVS_MODULE_NAME}; } $this->_debug_file = $dbparam{CVS_DEBUG_FILE}; - if ( $dbparam{CVS_CHECK_FOR_REPOSITORY} - && !( is_dir( $this->_repository ) - && is_dir( $this->_repository . "/CVSROOT" ) - && is_dir( $this->_repository . "/" . $this->_module_name ))) { + if ($dbparam{CVS_CHECK_FOR_REPOSITORY} + && !(is_dir($this->_repository) + && is_dir($this->_repository . "/CVSROOT") + && is_dir($this->_repository . "/" . $this->_module_name)) + ) { - $this->_cvsDebug( sprintf("Creating new repository [%s]", $this->_repository) ); + $this->_cvsDebug(sprintf("Creating new repository [%s]", $this->_repository)); // doesn't exist, need to create it and the replace the wiki // document directory. - $this->_mkdir( $this->_repository, 0775 ); + $this->_mkdir($this->_repository, 0775); // assume that the repository is a local directory, prefix :local: - if ( !ereg( "^:local:", $this->_repository ) ) { + if (!ereg("^:local:", $this->_repository)) { $this->_repository = ":local:" . $this->_repository; } - $cmdLine = sprintf( "cvs -d \"%s\" init", $this->_repository); - $this->_execCommand( $cmdLine, $cmdOutput, true ); + $cmdLine = sprintf("cvs -d \"%s\" init", $this->_repository); + $this->_execCommand($cmdLine, $cmdOutput, true); - $this->_mkdir( $this->_docDir, 0775 ); + $this->_mkdir($this->_docDir, 0775); $cmdLine = sprintf("cd %s; cvs -d \"%s\" import -m no_message " - ."%s V R", $this->_docDir, $this->_repository, - $this->_module_name ); - $this->_execCommand( $cmdLine, $cmdOutput, true ); + . "%s V R", $this->_docDir, $this->_repository, + $this->_module_name); + $this->_execCommand($cmdLine, $cmdOutput, true); // remove the wiki directory and check it out from the // CVS repository - $cmdLine = sprintf( "rm -fr %s; cd %s; cvs -d \"%s\" co %s", - $this->_docDir, dirname($this->_docDir), - $this->_repository, $this->_module_name); - $this->_execCommand( $cmdLine, $cmdOutput, true ); + $cmdLine = sprintf("rm -fr %s; cd %s; cvs -d \"%s\" co %s", + $this->_docDir, dirname($this->_docDir), + $this->_repository, $this->_module_name); + $this->_execCommand($cmdLine, $cmdOutput, true); // add the default pages using the update_pagedata $metaData = array(); $metaData[$AUTHOR] = "PhpWiki -- CVS Backend"; - if ( is_dir( $dbparam[CVS_PAGE_SOURCE] ) ) { - $d = opendir( $dbparam[CVS_PAGE_SOURCE] ); - while ( $entry = readdir( $d ) ) { + if (is_dir($dbparam[CVS_PAGE_SOURCE])) { + $d = opendir($dbparam[CVS_PAGE_SOURCE]); + while ($entry = readdir($d)) { $filename = $dbparam[CVS_PAGE_SOURCE] . "/" . $entry; - $this->_cvsDebug( sprintf("Found [%s] in [%s]", $entry, $dbparam[CVS_PAGE_SOURCE]) ); + $this->_cvsDebug(sprintf("Found [%s] in [%s]", $entry, $dbparam[CVS_PAGE_SOURCE])); - if ( is_file( $filename ) ) { - $metaData[CMD_CONTENT] = join('',file($filename)); - $this->update_pagedata( $entry, $metaData ); + if (is_file($filename)) { + $metaData[CMD_CONTENT] = join('', file($filename)); + $this->update_pagedata($entry, $metaData); } } - closedir( $d ); + closedir($d); } // ensure that the results of the is_dir are cleared @@ -150,20 +151,20 @@ extends WikiDB_backend // file always has the name, i.e. '_$pagename'. $metaFile = $this->_docDir . "/CVS/_" . $pagename; - if ( file_exists( $metaFile ) ) { + if (file_exists($metaFile)) { $megaHash = - unserialize(join( '',$this->_readFileWithPath($metaFile))); + unserialize(join('', $this->_readFileWithPath($metaFile))); $filename = $this->_docDir . "/" . $pagename; - if ( file_exists( $filename ) ) { - $megaHash[CMD_CONTENT] = $this->_readFileWithPath( $filename ); + if (file_exists($filename)) { + $megaHash[CMD_CONTENT] = $this->_readFileWithPath($filename); } else { $megaHash[CMD_CONTENT] = ""; } - $this->_updateMostRecent( $pagename ); - $this->_updateMostPopular( $pagename ); + $this->_updateMostRecent($pagename); + $this->_updateMostPopular($pagename); return $megaHash; } else { @@ -175,18 +176,18 @@ extends WikiDB_backend * This will create a new page if page being requested does not * exist. */ - function update_pagedata($pagename, $newdata = array() ) + function update_pagedata($pagename, $newdata = array()) { // check argument - if ( ! is_array( $newdata ) ) { + if (!is_array($newdata)) { trigger_error("update_pagedata: Argument 'newdata' was not array", - E_USER_WARNING); + E_USER_WARNING); } // retrieve the meta data - $metaData = $this->get_pagedata( $pagename ); + $metaData = $this->get_pagedata($pagename); - if ( ! $metaData ) { + if (!$metaData) { $this->_cvsDebug("update_pagedata: no meta data found"); // this means that the page does not exist, we need to create // it. @@ -195,25 +196,25 @@ extends WikiDB_backend $metaData[CMD_CREATED] = time(); $metaData[CMD_VERSION] = "1"; - if ( ! isset($newdata[CMD_CONTENT])) { + if (!isset($newdata[CMD_CONTENT])) { $metaData[CMD_CONTENT] = ""; } else { $metaData[CMD_CONTENT] = $newdata[CMD_CONTENT]; } // create an empty page ... - $this->_writePage( $pagename, $metaData[CMD_CONTENT] ); - $this->_addPage( $pagename ); + $this->_writePage($pagename, $metaData[CMD_CONTENT]); + $this->_addPage($pagename); // make sure that the page is written and committed a second time - unset( $newdata[CMD_CONTENT] ); - unset( $metaData[CMD_CONTENT] ); + unset($newdata[CMD_CONTENT]); + unset($metaData[CMD_CONTENT]); } // change any meta data information - foreach ( $newdata as $key => $value ) { - if ( $value == false || empty( $value ) ) { - unset( $metaData[$key] ); + foreach ($newdata as $key => $value) { + if ($value == false || empty($value)) { + unset($metaData[$key]); } else { $metaData[$key] = $value; } @@ -221,22 +222,22 @@ extends WikiDB_backend // update the page data, if required. Use newdata because it could // be empty and thus unset($metaData[CMD_CONTENT]). - if ( isset( $newdata[CMD_CONTENT] ) ) { - $this->_writePage( $pagename, $newdata[CMD_CONTENT] ); + if (isset($newdata[CMD_CONTENT])) { + $this->_writePage($pagename, $newdata[CMD_CONTENT]); } // remove any content from the meta data before storing it - unset( $metaData[CMD_CONTENT] ); + unset($metaData[CMD_CONTENT]); $metaData[CMD_LAST_MODIFIED] = time(); - $metaData[CMD_VERSION] = $this->_commitPage( $pagename, $metaData ); - $this->_writeMetaInfo( $pagename, $metaData ); + $metaData[CMD_VERSION] = $this->_commitPage($pagename, $metaData); + $this->_writeMetaInfo($pagename, $metaData); } function get_latest_version($pagename) { - $metaData = $this->get_pagedata( $pagename ); - if ( $metaData ) { + $metaData = $this->get_pagedata($pagename); + if ($metaData) { // the version number is everything after the '1.' return $metaData[CMD_VERSION]; } else { @@ -257,15 +258,15 @@ extends WikiDB_backend */ function get_versiondata($pagename, $version, $want_content = false) { - $this->_cvsDebug( "get_versiondata: [$pagename] [$version] [$want_content]" ); + $this->_cvsDebug("get_versiondata: [$pagename] [$version] [$want_content]"); $filedata = ""; - if ( $want_content ) { + if ($want_content) { // retrieve the version from the repository $cmdLine = sprintf("cvs -d \"%s\" co -p -r 1.%d %s/%s 2>&1", - $this->_repository, $version, - $this->_module_name, $pagename ); - $this->_execCommand( $cmdLine, $filedata, true ); + $this->_repository, $version, + $this->_module_name, $pagename); + $this->_execCommand($cmdLine, $filedata, true); // TODO: DEBUG: 5 is a magic number here, depending on the // TODO: DEBUG: version of cvs used here, 5 might have to @@ -273,8 +274,8 @@ extends WikiDB_backend // TODO: DEBUG: doing this. // the first 5 lines contain various bits of // administrative information that can be ignored. - for ( $i = 0; $i < 5; $i++ ) { - array_shift( $filedata ); + for ($i = 0; $i < 5; $i++) { + array_shift($filedata); } } @@ -283,24 +284,24 @@ extends WikiDB_backend * in the log message for the revision in serialized form. */ $cmdLine = sprintf("cd %s; cvs log -r1.%d %s", $this->_docDir, - $version, $pagename ); - $this->_execCommand( $cmdLine, $logdata, true ); + $version, $pagename); + $this->_execCommand($cmdLine, $logdata, true); // shift log data until we get to the 'revision X.X' line // FIXME: ensure that we don't enter an endless loop here - while ( !ereg( "^revision 1.([0-9]+)$", $logdata[0], $revInfo ) ) { - array_shift( $logdata ); + while (!ereg("^revision 1.([0-9]+)$", $logdata[0], $revInfo)) { + array_shift($logdata); } // serialized hash information now stored in position 2 - $rVal = unserialize( _unescape( $logdata[2] ) ); + $rVal = unserialize(_unescape($logdata[2])); // version information is incorrect $rVal[CMD_VERSION] = $revInfo[1]; $rVal[CMD_CONTENT] = $filedata; - foreach ( $rVal as $key => $value ) { - $this->_cvsDebug( "$key == [$value]" ); + foreach ($rVal as $key => $value) { + $this->_cvsDebug("$key == [$value]"); } return $rVal; @@ -318,18 +319,18 @@ extends WikiDB_backend */ function purge_page($pagename) { - $this->_cvsDebug( "delete_page [$pagename]") ; + $this->_cvsDebug("delete_page [$pagename]"); $filename = $this->_docDir . "/" . $pagename; $metaFile = $this->_docDir . "/CVS/_" . $pagename; // obtain a write block before deleting the file - if ( $this->_deleteFile( $filename ) == false ) { + if ($this->_deleteFile($filename) == false) { return false; } - $this->_deleteFile( $metaFile ); + $this->_deleteFile($metaFile); - $this->_removePage( $pagename ); + $this->_removePage($pagename); return true; } @@ -342,16 +343,16 @@ extends WikiDB_backend */ function rename_page($pagename, $to) { - $this->_cvsDebug( "rename_page [$pagename,$to]") ; - $data = get_pagedata($pagename); - if (isset($data['pagename'])) - $data['pagename'] = $to; - //$version = $this->get_latest_version($pagename); - //$vdata = get_versiondata($pagename, $version, 1); + $this->_cvsDebug("rename_page [$pagename,$to]"); + $data = get_pagedata($pagename); + if (isset($data['pagename'])) + $data['pagename'] = $to; + //$version = $this->get_latest_version($pagename); + //$vdata = get_versiondata($pagename, $version, 1); //$data[CMD_CONTENT] = $vdata[CMD_CONTENT]; - $this->delete_page($pagename); - $this->update_pagedata($to, $data); - return true; + $this->delete_page($pagename); + $this->update_pagedata($to, $data); + return true; } function delete_versiondata($pagename, $version) @@ -382,13 +383,13 @@ extends WikiDB_backend function set_links($pagename, $links) { // TODO: needs to be tested .... - $megaHash = get_pagedata( $pagename ); + $megaHash = get_pagedata($pagename); $megaHash[CMD_LINK_ATT] = $links; - $this->_writeMetaInfo( $pagename, $megaHash ); + $this->_writeMetaInfo($pagename, $megaHash); } - function get_links($pagename, $reversed=true, $include_empty=false, - $sortby='', $limit='', $exclude='') + function get_links($pagename, $reversed = true, $include_empty = false, + $sortby = '', $limit = '', $exclude = '') { // TODO: ignores the $reversed argument and returns // TODO: the value of _links_ attribute of the meta information @@ -396,7 +397,7 @@ extends WikiDB_backend // TODO: need to do a grep on all files for the pagename in // TODO: in question and return all those page names that contained // TODO: the required pagename! - $megaHash = get_pagedata( $pagename ); + $megaHash = get_pagedata($pagename); return $megaHash[CMD_LINK_ATT]; } @@ -406,41 +407,42 @@ extends WikiDB_backend return new WikiDB_backend_dumb_AllRevisionsIter($this, $pagename); } */ - function get_all_pages($include_empty=false, $sortby='', $limit='') + function get_all_pages($include_empty = false, $sortby = '', $limit = '') { // FIXME: this ignores the parameters. return new Cvs_Backend_Array_Iterator( - $this->_getAllFileNamesInDir( $this->_docDir )); + $this->_getAllFileNamesInDir($this->_docDir)); } - function text_search($search, $fullsearch = false, $orderby=false, $limit='', $exclude='') + function text_search($search, $fullsearch = false, $orderby = false, $limit = '', $exclude = '') { - if ( $fullsearch ) { + if ($fullsearch) { $iter = new Cvs_Backend_Full_Search_Iterator( - $this->_getAllFileNamesInDir( $this->_docDir ), - $search, - $this->_docDir ); + $this->_getAllFileNamesInDir($this->_docDir), + $search, + $this->_docDir); $iter->stoplisted =& $search->stoplisted; return $iter; } else { return new Cvs_Backend_Title_Search_Iterator( - $this->_getAllFileNamesInDir( $this->_docDir ), - $search); + $this->_getAllFileNamesInDir($this->_docDir), + $search); } } - function most_popular($limit, $sortby='') { + function most_popular($limit, $sortby = '') + { // TODO: needs to be tested ... $mp = $this->_getMostPopular(); - if ($limit < 0){ - asort ($mp, SORT_NUMERIC); + if ($limit < 0) { + asort($mp, SORT_NUMERIC); $limit = -$limit; } else { - arsort( $mp, SORT_NUMERIC ); + arsort($mp, SORT_NUMERIC); } $returnVal = array(); - while ( (list($key, $val) = each($a)) && $limit > 0 ) { + while ((list($key, $val) = each($a)) && $limit > 0) { $returnVal[] = $key; $limit--; } @@ -458,30 +460,30 @@ extends WikiDB_backend $mr = $this->_getMostRecent(); $rev = false; $returnVal = array(); - if ( isset( $params['limit'] ) ) { + if (isset($params['limit'])) { $limit = $params['limit']; $rev = $limit < 0; } - if ($rev){ - arsort( $mr, SORT_NUMERIC ); + if ($rev) { + arsort($mr, SORT_NUMERIC); } else { - asort( $mr, SORT_NUMERIC ); + asort($mr, SORT_NUMERIC); } - if ( isset( $limit ) ) { - while ( (list($key, $val) = each($a)) && $limit > 0 ) { + if (isset($limit)) { + while ((list($key, $val) = each($a)) && $limit > 0) { $returnVal[] = $key; $limit--; } - } elseif ( isset( $params['since'] ) ) { - while ( (list($key, $val) = each($a)) ) { + } elseif (isset($params['since'])) { + while ((list($key, $val) = each($a))) { - if ( $val > $params['since'] ) { + if ($val > $params['since']) { $returnVal[] = $key; } } } - return new Cvs_Backend_Array_Iterator( $returnVal ); + return new Cvs_Backend_Array_Iterator($returnVal); } function lock($write_lock = true) @@ -496,7 +498,7 @@ extends WikiDB_backend trigger_error("unlock: Not Implemented", E_USER_WARNING); } - function close () + function close() { } @@ -525,11 +527,11 @@ extends WikiDB_backend $page_names = $this->_getAllFileNamesInDir($this->_docDir); $meta_names = $this->_getAllFileNamesInDir($this->_docDir . "/CVS"); - array_walk( $meta_names, '_strip_leading_underscore' ); - reset( $meta_names ); - $no_meta_files = array_diff( $page_names, $meta_names ); + array_walk($meta_names, '_strip_leading_underscore'); + reset($meta_names); + $no_meta_files = array_diff($page_names, $meta_names); - array_walk( $no_meta_files, '_create_meta_file', $this ); + array_walk($no_meta_files, '_create_meta_file', $this); return true; } @@ -542,8 +544,8 @@ extends WikiDB_backend // TODO: // TODO: test this .... i.e. add test to unit test file. // TODO: - $cmdLine = sprintf( "cd %s; cvs update -d 2>&1", $this->_docDir ); - $this->_execCommand( $cmdLine, $cmdOutput, true ); + $cmdLine = sprintf("cd %s; cvs update -d 2>&1", $this->_docDir); + $this->_execCommand($cmdLine, $cmdOutput, true); return true; } @@ -553,17 +555,17 @@ extends WikiDB_backend // directly. // ..-.-..-.-..-.-.. .--..-......-.--. --.-....----..... // - function _create_meta_file( $page_name, $key, &$backend ) + function _create_meta_file($page_name, $key, &$backend) { // this is used as part of an array walk and therefore takes // the backend argument $backend->_cvsDebug(sprintf("Creating meta file for [%s]", $page_name)); - $backend->update_pagedata( $page_name, array() ); + $backend->update_pagedata($page_name, array()); } - function _strip_leading_underscore( &$item ) + function _strip_leading_underscore(&$item) { - $item = ereg_replace( "^_", "", $item ); + $item = ereg_replace("^_", "", $item); } /** @@ -571,16 +573,16 @@ extends WikiDB_backend * for the following page. If the page was not defined, it is entered * with a value of 1. */ - function _updateMostPopular( $pagename ) + function _updateMostPopular($pagename) { $mp = $this->_getMostPopular(); - if ( isset( $mp[$pagename] ) ) { + if (isset($mp[$pagename])) { $mp[$pagename]++; } else { $mp[$pagename] = 1; } - $this->_writeFileWithPath( $this->_docDir . "/CVS/" . CVS_MP_FILE, - serialize( $mp ) ); + $this->_writeFileWithPath($this->_docDir . "/CVS/" . CVS_MP_FILE, + serialize($mp)); } /** @@ -590,85 +592,88 @@ extends WikiDB_backend function _getMostPopular() { $mostPopular = $this->_docDir . "/CVS/" . CVS_MP_FILE; - if ( !file_exists( $mostPopular ) ) { - $this->_writeFileWithPath( $mostPopular, serialize( array() ) ); + if (!file_exists($mostPopular)) { + $this->_writeFileWithPath($mostPopular, serialize(array())); } - return unserialize(join( '',$this->_readFileWithPath($mostPopular))); + return unserialize(join('', $this->_readFileWithPath($mostPopular))); } function _getMostRecent() { $mostRecent = $this->_docDir . "/CVS/" . CVS_MR_FILE; - if ( !file_exists( $mostRecent ) ) { - $this->_writeFileWithPath( $mostRecent, serialize( array() ) ); + if (!file_exists($mostRecent)) { + $this->_writeFileWithPath($mostRecent, serialize(array())); } - return unserialize(join( '',$this->_readFileWithPath($mostRecent))); + return unserialize(join('', $this->_readFileWithPath($mostRecent))); } - function _updateMostRecent( $pagename ) + function _updateMostRecent($pagename) { $mr = $this->_getMostRecent(); $mr[$pagename] = time(); - $this->_writeFileWithPath( $this->_docDir . "/CVS/" . CVS_MR_FILE, - serialize( $mr ) ); + $this->_writeFileWithPath($this->_docDir . "/CVS/" . CVS_MR_FILE, + serialize($mr)); } - function _writeMetaInfo( $pagename, $hashInfo ) + function _writeMetaInfo($pagename, $hashInfo) { - $this->_writeFileWithPath( $this->_docDir . "/CVS/_" . $pagename, - serialize( $hashInfo ) ); + $this->_writeFileWithPath($this->_docDir . "/CVS/_" . $pagename, + serialize($hashInfo)); } - function _writePage( $pagename, $content ) + + function _writePage($pagename, $content) { - $this->_writeFileWithPath( $this->_docDir . "/". $pagename, $content ); + $this->_writeFileWithPath($this->_docDir . "/" . $pagename, $content); } - function _removePage( $pagename ) + + function _removePage($pagename) { $cmdLine = sprintf("cd %s; cvs remove %s 2>&1; cvs commit -m '%s' " - ."%s 2>&1", $this->_docDir, $pagename, - "remove page", $pagename ); + . "%s 2>&1", $this->_docDir, $pagename, + "remove page", $pagename); - $this->_execCommand( $cmdLine, $cmdRemoveOutput, true ); + $this->_execCommand($cmdLine, $cmdRemoveOutput, true); } /** * this returns the new version number of the file. */ - function _commitPage( $pagename, &$meta_data ) + function _commitPage($pagename, &$meta_data) { - $cmdLine = sprintf( "cd %s; cvs commit -m \"%s\" %s 2>&1", - $this->_docDir, - escapeshellcmd( serialize( $meta_data ) ), - $pagename ); - $this->_execCommand( $cmdLine, $cmdOutput, true ); + $cmdLine = sprintf("cd %s; cvs commit -m \"%s\" %s 2>&1", + $this->_docDir, + escapeshellcmd(serialize($meta_data)), + $pagename); + $this->_execCommand($cmdLine, $cmdOutput, true); - $cmdOutput = implode( "\n", $cmdOutput ); + $cmdOutput = implode("\n", $cmdOutput); $revInfo = array(); - ereg( "\nnew revision: 1[.]([0-9]+); previous revision: ", $cmdOutput, - $revInfo ); + ereg("\nnew revision: 1[.]([0-9]+); previous revision: ", $cmdOutput, + $revInfo); - $this->_cvsDebug( "CP: revInfo 0: $revInfo[0]" ); - $this->_cvsDebug( "CP: $cmdOutput" ); - if ( isset( $revInfo[1] ) ) { - $this->_cvsDebug( "CP: got revision information" ); + $this->_cvsDebug("CP: revInfo 0: $revInfo[0]"); + $this->_cvsDebug("CP: $cmdOutput"); + if (isset($revInfo[1])) { + $this->_cvsDebug("CP: got revision information"); return $revInfo[1]; } else { - ereg( "\ninitial revision: 1[.]([0-9]+)", $cmdOutput, $revInfo ); - if ( isset( $revInfo[1] ) ) { - $this->_cvsDebug( "CP: is initial release" ); + ereg("\ninitial revision: 1[.]([0-9]+)", $cmdOutput, $revInfo); + if (isset($revInfo[1])) { + $this->_cvsDebug("CP: is initial release"); return 1; } - $this->_cvsDebug( "CP: returning old version" ); + $this->_cvsDebug("CP: returning old version"); return $meta_data[CMD_VERSION]; } } - function _addPage( $pagename ) + + function _addPage($pagename) { // TODO: need to add a check for the mimetype so that binary // TODO: files are added as binary files $cmdLine = sprintf("cd %s; cvs add %s 2>&1", $this->_docDir, - $pagename ); - $this->_execCommand( $cmdLine, $cmdAddOutput, true ); + $pagename); + $this->_execCommand($cmdLine, $cmdAddOutput, true); } /** @@ -676,67 +681,67 @@ extends WikiDB_backend * in a particular directory. The list is sorted according the * string representation of the filenames. */ - function _getAllFileNamesInDir( $dirName ) + function _getAllFileNamesInDir($dirName) { $namelist = array(); - $d = opendir( $dirName ); - while ( $entry = readdir( $d ) ) { + $d = opendir($dirName); + while ($entry = readdir($d)) { $namelist[] = $entry; } - closedir( $d ); - sort( $namelist, SORT_STRING ); + closedir($d); + sort($namelist, SORT_STRING); return $namelist; } /** * Recursively create all directories. */ - function _mkdir( $path, $mode ) + function _mkdir($path, $mode) { - $directoryName = dirname( $path ); - if ( $directoryName != "/" && $directoryName != "\\" - && !is_dir( $directoryName ) && $directoryName != "" ) { - $rVal = $this->_mkdir( $directoryName, $mode ); - } - else { + $directoryName = dirname($path); + if ($directoryName != "/" && $directoryName != "\\" + && !is_dir($directoryName) && $directoryName != "" + ) { + $rVal = $this->_mkdir($directoryName, $mode); + } else { $rVal = true; } - return ($rVal && @mkdir( $path, $mode ) ); + return ($rVal && @mkdir($path, $mode)); } /** * Recursively create all directories and then the file. */ - function _createFile( $path, $mode ) + function _createFile($path, $mode) { - $this->_mkdir( dirname( $path ), $mode ); - touch( $path ); - chmod( $path, $mode ); + $this->_mkdir(dirname($path), $mode); + touch($path); + chmod($path, $mode); } /** * The lord giveth, and the lord taketh. */ - function _deleteFile( $filename ) + function _deleteFile($filename) { - if( $fd = fopen($filename, 'a') ) { + if ($fd = fopen($filename, 'a')) { - $locked = flock($fd,2); // Exclusive blocking lock + $locked = flock($fd, 2); // Exclusive blocking lock if (!$locked) { $this->_cvsError("Unable to delete file, lock was not obtained.", - __LINE__, $filename, EM_NOTICE_ERRORS ); + __LINE__, $filename, EM_NOTICE_ERRORS); } - if ( ($rVal = unlink( $filename )) != 0 ) { - $this->_cvsDebug( "[$filename] --> Unlink returned [$rVal]" ); + if (($rVal = unlink($filename)) != 0) { + $this->_cvsDebug("[$filename] --> Unlink returned [$rVal]"); } return $rVal; } else { - $this->_cvsError( "deleteFile: Unable to open file", - __LINE__, $filename, EM_NOTICE_ERRORS ); + $this->_cvsError("deleteFile: Unable to open file", + __LINE__, $filename, EM_NOTICE_ERRORS); return false; } } @@ -745,45 +750,44 @@ extends WikiDB_backend * Called when something happened that causes the CVS backend to * fail. */ - function _cvsError( $msg = "no message", - $errline = 0, - $errfile = "lib/WikiDB/backend/cvs.php", - $errno = EM_FATAL_ERRORS) + function _cvsError($msg = "no message", + $errline = 0, + $errfile = "lib/WikiDB/backend/cvs.php", + $errno = EM_FATAL_ERRORS) { - $err = new PhpError( $errno, "[CVS(be)]: " . $msg, $errfile, $errline); + $err = new PhpError($errno, "[CVS(be)]: " . $msg, $errfile, $errline); // send error to the debug routine - $this->_cvsDebug( $err->asXML() ); + $this->_cvsDebug($err->asXML()); // send the error to the error manager - $GLOBALS['ErrorManager']->handleError( $err ); + $GLOBALS['ErrorManager']->handleError($err); } /** * Debug function specifically for the CVS database functions. * Can be deactived by setting the WikiDB['debug_file'] to "" */ - function _cvsDebug( $msg ) + function _cvsDebug($msg) { - if ( $this->_debug_file == "" ) { + if ($this->_debug_file == "") { return; } - if ( !file_exists( $this->_debug_file ) ) { - $this->_createFile( $this->_debug_file, 0755 ); + if (!file_exists($this->_debug_file)) { + $this->_createFile($this->_debug_file, 0755); } - if ( $fdlock = @fopen( $this->_debug_file, 'a' ) ) { - $locked = flock( $fdlock, 2 ); - if ( !$locked ) { - fclose( $fdlock ); + if ($fdlock = @fopen($this->_debug_file, 'a')) { + $locked = flock($fdlock, 2); + if (!$locked) { + fclose($fdlock); return; } - $fdappend = @fopen( $this->_debug_file, 'a' ); - fwrite( $fdappend, ($msg . "\n") ); - fclose( $fdappend ); - fclose( $fdlock ); - } - else { + $fdappend = @fopen($this->_debug_file, 'a'); + fwrite($fdappend, ($msg . "\n")); + fclose($fdappend); + fclose($fdlock); + } else { // TODO: this should be replaced ... printf("unable to locate/open [%s], turning debug off\n", $filename); $this->_debug_file = ""; @@ -794,17 +798,17 @@ extends WikiDB_backend * Execute a command and potentially exit if the flag exitOnNonZero is * set to true and the return value was nonZero */ - function _execCommand( $cmdLine, &$cmdOutput, $exitOnNonZero ) + function _execCommand($cmdLine, &$cmdOutput, $exitOnNonZero) { - $this->_cvsDebug( sprintf("Preparing to execute [%s]", $cmdLine) ); - exec( $cmdLine, $cmdOutput, $cmdReturnVal ); - if ( $exitOnNonZero && ($cmdReturnVal != 0) ) { - $this->_cvsDebug( sprintf("Command failed [%s], Output: ", $cmdLine) ."[". - join("\n",$cmdOutput) . "]" ); - $this->_cvsError( sprintf("Command failed [%s], Return value: %s", $cmdLine, $cmdReturnVal), - __LINE__ ); + $this->_cvsDebug(sprintf("Preparing to execute [%s]", $cmdLine)); + exec($cmdLine, $cmdOutput, $cmdReturnVal); + if ($exitOnNonZero && ($cmdReturnVal != 0)) { + $this->_cvsDebug(sprintf("Command failed [%s], Output: ", $cmdLine) . "[" . + join("\n", $cmdOutput) . "]"); + $this->_cvsError(sprintf("Command failed [%s], Return value: %s", $cmdLine, $cmdReturnVal), + __LINE__); } - $this->_cvsDebug( "Done execution [" . join("\n", $cmdOutput) . "]" ); + $this->_cvsDebug("Done execution [" . join("\n", $cmdOutput) . "]"); return $cmdReturnVal; } @@ -812,21 +816,21 @@ extends WikiDB_backend /** * Read locks a file, reads it, and returns it contents */ - function _readFileWithPath( $filename ) + function _readFileWithPath($filename) { - if ( $fd = @fopen( $filename, "r" ) ) { - $locked = flock( $fd, 1 ); // read lock - if ( !$locked ) { - fclose( $fd ); - $this->_cvsError( "Unable to obtain read lock.", __LINE__ ); + if ($fd = @fopen($filename, "r")) { + $locked = flock($fd, 1); // read lock + if (!$locked) { + fclose($fd); + $this->_cvsError("Unable to obtain read lock.", __LINE__); } - $content = file( $filename ); - fclose( $fd ); + $content = file($filename); + fclose($fd); return $content; } else { - $this->_cvsError( sprintf("Unable to open file '%s' for reading", $filename), - __LINE__ ); + $this->_cvsError(sprintf("Unable to open file '%s' for reading", $filename), + __LINE__); return false; } } @@ -838,13 +842,13 @@ extends WikiDB_backend * * Nothing is returned, might be useful to return something ;-) */ - function _writeFileWithPath( $filename, $contents ) + function _writeFileWithPath($filename, $contents) { // TODO: $contents should probably be a reference parameter ... - if( $fd = fopen($filename, 'a') ) { - $locked = flock($fd,2); // Exclusive blocking lock + if ($fd = fopen($filename, 'a')) { + $locked = flock($fd, 2); // Exclusive blocking lock if (!$locked) { - $this->_cvsError( "Timeout while obtaining lock.", __LINE__ ); + $this->_cvsError("Timeout while obtaining lock.", __LINE__); } // Second filehandle -- we use this to write the contents @@ -853,33 +857,34 @@ extends WikiDB_backend fclose($fdsafe); fclose($fd); } else { - $this->_cvsError( sprintf("Could not open file '%s' for writing", $filename), - __LINE__ ); + $this->_cvsError(sprintf("Could not open file '%s' for writing", $filename), + __LINE__); } } - /** - * Copy the contents of the source directory to the destination directory. - */ - function _copyFilesFromDirectory( $src, $dest ) + /** + * Copy the contents of the source directory to the destination directory. + */ + function _copyFilesFromDirectory($src, $dest) { - $this->_cvsDebug( sprintf("Copying from [%s] to [%s]", $src, $dest) ); - - if ( is_dir( $src ) && is_dir( $dest ) ) { - $this->_cvsDebug( "Copying " ); - $d = opendir( $src ); - while ( $entry = readdir( $d ) ) { - if ( is_file( $src . "/" . $entry ) - && copy( $src . "/" . $entry, $dest . "/" . $entry ) ) { - $this->_cvsDebug( sprintf("Copied to [%s]", "$dest/$entry") ); + $this->_cvsDebug(sprintf("Copying from [%s] to [%s]", $src, $dest)); + + if (is_dir($src) && is_dir($dest)) { + $this->_cvsDebug("Copying "); + $d = opendir($src); + while ($entry = readdir($d)) { + if (is_file($src . "/" . $entry) + && copy($src . "/" . $entry, $dest . "/" . $entry) + ) { + $this->_cvsDebug(sprintf("Copied to [%s]", "$dest/$entry")); } else { - $this->_cvsDebug( sprintf("Failed to copy [%s]", "$src/$entry") ); + $this->_cvsDebug(sprintf("Failed to copy [%s]", "$src/$entry")); } } - closedir( $d ); + closedir($d); return true; } else { - $this->_cvsDebug( "Not copying" ); + $this->_cvsDebug("Not copying"); return false; } } @@ -892,12 +897,12 @@ extends WikiDB_backend * \; --> ; * \" --> " */ - function _unescape( $val ) + function _unescape($val) { - $val = str_replace( "\\{", "{", $val ); - $val = str_replace( "\\}", "}", $val ); - $val = str_replace( "\\;", ";", $val ); - $val = str_replace( "\\\"", "\"", $val ); + $val = str_replace("\\{", "{", $val); + $val = str_replace("\\}", "}", $val); + $val = str_replace("\\;", ";", $val); + $val = str_replace("\\\"", "\"", $val); return $val; } @@ -906,9 +911,9 @@ extends WikiDB_backend * Function for removing the newlines from the ends of the * file data returned from file(..). This is used in retrievePage */ - function _strip_newlines( &$item, $key ) + function _strip_newlines(&$item, $key) { - $item = ereg_replace( "\n$", "", $item ); + $item = ereg_replace("\n$", "", $item); } } /* End of WikiDB_backend_cvs class */ @@ -917,44 +922,45 @@ extends WikiDB_backend * Generic iterator for stepping through an array of values. */ class Cvs_Backend_Array_Iterator -extends WikiDB_backend_iterator + extends WikiDB_backend_iterator { var $_array; - function Cvs_Backend_Iterator( $arrayValue = Array() ) + function Cvs_Backend_Iterator($arrayValue = Array()) { $this->_array = $arrayValue; } function next() { - while ( ($rVal = array_pop( $this->_array )) != NULL ) { + while (($rVal = array_pop($this->_array)) != NULL) { return $rVal; } return false; } - function count() { + function count() + { return count($this->_array); } function free() { - unset( $this->_array ); + unset($this->_array); } } class Cvs_Backend_Full_Search_Iterator -extends Cvs_Backend_Array_Iterator + extends Cvs_Backend_Array_Iterator { var $_searchString = ''; var $_docDir = ""; - function Cvs_Backend_Title_Search_Iterator( $arrayValue = Array(), - $searchString = "", - $documentDir = ".") + function Cvs_Backend_Title_Search_Iterator($arrayValue = Array(), + $searchString = "", + $documentDir = ".") { - $this->Cvs_Backend_Array_Iterator( $arrayValue ); + $this->Cvs_Backend_Array_Iterator($arrayValue); $_searchString = $searchString; $_docDir = $documentDir; } @@ -963,8 +969,8 @@ extends Cvs_Backend_Array_Iterator { do { $pageName = Cvs_Backend_Array_Iterator::next(); - } while ( !$this->_searchFile( $_searchString, - $_docDir . "/" . $pageName )); + } while (!$this->_searchFile($_searchString, + $_docDir . "/" . $pageName)); return $pageName; } @@ -975,16 +981,16 @@ extends Cvs_Backend_Array_Iterator * false if the search string wasn't find or the file was a directory * or could not be read. */ - function _searchFile( $searchString, $fileName ) + function _searchFile($searchString, $fileName) { // TODO: using grep here, it might make more sense to use // TODO: some sort of inbuilt/language specific method for // TODO: searching files. - $cmdLine = sprintf( "grep -E -i '%s' %s > /dev/null 2>&1", - $searchString, $fileName ); + $cmdLine = sprintf("grep -E -i '%s' %s > /dev/null 2>&1", + $searchString, $fileName); - return ( WikiDB_backend_cvs::_execCommand( $cmdLine, $cmdOutput, - false ) == 0 ); + return (WikiDB_backend_cvs::_execCommand($cmdLine, $cmdOutput, + false) == 0); } } @@ -992,14 +998,14 @@ extends Cvs_Backend_Array_Iterator * Iterator used for doing a title search. */ class Cvs_Backend_Title_Search_Iterator -extends Cvs_Backend_Array_Iterator + extends Cvs_Backend_Array_Iterator { var $_searchString = ''; - function Cvs_Backend_Title_Search_Iterator( $arrayValue = Array(), - $searchString = "") + function Cvs_Backend_Title_Search_Iterator($arrayValue = Array(), + $searchString = "") { - $this->Cvs_Backend_Array_Iterator( $arrayValue ); + $this->Cvs_Backend_Array_Iterator($arrayValue); $_searchString = $searchString; } @@ -1007,7 +1013,7 @@ extends Cvs_Backend_Array_Iterator { do { $pageName = Cvs_Backend_Array_Iterator::next(); - } while ( !eregi( $this->_searchString, $pageName ) ); + } while (!eregi($this->_searchString, $pageName)); return $pageName; } diff --git a/lib/WikiDB/backend/dba.php b/lib/WikiDB/backend/dba.php index 62c7202c3..c7ee202f6 100644 --- a/lib/WikiDB/backend/dba.php +++ b/lib/WikiDB/backend/dba.php @@ -4,9 +4,10 @@ require_once 'lib/WikiDB/backend/dbaBase.php'; require_once 'lib/DbaDatabase.php'; class WikiDB_backend_dba -extends WikiDB_backend_dbaBase + extends WikiDB_backend_dbaBase { - function WikiDB_backend_dba ($dbparams) { + function WikiDB_backend_dba($dbparams) + { $directory = '/tmp'; $prefix = 'wiki_'; $dba_handler = 'gdbm'; @@ -19,12 +20,12 @@ extends WikiDB_backend_dbaBase $db = new DbaDatabase($dbfile, false, $dba_handler); $db->set_timeout($timeout); - // Workaround for BDB 4.1 bugs - if (file_exists($dbfile)) { + // Workaround for BDB 4.1 bugs + if (file_exists($dbfile)) { $mode = 'w'; - } else { + } else { $mode = 'c'; - } + } if (!$db->open($mode)) { trigger_error(sprintf(_("%s: Can't open dba database"), $dbfile), E_USER_ERROR); global $request; @@ -33,7 +34,9 @@ extends WikiDB_backend_dbaBase $this->WikiDB_backend_dbaBase($db); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/backend/dbaBase.php b/lib/WikiDB/backend/dbaBase.php index af72e7338765205b5cf4754160643bf3d7ee97d7..1bc766832494acfa8602db2dca40bbfca45232f6 100644 GIT binary patch delta 3201 zcma)8drVu`8P_#7*w@&AUp#Eg1uobI^DxgPU@$n~k`6Es(xiES!Ixka2-qehP^Pt2 zm+p^dA-`5zw{>Z^Rm!?_A-#(#HZ3KSHg!t17Ip2`MM}DAe`HDXN4q6!Q?1*%=h`NZ zPU@9>ufOk{^L@YXdA?^qXRbY=SUs;&a^%5zRjbxn&WFcBE>@y*G-kNR^kP|hwjy2P za7)mJIM&TMrsI)m!NFlf-KxMVWuxJu6BmZi8_z}misr#UU2Ef|v_2Awrxxz(4l zQ!=X%?U`z7+Gi66I7jptD0~Jt3;Bd~`N%F;B5FU!OZa9(2ZWi>v~ZXIh-4o2eyzI29&n2JnC;z{Dm$ido{ zB#jG|dx%z>dpCKnIscB`RW{t%qhTUA9yVd!rNq%HJ8oz#WJQbLR=t$O_%v2(Y=%%Y z8am>1$oL$bw~bU+O`jaf9E}l0wYv(4!gzFEAiyIt)bCR?gPhaI~%szpwM)R^6}CWNYdZUtS{_C4?nzcEd5e#TLNVuf%AZmDIiw{o!={ zyCImyd0cp5{19GmY{%P;YABkVIrm`)Q*FZA^(y$Awxg{`O{22XREYHnHC7EuO269F z1mE6FTy3hRdo0aWm)J;#6~qSz3z< zF(K~cQwF=RXtIi*G+$O^OUrjY;-9wmFtE2al%=*4lW7Yi;XXJ^9Y#2Eq+FP9?V%}o z&8x*9TD35FElO!Os@e;Y<~0)rkJ?fdws>tSNzpQD+C3@mPrdmmt`+Zk&30)IQGG~= z#-x&x@+_6x%l zYL^nP20hqQp~FUdF7^1;_GWxwP@~A#NWVLL-Sqo?Upw{m`@XDHls@vg=~`Zg75cJl z)OUDEl(I0}!6Oziq!IKqx{|!rj%LgX$%v}(QAa)2{YrX%-Iamz&Mhgr)z2c*$4`vZypl1?=?{H}yN8{DLY zz)(W7EErJ19!SUbZBBwI1HnKx9^YoVOP`!&M$$S-@0d_xV_QAe_UfSNvQr$6u0e|H zhXFfU2J@+ZC7hBy=eq(_*1Agtw!1rJtJH&*{l%E?cHO~~vHrZfTH>8((BN~wH3c^b zwJcDXfVx=(PXzJ_6b+saJV>F)s(F0crAw$+Vzn^~O%E8T8}|0=&==BQu4rpC#WOP3#WvA8mv&&vN>*kyUc8^gN0Hk6WM zo;x_LJN<-Ht=rZ$Y`J_$Y^mda@zz%Ry|U4lj;8hts1v4|kqu(O5 z23tq#VGSil*};$l57z40iKrkrlasI!CqsD(mc@@$MR+gNk-W;K3Hel6qQw#i-+d<% z{^r~(emwSP2Hzu7;pK1v$$yo|3NI++(eUL1e`UlcBd;mwbk#fcRPSA5 lqz4KMu(ZHpYOx1r7b`H*sK?dC_hpw|SUM>q8GW>o`5%A<{3`$e delta 2408 zcmaJ@3rt(*71lNQ!NswSUj&Hp1q`;aF*Z*pU>kxl0TKcs4g@l6V=lzO7{?DN1rn-i zYdht^@-2$mv`v#eq_yhQ?zW0LHC@{&lcqhgw0pE&+pOy}O`DolQ>8ZR)a<_(;w;m) zD_#BP{^vjEKj%BI`_~6WXTPAHdqs@b#qBc2Qe&E$j98JJuHx(xl?WZODyexc6Pshr zh|5|DLx-1T`~e-llv#w;S74KRrX%q*YsF$g5Z4M8bKk@CTQZv2csN^OI|WB=J|84yWo-@)ehwrsI*B zv>l~}{aCRV;F3Z>FU(^MoAfh${vzbK4& zLSK$$JB){R?{ELF>GE;}PAu(r_{+}4Pd z#zMSNI*F6Edi+gO!<{TE<-MLjNUlPOAt?A5Qx{>)a0$12Rj4fAaOC326? zsK-seoOtS}WG0uGO8#mVKQ+FLN02D$)vI@xi6Lw z%nh+~$;^@mp{8;;!qSreX$&e{wUmb&a7ihQHYiw+*R)~2J(o-*SIvSOW`=MD>R#ri zV`jqLB=6-fMiQA&ij7AyvH3)r9K#0<+aPM(jvb8+m}`8A;te%nPm@xhh(S2fbP8q7 zZaQbhGS=#}Pz@I#)!Zj?SwS6MKy!-^r+136+G3X9Ev{u6ueFSTX|2GX)*WZu4xCET zc(b(%Xm#L6dKzK(Ml!G8uTsXQ8H?aEJ7py$gjIJX4D(Vv?N)KGxIY%<7m$a$($-6n zSW7%jxZO&ZeQwbyTGQ>ED5pDJ4jF!UcK}V{h`N( zpLo=`;8mc-YY?r{_=?w_+j`zx%5VL~YeT+I2ZPVgqfvMl4H_4H<7gSKL3r4Ox4mkl zy?UJP@Zq-|btvrIhWgG{Bs!b%OlJVMI(>Py^)&i-wiCR{@WY)RNV-g_yO{AEi8#Nv zs|!zdx$(!Y4*as2hTG3z%5R6SUyO@>JpoTaz?9&IUx|PCdxbLxyBi7CVtlfT!IkbB zB>T0<3sed+ErDX}4p^Y<6JsqP!B+!TLaT5!parA669g?E5GhMKEN_Forw#KxRd}pt zA3i0t>M)JYT|M~bu6~3%_MY z&~d%bg^!MC5!DtE+p39D)(joZ?Mk}m*esg%3yC1<|lu31yK41EUtaHK@Re(TdG| z9)|ByZKxl!%J?Cdh|IAV8!toYn7klDV3;J$e-+L#3qCuz1ry`NgrkRR%t`2-^v1~D zJmL`fyK!i|9b3mWqWW51h&wQ@BlX6`4?Qfx=M!Jg4cybAo5H~3haW!(SHnd(9sXT0 znFr}iigcM|JQ8IsX2xtchs<^yi)6V^BMM6WZ_|;lc&37ZK5BxC)njk85EIeuI3I1m z_2^m3ii%<#PEP4D!AkM{spWfiym*Q=YxsJZ&L*OK^)u5cmbF-MgSFvFu@ScEPV(b$ zg>*6JjE>GtS{gGwHg0X^dsH3~h9y=fc*5+KaAUEjMBJCN?@(ug`P}d4UJwcMYd!g< zuwK$>;Ovod$BtHr@)&Yaa-o*HmM*8nLO;M`x-!Dg#|ecJ+H5wtA-@;=1^H*{q=+vC2y=bKfa^=Y!ng1L80VJX j!=Y6lF0WkV4y`&UoH{lS>Ua$-$NvoV+6C^#wPxyHJz5#J diff --git a/lib/WikiDB/backend/dumb/AllRevisionsIter.php b/lib/WikiDB/backend/dumb/AllRevisionsIter.php index deaa0cffa..6ba09cb44 100644 --- a/lib/WikiDB/backend/dumb/AllRevisionsIter.php +++ b/lib/WikiDB/backend/dumb/AllRevisionsIter.php @@ -7,7 +7,7 @@ * of a WikiDB_backend, and so it should work with all backends. */ class WikiDB_backend_dumb_AllRevisionsIter -extends WikiDB_backend_iterator + extends WikiDB_backend_iterator { /** * Constructor. @@ -16,7 +16,8 @@ extends WikiDB_backend_iterator * @param $backend object A WikiDB_backend. * @param $pagename string Page whose revisions to get. */ - function WikiDB_backend_dumb_AllRevisionsIter(&$backend, $pagename) { + function WikiDB_backend_dumb_AllRevisionsIter(&$backend, $pagename) + { $this->_backend = &$backend; $this->_pagename = $pagename; $this->_lastversion = -1; @@ -27,7 +28,8 @@ extends WikiDB_backend_iterator * * @see WikiDB_backend_iterator_next; */ - function next () { + function next() + { $backend = &$this->_backend; $pagename = &$this->_pagename; $version = &$this->_lastversion; @@ -45,18 +47,18 @@ extends WikiDB_backend_iterator if ($version == 0) return false; - if (is_string($vdata) and !empty($vdata)) { - $vdata1 = @unserialize($vdata); + if (is_string($vdata) and !empty($vdata)) { + $vdata1 = @unserialize($vdata); if (empty($vdata1)) { if (DEBUG) // string but unseriazible - trigger_error ("Broken page $pagename ignored. Run Check WikiDB", E_USER_WARNING); - return false; + trigger_error("Broken page $pagename ignored. Run Check WikiDB", E_USER_WARNING); + return false; } $vdata = $vdata1; - } + } $rev = array('versiondata' => $vdata, - 'pagename' => $pagename, - 'version' => $version); + 'pagename' => $pagename, + 'version' => $version); if (!empty($vdata['%pagedata'])) { $rev['pagedata'] = $vdata['%pagedata']; @@ -64,7 +66,9 @@ extends WikiDB_backend_iterator return $rev; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/backend/dumb/BackLinkIter.php b/lib/WikiDB/backend/dumb/BackLinkIter.php index 0ddeb6af4..5a93583ea 100644 --- a/lib/WikiDB/backend/dumb/BackLinkIter.php +++ b/lib/WikiDB/backend/dumb/BackLinkIter.php @@ -9,15 +9,17 @@ require_once 'lib/WikiDB/backend.php'; * This is mostly here for testing, 'cause it's slow,slow,slow. */ class WikiDB_backend_dumb_BackLinkIter -extends WikiDB_backend_iterator + extends WikiDB_backend_iterator { - function WikiDB_backend_dumb_BackLinkIter(&$backend, &$all_pages, $pagename) { + function WikiDB_backend_dumb_BackLinkIter(&$backend, &$all_pages, $pagename) + { $this->_pages = $all_pages; $this->_backend = &$backend; $this->_target = $pagename; } - function next() { + function next() + { while ($page = $this->_pages->next()) { $pagename = $page['pagename']; $links = $this->_backend->get_links($pagename, false); @@ -30,7 +32,8 @@ extends WikiDB_backend_iterator } } - function free() { + function free() + { $this->_pages->free(); } } diff --git a/lib/WikiDB/backend/dumb/LinkSearchIter.php b/lib/WikiDB/backend/dumb/LinkSearchIter.php index 91353c416..55745fe55 100644 --- a/lib/WikiDB/backend/dumb/LinkSearchIter.php +++ b/lib/WikiDB/backend/dumb/LinkSearchIter.php @@ -36,125 +36,130 @@ */ class WikiDB_backend_dumb_LinkSearchIter -extends WikiDB_backend_iterator + extends WikiDB_backend_iterator { function WikiDB_backend_dumb_LinkSearchIter(&$backend, &$pageiter, $search, $linktype, - $relation=false, $options=array()) + $relation = false, $options = array()) { - $this->_backend = &$backend; - $this->_pages = $pageiter; - $this->search = $search; // search the linkvalue. it should be the value or pagename - $this->relation = $relation; // limit the search to this linkname - $this->linktype = $linktype; - $this->_reverse = false; - $this->_want_relations = true; - $this->sortby = isset($options['sortby']) ? $options['sortby'] : ''; - $this->limit = isset($options['limit']) ? $options['limit'] : ''; - $this->exclude = isset($options['exclude']) ? $options['exclude'] : ''; - $this->_field = 'pagename'; // the name of the linkvalue field to apply the search - $this->_dbi =& $GLOBALS['request']->_dbi; - if ($linktype == 'relation') { + $this->_backend = &$backend; + $this->_pages = $pageiter; + $this->search = $search; // search the linkvalue. it should be the value or pagename + $this->relation = $relation; // limit the search to this linkname + $this->linktype = $linktype; + $this->_reverse = false; $this->_want_relations = true; - $this->_field = 'linkrelation'; - } - if ($linktype == 'attribute') { - $this->_want_relations = true; - $this->_field = 'attribute'; - } - if ($linktype == 'linkfrom') { - $this->_reverse = true; - } - $this->_page = false; + $this->sortby = isset($options['sortby']) ? $options['sortby'] : ''; + $this->limit = isset($options['limit']) ? $options['limit'] : ''; + $this->exclude = isset($options['exclude']) ? $options['exclude'] : ''; + $this->_field = 'pagename'; // the name of the linkvalue field to apply the search + $this->_dbi =& $GLOBALS['request']->_dbi; + if ($linktype == 'relation') { + $this->_want_relations = true; + $this->_field = 'linkrelation'; + } + if ($linktype == 'attribute') { + $this->_want_relations = true; + $this->_field = 'attribute'; + } + if ($linktype == 'linkfrom') { + $this->_reverse = true; + } + $this->_page = false; } // iterate a nested page-links loop. there will be multiple results per page. // we must keep the page iter internally. - function next() { + function next() + { while (1) { - if (!isset($this->_links) or count($this->_links) == 0) { - $page = $this->_next_page(); // initialize all links of this page - if (!$page) return false; - } else { - $page = $this->_page; - } - // iterate the links. the links are pushed into the handy triple by _get_links - while ($link = array_shift($this->_links)) { - // unmatching relations are already filtered out - if ($this->search->match($link['linkvalue'])) { //pagename or attr-value - if ($link['linkname']) - return array('pagename' => $page, - 'linkname' => $link['linkname'], - 'linkvalue'=> $link['linkvalue']); - else - return array('pagename' => $page, - 'linkvalue'=> $link['linkvalue']); - } - } - // no links on this page anymore. + if (!isset($this->_links) or count($this->_links) == 0) { + $page = $this->_next_page(); // initialize all links of this page + if (!$page) return false; + } else { + $page = $this->_page; + } + // iterate the links. the links are pushed into the handy triple by _get_links + while ($link = array_shift($this->_links)) { + // unmatching relations are already filtered out + if ($this->search->match($link['linkvalue'])) { //pagename or attr-value + if ($link['linkname']) + return array('pagename' => $page, + 'linkname' => $link['linkname'], + 'linkvalue' => $link['linkvalue']); + else + return array('pagename' => $page, + 'linkvalue' => $link['linkvalue']); + } + } + // no links on this page anymore. } } // initialize the links also - function _next_page() { - unset($this->_links); - if (!($next = $this->_pages->next())) - return false; - $this->_page = $next['pagename']; - while(!($this->_links = $this->_get_links($this->_page))) { + function _next_page() + { + unset($this->_links); if (!($next = $this->_pages->next())) return false; $this->_page = $next['pagename']; - } - return $this->_page; + while (!($this->_links = $this->_get_links($this->_page))) { + if (!($next = $this->_pages->next())) + return false; + $this->_page = $next['pagename']; + } + return $this->_page; } // get the links of each page in advance - function _get_links($pagename) { - $links = array(); - if ($this->linktype == 'attribute') { - $page = $this->_dbi->getPage($pagename); - $attribs = $page->get('attributes'); - if ($attribs) { - foreach ($attribs as $attribute => $value) { - if ($this->relation and !$this->relation->match($attribute)) continue; - // The logical operator and unit unification (not yet) is encoded into - // a seperate search object. - if (!$this->search->match($value)) continue; - $links[] = array('pagename' => $pagename, - 'linkname' => $attribute, - 'linkvalue' => $value); - } + function _get_links($pagename) + { + $links = array(); + if ($this->linktype == 'attribute') { + $page = $this->_dbi->getPage($pagename); + $attribs = $page->get('attributes'); + if ($attribs) { + foreach ($attribs as $attribute => $value) { + if ($this->relation and !$this->relation->match($attribute)) continue; + // The logical operator and unit unification (not yet) is encoded into + // a seperate search object. + if (!$this->search->match($value)) continue; + $links[] = array('pagename' => $pagename, + 'linkname' => $attribute, + 'linkvalue' => $value); + } + } + unset($attribs); + } else { + $link_iter = $this->_backend->get_links($pagename, $this->_reverse, true, + $this->sortby, $this->limit, + $this->exclude, $this->_want_relations); + // we already stepped through all links. make use of that. + if ($this->_want_relations + and isset($link_iter->_options['found_relations']) + and $link_iter->_options['found_relations'] == 0 + ) { + $link_iter->free(); + return $links; + } + while ($link = $link_iter->next()) { + if (empty($link[$this->_field])) continue; + if ($this->_want_relations and $this->relation + and !$this->relation->match($link['linkrelation']) + ) continue; + // check hash values, with/out want_relations + $links[] = array('pagename' => $pagename, + 'linkname' => $this->_want_relations ? $link['linkrelation'] : '', + 'linkvalue' => $link['pagename']); + } + $link_iter->free(); } - unset($attribs); - } else { - $link_iter = $this->_backend->get_links($pagename, $this->_reverse, true, - $this->sortby, $this->limit, - $this->exclude, $this->_want_relations); - // we already stepped through all links. make use of that. - if ($this->_want_relations - and isset($link_iter->_options['found_relations']) - and $link_iter->_options['found_relations'] == 0) - { - $link_iter->free(); return $links; - } - while ($link = $link_iter->next()) { - if (empty($link[$this->_field])) continue; - if ($this->_want_relations and $this->relation - and !$this->relation->match($link['linkrelation'])) continue; - // check hash values, with/out want_relations - $links[] = array('pagename' => $pagename, - 'linkname' => $this->_want_relations ? $link['linkrelation'] : '', - 'linkvalue' => $link['pagename']); - } - $link_iter->free(); - } - return $links; } - function free() { - $this->_page = false; - unset($this->_links); + function free() + { + $this->_page = false; + unset($this->_links); $this->_pages->free(); } } diff --git a/lib/WikiDB/backend/dumb/MostPopularIter.php b/lib/WikiDB/backend/dumb/MostPopularIter.php index d624dda4a..beb328c8f 100644 --- a/lib/WikiDB/backend/dumb/MostPopularIter.php +++ b/lib/WikiDB/backend/dumb/MostPopularIter.php @@ -9,9 +9,10 @@ require_once 'lib/WikiDB/backend.php'; * methods. */ class WikiDB_backend_dumb_MostPopularIter -extends WikiDB_backend_iterator + extends WikiDB_backend_iterator { - function WikiDB_backend_dumb_MostPopularIter($backend, &$all_pages, $limit) { + function WikiDB_backend_dumb_MostPopularIter($backend, &$all_pages, $limit) + { $this->_pages = array(); $pages = &$this->_pages; @@ -21,11 +22,10 @@ extends WikiDB_backend_iterator $pages[] = $page; } - if($limit < 0){ //sort pages in reverse order - ie least popular first. + if ($limit < 0) { //sort pages in reverse order - ie least popular first. usort($pages, 'WikiDB_backend_dumb_MostPopularIter_sortf_rev'); $limit = -$limit; - } - else usort($pages, 'WikiDB_backend_dumb_MostPopularIter_sortf'); + } else usort($pages, 'WikiDB_backend_dumb_MostPopularIter_sortf'); if ($limit < 0) { $pages = array_reverse($pages); @@ -36,16 +36,19 @@ extends WikiDB_backend_iterator array_splice($pages, $limit); } - function next() { + function next() + { return array_shift($this->_pages); } - function free() { + function free() + { unset($this->_pages); } } -function WikiDB_backend_dumb_MostPopularIter_sortf($a,$b) { +function WikiDB_backend_dumb_MostPopularIter_sortf($a, $b) +{ $ahits = $bhits = 0; if (isset($a['pagedata']['hits'])) $ahits = (int)$a['pagedata']['hits']; @@ -54,7 +57,8 @@ function WikiDB_backend_dumb_MostPopularIter_sortf($a,$b) { return $bhits - $ahits; } -function WikiDB_backend_dumb_MostPopularIter_sortf_rev($a,$b) { +function WikiDB_backend_dumb_MostPopularIter_sortf_rev($a, $b) +{ $ahits = $bhits = 0; if (isset($a['pagedata']['hits'])) $ahits = (int)$a['pagedata']['hits']; diff --git a/lib/WikiDB/backend/dumb/MostRecentIter.php b/lib/WikiDB/backend/dumb/MostRecentIter.php index 75bfa28a0..4138795de 100644 --- a/lib/WikiDB/backend/dumb/MostRecentIter.php +++ b/lib/WikiDB/backend/dumb/MostRecentIter.php @@ -7,16 +7,19 @@ require_once 'lib/WikiDB/backend.php'; * This iterator will work with any backends. */ class WikiDB_backend_dumb_MostRecentIter -extends WikiDB_backend_iterator + extends WikiDB_backend_iterator { - function WikiDB_backend_dumb_MostRecentIter(&$backend, &$pages, $params) { + function WikiDB_backend_dumb_MostRecentIter(&$backend, &$pages, $params) + { $limit = false; extract($params); if ($exclude_major_revisions) $include_minor_revisions = true; $reverse = $limit < 0; - if($reverse){$limit = -$limit;} + if ($reverse) { + $limit = -$limit; + } $this->_revisions = array(); while ($page = $pages->next()) { $revs = $backend->get_all_revisions($page['pagename']); @@ -25,13 +28,12 @@ extends WikiDB_backend_iterator if (!$vdata) continue; assert(is_array($vdata)); if (empty($vdata['mtime'])) { - $vdata['mtime'] = 0; - } + $vdata['mtime'] = 0; + } if (!empty($vdata['is_minor_edit'])) { if (!$include_minor_revisions) continue; - } - else { + } else { if ($exclude_major_revisions) continue; } @@ -55,22 +57,26 @@ extends WikiDB_backend_iterator } } - function next() { + function next() + { return array_shift($this->_revisions); } - function free() { + function free() + { unset($this->_revisions); } } -function WikiDB_backend_dumb_MostRecentIter_sortf($a, $b) { +function WikiDB_backend_dumb_MostRecentIter_sortf($a, $b) +{ $acreated = $a['versiondata']['mtime']; $bcreated = $b['versiondata']['mtime']; return $bcreated - $acreated; } -function WikiDB_backend_dumb_MostRecentIter_sortf_rev($a, $b) { +function WikiDB_backend_dumb_MostRecentIter_sortf_rev($a, $b) +{ $acreated = $a['versiondata']['mtime']; $bcreated = $b['versiondata']['mtime']; return $acreated - $bcreated; diff --git a/lib/WikiDB/backend/dumb/TextSearchIter.php b/lib/WikiDB/backend/dumb/TextSearchIter.php index 195a03ca3..d7f601039 100644 --- a/lib/WikiDB/backend/dumb/TextSearchIter.php +++ b/lib/WikiDB/backend/dumb/TextSearchIter.php @@ -1,28 +1,29 @@ _backend = &$backend; $this->_pages = $pages; $this->_fulltext = $fulltext; - $this->_search =& $search; - $this->_index = 0; + $this->_search =& $search; + $this->_index = 0; $this->_stoplist =& $search->_stoplist; $this->stoplisted = array(); - $this->_from = 0; - if (isset($options['limit'])) // extract from,count from limit - list($this->_from, $this->_count) = WikiDB_backend::limit($options['limit']); + $this->_from = 0; + if (isset($options['limit'])) // extract from,count from limit + list($this->_from, $this->_count) = WikiDB_backend::limit($options['limit']); else - $this->_count = 0; + $this->_count = 0; if (isset($options['exclude'])) $this->_exclude = $options['exclude']; else $this->_exclude = false; } - function _get_content(&$page) { + function _get_content(&$page) + { $backend = &$this->_backend; $pagename = $page['pagename']; @@ -33,54 +34,59 @@ extends WikiDB_backend_iterator return $page['versiondata']['%content']; } - function _match(&$page) { + function _match(&$page) + { $text = $page['pagename']; if ($result = $this->_search->match($text)) { // first match the pagename only return $this->_search->score($text) * 2.0; - } + } if ($this->_fulltext) { // eliminate stoplist words from fulltext search - if (preg_match("/^".$this->_stoplist."$/i", $text)) { + if (preg_match("/^" . $this->_stoplist . "$/i", $text)) { $this->stoplisted[] = $text; return $result; } $text .= "\n" . $this->_get_content($page); // Todo: Bonus for meta keywords (* 1.5) and headers if ($this->_search->match($text)) - return $this->_search->score($text); + return $this->_search->score($text); } else { return $result; - } + } } - function next() { + function next() + { $pages = &$this->_pages; while ($page = $pages->next()) { if ($score = $this->_match($page)) { - $this->_index++; - if (($this->_from > 0) and ($this->_index <= $this->_from)) + $this->_index++; + if (($this->_from > 0) and ($this->_index <= $this->_from)) // not yet reached the offset - continue; + continue; /*if ($this->_count and ($this->_index > $this->_count)) { // reached the limit, but need getTotal $this->_count++; return false; }*/ if (is_array($page)) - $page['score'] = $score; - else - $page->score = $score; + $page['score'] = $score; + else + $page->score = $score; return $page; } } return false; } - function free() { + function free() + { $this->_pages->free(); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/backend/dumb/WantedPagesIter.php b/lib/WikiDB/backend/dumb/WantedPagesIter.php index cbc503076..003d868af 100644 --- a/lib/WikiDB/backend/dumb/WantedPagesIter.php +++ b/lib/WikiDB/backend/dumb/WantedPagesIter.php @@ -6,11 +6,12 @@ * This is mostly here for testing, 'cause it's slow,slow,slow. */ class WikiDB_backend_dumb_WantedPagesIter -extends WikiDB_backend_iterator + extends WikiDB_backend_iterator { - function WikiDB_backend_dumb_WantedPagesIter(&$backend, &$all_pages, $exclude='', $sortby='', $limit='') { - $this->_allpages = $all_pages; - $this->_allpages_array = $all_pages->asArray(); + function WikiDB_backend_dumb_WantedPagesIter(&$backend, &$all_pages, $exclude = '', $sortby = '', $limit = '') + { + $this->_allpages = $all_pages; + $this->_allpages_array = $all_pages->asArray(); $this->_backend = &$backend; if (!is_array($exclude)) $this->exclude = $exclude ? PageList::explodePageList($exclude) : array(); @@ -27,7 +28,8 @@ extends WikiDB_backend_iterator $this->pagelinks = array(); } - function next() { + function next() + { while ($page = $this->_allpages->next()) { while ($this->pagelinks) { // deferred return return array_pop($this->pagelinks); @@ -40,7 +42,7 @@ extends WikiDB_backend_iterator if ($this->limit and $this->pos > $this->limit) break; if ($this->exclude and in_array($link['pagename'], $this->exclude)) continue; // better membership for a pageiterator? - if (! in_array($link['pagename'], $this->_allpages_array)) { + if (!in_array($link['pagename'], $this->_allpages_array)) { if ($this->from and $this->pos < $this->from) continue; // collect all links per page and return them deferred $link['wantedfrom'] = $pagename; @@ -55,7 +57,8 @@ extends WikiDB_backend_iterator return false; } - function free() { + function free() + { unset($this->_allpages_array); $this->_allpages->free(); unset($this->_allpages); diff --git a/lib/WikiDB/backend/file.php b/lib/WikiDB/backend/file.php index de32be801..1adecf11c 100644 --- a/lib/WikiDB/backend/file.php +++ b/lib/WikiDB/backend/file.php @@ -44,16 +44,16 @@ require_once 'lib/WikiDB/backend.php'; require_once 'lib/ErrorManager.php'; class WikiDB_backend_file -extends WikiDB_backend + extends WikiDB_backend { var $data_dir; var $_dir_names; - var $_page_data; // temporarily stores the pagedata (via _loadPageData) - var $_page_version_data; // temporarily stores the versiondata (via _loadVersionData) - var $_latest_versions; // temporarily stores the latest version-numbers (for every pagename) + var $_page_data; // temporarily stores the pagedata (via _loadPageData) + var $_page_version_data; // temporarily stores the versiondata (via _loadVersionData) + var $_latest_versions; // temporarily stores the latest version-numbers (for every pagename) - function WikiDB_backend_file( $dbparam ) + function WikiDB_backend_file($dbparam) { $this->data_dir = $dbparam['directory']; if (file_exists($this->data_dir) and is_file($this->data_dir)) @@ -63,10 +63,10 @@ extends WikiDB_backend } $this->_dir_names - = array('ver_data' => $this->data_dir.'/'.'ver_data', - 'page_data' => $this->data_dir.'/'.'page_data', - 'latest_ver' => $this->data_dir.'/'.'latest_ver', - 'links' => $this->data_dir.'/'.'links' ); + = array('ver_data' => $this->data_dir . '/' . 'ver_data', + 'page_data' => $this->data_dir . '/' . 'page_data', + 'latest_ver' => $this->data_dir . '/' . 'latest_ver', + 'links' => $this->data_dir . '/' . 'links'); foreach ($this->_dir_names as $key => $val) { if (file_exists($val) and is_file($val)) @@ -83,90 +83,98 @@ extends WikiDB_backend // ********************************************************************* // common file load / save functions: - function _pagename2filename($type, $pagename, $version) { - if ($version == 0) - return $this->_dir_names[$type].'/'.urlencode($pagename); - else - return $this->_dir_names[$type].'/'.urlencode($pagename).'--'.$version; - } - - function _loadPage($type, $pagename, $version, $set_pagename = true) { - $filename = $this->_pagename2filename($type, $pagename, $version); - if (!file_exists($filename)) return NULL; - if (!filesize($filename)) return array(); - if ($fd = @fopen($filename, "rb")) { - $locked = flock($fd, 1); # Read lock - if (!$locked) { - ExitWiki("Timeout while obtaining lock. Please try again"); - } - if ($data = fread($fd, filesize($filename))) { - $pd = unserialize($data); - if ($set_pagename == true) - $pd['pagename'] = $pagename; - if ($version != 0) - $pd['version'] = $version; - if (!is_array($pd)) - ExitWiki(sprintf(gettext("'%s': corrupt file"), - htmlspecialchars($filename))); - else - return $pd; - } - fclose($fd); - } - return NULL; + function _pagename2filename($type, $pagename, $version) + { + if ($version == 0) + return $this->_dir_names[$type] . '/' . urlencode($pagename); + else + return $this->_dir_names[$type] . '/' . urlencode($pagename) . '--' . $version; } - function _savePage($type, $pagename, $version, $data) { + function _loadPage($type, $pagename, $version, $set_pagename = true) + { $filename = $this->_pagename2filename($type, $pagename, $version); - if($fd = fopen($filename, 'a+b')) { - $locked = flock($fd,2); // Exclusive blocking lock - if (!$locked) { - ExitWiki("Timeout while obtaining lock. Please try again"); - } - - rewind($fd); - ftruncate($fd, 0); - $pagedata = serialize($data); - $len = strlen($pagedata); - $num = fwrite($fd, $pagedata, $len); - assert($num == $len); - fclose($fd); + if (!file_exists($filename)) return NULL; + if (!filesize($filename)) return array(); + if ($fd = @fopen($filename, "rb")) { + $locked = flock($fd, 1); # Read lock + if (!$locked) { + ExitWiki("Timeout while obtaining lock. Please try again"); + } + if ($data = fread($fd, filesize($filename))) { + $pd = unserialize($data); + if ($set_pagename == true) + $pd['pagename'] = $pagename; + if ($version != 0) + $pd['version'] = $version; + if (!is_array($pd)) + ExitWiki(sprintf(gettext("'%s': corrupt file"), + htmlspecialchars($filename))); + else + return $pd; + } + fclose($fd); + } + return NULL; + } + + function _savePage($type, $pagename, $version, $data) + { + $filename = $this->_pagename2filename($type, $pagename, $version); + if ($fd = fopen($filename, 'a+b')) { + $locked = flock($fd, 2); // Exclusive blocking lock + if (!$locked) { + ExitWiki("Timeout while obtaining lock. Please try again"); + } + + rewind($fd); + ftruncate($fd, 0); + $pagedata = serialize($data); + $len = strlen($pagedata); + $num = fwrite($fd, $pagedata, $len); + assert($num == $len); + fclose($fd); } else { - ExitWiki("Error while writing page '$pagename'"); + ExitWiki("Error while writing page '$pagename'"); } } - function _removePage($type, $pagename, $version) { + function _removePage($type, $pagename, $version) + { $filename = $this->_pagename2filename($type, $pagename, $version); if (!file_exists($filename)) return NULL; $f = @unlink($filename); if ($f == false) - trigger_error("delete file failed: ".$filename." ver: ".$version, E_USER_WARNING); + trigger_error("delete file failed: " . $filename . " ver: " . $version, E_USER_WARNING); } // ********************************************************************* // ********************************************************************* // Load/Save Version-Data - function _loadVersionData($pagename, $version) { + function _loadVersionData($pagename, $version) + { if ($this->_page_version_data != NULL) { - if ( ($this->_page_version_data['pagename'] == $pagename) && - ($this->_page_version_data['version'] == $version) ) { + if (($this->_page_version_data['pagename'] == $pagename) && + ($this->_page_version_data['version'] == $version) + ) { return $this->_page_version_data; - } + } } $vd = $this->_loadPage('ver_data', $pagename, $version); if ($vd != NULL) { $this->_page_version_data = $vd; - if ( ($this->_page_version_data['pagename'] == $pagename) && - ($this->_page_version_data['version'] == $version) ) { + if (($this->_page_version_data['pagename'] == $pagename) && + ($this->_page_version_data['version'] == $version) + ) { return $this->_page_version_data; - } + } } return NULL; } - function _saveVersionData($pagename, $version, $data) { + function _saveVersionData($pagename, $version, $data) + { $this->_savePage('ver_data', $pagename, $version, $data); // check if this is a newer version: @@ -178,11 +186,12 @@ extends WikiDB_backend // ********************************************************************* // Load/Save Page-Data - function _loadPageData($pagename) { + function _loadPageData($pagename) + { if ($this->_page_data != NULL) { if ($this->_page_data['pagename'] == $pagename) { return $this->_page_data; - } + } } $pd = $this->_loadPage('page_data', $pagename, 0); if ($pd != NULL) @@ -190,39 +199,42 @@ extends WikiDB_backend if ($this->_page_data != NULL) { if ($this->_page_data['pagename'] == $pagename) { return $this->_page_data; - } + } } - return array(); // no values found + return array(); // no values found } - function _savePageData($pagename, $data) { + function _savePageData($pagename, $data) + { $this->_savePage('page_data', $pagename, 0, $data); } // ********************************************************************* // Load/Save Latest-Version - function _saveLatestVersions() { + function _saveLatestVersions() + { $data = $this->_latest_versions; if ($data == NULL) $data = array(); $this->_savePage('latest_ver', 'latest_versions', 0, $data); } - function _setLatestVersion($pagename, $version) { + function _setLatestVersion($pagename, $version) + { // make sure the page version list is loaded: $this->_getLatestVersion($pagename); if ($version > 0) { $this->_getLatestVersion($pagename); $this->_latest_versions[$pagename] = $version; - } - else { + } else { // Remove this page from the Latest-Version-List: unset($this->_latest_versions[$pagename]); } $this->_saveLatestVersions(); } - function _loadLatestVersions() { + function _loadLatestVersions() + { if ($this->_latest_versions != NULL) return; @@ -233,23 +245,27 @@ extends WikiDB_backend $this->_latest_versions = array(); // empty array } - function _getLatestVersion($pagename) { - $this->_loadLatestVersions(); - if (array_key_exists($pagename, $this->_latest_versions) == false) - return 0; // do version exists - return $this->_latest_versions[$pagename]; + function _getLatestVersion($pagename) + { + $this->_loadLatestVersions(); + if (array_key_exists($pagename, $this->_latest_versions) == false) + return 0; // do version exists + return $this->_latest_versions[$pagename]; } // ********************************************************************* // Load/Save Page-Links - function _loadPageLinks($pagename) { + function _loadPageLinks($pagename) + { $pd = $this->_loadPage('links', $pagename, 0, false); if ($pd != NULL) - return $pd;; - return array(); // no values found + return $pd; + ; + return array(); // no values found } - function _savePageLinks($pagename, $links) { + function _savePageLinks($pagename, $links) + { $this->_savePage('links', $pagename, 0, $links); } @@ -268,7 +284,8 @@ extends WikiDB_backend * don't think we need this...) * */ - function get_pagedata($pagename) { + function get_pagedata($pagename) + { return $this->_loadPageData($pagename); } @@ -299,10 +316,11 @@ extends WikiDB_backend * This will create a new page if page being requested does not * exist. */ - function update_pagedata($pagename, $newdata) { + function update_pagedata($pagename, $newdata) + { $data = $this->get_pagedata($pagename); if (count($data) == 0) { - $this->_savePageData($pagename, $newdata); // create a new pagedata-file + $this->_savePageData($pagename, $newdata); // create a new pagedata-file return; } @@ -312,7 +330,7 @@ extends WikiDB_backend else $data[$key] = $val; } - $this->_savePageData($pagename, $data); // write new pagedata-file + $this->_savePageData($pagename, $data); // write new pagedata-file } /** @@ -322,7 +340,8 @@ extends WikiDB_backend * @return int The latest version number for the page. Returns zero if * no versions of a page exist. */ - function get_latest_version($pagename) { + function get_latest_version($pagename) + { return $this->_getLatestVersion($pagename); } @@ -336,7 +355,8 @@ extends WikiDB_backend * * FIXED: Check if this version really exists! */ - function get_previous_version($pagename, $version) { + function get_previous_version($pagename, $version) + { $prev = ($version > 0 ? $version - 1 : 0); while ($prev and !file_exists($this->_pagename2filename('ver_data', $pagename, $prev))) { $prev--; @@ -369,8 +389,9 @@ extends WikiDB_backend * For description of other version meta-data see WikiDB_PageRevision::get(). * @see WikiDB_PageRevision::get */ - function get_versiondata($pagename, $version, $want_content = false) { - $vd = $this->_loadVersionData($pagename, $version); + function get_versiondata($pagename, $version, $want_content = false) + { + $vd = $this->_loadVersionData($pagename, $version); if ($vd == NULL) return false; return $vd; @@ -381,13 +402,14 @@ extends WikiDB_backend * * @access protected Via WikiDB */ - function rename_page($pagename, $to) { + function rename_page($pagename, $to) + { $version = _getLatestVersion($pagename); foreach ($this->_dir_names as $type => $path) { if (is_dir($path)) { $filename = $this->_pagename2filename($type, $pagename, $version); $new = $this->_pagename2filename($type, $to, $version); - @rename($filename,$new); + @rename($filename, $new); } } $this->update_pagedata($pagename, array('pagename' => $to)); @@ -397,7 +419,8 @@ extends WikiDB_backend /** * See ADODB for a better delete_page(), which can be undone and is seen in RecentChanges. */ - function delete_page($pagename) { + function delete_page($pagename) + { $this->purge_page($pagename); } @@ -408,7 +431,8 @@ extends WikiDB_backend * * @param $pagename string Page name. */ - function purge_page($pagename) { + function purge_page($pagename) + { $ver = $this->get_latest_version($pagename); while ($ver > 0) { $this->_removePage('ver_data', $pagename, $ver); @@ -432,17 +456,19 @@ extends WikiDB_backend * @param $pagename string Page name. * @param $version integer Version to delete. */ - function delete_versiondata($pagename, $version) { + function delete_versiondata($pagename, $version) + { if ($this->get_latest_version($pagename) == $version) { // try to delete the latest version! // so check if an older version exist: if ($this->get_versiondata($pagename, - $this->get_previous_version($pagename, $version), - false) == false) { - // there is no older version.... - // so the completely page will be removed: - $this->delete_page($pagename); - return; + $this->get_previous_version($pagename, $version), + false) == false + ) { + // there is no older version.... + // so the completely page will be removed: + $this->delete_page($pagename); + return; } } $this->_removePage('ver_data', $pagename, $version); @@ -460,7 +486,8 @@ extends WikiDB_backend * * @see get_versiondata */ - function set_versiondata($pagename, $version, $data) { + function set_versiondata($pagename, $version, $data) + { $this->_saveVersionData($pagename, $version, $data); } @@ -476,7 +503,8 @@ extends WikiDB_backend * @param $newdata hash New revision metadata. * @see set_versiondata, get_versiondata */ - function update_versiondata($pagename, $version, $newdata) { + function update_versiondata($pagename, $version, $newdata) + { $data = $this->get_versiondata($pagename, $version, true); if (!$data) { assert($data); @@ -498,7 +526,8 @@ extends WikiDB_backend * * @param $links array List of page(names) which page links to. */ - function set_links($pagename, $links) { + function set_links($pagename, $links) + { $this->_savePageLinks($pagename, $links); } @@ -511,21 +540,21 @@ extends WikiDB_backend * FIXME: array or iterator? * @return object A WikiDB_backend_iterator. */ - function get_links($pagename, $reversed=true, $include_empty=false, - $sortby='', $limit='', $exclude='', - $want_relations=false) + function get_links($pagename, $reversed = true, $include_empty = false, + $sortby = '', $limit = '', $exclude = '', + $want_relations = false) { if ($reversed == false) return new WikiDB_backend_file_iter($this, $this->_loadPageLinks($pagename)); $this->_loadLatestVersions(); - $pagenames = $this->_latest_versions; // now we have an array with the key is the pagename of all pages + $pagenames = $this->_latest_versions; // now we have an array with the key is the pagename of all pages - $out = array(); // create empty out array + $out = array(); // create empty out array foreach ($pagenames as $key => $val) { $links = $this->_loadPageLinks($key); - foreach ($links as $key2 => $val2) { + foreach ($links as $key2 => $val2) { if ($val2['linkto'] == $pagename) array_push($out, $key); } @@ -565,7 +594,8 @@ extends WikiDB_backend * * @return object A WikiDB_backend_iterator. */ - function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') { + function get_all_pages($include_empty = false, $sortby = '', $limit = '', $exclude = '') + { require_once 'lib/PageList.php'; $this->_loadLatestVersions(); $a = array_keys($this->_latest_versions); @@ -573,18 +603,25 @@ extends WikiDB_backend return new WikiDB_backend_file_iter($this, $a); $sortby = $this->sortby($sortby, 'db', $this->sortable_columns()); switch ($sortby) { - case '': break; - case 'pagename ASC': sort($a); break; - case 'pagename DESC': rsort($a); break; + case '': + break; + case 'pagename ASC': + sort($a); + break; + case 'pagename DESC': + rsort($a); + break; } return new WikiDB_backend_file_iter($this, $a); } - function sortable_columns() { + function sortable_columns() + { return array('pagename'); } - function numPages($filter=false, $exclude='') { + function numPages($filter = false, $exclude = '') + { $this->_loadLatestVersions(); return count($this->_latest_versions); } @@ -601,7 +638,8 @@ extends WikiDB_backend * * All backends should support write locking. */ - function lock($write_lock = true) { + function lock($write_lock = true) + { //trigger_error("lock: Not Implemented", E_USER_WARNING); } @@ -612,14 +650,16 @@ extends WikiDB_backend * unlock() is called as many times as lock() has been. If $force is * set to true, the the database is unconditionally unlocked. */ - function unlock($force = false) { + function unlock($force = false) + { //trigger_error("unlock: Not Implemented", E_USER_WARNING); } /** * Close database. */ - function close () { + function close() + { //trigger_error("close: Not Implemented", E_USER_WARNING); } @@ -628,15 +668,17 @@ extends WikiDB_backend * * This should flush all unwritten data to the filesystem. */ - function sync() { + function sync() + { //trigger_error("sync: Not Implemented", E_USER_WARNING); } /** * Optimize the database. */ - function optimize() { - return 0;//trigger_error("optimize: Not Implemented", E_USER_WARNING); + function optimize() + { + return 0; //trigger_error("optimize: Not Implemented", E_USER_WARNING); } /** @@ -650,7 +692,8 @@ extends WikiDB_backend * * @return boolean True iff database is in a consistent state. */ - function check() { + function check() + { //trigger_error("check: Not Implemented", E_USER_WARNING); } @@ -662,14 +705,16 @@ extends WikiDB_backend * * @return boolean True iff successful. */ - function rebuild() { + function rebuild() + { //trigger_error("rebuild: Not Implemented", E_USER_WARNING); } - function _parse_searchwords($search) { + function _parse_searchwords($search) + { $search = strtolower(trim($search)); if (!$search) - return array(array(),array()); + return array(array(), array()); $words = preg_split('/\s+/', $search); $exclude = array(); @@ -683,11 +728,14 @@ extends WikiDB_backend return array($words, $exclude); } -}; +} + +; class WikiDB_backend_file_iter extends WikiDB_backend_iterator { - function WikiDB_backend_file_iter(&$backend, &$query_result, $options=array()) { + function WikiDB_backend_file_iter(&$backend, &$query_result, $options = array()) + { $this->_backend = &$backend; $this->_result = $query_result; $this->_options = $options; @@ -696,7 +744,8 @@ class WikiDB_backend_file_iter extends WikiDB_backend_iterator reset($this->_result); } - function next() { + function next() + { if (!$this->_result) return false; if (count($this->_result) <= 0) @@ -717,7 +766,7 @@ class WikiDB_backend_file_iter extends WikiDB_backend_iterator unset($pagedata['_cached_html']); unset($pagedata['pagename']); $rec = array('pagename' => $pn, - 'pagedata' => $pagedata); + 'pagedata' => $pagedata); if (is_array($e[1])) { $rec['linkrelation'] = $e[1]['relation']; } @@ -725,14 +774,20 @@ class WikiDB_backend_file_iter extends WikiDB_backend_iterator //$rec['versiondata'] = $backend->get_versiondata($pn, $rec['version'], true); return $rec; } - function asArray() { + + function asArray() + { reset($this->_result); return $this->_result; } - function count() { + + function count() + { return count($this->_result); } - function free () { + + function free() + { $this->_result = array(); } } diff --git a/lib/WikiDB/backend/flatfile.php b/lib/WikiDB/backend/flatfile.php index 4c0558b14..1a6edce09 100644 --- a/lib/WikiDB/backend/flatfile.php +++ b/lib/WikiDB/backend/flatfile.php @@ -35,64 +35,66 @@ require_once 'lib/WikiDB/backend/file.php'; require_once 'lib/loadsave.php'; class WikiDB_backend_flatfile -extends WikiDB_backend_file + extends WikiDB_backend_file { // ********************************************************************* // common file load / save functions: // FilenameForPage is from loadsave.php - function _pagename2filename($type, $pagename, $version) { + function _pagename2filename($type, $pagename, $version) + { $fpagename = FilenameForPage($pagename); if (strstr($fpagename, "/")) { $fpagename = preg_replace("/\//", "%2F", $fpagename); } - return $this->_dir_names[$type].'/'.$fpagename; -/* if ($version == 0) - return $this->_dir_names[$type].'/'.FilenameForPage($pagename); - else - return $this->_dir_names[$type].'/'.FilenameForPage($pagename).'--'.$version; -*/ + return $this->_dir_names[$type] . '/' . $fpagename; + /* if ($version == 0) + return $this->_dir_names[$type].'/'.FilenameForPage($pagename); + else + return $this->_dir_names[$type].'/'.FilenameForPage($pagename).'--'.$version; + */ } // Load/Save Page-Data - function _loadPageData($pagename) { - if ($this->_page_data != NULL) { + function _loadPageData($pagename) + { + if ($this->_page_data != NULL) { if ($this->_page_data['pagename'] == $pagename) { return $this->_page_data; - } - } - //$pd = $this->_loadPage('page_data', $pagename, 0); + } + } + //$pd = $this->_loadPage('page_data', $pagename, 0); - $filename = $this->_pagename2filename('page_data', $pagename, 0); - if (!file_exists($filename)) return NULL; - if (!filesize($filename)) return array(); - if ($fd = @fopen($filename, "rb")) { - $locked = flock($fd, 1); // Read lock - if (!$locked) { - ExitWiki("Timeout while obtaining lock. Please try again"); - } - if ($data = fread($fd, filesize($filename))) { - // This is the only difference from file: - if ($parts = ParseMimeifiedPages($data)) { - $pd = $parts[0]; - } - //if ($set_pagename == true) - $pd['pagename'] = $pagename; - //if ($version != 0) $pd['version'] = $version; - if (!is_array($pd)) - ExitWiki(sprintf(gettext("'%s': corrupt file"), - htmlspecialchars($filename))); - } - fclose($fd); - } + $filename = $this->_pagename2filename('page_data', $pagename, 0); + if (!file_exists($filename)) return NULL; + if (!filesize($filename)) return array(); + if ($fd = @fopen($filename, "rb")) { + $locked = flock($fd, 1); // Read lock + if (!$locked) { + ExitWiki("Timeout while obtaining lock. Please try again"); + } + if ($data = fread($fd, filesize($filename))) { + // This is the only difference from file: + if ($parts = ParseMimeifiedPages($data)) { + $pd = $parts[0]; + } + //if ($set_pagename == true) + $pd['pagename'] = $pagename; + //if ($version != 0) $pd['version'] = $version; + if (!is_array($pd)) + ExitWiki(sprintf(gettext("'%s': corrupt file"), + htmlspecialchars($filename))); + } + fclose($fd); + } - if ($pd != NULL) + if ($pd != NULL) $this->_page_data = $pd; - if ($this->_page_data != NULL) { + if ($this->_page_data != NULL) { if ($this->_page_data['pagename'] == $pagename) { return $this->_page_data; - } - } - return array(); // no values found + } + } + return array(); // no values found } /** Store latest version as full page_data flatfile, @@ -101,7 +103,8 @@ extends WikiDB_backend_file * If the given ($pagename,$version) is already in the database, * this method completely overwrites any stored data for that version. */ - function _saveVersionData($pagename, $version, $data) { + function _saveVersionData($pagename, $version, $data) + { // check if this is a newer version: if ($this->_getLatestVersion($pagename) < $version) { // write new latest-version-info @@ -119,7 +122,8 @@ extends WikiDB_backend_file // Store as full page_data flatfile // pagedata: date, pagename, hits // versiondata: _cached_html and the rest - function _savePageData($pagename, $data) { + function _savePageData($pagename, $data) + { $type = 'page_data'; $version = 1; @@ -131,10 +135,10 @@ extends WikiDB_backend_file if (USECACHE and empty($data['pagedata'])) { $cache =& $this->_wikidb->_cache; if (!empty($cache->_pagedata_cache[$pagename]) - and is_array($cache->_pagedata_cache[$pagename])) - { + and is_array($cache->_pagedata_cache[$pagename]) + ) { $cachedata = &$cache->_pagedata_cache[$pagename]; - foreach($data as $key => $val) + foreach ($data as $key => $val) $cachedata[$key] = $val; } else { $cache->_pagedata_cache[$pagename] = $data; @@ -166,32 +170,33 @@ extends WikiDB_backend_file if ($k == 'pagedata') $current->_data = array_merge($current->_data, $v); elseif ($k == 'versiondata') - $current->_data = array_merge($current->_data, $v); - else + $current->_data = array_merge($current->_data, $v); else $current->_data[$k] = $v; } $this->_page_data = $current->_data; $pagedata = "Date: " . Rfc2822DateTime($current->get('mtime')) . "\r\n"; $pagedata .= sprintf("Mime-Version: 1.0 (Produced by PhpWiki %s)\r\n", - PHPWIKI_VERSION); + PHPWIKI_VERSION); $pagedata .= MimeifyPageRevision($page, $current); if ($fd = fopen($filename, 'a+b')) { - $locked = flock($fd, 2); // Exclusive blocking lock - if (!$locked) { - ExitWiki("Timeout while obtaining lock. Please try again"); - } - rewind($fd); - ftruncate($fd, 0); + $locked = flock($fd, 2); // Exclusive blocking lock + if (!$locked) { + ExitWiki("Timeout while obtaining lock. Please try again"); + } + rewind($fd); + ftruncate($fd, 0); $len = strlen($pagedata); - $num = fwrite($fd, $pagedata, $len); - assert($num == $len); - fclose($fd); + $num = fwrite($fd, $pagedata, $len); + assert($num == $len); + fclose($fd); } else { - ExitWiki("Error while writing page '$pagename'"); + ExitWiki("Error while writing page '$pagename'"); } } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/cvs.php b/lib/WikiDB/cvs.php index 86cf998c5..432bb9fd3 100644 --- a/lib/WikiDB/cvs.php +++ b/lib/WikiDB/cvs.php @@ -13,17 +13,18 @@ require_once 'lib/WikiDB/backend/cvs.php'; * */ class WikiDB_cvs -extends WikiDB + extends WikiDB { var $_backend; /** * Constructor requires the DB parameters. */ - function WikiDB_cvs( $dbparams ) { + function WikiDB_cvs($dbparams) + { if (loadPhpExtension('cvsclient')) - $this->_backend = new WikiDB_backend_cvsclient( $dbparams ); + $this->_backend = new WikiDB_backend_cvsclient($dbparams); else - $this->_backend = new WikiDB_backend_cvs( $dbparams ); + $this->_backend = new WikiDB_backend_cvs($dbparams); } } diff --git a/lib/WikiDB/dba.php b/lib/WikiDB/dba.php index 85b40332a..841f421a6 100644 --- a/lib/WikiDB/dba.php +++ b/lib/WikiDB/dba.php @@ -7,16 +7,20 @@ require_once 'lib/WikiDB/backend/dba.php'; */ class WikiDB_dba extends WikiDB { - function WikiDB_dba ($dbparams) { + function WikiDB_dba($dbparams) + { $backend = new WikiDB_backend_dba($dbparams); $this->WikiDB($backend, $dbparams); if (empty($dbparams['directory']) - || preg_match('@^/tmp\b@', $dbparams['directory'])) + || preg_match('@^/tmp\b@', $dbparams['directory']) + ) trigger_error(sprintf(_("The %s files are in the %s directory. Please read the INSTALL file and move the database to a permanent location or risk losing all the pages!"), - "DBA", "/tmp"), E_USER_WARNING); + "DBA", "/tmp"), E_USER_WARNING); } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiDB/file.php b/lib/WikiDB/file.php index 63999d8d5..652fb7096 100644 --- a/lib/WikiDB/file.php +++ b/lib/WikiDB/file.php @@ -34,15 +34,16 @@ class WikiDB_file extends WikiDB /** * Constructor requires the DB parameters. */ - function WikiDB_file( $dbparams ) + function WikiDB_file($dbparams) { - $backend = new WikiDB_backend_file( $dbparams ); + $backend = new WikiDB_backend_file($dbparams); $this->WikiDB($backend, $dbparams); if (empty($dbparams['directory']) - || preg_match('@^/tmp\b@', $dbparams['directory'])) + || preg_match('@^/tmp\b@', $dbparams['directory']) + ) trigger_error(sprintf(_("The %s files are in the %s directory. Please read the INSTALL file and move the database to a permanent location or risk losing all the pages!"), - "Page", "/tmp"), E_USER_WARNING); + "Page", "/tmp"), E_USER_WARNING); } } diff --git a/lib/WikiDB/flatfile.php b/lib/WikiDB/flatfile.php index 22a767794..cbfa3f92a 100644 --- a/lib/WikiDB/flatfile.php +++ b/lib/WikiDB/flatfile.php @@ -33,16 +33,17 @@ class WikiDB_flatfile extends WikiDB /** * Constructor requires the DB parameters. */ - function WikiDB_flatfile( $dbparams ) + function WikiDB_flatfile($dbparams) { - $backend = new WikiDB_backend_flatfile( $dbparams ); + $backend = new WikiDB_backend_flatfile($dbparams); $backend->_wikidb =& $this; $this->WikiDB($backend, $dbparams); if (empty($dbparams['directory']) - || preg_match('@^/tmp\b@', $dbparams['directory'])) + || preg_match('@^/tmp\b@', $dbparams['directory']) + ) trigger_error(sprintf(_("The %s files are in the %s directory. Please read the INSTALL file and move the database to a permanent location or risk losing all the pages!"), - "Page", "/tmp"), E_USER_WARNING); + "Page", "/tmp"), E_USER_WARNING); } } diff --git a/lib/WikiGroup.php b/lib/WikiGroup.php index e80cbdd52..3063174e2 100644 --- a/lib/WikiGroup.php +++ b/lib/WikiGroup.php @@ -23,18 +23,19 @@ if (!defined('GROUP_METHOD') or !in_array(GROUP_METHOD, - array('NONE','WIKIPAGE','DB','FILE','LDAP'))) + array('NONE', 'WIKIPAGE', 'DB', 'FILE', 'LDAP')) +) trigger_error(_("No or unsupported GROUP_METHOD defined"), E_USER_WARNING); /* Special group names for ACL */ -define('GROUP_EVERY', _("Every")); -define('GROUP_ANONYMOUS', _("Anonymous Users")); -define('GROUP_BOGOUSER', _("Bogo Users")); -define('GROUP_SIGNED', _("Signed Users")); -define('GROUP_AUTHENTICATED', _("Authenticated Users")); -define('GROUP_ADMIN', _("Administrators")); -define('GROUP_OWNER', _("Owner")); -define('GROUP_CREATOR', _("Creator")); +define('GROUP_EVERY', _("Every")); +define('GROUP_ANONYMOUS', _("Anonymous Users")); +define('GROUP_BOGOUSER', _("Bogo Users")); +define('GROUP_SIGNED', _("Signed Users")); +define('GROUP_AUTHENTICATED', _("Authenticated Users")); +define('GROUP_ADMIN', _("Administrators")); +define('GROUP_OWNER', _("Owner")); +define('GROUP_CREATOR', _("Creator")); /** * WikiGroup is an abstract class to provide the base functions for determining @@ -55,7 +56,8 @@ define('GROUP_CREATOR', _("Creator")); * @author Joby Walker * @author Reini Urban */ -class WikiGroup{ +class WikiGroup +{ /** User name */ var $username = ''; /** User object if different from current user */ @@ -72,7 +74,8 @@ class WikiGroup{ * $group = &WikiGroup::getGroup(); * @param object $request The global WikiRequest object -- ignored. */ - function WikiGroup($not_current = false) { + function WikiGroup($not_current = false) + { $this->not_current = $not_current; //$this->request =& $GLOBALS['request']; } @@ -83,7 +86,8 @@ class WikiGroup{ * the stored $this->username * @return string Current username. */ - function _getUserName(){ + function _getUserName() + { global $request; $user = (!empty($this->user)) ? $this->user : $request->getUser(); $username = $user->getID(); @@ -92,7 +96,7 @@ class WikiGroup{ $this->username = $username; } if (!$this->not_current) - $this->user = $user; + $this->user = $user; return $username; } @@ -102,8 +106,9 @@ class WikiGroup{ * @param object $request The global WikiRequest object. * @return object Subclass of WikiGroup selected via GROUP_METHOD. */ - function getGroup($not_current = false){ - switch (GROUP_METHOD){ + function getGroup($not_current = false) + { + switch (GROUP_METHOD) { case "NONE": return new GroupNone($not_current); break; @@ -117,8 +122,8 @@ class WikiGroup{ return new GroupDb_PearDB($not_current); } else { trigger_error("GROUP_METHOD = DB: Unsupported dbtype " - . $GLOBALS['DBParams']['dbtype'], - E_USER_ERROR); + . $GLOBALS['DBParams']['dbtype'], + E_USER_ERROR); } break; case "FILE": @@ -136,36 +141,43 @@ class WikiGroup{ /** ACL PagePermissions will need those special groups based on the User status only. * translated */ - function specialGroup($group){ - return in_array($group,$this->specialGroups()); + function specialGroup($group) + { + return in_array($group, $this->specialGroups()); } + /** untranslated */ - function _specialGroup($group){ - return in_array($group,$this->_specialGroups()); + function _specialGroup($group) + { + return in_array($group, $this->_specialGroups()); } + /** translated */ - function specialGroups(){ + function specialGroups() + { return array( - GROUP_EVERY, - GROUP_ANONYMOUS, - GROUP_BOGOUSER, - GROUP_SIGNED, - GROUP_AUTHENTICATED, - GROUP_ADMIN, - GROUP_OWNER, - GROUP_CREATOR); + GROUP_EVERY, + GROUP_ANONYMOUS, + GROUP_BOGOUSER, + GROUP_SIGNED, + GROUP_AUTHENTICATED, + GROUP_ADMIN, + GROUP_OWNER, + GROUP_CREATOR); } + /** untranslated */ - function _specialGroups(){ + function _specialGroups() + { return array( - "_EVERY", - "_ANONYMOUS", - "_BOGOUSER", - "_SIGNED", - "_AUTHENTICATED", - "_ADMIN", - "_OWNER", - "_CREATOR"); + "_EVERY", + "_ANONYMOUS", + "_BOGOUSER", + "_SIGNED", + "_AUTHENTICATED", + "_ADMIN", + "_OWNER", + "_CREATOR"); } /** @@ -176,20 +188,22 @@ class WikiGroup{ * @param string $group Name of the group to check for membership (ignored). * @return boolean True if user is a member, else false (always false). */ - function isMember($group){ + function isMember($group) + { if (isset($this->membership[$group])) return $this->membership[$group]; if ($this->specialGroup($group)) { return $this->isSpecialMember($group); } else { trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s", - 'isMember', GROUP_METHOD), - E_USER_WARNING); + 'isMember', GROUP_METHOD), + E_USER_WARNING); } return false; } - function isSpecialMember($group){ + function isSpecialMember($group) + { global $request; if (isset($this->membership[$group])) @@ -199,24 +213,24 @@ class WikiGroup{ case GROUP_EVERY: return $this->membership[$group] = true; case GROUP_ANONYMOUS: - return $this->membership[$group] = ! $user->isSignedIn(); + return $this->membership[$group] = !$user->isSignedIn(); case GROUP_BOGOUSER: - return $this->membership[$group] = (isa($user,'_BogoUser') - and $user->_level >= WIKIAUTH_BOGO); + return $this->membership[$group] = (isa($user, '_BogoUser') + and $user->_level >= WIKIAUTH_BOGO); case GROUP_SIGNED: return $this->membership[$group] = $user->isSignedIn(); case GROUP_AUTHENTICATED: return $this->membership[$group] = $user->isAuthenticated(); case GROUP_ADMIN: return $this->membership[$group] = (isset($user->_level) - and $user->_level == WIKIAUTH_ADMIN); + and $user->_level == WIKIAUTH_ADMIN); case GROUP_OWNER: case GROUP_CREATOR: return false; default: trigger_error(__sprintf("Undefined method %s for special group %s", - 'isMember',$group), - E_USER_WARNING); + 'isMember', $group), + E_USER_WARNING); } return false; } @@ -228,14 +242,16 @@ class WikiGroup{ * array is returned. * @return array Array of groups to which the user belongs (always empty). */ - function getAllGroupsIn(){ + function getAllGroupsIn() + { trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s", - 'getAllGroupsIn', GROUP_METHOD), - E_USER_WARNING); + 'getAllGroupsIn', GROUP_METHOD), + E_USER_WARNING); return array(); } - function _allUsers() { + function _allUsers() + { static $result = array(); if (!empty($result)) return $result; @@ -258,15 +274,15 @@ class WikiGroup{ if ($dbi and $dbh->getAuthParam('pref_select')) { //get prefs table - $sql = preg_replace('/SELECT .+ FROM/i','SELECT userid FROM', - $dbh->getAuthParam('pref_select')); + $sql = preg_replace('/SELECT .+ FROM/i', 'SELECT userid FROM', + $dbh->getAuthParam('pref_select')); //don't strip WHERE, only the userid stuff. - $sql = preg_replace('/(WHERE.*?)\s+\w+\s*=\s*["\']\$userid[\'"]/i','\\1 AND 1', $sql); - $sql = str_replace('WHERE AND 1','',$sql); + $sql = preg_replace('/(WHERE.*?)\s+\w+\s*=\s*["\']\$userid[\'"]/i', '\\1 AND 1', $sql); + $sql = str_replace('WHERE AND 1', '', $sql); if (isa($dbi, 'ADOConnection')) { $db_result = $dbi->Execute($sql); foreach ($db_result->GetArray() as $u) { - $users = array_merge($users,array_values($u)); + $users = array_merge($users, array_values($u)); } } elseif (isa($dbi, 'DB_common')) { // PearDB $users = array_merge($users, $dbi->getCol($sql)); @@ -277,13 +293,13 @@ class WikiGroup{ // Fixme: don't strip WHERE, only the userid stuff. if ($dbi and $dbh->getAuthParam('auth_user_exists')) { //don't strip WHERE, only the userid stuff. - $sql = preg_replace('/(WHERE.*?)\s+\w+\s*=\s*["\']\$userid[\'"]/i','\\1 AND 1', - $dbh->getAuthParam('auth_user_exists')); - $sql = str_replace('WHERE AND 1','', $sql); + $sql = preg_replace('/(WHERE.*?)\s+\w+\s*=\s*["\']\$userid[\'"]/i', '\\1 AND 1', + $dbh->getAuthParam('auth_user_exists')); + $sql = str_replace('WHERE AND 1', '', $sql); if (isa($dbi, 'ADOConnection')) { $db_result = $dbi->Execute($sql); foreach ($db_result->GetArray() as $u) { - $users = array_merge($users, array_values($u)); + $users = array_merge($users, array_values($u)); } } elseif (isa($dbi, 'DB_common')) { $users = array_merge($users, $dbi->getCol($sql)); @@ -293,7 +309,7 @@ class WikiGroup{ // remove empty and duplicate users $result = array(); foreach ($users as $u) { - if (empty($u) or in_array($u,$result)) continue; + if (empty($u) or in_array($u, $result)) continue; $result[] = $u; } return $result; @@ -307,56 +323,58 @@ class WikiGroup{ * @param string $group Name of the group to get the full membership list of. * @return array Array of usernames that have joined the group (always empty). */ - function getMembersOf($group){ + function getMembersOf($group) + { if ($this->specialGroup($group)) { return $this->getSpecialMembersOf($group); } trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s", - 'getMembersOf', GROUP_METHOD), - E_USER_WARNING); + 'getMembersOf', GROUP_METHOD), + E_USER_WARNING); return array(); } - function getSpecialMembersOf($group) { + function getSpecialMembersOf($group) + { //$request = &$this->request; $all = $this->_allUsers(); $users = array(); switch ($group) { - case GROUP_EVERY: - return $all; - case GROUP_ANONYMOUS: - return $users; - case GROUP_BOGOUSER: - foreach ($all as $u) { - if (isWikiWord($u)) $users[] = $u; - } - return $users; - case GROUP_SIGNED: - foreach ($all as $u) { - $user = WikiUser($u); - if ($user->isSignedIn()) $users[] = $u; - } - return $users; - case GROUP_AUTHENTICATED: - foreach ($all as $u) { - $user = WikiUser($u); - if ($user->isAuthenticated()) $users[] = $u; - } - return $users; - case GROUP_ADMIN: - foreach ($all as $u) { - $user = WikiUser($u); - if (isset($user->_level) and $user->_level == WIKIAUTH_ADMIN) - $users[] = $u; - } - return $users; - case GROUP_OWNER: - case GROUP_CREATOR: - // this could get complex so just return an empty array - return false; - default: - trigger_error(__sprintf("Unknown special group '%s'", $group), - E_USER_WARNING); + case GROUP_EVERY: + return $all; + case GROUP_ANONYMOUS: + return $users; + case GROUP_BOGOUSER: + foreach ($all as $u) { + if (isWikiWord($u)) $users[] = $u; + } + return $users; + case GROUP_SIGNED: + foreach ($all as $u) { + $user = WikiUser($u); + if ($user->isSignedIn()) $users[] = $u; + } + return $users; + case GROUP_AUTHENTICATED: + foreach ($all as $u) { + $user = WikiUser($u); + if ($user->isAuthenticated()) $users[] = $u; + } + return $users; + case GROUP_ADMIN: + foreach ($all as $u) { + $user = WikiUser($u); + if (isset($user->_level) and $user->_level == WIKIAUTH_ADMIN) + $users[] = $u; + } + return $users; + case GROUP_OWNER: + case GROUP_CREATOR: + // this could get complex so just return an empty array + return false; + default: + trigger_error(__sprintf("Unknown special group '%s'", $group), + E_USER_WARNING); } } @@ -369,10 +387,11 @@ class WikiGroup{ * @param string $user Username to add to the group (default = current user). * @return bool On true user was added, false if not. */ - function setMemberOf($group, $user = false){ + function setMemberOf($group, $user = false) + { trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s", - 'setMemberOf', GROUP_METHOD), - E_USER_WARNING); + 'setMemberOf', GROUP_METHOD), + E_USER_WARNING); return false; } @@ -385,10 +404,11 @@ class WikiGroup{ * @param string $user Username to remove from the group (default = current user). * @return bool On true user was removed, false if not. */ - function removeMemberOf($group, $user = false){ + function removeMemberOf($group, $user = false) + { trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s", - 'removeMemberOf', GROUP_METHOD), - E_USER_WARNING); + 'removeMemberOf', GROUP_METHOD), + E_USER_WARNING); return false; } } @@ -400,7 +420,8 @@ class WikiGroup{ * no results. Use GroupNone if group controls are not desired. * @author Joby Walker */ -class GroupNone extends WikiGroup{ +class GroupNone extends WikiGroup +{ /** * Constructor @@ -408,7 +429,8 @@ class GroupNone extends WikiGroup{ * Ignores the parameter provided. * @param object $request The global WikiRequest object - ignored. */ - function GroupNone() { + function GroupNone() + { //$this->request = &$GLOBALS['request']; return; } @@ -420,7 +442,8 @@ class GroupNone extends WikiGroup{ * @param string $group Name of the group to check for membership (ignored). * @return boolean True if user is a member, else false (always false). */ - function isMember($group){ + function isMember($group) + { if ($this->specialGroup($group)) { return $this->isSpecialMember($group); } else { @@ -435,7 +458,8 @@ class GroupNone extends WikiGroup{ * @param string $group Name of the group to check for membership (ignored). * @return array Array of groups to which the user belongs (always empty). */ - function getAllGroupsIn(){ + function getAllGroupsIn() + { return array(); } @@ -446,7 +470,8 @@ class GroupNone extends WikiGroup{ * @param string $group Name of the group to check for membership (ignored). * @return array Array of groups user belongs to (always empty). */ - function getMembersOf($group){ + function getMembersOf($group) + { return array(); } @@ -460,7 +485,8 @@ class GroupNone extends WikiGroup{ * membership list on the page. * @author Joby Walker */ -class GroupWikiPage extends WikiGroup{ +class GroupWikiPage extends WikiGroup +{ /** * Constructor @@ -468,7 +494,8 @@ class GroupWikiPage extends WikiGroup{ * Initializes the three superclass instance variables * @param object $request The global WikiRequest object. */ - function GroupWikiPage() { + function GroupWikiPage() + { //$this->request = &$GLOBALS['request']; $this->username = $this->_getUserName(); //$this->username = null; @@ -485,7 +512,8 @@ class GroupWikiPage extends WikiGroup{ * @param string $group Name of the group to check for membership. * @return boolean True if user is a member, else false. */ - function isMember($group){ + function isMember($group) + { if (isset($this->membership[$group])) { return $this->membership[$group]; } @@ -504,23 +532,24 @@ class GroupWikiPage extends WikiGroup{ } /** - * Private method to take a WikiDB_Page and parse to determine if the - * current_user is a member of the group. - * @param object $group_page WikiDB_Page object for the group's page - * @return boolean True if user is a member, else false. - * @access private - */ - function _inGroupPage($group_page, $strict=false){ + * Private method to take a WikiDB_Page and parse to determine if the + * current_user is a member of the group. + * @param object $group_page WikiDB_Page object for the group's page + * @return boolean True if user is a member, else false. + * @access private + */ + function _inGroupPage($group_page, $strict = false) + { $group_revision = $group_page->getCurrentRevision(); if ($group_revision->hasDefaultContents()) { $group = $group_page->getName(); if ($strict) trigger_error(sprintf(_("Group page '%s' does not exist"), $group), - E_USER_WARNING); + E_USER_WARNING); return false; } $contents = $group_revision->getContent(); $match = '/^\s*[\*\#]+\s*\[?' . $this->username . '\]?(\s|$)/'; - foreach ($contents as $line){ + foreach ($contents as $line) { if (preg_match($match, $line)) { return true; } @@ -536,7 +565,8 @@ class GroupWikiPage extends WikiGroup{ * @param string $group Name of the group to check for membership. * @return array Array of groups to which the user belongs. */ - function getAllGroupsIn(){ + function getAllGroupsIn() + { $membership = array(); $specialgroups = $this->specialGroups(); @@ -548,7 +578,7 @@ class GroupWikiPage extends WikiGroup{ $dbh = &$request->_dbi; $master_page = $request->getPage(CATEGORY_GROUP_PAGE); $master_list = $master_page->getLinks(true); - while ($group_page = $master_list->next()){ + while ($group_page = $master_list->next()) { $group = $group_page->getName(); $this->membership[$group] = $this->_inGroupPage($group_page); } @@ -566,22 +596,23 @@ class GroupWikiPage extends WikiGroup{ * @param string $group Name of the group to get the full membership list of. * @return array Array of usernames that have joined the group (always empty). */ - function getMembersOf($group){ + function getMembersOf($group) + { if ($this->specialGroup($group)) return $this->getSpecialMembersOf($group); $group_page = $GLOBALS['request']->getPage($group); $group_revision = $group_page->getCurrentRevision(); if ($group_revision->hasDefaultContents()) { - trigger_error(sprintf(_("Group %s does not exist"),$group), E_USER_WARNING); + trigger_error(sprintf(_("Group %s does not exist"), $group), E_USER_WARNING); return array(); } $contents = $group_revision->getContent(); // This is not really a reliable way to check if a string is a username. But better than nothing. $match = '/^(\s*[\*\#]+\s*\[?)(\w+)(\]?\s*)$/'; $members = array(); - foreach ($contents as $line){ - if (preg_match($match, $line, $matches)){ + foreach ($contents as $line) { + if (preg_match($match, $line, $matches)) { $members[] = $matches[2]; } } @@ -595,7 +626,8 @@ class GroupWikiPage extends WikiGroup{ * Fixme: adodb * @author ReiniUrban */ -class GroupDb extends WikiGroup { +class GroupDb extends WikiGroup +{ var $_is_member, $_group_members, $_user_groups; @@ -604,7 +636,8 @@ class GroupDb extends WikiGroup { * * @param object $request The global WikiRequest object. ignored */ - function GroupDb() { + function GroupDb() + { global $DBAuthParams, $DBParams; //$this->request = &$GLOBALS['request']; $this->username = $this->_getUserName(); @@ -612,15 +645,16 @@ class GroupDb extends WikiGroup { if (empty($DBAuthParams['group_members']) or empty($DBAuthParams['user_groups']) or - empty($DBAuthParams['is_member'])) { + empty($DBAuthParams['is_member']) + ) { trigger_error(_("No or not enough GROUP_DB SQL statements defined"), - E_USER_WARNING); + E_USER_WARNING); return new GroupNone(); } // FIXME: This only works with ENABLE_USER_NEW if (empty($this->user)) { // use _PassUser::prepare instead - if (isa($request->getUser(),'_PassUser')) + if (isa($request->getUser(), '_PassUser')) $user = $request->getUser(); else $user = new _PassUser($this->username); @@ -631,9 +665,9 @@ class GroupDb extends WikiGroup { } if (isa($this->user, '_PassUser')) { // TODO: safety by Charles Corrigan $this->_is_member = $user->prepare($DBAuthParams['is_member'], - array('userid','groupname')); - $this->_group_members = $user->prepare($DBAuthParams['group_members'],'groupname'); - $this->_user_groups = $user->prepare($DBAuthParams['user_groups'],'userid'); + array('userid', 'groupname')); + $this->_group_members = $user->prepare($DBAuthParams['group_members'], 'groupname'); + $this->_user_groups = $user->prepare($DBAuthParams['user_groups'], 'userid'); $this->dbh = $user->_auth_dbi; } } @@ -644,7 +678,8 @@ class GroupDb extends WikiGroup { * * @author ReiniUrban */ -class GroupDb_PearDB extends GroupDb { +class GroupDb_PearDB extends GroupDb +{ /** * Determines if the current user is a member of a database group. @@ -652,14 +687,15 @@ class GroupDb_PearDB extends GroupDb { * @param string $group Name of the group to check for membership. * @return boolean True if user is a member, else false. */ - function isMember($group) { + function isMember($group) + { if (isset($this->membership[$group])) { return $this->membership[$group]; } $dbh = & $this->dbh; $db_result = $dbh->query(sprintf($this->_is_member, - $dbh->quote($this->username), - $dbh->quote($group))); + $dbh->quote($this->username), + $dbh->quote($group))); if ($db_result->numRows() > 0) { $this->membership[$group] = true; return true; @@ -678,7 +714,8 @@ class GroupDb_PearDB extends GroupDb { * @param string $group Name of the group to check for membership. * @return array Array of groups to which the user belongs. */ - function getAllGroupsIn(){ + function getAllGroupsIn() + { $membership = array(); $dbh = & $this->dbh; @@ -707,11 +744,12 @@ class GroupDb_PearDB extends GroupDb { * @param string $group Name of the group to get the full membership list of. * @return array Array of usernames that have joined the group. */ - function getMembersOf($group){ + function getMembersOf($group) + { $members = array(); $dbh = & $this->dbh; - $db_result = $dbh->query(sprintf($this->_group_members,$dbh->quote($group))); + $db_result = $dbh->query(sprintf($this->_group_members, $dbh->quote($group))); if ($db_result->numRows() > 0) { while (list($userid) = $db_result->fetchRow(DB_FETCHMODE_ORDERED)) { $members[] = $userid; @@ -729,7 +767,8 @@ class GroupDb_PearDB extends GroupDb { * * @author ReiniUrban */ -class GroupDb_ADODB extends GroupDb { +class GroupDb_ADODB extends GroupDb +{ /** * Determines if the current user is a member of a database group. @@ -737,13 +776,14 @@ class GroupDb_ADODB extends GroupDb { * @param string $group Name of the group to check for membership. * @return boolean True if user is a member, else false. */ - function isMember($group) { + function isMember($group) + { if (isset($this->membership[$group])) { return $this->membership[$group]; } $dbh = & $this->dbh; - $rs = $dbh->Execute(sprintf($this->_is_member,$dbh->qstr($this->username), - $dbh->qstr($group))); + $rs = $dbh->Execute(sprintf($this->_is_member, $dbh->qstr($this->username), + $dbh->qstr($group))); if ($rs->EOF) { $rs->Close(); } else { @@ -767,7 +807,8 @@ class GroupDb_ADODB extends GroupDb { * @param string $group Name of the group to check for membership. * @return array Array of groups to which the user belongs. */ - function getAllGroupsIn(){ + function getAllGroupsIn() + { $membership = array(); $dbh = & $this->dbh; @@ -797,10 +838,11 @@ class GroupDb_ADODB extends GroupDb { * @param string $group Name of the group to get the full membership list of. * @return array Array of usernames that have joined the group. */ - function getMembersOf($group){ + function getMembersOf($group) + { $members = array(); $dbh = & $this->dbh; - $rs = $dbh->Execute(sprintf($this->_group_members,$dbh->qstr($group))); + $rs = $dbh->Execute(sprintf($this->_group_members, $dbh->qstr($group))); if (!$rs->EOF and $rs->numRows() > 0) { while (!$rs->EOF) { $members[] = reset($rs->fields); @@ -821,14 +863,16 @@ class GroupDb_ADODB extends GroupDb { * * @author ReiniUrban */ -class GroupFile extends WikiGroup { +class GroupFile extends WikiGroup +{ /** * Constructor * * @param object $request The global WikiRequest object. */ - function GroupFile(){ + function GroupFile() + { //$this->request = &$GLOBALS['request']; $this->username = $this->_getUserName(); //$this->username = null; @@ -836,16 +880,16 @@ class GroupFile extends WikiGroup { if (!defined('AUTH_GROUP_FILE')) { trigger_error(sprintf(_("%s: not defined"), "AUTH_GROUP_FILE"), - E_USER_WARNING); + E_USER_WARNING); return false; } if (!file_exists(AUTH_GROUP_FILE)) { trigger_error(sprintf(_("Cannot open AUTH_GROUP_FILE %s"), AUTH_GROUP_FILE), - E_USER_WARNING); + E_USER_WARNING); return false; } require_once 'lib/pear/File_Passwd.php'; - $this->_file = new File_Passwd(AUTH_GROUP_FILE,false,AUTH_GROUP_FILE.".lock"); + $this->_file = new File_Passwd(AUTH_GROUP_FILE, false, AUTH_GROUP_FILE . ".lock"); } /** @@ -858,7 +902,8 @@ class GroupFile extends WikiGroup { * @param string $group Name of the group to check for membership. * @return boolean True if user is a member, else false. */ - function isMember($group) { + function isMember($group) + { //$request = $this->request; //$username = $this->username; if (isset($this->membership[$group])) { @@ -866,13 +911,13 @@ class GroupFile extends WikiGroup { } if (is_array($this->_file->users)) { - foreach ($this->_file->users as $g => $u) { - $users = explode(' ',$u); - if (in_array($this->username,$users)) { - $this->membership[$group] = true; - return true; + foreach ($this->_file->users as $g => $u) { + $users = explode(' ', $u); + if (in_array($this->username, $users)) { + $this->membership[$group] = true; + return true; + } } - } } $this->membership[$group] = false; if ($this->specialGroup($group)) @@ -887,18 +932,19 @@ class GroupFile extends WikiGroup { * @param string $group Name of the group to check for membership. * @return array Array of groups to which the user belongs. */ - function getAllGroupsIn(){ + function getAllGroupsIn() + { //$username = $this->_getUserName(); $membership = array(); if (is_array($this->_file->users)) { - foreach ($this->_file->users as $group => $u) { - $users = explode(' ',$u); - if (in_array($this->username,$users)) { - $this->membership[$group] = true; - $membership[] = $group; + foreach ($this->_file->users as $group => $u) { + $users = explode(' ', $u); + if (in_array($this->username, $users)) { + $this->membership[$group] = true; + $membership[] = $group; + } } - } } $specialgroups = $this->specialGroups(); @@ -918,10 +964,11 @@ class GroupFile extends WikiGroup { * @param string $group Name of the group to get the full membership list of. * @return array Array of usernames that have joined the group. */ - function getMembersOf($group){ + function getMembersOf($group) + { $members = array(); if (!empty($this->_file->users[$group])) { - $members = explode(' ',$this->_file->users[$group]); + $members = explode(' ', $this->_file->users[$group]); } if ($this->specialGroup($group)) { $members = array_merge($members, $this->getSpecialMembersOf($group)); @@ -935,42 +982,44 @@ class GroupFile extends WikiGroup { * * @author ReiniUrban */ -class GroupLdap extends WikiGroup { +class GroupLdap extends WikiGroup +{ /** * Constructor * * @param object $request The global WikiRequest object. */ - function GroupLdap(){ + function GroupLdap() + { //$this->request = &$GLOBALS['request']; $this->username = $this->_getUserName(); $this->membership = array(); if (!defined("LDAP_AUTH_HOST")) { trigger_error(sprintf(_("%s not defined"), "LDAP_AUTH_HOST"), - E_USER_WARNING); + E_USER_WARNING); return false; } // We should ignore multithreaded environments, not generally windows. // CGI does work. - if (! function_exists('ldap_connect') and (!isWindows() or isCGI())) { + if (!function_exists('ldap_connect') and (!isWindows() or isCGI())) { // on MacOSX >= 4.3 you'll need PHP_SHLIB_SUFFIX instead. - dl("ldap".defined('PHP_SHLIB_SUFFIX') ? PHP_SHLIB_SUFFIX : DLL_EXT); - if (! function_exists('ldap_connect')) { + dl("ldap" . defined('PHP_SHLIB_SUFFIX') ? PHP_SHLIB_SUFFIX : DLL_EXT); + if (!function_exists('ldap_connect')) { trigger_error(_("No LDAP in this PHP version"), E_USER_WARNING); return false; } } if (!defined("LDAP_BASE_DN")) - define("LDAP_BASE_DN",''); + define("LDAP_BASE_DN", ''); $this->base_dn = LDAP_BASE_DN; // if no users ou (organizational unit) is defined, // then take out the ou= from the base_dn (if exists) and append a default // from users and group if (!LDAP_OU_USERS) if (strstr(LDAP_BASE_DN, "ou=")) - $this->base_dn = preg_replace("/(ou=\w+,)?()/","\$2", LDAP_BASE_DN); + $this->base_dn = preg_replace("/(ou=\w+,)?()/", "\$2", LDAP_BASE_DN); if (!isset($this->user) or !isa($this->user, '_LDAPPassUser')) $this->_user = new _LDAPPassUser('LdapGroupTest'); // to have a valid username @@ -985,13 +1034,14 @@ class GroupLdap extends WikiGroup { * @param string $group Name of the group to check for membership. * @return boolean True if user is a member, else false. */ - function isMember($group) { + function isMember($group) + { if (isset($this->membership[$group])) { return $this->membership[$group]; } //$request = $this->request; //$username = $this->_getUserName(); - $this->membership[$group] = in_array($this->username,$this->getMembersOf($group)); + $this->membership[$group] = in_array($this->username, $this->getMembersOf($group)); if ($this->membership[$group]) return true; if ($this->specialGroup($group)) @@ -1004,7 +1054,8 @@ class GroupLdap extends WikiGroup { * @param string $group Name of the group to check for membership. * @return array Array of groups to which the user belongs. */ - function getAllGroupsIn(){ + function getAllGroupsIn() + { //$request = &$this->request; //$username = $this->_getUserName(); $membership = array(); @@ -1019,36 +1070,36 @@ class GroupLdap extends WikiGroup { // must be a valid LDAP server, and username must not contain a wildcard if ($ldap = $this->_user->_init()) { - $st_search = LDAP_SEARCH_FIELD ? LDAP_SEARCH_FIELD."=".$this->username - : "uid=".$this->username; + $st_search = LDAP_SEARCH_FIELD ? LDAP_SEARCH_FIELD . "=" . $this->username + : "uid=" . $this->username; $sr = ldap_search($ldap, (LDAP_OU_USERS ? LDAP_OU_USERS : "ou=Users") - .($this->base_dn ? ",".$this->base_dn : ''), - $st_search); + . ($this->base_dn ? "," . $this->base_dn : ''), + $st_search); if (!$sr) { - $this->_user->_free(); + $this->_user->_free(); return $this->membership; } $info = ldap_get_entries($ldap, $sr); if (empty($info["count"])) { - $this->_user->_free(); + $this->_user->_free(); return $this->membership; } for ($i = 0; $i < $info["count"]; $i++) { if ($info[$i]["gidNumber"]["count"]) { $gid = $info[$i]["gidnumber"][0]; $sr2 = ldap_search($ldap, (LDAP_OU_GROUP ? LDAP_OU_GROUP : "ou=Groups") - .($this->base_dn ? ",".$this->base_dn : ''), - "gidNumber=$gid"); + . ($this->base_dn ? "," . $this->base_dn : ''), + "gidNumber=$gid"); if ($sr2) { $info2 = ldap_get_entries($ldap, $sr2); if (!empty($info2["count"])) - $membership[] = $info2[0]["cn"][0]; + $membership[] = $info2[0]["cn"][0]; } } } } else { trigger_error(fmt("Unable to connect to LDAP server %s", LDAP_AUTH_HOST), - E_USER_WARNING); + E_USER_WARNING); } $this->_user->_free(); //ldap_close($ldap); @@ -1063,11 +1114,12 @@ class GroupLdap extends WikiGroup { * @param string $group Name of the group to get the full membership list of. * @return array Array of usernames that have joined the group. */ - function getMembersOf($group){ + function getMembersOf($group) + { $members = array(); if ($ldap = $this->_user->_init()) { $base_dn = (LDAP_OU_GROUP ? LDAP_OU_GROUP : "ou=Groups") - .($this->base_dn ? ",".$this->base_dn : ''); + . ($this->base_dn ? "," . $this->base_dn : ''); $sr = ldap_search($ldap, $base_dn, "cn=$group"); if ($sr) $info = ldap_get_entries($ldap, $sr); @@ -1076,7 +1128,7 @@ class GroupLdap extends WikiGroup { trigger_error("LDAP_SEARCH: base=\"$base_dn\" \"(cn=$group)\" failed", E_USER_NOTICE); } $base_dn = (LDAP_OU_USERS ? LDAP_OU_USERS : "ou=Users") - .($this->base_dn ? ",".$this->base_dn : ''); + . ($this->base_dn ? "," . $this->base_dn : ''); for ($i = 0; $i < $info["count"]; $i++) { $gid = $info[$i]["gidNumber"][0]; //uid=* would be better probably diff --git a/lib/WikiPlugin.php b/lib/WikiPlugin.php index 2593097f3..126b6cf17 100644 --- a/lib/WikiPlugin.php +++ b/lib/WikiPlugin.php @@ -2,7 +2,8 @@ class WikiPlugin { - function getDefaultArguments() { + function getDefaultArguments() + { return array('description' => $this->getDescription()); } @@ -24,14 +25,16 @@ class WikiPlugin * any page which invokes the plugin uncacheable (by HTTP proxies * or browsers). */ - function managesValidators() { + function managesValidators() + { return false; } // FIXME: args? - function run ($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { trigger_error("WikiPlugin::run: pure virtual function", - E_USER_ERROR); + E_USER_ERROR); } /** Get wiki-pages linked to by plugin invocation. @@ -55,7 +58,8 @@ class WikiPlugin * @param string $basepage The pagename the plugin is invoked from. * @return array List of pagenames linked to (or false). */ - function getWikiPageLinks ($argstr, $basepage) { + function getWikiPageLinks($argstr, $basepage) + { return false; } @@ -74,15 +78,18 @@ class WikiPlugin * * @return string plugin name/target. */ - function getName() { - return preg_replace('/^.*_/', '', get_class($this)); + function getName() + { + return preg_replace('/^.*_/', '', get_class($this)); } - function getDescription() { + function getDescription() + { return $this->getName(); } - function getArgs($argstr, $request=false, $defaults=false) { + function getArgs($argstr, $request = false, $defaults = false) + { if ($defaults === false) { $defaults = $this->getDefaultArguments(); } @@ -90,27 +97,27 @@ class WikiPlugin list ($argstr_args, $argstr_defaults) = $this->parseArgStr($argstr); $args = array(); if (!empty($defaults)) - foreach ($defaults as $arg => $default_val) { - if (isset($argstr_args[$arg])) { - $args[$arg] = $argstr_args[$arg]; - } elseif ( $request and ($argval = $request->getArg($arg)) !== false ) { - $args[$arg] = $argval; - } elseif (isset($argstr_defaults[$arg])) { - $args[$arg] = (string) $argstr_defaults[$arg]; - } else { - $args[$arg] = $default_val; - } - // expand [arg] - if ($request and is_string($args[$arg]) and strstr($args[$arg], "[")) { - $args[$arg] = $this->expandArg($args[$arg], $request); - } + foreach ($defaults as $arg => $default_val) { + if (isset($argstr_args[$arg])) { + $args[$arg] = $argstr_args[$arg]; + } elseif ($request and ($argval = $request->getArg($arg)) !== false) { + $args[$arg] = $argval; + } elseif (isset($argstr_defaults[$arg])) { + $args[$arg] = (string)$argstr_defaults[$arg]; + } else { + $args[$arg] = $default_val; + } + // expand [arg] + if ($request and is_string($args[$arg]) and strstr($args[$arg], "[")) { + $args[$arg] = $this->expandArg($args[$arg], $request); + } - unset($argstr_args[$arg]); - unset($argstr_defaults[$arg]); - } + unset($argstr_args[$arg]); + unset($argstr_defaults[$arg]); + } foreach (array_merge($argstr_args, $argstr_defaults) as $arg => $val) { - // TODO: where the heck comes this from? Put the new method over there and peace. + // TODO: where the heck comes this from? Put the new method over there and peace. /*if ($request and $request->getArg('pagename') == _("PhpWikiAdministration") and $arg == 'overwrite') // silence this warning ;*/ @@ -133,20 +140,22 @@ class WikiPlugin // Patch by Dan F: // Expand [arg] to $request->getArg("arg") unless preceded by ~ - function expandArg($argval, &$request) { + function expandArg($argval, &$request) + { // return preg_replace('/\[(\w[\w\d]*)\]/e', '$request->getArg("$1")', // Replace the arg unless it is preceded by a ~ $ret = preg_replace('/([^~]|^)\[(\w[\w\d]*)\]/e', - '"$1" . $request->getArg("$2")', - $argval); + '"$1" . $request->getArg("$2")', + $argval); // Ditch the ~ so later versions can be expanded if desired return preg_replace('/~(\[\w[\w\d]*\])/', '$1', $ret); } - function parseArgStr($argstr) { + function parseArgStr($argstr) + { $args = array(); $defaults = array(); - if (empty($argstr)) + if (empty($argstr)) return array($args, $defaults); $arg_p = '\w+'; @@ -155,19 +164,19 @@ class WikiPlugin $opt_ws = '\s*'; $qq_p = '" ( (?:[^"\\\\]|\\\\.)* ) "'; //"<--kludge for brain-dead syntax coloring - $q_p = "' ( (?:[^'\\\\]|\\\\.)* ) '"; + $q_p = "' ( (?:[^'\\\\]|\\\\.)* ) '"; $gt_p = "_\\( $opt_ws $qq_p $opt_ws \\)"; $argspec_p = "($arg_p) $opt_ws ($op_p) $opt_ws (?: $qq_p|$q_p|$gt_p|($word_p))"; // handle plugin-list arguments seperately $plugin_p = ''; while (preg_match("/^($arg_p) $opt_ws ($op_p) $opt_ws ($plugin_p) $opt_ws/x", $argstr, $m)) { - @ list(,$arg, $op, $plugin_val) = $m; + @ list(, $arg, $op, $plugin_val) = $m; $argstr = substr($argstr, strlen($m[0])); $loader = new WikiPluginLoader(); $markup = null; $basepage = null; - $plugin_val = preg_replace(array("/^$/"),array(""),$plugin_val); + $plugin_val = preg_replace(array("/^$/"), array(""), $plugin_val); $val = $loader->expandPI($plugin_val, $GLOBALS['request'], $markup, $basepage); if ($op == '=') { $args[$arg] = $val; // comma delimited pagenames or array()? @@ -193,18 +202,14 @@ class WikiPlugin if ($qq_val) $val = stripslashes($qq_val); elseif ($count > 4 and $q_val) - $val = stripslashes($q_val); - elseif ($count >= 6 and $gt_val) - $val = _(stripslashes($gt_val)); - elseif ($count >= 7) - $val = $word_val; - else + $val = stripslashes($q_val); elseif ($count >= 6 and $gt_val) + $val = _(stripslashes($gt_val)); elseif ($count >= 7) + $val = $word_val; else $val = ''; if ($op == '=') { $args[$arg] = $val; - } - else { + } else { // NOTE: This does work for multiple args. Use the // separator character defined in your webserver // configuration, usually & or & (See @@ -217,62 +222,67 @@ class WikiPlugin } if ($argstr) { - $this->handle_plugin_args_cruft($argstr, $args); + $this->handle_plugin_args_cruft($argstr, $args); } return array($args, $defaults); } /* A plugin can override this function to define how any remaining text is handled */ - function handle_plugin_args_cruft($argstr, $args) { + function handle_plugin_args_cruft($argstr, $args) + { trigger_error(sprintf(_("trailing cruft in plugin args: '%s'"), - $argstr), E_USER_NOTICE); + $argstr), E_USER_NOTICE); } /* A plugin can override this to allow undeclared arguments. Or to silence the warning. */ - function allow_undeclared_arg($name, $value) { + function allow_undeclared_arg($name, $value) + { trigger_error(sprintf(_("Argument '%s' not declared by plugin."), - $name), E_USER_NOTICE); - return false; + $name), E_USER_NOTICE); + return false; } /* handle plugin-list argument: use run(). */ - function makeList($plugin_args, $request, $basepage) { + function makeList($plugin_args, $request, $basepage) + { $dbi = $request->getDbh(); $pagelist = $this->run($dbi, $plugin_args, $request, $basepage); $list = array(); if (is_object($pagelist) and isa($pagelist, 'PageList')) return $pagelist->pageNames(); elseif (is_array($pagelist)) - return $pagelist; - else + return $pagelist; else return $list; } - function getDefaultLinkArguments() { - return array('targetpage' => $this->getName(), - 'linktext' => $this->getName(), - 'description' => $this->getDescription(), - 'class' => 'wikiaction'); + function getDefaultLinkArguments() + { + return array('targetpage' => $this->getName(), + 'linktext' => $this->getName(), + 'description' => $this->getDescription(), + 'class' => 'wikiaction'); } - function getDefaultFormArguments() { + function getDefaultFormArguments() + { return array('targetpage' => $this->getName(), - 'buttontext' => $this->getName(), - 'class' => 'wikiaction', - 'method' => 'get', - 'textinput' => 's', - 'description'=> $this->getDescription(), - 'formsize' => 30); + 'buttontext' => $this->getName(), + 'class' => 'wikiaction', + 'method' => 'get', + 'textinput' => 's', + 'description' => $this->getDescription(), + 'formsize' => 30); } - function makeForm($argstr, $request) { + function makeForm($argstr, $request) + { $form_defaults = $this->getDefaultFormArguments(); $defaults = array_merge($form_defaults, - array('start_debug' => $request->getArg('start_debug')), - $this->getDefaultArguments()); + array('start_debug' => $request->getArg('start_debug')), + $this->getDefaultArguments()); $args = $this->getArgs($argstr, $request, $defaults); $plugin = $this->getName(); @@ -280,19 +290,19 @@ class WikiPlugin assert(!empty($textinput) && isset($args['textinput'])); $form = HTML::form(array('action' => WikiURL($args['targetpage']), - 'method' => $args['method'], - 'class' => $args['class'], - 'accept-charset' => $GLOBALS['charset'])); - if (! USE_PATH_INFO ) { + 'method' => $args['method'], + 'class' => $args['class'], + 'accept-charset' => $GLOBALS['charset'])); + if (!USE_PATH_INFO) { $pagename = $request->get('pagename'); $form->pushContent(HTML::input(array('type' => 'hidden', - 'name' => 'pagename', - 'value' => $args['targetpage']))); + 'name' => 'pagename', + 'value' => $args['targetpage']))); } if ($args['targetpage'] != $this->getName()) { $form->pushContent(HTML::input(array('type' => 'hidden', - 'name' => 'action', - 'value' => $this->getName()))); + 'name' => 'action', + 'value' => $this->getName()))); } $contents = HTML::div(); $contents->setAttr('class', $args['class']); @@ -313,8 +323,7 @@ class WikiPlugin $i->setAttr('size', $args['formsize']); if ($args['description']) $i->addTooltip($args['description']); - } - else { + } else { $i->setAttr('type', 'hidden'); } $contents->pushContent($i); @@ -324,43 +333,47 @@ class WikiPlugin $form->setAttr('enctype', 'multipart/form-data'); $form->setAttr('method', 'post'); $contents->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE', - 'value' => MAX_UPLOAD_SIZE, - 'type' => 'hidden'))); + 'value' => MAX_UPLOAD_SIZE, + 'type' => 'hidden'))); } } if (!empty($args['buttontext'])) $contents->pushContent(HTML::input(array('type' => 'submit', - 'class' => 'button', - 'value' => $args['buttontext']))); + 'class' => 'button', + 'value' => $args['buttontext']))); $form->pushContent($contents); return $form; } // box is used to display a fixed-width, narrow version with common header - function box($args=false, $request=false, $basepage=false) { + function box($args = false, $request = false, $basepage = false) + { if (!$request) $request =& $GLOBALS['request']; $dbi = $request->getDbh(); return $this->makeBox('', $this->run($dbi, $args, $request, $basepage)); } - function makeBox($title, $body) { + function makeBox($title, $body) + { if (!$title) $title = $this->getName(); - return HTML::div(array('class'=>'box'), - HTML::div(array('class'=>'box-title'), $title), - HTML::div(array('class'=>'box-data'), $body)); + return HTML::div(array('class' => 'box'), + HTML::div(array('class' => 'box-title'), $title), + HTML::div(array('class' => 'box-data'), $body)); } - function error ($message) { + function error($message) + { return HTML::span(array('class' => 'error'), - HTML::strong(fmt("Plugin %s failed.", $this->getName())), ' ', - $message); + HTML::strong(fmt("Plugin %s failed.", $this->getName())), ' ', + $message); } - function disabled ($message='') { + function disabled($message = '') + { $html[] = HTML::div(array('class' => 'title'), - fmt("Plugin %s disabled.", $this->getName()), - ' ', $message); + fmt("Plugin %s disabled.", $this->getName()), + ' ', $message); $html[] = HTML::pre($this->_pi); return HTML::div(array('class' => 'disabled-plugin'), $html); } @@ -369,7 +382,8 @@ class WikiPlugin // PageList object, which accepts options['types']. // Register custom PageList types for special plugins, like // 'hi_content' for WikiAdminSearcheplace, 'renamed_pagename' for WikiAdminRename, ... - function addPageListColumn ($array) { + function addPageListColumn($array) + { global $customPageListColumns; if (empty($customPageListColumns)) $customPageListColumns = array(); foreach ($array as $column => $obj) { @@ -378,18 +392,20 @@ class WikiPlugin } // provide a sample usage text for automatic edit-toolbar insertion - function getUsage() { + function getUsage() + { $args = $this->getDefaultArguments(); - $string = '<<'.$this->getName().' '; + $string = '<<' . $this->getName() . ' '; if ($args) { foreach ($args as $key => $value) { - $string .= ($key."||=".(string)$value." "); + $string .= ($key . "||=" . (string)$value . " "); } } return $string . '>>'; } - function getArgumentsDescription() { + function getArgumentsDescription() + { $arguments = HTML(); foreach ($this->getDefaultArguments() as $arg => $default) { // Work around UserPreferences plugin to avoid error @@ -398,8 +414,7 @@ class WikiPlugin // This is a bit flawed with UserPreferences object //$default = sprintf("array('%s')", // implode("', '", array_keys($default))); - } - else + } else if (stristr($default, ' ')) $default = "'$default'"; $arguments->pushcontent("$arg=$default", HTML::br()); @@ -409,18 +424,20 @@ class WikiPlugin } -class WikiPluginLoader { +class WikiPluginLoader +{ var $_errors; - function expandPI($pi, &$request, &$markup, $basepage=false) { + function expandPI($pi, &$request, &$markup, $basepage = false) + { if (!($ppi = $this->parsePi($pi))) return false; list($pi_name, $plugin, $plugin_args) = $ppi; if (!is_object($plugin)) { return new HtmlElement('div', - array('class' => 'error'), - $this->getErrorDetail()); + array('class' => 'error'), + $this->getErrorDetail()); } switch ($pi_name) { case 'plugin': @@ -430,7 +447,7 @@ class WikiPluginLoader { // to be able to know about itself, or even to change the markup XmlTree (CreateToc) $dbi->_markup = &$markup; // FIXME: could do better here... - if (! $plugin->managesValidators()) { + if (!$plugin->managesValidators()) { // Output of plugin (potentially) depends on // the state of the WikiDB (other than the current // page.) @@ -445,8 +462,8 @@ class WikiPluginLoader { $timestamp = $dbi->getTimestamp(); $request->appendValidators(array('dbi_timestamp' => $timestamp, - '%mtime' => (int)$timestamp, - '%weak' => true)); + '%mtime' => (int)$timestamp, + '%weak' => true)); } return $plugin->run($dbi, $plugin_args, $request, $basepage); case 'plugin-list': @@ -456,7 +473,8 @@ class WikiPluginLoader { } } - function getWikiPageLinks($pi, $basepage) { + function getWikiPageLinks($pi, $basepage) + { if (!($ppi = $this->parsePi($pi))) return false; list($pi_name, $plugin, $plugin_args) = $ppi; @@ -467,7 +485,8 @@ class WikiPluginLoader { return $plugin->getWikiPageLinks($plugin_args, $basepage); } - function parsePI($pi) { + function parsePI($pi) + { if (!preg_match('/^\s*<\?(plugin(?:-form|-link|-list)?)\s+(\w+)\s*(.*?)\s*\?>\s*$/s', $pi, $m)) return $this->_error(sprintf("Bad %s", 'PI')); @@ -477,13 +496,14 @@ class WikiPluginLoader { return array($pi_name, $plugin, $plugin_args); } - function getPlugin($plugin_name, $pi=false) { + function getPlugin($plugin_name, $pi = false) + { global $ErrorManager; global $AllAllowedPlugins; if (in_array($plugin_name, $AllAllowedPlugins) === false) { return $this->_error(sprintf(_("Plugin '%s' does not exist."), - $plugin_name)); + $plugin_name)); } // Note that there seems to be no way to trap parse errors @@ -500,7 +520,7 @@ class WikiPluginLoader { if (!class_exists($plugin_class)) { if ($include_failed) { return $this->_error(sprintf(_("Plugin '%s' does not exist."), - $plugin_name)); + $plugin_name)); } return $this->_error(sprintf(_("%s: no such class"), $plugin_class)); } @@ -509,27 +529,32 @@ class WikiPluginLoader { $plugin = new $plugin_class; if (!is_subclass_of($plugin, "WikiPlugin")) return $this->_error(sprintf(_("%s: not a subclass of WikiPlugin."), - $plugin_class)); + $plugin_class)); $plugin->_pi = $pi; return $plugin; } - function _plugin_error_filter ($err) { + function _plugin_error_filter($err) + { if (preg_match("/Failed opening '.*' for inclusion/", $err->errstr)) - return true; // Ignore this error --- it's expected. + return true; // Ignore this error --- it's expected. return false; } - function getErrorDetail() { + function getErrorDetail() + { return $this->_errors; } - function _error($message) { + function _error($message) + { $this->_errors = $message; return false; } -}; +} + +; // Local Variables: // mode: php diff --git a/lib/WikiPluginCached.php b/lib/WikiPluginCached.php index 60bcff5a3..3744c0e74 100644 --- a/lib/WikiPluginCached.php +++ b/lib/WikiPluginCached.php @@ -30,17 +30,17 @@ require_once 'lib/WikiPlugin.php'; // require_once "lib/plugincache-config.php"; // replaced by config.ini settings! // types: -define('PLUGIN_CACHED_HTML', 0); // cached html (extensive calculation) -define('PLUGIN_CACHED_IMG_INLINE', 1); // gd images -define('PLUGIN_CACHED_MAP', 2); // area maps -define('PLUGIN_CACHED_SVG', 3); // special SVG/SVGZ object -define('PLUGIN_CACHED_SVG_PNG', 4); // special SVG/SVGZ object with PNG fallback -define('PLUGIN_CACHED_SWF', 5); // special SWF (flash) object -define('PLUGIN_CACHED_PDF', 6); // special PDF object (inlinable?) -define('PLUGIN_CACHED_PS', 7); // special PS object (inlinable?) +define('PLUGIN_CACHED_HTML', 0); // cached html (extensive calculation) +define('PLUGIN_CACHED_IMG_INLINE', 1); // gd images +define('PLUGIN_CACHED_MAP', 2); // area maps +define('PLUGIN_CACHED_SVG', 3); // special SVG/SVGZ object +define('PLUGIN_CACHED_SVG_PNG', 4); // special SVG/SVGZ object with PNG fallback +define('PLUGIN_CACHED_SWF', 5); // special SWF (flash) object +define('PLUGIN_CACHED_PDF', 6); // special PDF object (inlinable?) +define('PLUGIN_CACHED_PS', 7); // special PS object (inlinable?) // boolean tests: -define('PLUGIN_CACHED_IMG_ONDEMAND', 64);// don't cache -define('PLUGIN_CACHED_STATIC', 128); // make it available via /uploads/, not via /getimg.php?id= +define('PLUGIN_CACHED_IMG_ONDEMAND', 64); // don't cache +define('PLUGIN_CACHED_STATIC', 128); // make it available via /uploads/, not via /getimg.php?id= /** * An extension of the WikiPlugin class to allow image output and @@ -59,6 +59,7 @@ define('PLUGIN_CACHED_STATIC', 128); // make it available via /uploads/, no class WikiPluginCached extends WikiPlugin { var $_static; + /** * Produces URL and id number from plugin arguments which later on, * will allow to find a cached image or to reconstruct the complete @@ -73,26 +74,27 @@ class WikiPluginCached extends WikiPlugin * * TODO: check if args is needed at all (on lost cache) */ - function genUrl($cache, $argarray) { + function genUrl($cache, $argarray) + { global $request; //$cacheparams = $GLOBALS['CacheParams']; - $plugincall = serialize( array( + $plugincall = serialize(array( 'pluginname' => $this->getName(), - 'arguments' => $argarray ) ); - $id = $cache->generateId( $plugincall ); + 'arguments' => $argarray)); + $id = $cache->generateId($plugincall); $plugincall_arg = rawurlencode($plugincall); //$plugincall_arg = md5($plugincall); // will not work if plugin has to recreate content and cache is lost $url = DATA_PATH . '/getimg.php?'; - if (($lastchar = substr($url,-1)) == '/') { + if (($lastchar = substr($url, -1)) == '/') { $url = substr($url, 0, -1); } if (strlen($plugincall_arg) > PLUGIN_CACHED_MAXARGLEN) { // we can't send the data as URL so we just send the id - if (!$request->getSessionVar('imagecache'.$id)) { - $request->setSessionVar('imagecache'.$id, $plugincall); + if (!$request->getSessionVar('imagecache' . $id)) { + $request->setSessionVar('imagecache' . $id, $plugincall); } $plugincall_arg = false; // not needed anymore } @@ -100,7 +102,7 @@ class WikiPluginCached extends WikiPlugin if ($lastchar == '?') { // this indicates that a direct call of the image creation // script is wished ($url is assumed to link to the script) - $url .= "id=$id" . ($plugincall_arg ? '&args='.$plugincall_arg : ''); + $url .= "id=$id" . ($plugincall_arg ? '&args=' . $plugincall_arg : ''); } else { // Not yet supported. // We are supposed to use the indirect 404 ErrorDocument method @@ -108,7 +110,7 @@ class WikiPluginCached extends WikiPlugin // cache_dir and the image creation script is referred to in the // ErrorDocument 404 directive.) $url .= '/' . PLUGIN_CACHED_FILENAME_PREFIX . $id . '.img' - . ($plugincall_arg ? '?args='.$plugincall_arg : ''); + . ($plugincall_arg ? '?args=' . $plugincall_arg : ''); } if ($request->getArg("start_debug") and (DEBUG & _DEBUG_REMOTE)) $url .= "&start_debug=1"; @@ -134,18 +136,20 @@ class WikiPluginCached extends WikiPlugin * @see #getImage * @see #getMap */ - function run ($dbi, $argstr, &$request, $basepage) { + function run($dbi, $argstr, &$request, $basepage) + { $cache = $this->newCache(); //$cacheparams = $GLOBALS['CacheParams']; $sortedargs = $this->getArgs($argstr, $request); - if (is_array($sortedargs) ) + if (is_array($sortedargs)) ksort($sortedargs); $this->_args =& $sortedargs; $this->_type = $this->getPluginType(); $this->_static = false; if ($this->_type & PLUGIN_CACHED_STATIC - or $request->getArg('action') == 'pdf') // htmldoc doesn't grok subrequests + or $request->getArg('action') == 'pdf' + ) // htmldoc doesn't grok subrequests { $this->_type = $this->_type & ~PLUGIN_CACHED_STATIC; $this->_static = true; @@ -192,7 +196,7 @@ class WikiPluginCached extends WikiPlugin $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html'); if ($this->_static) $url = $content['url']; $content['html'] = $do_save ? $this->embedImg($url, $dbi, $sortedargs, $request) : false; - } elseif (!empty($content['url']) && $this->_static) { // already in cache + } elseif (!empty($content['url']) && $this->_static) { // already in cache $content['html'] = $this->embedImg($content['url'], $dbi, $sortedargs, $request); } elseif (!empty($content['image']) && $this->_static) { // copy from cache to upload $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html'); @@ -201,7 +205,7 @@ class WikiPluginCached extends WikiPlugin } break; case PLUGIN_CACHED_MAP: - if (!$content || !$content['image'] || !$content['html'] ) { + if (!$content || !$content['image'] || !$content['html']) { $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html'); if ($this->_static) $url = $content['url']; $content['html'] = $do_save @@ -210,7 +214,7 @@ class WikiPluginCached extends WikiPlugin } break; case PLUGIN_CACHED_SVG: - if (!$content || !$content['html'] ) { + if (!$content || !$content['html']) { $do_save = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html'); if ($this->_static) $url = $content['url']; $args = array(); //width+height => object args @@ -218,14 +222,14 @@ class WikiPluginCached extends WikiPlugin if (!empty($sortedargs['height'])) $args['height'] = $sortedargs['height']; $content['html'] = $do_save ? $this->embedObject($url, 'image/svg+xml', $args, - HTML::embed(array_merge( - array('src'=>$url, 'type'=>'image/svg+xml'), - $args))) + HTML::embed(array_merge( + array('src' => $url, 'type' => 'image/svg+xml'), + $args))) : false; } break; case PLUGIN_CACHED_SVG_PNG: - if (!$content || !$content['html'] ) { + if (!$content || !$content['html']) { $do_save_svg = $this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html'); if ($this->_static) $url = $content['url']; // hack alert! somehow we should know which argument will produce the secondary image (PNG) @@ -237,7 +241,7 @@ class WikiPluginCached extends WikiPlugin if (!empty($sortedargs['height'])) $args['height'] = $sortedargs['height']; $content['html'] = $do_save_svg ? $this->embedObject($url, 'image/svg+xml', $args, - $this->embedImg($pngcontent['url'], $dbi, $sortedargs, $request)) + $this->embedImg($pngcontent['url'], $dbi, $sortedargs, $request)) : false; } break; @@ -269,7 +273,8 @@ class WikiPluginCached extends WikiPlugin *
    • PLUGIN_CACHED_MAP
    • *
    */ - function getPluginType() { + function getPluginType() + { return PLUGIN_CACHED_IMG_ONDEMAND; } @@ -288,9 +293,10 @@ class WikiPluginCached extends WikiPlugin * @return imagehandle image handle if successful * false if an error occured */ - function getImage($dbi,$argarray,$request) { + function getImage($dbi, $argarray, $request) + { trigger_error('WikiPluginCached::getImage: pure virtual function in file ' - . __FILE__ . ' line ' . __LINE__, E_USER_ERROR); + . __FILE__ . ' line ' . __LINE__, E_USER_ERROR); return false; } @@ -311,7 +317,8 @@ class WikiPluginCached extends WikiPlugin * @return string format: '+seconds' * '0' never expires */ - function getExpire($dbi,$argarray,$request) { + function getExpire($dbi, $argarray, $request) + { return '0'; // persist forever } @@ -327,7 +334,8 @@ class WikiPluginCached extends WikiPlugin * @param request Request ??? * @return string 'png', 'jpeg' or 'gif' */ - function getImageType(&$dbi, $argarray, &$request) { + function getImageType(&$dbi, $argarray, &$request) + { if (in_array($argarray['imgtype'], preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES))) return $argarray['imgtype']; else @@ -346,8 +354,9 @@ class WikiPluginCached extends WikiPlugin * @param request Request ??? * @return string "alt" description of the image */ - function getAlt($dbi,$argarray,$request) { - return 'getName().' '.$this->glueArgs($argarray).'?>'; + function getAlt($dbi, $argarray, $request) + { + return 'getName() . ' ' . $this->glueArgs($argarray) . '?>'; } /** @@ -365,9 +374,10 @@ class WikiPluginCached extends WikiPlugin * @return string html to be printed in place of the plugin command * false if an error occured */ - function getHtml($dbi, $argarray, $request, $basepage) { + function getHtml($dbi, $argarray, $request, $basepage) + { trigger_error('WikiPluginCached::getHtml: pure virtual function in file ' - . __FILE__ . ' line ' . __LINE__, E_USER_ERROR); + . __FILE__ . ' line ' . __LINE__, E_USER_ERROR); } /** @@ -387,9 +397,10 @@ class WikiPluginCached extends WikiPlugin * image. * array(false,false) if an error occured */ - function getMap($dbi, $argarray, $request) { + function getMap($dbi, $argarray, $request) + { trigger_error('WikiPluginCached::getHtml: pure virtual function in file ' - . __FILE__ . ' line ' . __LINE__, E_USER_ERROR); + . __FILE__ . ' line ' . __LINE__, E_USER_ERROR); } /* --------------------- produce Html ----------------------------- */ @@ -410,15 +421,16 @@ class WikiPluginCached extends WikiPlugin * @param request Request ??? * @return string html output */ - function embedMap($id,$url,$map,&$dbi,$argarray,&$request) { + function embedMap($id, $url, $map, &$dbi, $argarray, &$request) + { // id is not unique if the same map is produced twice - $key = substr($id,0,8).substr(microtime(),0,6); - return HTML(HTML::map(array( 'name' => $key ), $map ), - HTML::img( array( - 'src' => $url, - // 'alt' => htmlspecialchars($this->getAlt($dbi,$argarray,$request)) - 'usemap' => '#'.$key )) - ); + $key = substr($id, 0, 8) . substr(microtime(), 0, 6); + return HTML(HTML::map(array('name' => $key), $map), + HTML::img(array( + 'src' => $url, + // 'alt' => htmlspecialchars($this->getAlt($dbi,$argarray,$request)) + 'usemap' => '#' . $key)) + ); } /** @@ -437,30 +449,32 @@ class WikiPluginCached extends WikiPlugin * @param request Request ??? * @return string html output */ - function embedImg($url, $dbi, $argarray, $request) { - return HTML::img( array( + function embedImg($url, $dbi, $argarray, $request) + { + return HTML::img(array( 'src' => $url, - 'alt' => htmlspecialchars($this->getAlt($dbi, $argarray, $request)) ) ); + 'alt' => htmlspecialchars($this->getAlt($dbi, $argarray, $request)))); } /** * svg?, swf, ... - - - - - Example Audio File - + + + + + Example Audio File + * See http://www.protocol7.com/svg-wiki/?EmbedingSvgInHTML - - -

    Alternate Content like

    -
    + + +

    Alternate Content like

    +
    */ // how to handle alternate images? always provide alternate static images? - function embedObject($url, $type, $args = false, $params = false) { + function embedObject($url, $type, $args = false, $params = false) + { if (!$args) $args = array(); $object = HTML::object(array_merge($args, array('src' => $url, 'type' => $type))); if ($params) @@ -479,7 +493,8 @@ class WikiPluginCached extends WikiPlugin * @access static protected * @return Cache copy of the cache object */ - function newCache() { + function newCache() + { static $staticcache; if (!is_object($staticcache)) { @@ -493,15 +508,15 @@ class WikiPluginCached extends WikiPlugin require_once 'lib/pear/Cache.php'; } $cacheparams = array(); - foreach (explode(':','database:cache_dir:filename_prefix:highwater:lowwater' - .':maxlifetime:maxarglen:usecache:force_syncmap') as $key) { - $cacheparams[$key] = constant('PLUGIN_CACHED_'.strtoupper($key)); + foreach (explode(':', 'database:cache_dir:filename_prefix:highwater:lowwater' + . ':maxlifetime:maxarglen:usecache:force_syncmap') as $key) { + $cacheparams[$key] = constant('PLUGIN_CACHED_' . strtoupper($key)); } $cacheparams['imgtypes'] = preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES); $staticcache = new Cache(PLUGIN_CACHED_DATABASE, $cacheparams); $staticcache->gc_maxlifetime = PLUGIN_CACHED_MAXLIFETIME; - if (! PLUGIN_CACHED_USECACHE ) { + if (!PLUGIN_CACHED_USECACHE) { $staticcache->setCaching(false); } } @@ -518,39 +533,41 @@ class WikiPluginCached extends WikiPlugin * 'html' in case of an error */ - function decideImgType($wish) { - if ($wish=='html') return $wish; - if ($wish=='jpg') { $wish = 'jpeg'; } + function decideImgType($wish) + { + if ($wish == 'html') return $wish; + if ($wish == 'jpg') { + $wish = 'jpeg'; + } $supportedtypes = array(); // Todo: swf, pdf, ... $imagetypes = array( - 'png' => IMG_PNG, - 'gif' => IMG_GIF, - 'jpeg' => IMG_JPEG, - 'wbmp' => IMG_WBMP, - 'xpm' => IMG_XPM, + 'png' => IMG_PNG, + 'gif' => IMG_GIF, + 'jpeg' => IMG_JPEG, + 'wbmp' => IMG_WBMP, + 'xpm' => IMG_XPM, /* // these do work but not with the ImageType bitmask 'gd' => IMG_GD, 'gd2' => IMG_GD, 'xbm' => IMG_XBM, */ - ); + ); if (function_exists('ImageTypes')) { $presenttypes = ImageTypes(); foreach ($imagetypes as $imgtype => $bitmask) - if ( $presenttypes && $bitmask ) + if ($presenttypes && $bitmask) array_push($supportedtypes, $imgtype); } else { foreach ($imagetypes as $imgtype => $bitmask) - if (function_exists("Image".$imgtype)) + if (function_exists("Image" . $imgtype)) array_push($supportedtypes, $imgtype); } if (in_array($wish, $supportedtypes)) return $wish; elseif (!empty($supportedtypes)) - return reset($supportedtypes); - else + return reset($supportedtypes); else return 'html'; } // decideImgType @@ -567,11 +584,12 @@ class WikiPluginCached extends WikiPlugin * @return void * @see decideImageType */ - function writeImage($imgtype, $imghandle, $imgfile=false) { + function writeImage($imgtype, $imghandle, $imgfile = false) + { if ($imgtype != 'html') { $func = "Image" . strtoupper($imgtype); if ($imgfile) { - $func($imghandle,$imgfile); + $func($imghandle, $imgfile); } else { $func($imghandle); } @@ -586,19 +604,20 @@ class WikiPluginCached extends WikiPlugin * @param doctype string 'gif', 'png', 'jpeg', 'html' * @return void */ - function writeHeader($doctype) { + function writeHeader($doctype) + { static $IMAGEHEADER = array( - 'gif' => 'Content-type: image/gif', - 'png' => 'Content-type: image/png', + 'gif' => 'Content-type: image/gif', + 'png' => 'Content-type: image/png', 'jpeg' => 'Content-type: image/jpeg', - 'xbm' => 'Content-type: image/xbm', - 'xpm' => 'Content-type: image/xpm', - 'gd' => 'Content-type: image/gd', - 'gd2' => 'Content-type: image/gd2', + 'xbm' => 'Content-type: image/xbm', + 'xpm' => 'Content-type: image/xpm', + 'gd' => 'Content-type: image/gd', + 'gd2' => 'Content-type: image/gd2', 'wbmp' => 'Content-type: image/vnd.wap.wbmp', // wireless bitmaps for PDA's and such. - 'html' => 'Content-type: text/html' ); - // Todo: swf, pdf, svg, svgz - Header($IMAGEHEADER[$doctype]); + 'html' => 'Content-type: text/html'); + // Todo: swf, pdf, svg, svgz + Header($IMAGEHEADER[$doctype]); } @@ -611,15 +630,16 @@ class WikiPluginCached extends WikiPlugin * @param argarray array contains all arguments to be converted * @return string concated arguments */ - function glueArgs($argarray) { + function glueArgs($argarray) + { if (!empty($argarray)) { $argstr = ''; - while (list($key,$value)=each($argarray)) { - $argstr .= $key. '=' . '"' . $value . '" '; + while (list($key, $value) = each($argarray)) { + $argstr .= $key . '=' . '"' . $value . '" '; // FIXME: How are values quoted? Can a value contain '"'? // TODO: rawurlencode(value) } - return substr($argstr, 0, strlen($argstr)-1); + return substr($argstr, 0, strlen($argstr) - 1); } return ''; } // glueArgs @@ -643,18 +663,19 @@ class WikiPluginCached extends WikiPlugin * Param id and param plugincall are * also return values. */ - function checkCall1(&$id, &$plugincall, $cache, $request, $errorformat) { + function checkCall1(&$id, &$plugincall, $cache, $request, $errorformat) + { $id = $request->getArg('id'); $plugincall = rawurldecode($request->getArg('args')); if (!$id) { - if (!$plugincall) { + if (!$plugincall) { // This should never happen, so do not gettextify. $errortext = "Neither 'args' nor 'id' given. Cannot proceed without parameters."; $this->printError($errorformat, $errortext); return false; } else { - $id = $cache->generateId( $plugincall ); + $id = $cache->generateId($plugincall); } } return true; @@ -672,16 +693,17 @@ class WikiPluginCached extends WikiPlugin * @return boolean false if an error occurs, true otherwise. * */ - function checkCall2(&$plugincall, $request) { + function checkCall2(&$plugincall, $request) + { // if plugincall wasn't sent by URL, it must have been // stored in a session var instead and we can retreive it from there if (!$plugincall) { - if (!$plugincall=$request->getSessionVar('imagecache'.$id)) { + if (!$plugincall = $request->getSessionVar('imagecache' . $id)) { // I think this is the only error which may occur // without having written bad code. So gettextify it. $errortext = sprintf( - gettext ("There is no image creation data available to id '%s'. Please reload referring page." ), - $id ); + gettext("There is no image creation data available to id '%s'. Please reload referring page."), + $id); $this->printError($errorformat, $errortext); return false; } @@ -703,11 +725,12 @@ class WikiPluginCached extends WikiPlugin * @param errorformat string outputs errors in 'png', 'gif', 'jpg' or 'html' * @return boolean error status; true=ok; false=error */ - function produceImage(&$content, $plugin, $dbi, $argarray, $request, $errorformat) { + function produceImage(&$content, $plugin, $dbi, $argarray, $request, $errorformat) + { $plugin->resetError(); $content['html'] = $imagehandle = false; - if ($plugin->getPluginType() == PLUGIN_CACHED_MAP ) { - list($imagehandle,$content['html']) = $plugin->getMap($dbi, $argarray, $request); + if ($plugin->getPluginType() == PLUGIN_CACHED_MAP) { + list($imagehandle, $content['html']) = $plugin->getMap($dbi, $argarray, $request); } else { $imagehandle = $plugin->getImage($dbi, $argarray, $request); } @@ -716,10 +739,10 @@ class WikiPluginCached extends WikiPlugin = $this->decideImgType($plugin->getImageType($dbi, $argarray, $request)); $errortext = $plugin->getError(); - if (!$imagehandle||$errortext) { + if (!$imagehandle || $errortext) { if (!$errortext) { - $errortext = "'getName(). ' ' - . $this->glueArgs($argarray)." ?>' returned no image, " + $errortext = "'getName() . ' ' + . $this->glueArgs($argarray) . " ?>' returned no image, " . " although no error was reported."; } $this->printError($errorformat, $errortext); @@ -730,7 +753,7 @@ class WikiPluginCached extends WikiPlugin if (!empty($this->_static)) { $ext = "." . $content['imagetype']; if (is_string($imagehandle) and file_exists($imagehandle)) { - if (preg_match("/.(\w+)$/",$imagehandle,$m)) { + if (preg_match("/.(\w+)$/", $imagehandle, $m)) { $ext = "." . $m[1]; } } @@ -756,7 +779,7 @@ class WikiPluginCached extends WikiPlugin return true; } if (file_exists($tmpfile)) { - $fp = fopen($tmpfile,'rb'); + $fp = fopen($tmpfile, 'rb'); $content['image'] = fread($fp, filesize($tmpfile)); fclose($fp); if (!empty($this->_static)) { @@ -772,28 +795,30 @@ class WikiPluginCached extends WikiPlugin return false; } - function staticUrl ($tmpfile) { + function staticUrl($tmpfile) + { $content['file'] = $tmpfile; $content['url'] = getUploadDataPath() . basename($tmpfile); return $content; } - function tempnam($prefix = "") { - if (preg_match("/^(.+)\.(\w{2,4})$/", $prefix, $m)) { - $prefix = $m[1]; - $ext = ".".$m[2]; - } else { - $ext = isWindows()? ".tmp" : ""; - } + function tempnam($prefix = "") + { + if (preg_match("/^(.+)\.(\w{2,4})$/", $prefix, $m)) { + $prefix = $m[1]; + $ext = "." . $m[2]; + } else { + $ext = isWindows() ? ".tmp" : ""; + } $temp = tempnam(isWindows() ? str_replace('/', "\\", PLUGIN_CACHED_CACHE_DIR) - : PLUGIN_CACHED_CACHE_DIR, - $prefix ? $prefix : PLUGIN_CACHED_FILENAME_PREFIX); + : PLUGIN_CACHED_CACHE_DIR, + $prefix ? $prefix : PLUGIN_CACHED_FILENAME_PREFIX); if (isWindows()) { - if ($ext != ".tmp") unlink($temp); + if ($ext != ".tmp") unlink($temp); $temp = preg_replace("/\.tmp$/", $ext, $temp); - } else { - $temp .= $ext; - } + } else { + $temp .= $ext; + } return $temp; } @@ -806,8 +831,9 @@ class WikiPluginCached extends WikiPlugin * @param request Request ??? * @param errorformat string outputs errors in 'png', 'gif', 'jpeg' or 'html' */ - function fetchImageFromCache($dbi, $request, $errorformat='png') { - $cache = $this->newCache(); + function fetchImageFromCache($dbi, $request, $errorformat = 'png') + { + $cache = $this->newCache(); $errorformat = $this->decideImgType($errorformat); // get id if (!$this->checkCall1($id, $plugincall, $cache, $request, $errorformat)) return false; @@ -836,7 +862,7 @@ class WikiPluginCached extends WikiPlugin if (!$this->checkCall2($plugincall, $request)) return false; $pluginname = $plugincall['pluginname']; - $argarray = $plugincall['arguments']; + $argarray = $plugincall['arguments']; $loader = new WikiPluginLoader; $plugin = $loader->getPlugin($pluginname); @@ -849,7 +875,8 @@ class WikiPluginCached extends WikiPlugin } if (!$this->produceImage($content, $plugin, $dbi, $argarray, - $request, $errorformat)) + $request, $errorformat) + ) return false; $expire = $plugin->getExpire($dbi, $argarray, $request); @@ -876,7 +903,8 @@ class WikiPluginCached extends WikiPlugin * @access private * @return void */ - function resetError() { + function resetError() + { $this->_errortext = ''; } @@ -886,7 +914,8 @@ class WikiPluginCached extends WikiPlugin * @access protected * @return string error messages printed with complain. */ - function getError() { + function getError() + { return $this->_errortext; } @@ -900,7 +929,8 @@ class WikiPluginCached extends WikiPlugin * multiple lines with '\n') * @return void */ - function complain($addtext) { + function complain($addtext) + { $this->_errortext .= $addtext; } @@ -913,28 +943,29 @@ class WikiPluginCached extends WikiPlugin * @param errortext string guess what? * @return void */ - function printError($imgtype, $errortext) { - $imgtype = $this->decideImgType($imgtype); - - $talkedallready = ob_get_contents() || headers_sent(); - if (($imgtype=='html') || $talkedallready) { - if (is_object($errortext)) - $errortext = $errortext->asXml(); - trigger_error($errortext, E_USER_WARNING); - } else { - $red = array(255,0,0); - $grey = array(221,221,221); - if (is_object($errortext)) - $errortext = $errortext->asString(); - $im = $this->text2img($errortext, 2, $red, $grey); - if (!$im) { - trigger_error($errortext, E_USER_WARNING); - return; - } - $this->writeHeader($imgtype); - $this->writeImage($imgtype, $im); - ImageDestroy($im); - } + function printError($imgtype, $errortext) + { + $imgtype = $this->decideImgType($imgtype); + + $talkedallready = ob_get_contents() || headers_sent(); + if (($imgtype == 'html') || $talkedallready) { + if (is_object($errortext)) + $errortext = $errortext->asXml(); + trigger_error($errortext, E_USER_WARNING); + } else { + $red = array(255, 0, 0); + $grey = array(221, 221, 221); + if (is_object($errortext)) + $errortext = $errortext->asString(); + $im = $this->text2img($errortext, 2, $red, $grey); + if (!$im) { + trigger_error($errortext, E_USER_WARNING); + return; + } + $this->writeHeader($imgtype); + $this->writeImage($imgtype, $im); + ImageDestroy($im); + } } // printError @@ -953,21 +984,22 @@ class WikiPluginCached extends WikiPlugin * @param bgcol array background color; array(red,green,blue) * @return string image handle for gd routines */ - function text2img($txt,$fontnr,$textcol,$bgcol) { + function text2img($txt, $fontnr, $textcol, $bgcol) + { // basic (!) output for error handling // check parameters - if ($fontnr<1 || $fontnr>5) { + if ($fontnr < 1 || $fontnr > 5) { $fontnr = 2; } if (!is_array($textcol) || !is_array($bgcol)) { - $textcol = array(0,0,0); - $bgcol = array(255,255,255); + $textcol = array(0, 0, 0); + $bgcol = array(255, 255, 255); } - foreach( array_merge($textcol,$bgcol) as $component) { - if ($component<0 || $component > 255) { - $textcol = array(0,0,0); - $bgcol = array(255,255,255); + foreach (array_merge($textcol, $bgcol) as $component) { + if ($component < 0 || $component > 255) { + $textcol = array(0, 0, 0); + $bgcol = array(255, 255, 255); break; } } @@ -975,23 +1007,24 @@ class WikiPluginCached extends WikiPlugin // prepare Parameters // set maximum values - $IMAGESIZE = array( - 'cols' => 80, - 'rows' => 25, - 'width' => 600, - 'height' => 350 ); + $IMAGESIZE = array( + 'cols' => 80, + 'rows' => 25, + 'width' => 600, + 'height' => 350); if (function_exists('ImageFontWidth')) { - $charx = ImageFontWidth($fontnr); - $chary = ImageFontHeight($fontnr); + $charx = ImageFontWidth($fontnr); + $chary = ImageFontHeight($fontnr); } else { - $charx = 10; $chary = 10; + $charx = 10; + $chary = 10; } - $marginx = $charx; - $marginy = floor($chary/2); + $marginx = $charx; + $marginy = floor($chary / 2); - $IMAGESIZE['cols'] = min($IMAGESIZE['cols'], floor(($IMAGESIZE['width'] - 2*$marginx )/$charx)); - $IMAGESIZE['rows'] = min($IMAGESIZE['rows'], floor(($IMAGESIZE['height'] - 2*$marginy )/$chary)); + $IMAGESIZE['cols'] = min($IMAGESIZE['cols'], floor(($IMAGESIZE['width'] - 2 * $marginx) / $charx)); + $IMAGESIZE['rows'] = min($IMAGESIZE['rows'], floor(($IMAGESIZE['height'] - 2 * $marginy) / $chary)); // split lines $y = 0; @@ -1000,13 +1033,13 @@ class WikiPluginCached extends WikiPlugin $len = strlen($txt); $npos = strpos($txt, "\n"); - if ($npos===false) { - $breaklen = min($IMAGESIZE['cols'],$len); + if ($npos === false) { + $breaklen = min($IMAGESIZE['cols'], $len); } else { - $breaklen = min($npos+1, $IMAGESIZE['cols']); + $breaklen = min($npos + 1, $IMAGESIZE['cols']); } $lines[$y] = chop(substr($txt, 0, $breaklen)); - $wx = max($wx,strlen($lines[$y++])); + $wx = max($wx, strlen($lines[$y++])); $txt = substr($txt, $breaklen); } while ($txt && ($y < $IMAGESIZE['rows'])); @@ -1014,30 +1047,31 @@ class WikiPluginCached extends WikiPlugin $IMAGESIZE['rows'] = $y; $IMAGESIZE['cols'] = $wx; - $IMAGESIZE['width'] = $IMAGESIZE['cols'] * $charx + 2*$marginx; - $IMAGESIZE['height'] = $IMAGESIZE['rows'] * $chary + 2*$marginy; + $IMAGESIZE['width'] = $IMAGESIZE['cols'] * $charx + 2 * $marginx; + $IMAGESIZE['height'] = $IMAGESIZE['rows'] * $chary + 2 * $marginy; // create blank image - $im = @ImageCreate($IMAGESIZE['width'],$IMAGESIZE['height']); + $im = @ImageCreate($IMAGESIZE['width'], $IMAGESIZE['height']); $col = ImageColorAllocate($im, $textcol[0], $textcol[1], $textcol[2]); - $bg = ImageColorAllocate($im, $bgcol[0], $bgcol[1], $bgcol[2]); + $bg = ImageColorAllocate($im, $bgcol[0], $bgcol[1], $bgcol[2]); - ImageFilledRectangle($im, 0, 0, $IMAGESIZE['width']-1, $IMAGESIZE['height']-1, $bg); + ImageFilledRectangle($im, 0, 0, $IMAGESIZE['width'] - 1, $IMAGESIZE['height'] - 1, $bg); // write text lines - foreach($lines as $nr => $textstr) { - ImageString( $im, $fontnr, $marginx, $marginy+$nr*$chary, - $textstr, $col ); + foreach ($lines as $nr => $textstr) { + ImageString($im, $fontnr, $marginx, $marginy + $nr * $chary, + $textstr, $col); } return $im; } // text2img - function newFilterThroughCmd($input, $commandLine) { + function newFilterThroughCmd($input, $commandLine) + { $descriptorspec = array( - 0 => array("pipe", "r"), // stdin is a pipe that the child will read from - 1 => array("pipe", "w"), // stdout is a pipe that the child will write to - 2 => array("pipe", "w"), // stdout is a pipe that the child will write to + 0 => array("pipe", "r"), // stdin is a pipe that the child will read from + 1 => array("pipe", "w"), // stdout is a pipe that the child will write to + 2 => array("pipe", "w"), // stdout is a pipe that the child will write to ); $process = proc_open("$commandLine", $descriptorspec, $pipes); @@ -1049,12 +1083,12 @@ class WikiPluginCached extends WikiPlugin fwrite($pipes[0], $input); fclose($pipes[0]); $buf = ""; - while(!feof($pipes[1])) { + while (!feof($pipes[1])) { $buf .= fgets($pipes[1], 1024); } fclose($pipes[1]); $stderr = ''; - while(!feof($pipes[2])) { + while (!feof($pipes[2])) { $stderr .= fgets($pipes[2], 1024); } fclose($pipes[2]); @@ -1067,7 +1101,8 @@ class WikiPluginCached extends WikiPlugin } // run "echo $source | $commandLine" and return result - function filterThroughCmd($source, $commandLine) { + function filterThroughCmd($source, $commandLine) + { return $this->newFilterThroughCmd($source, $commandLine); } @@ -1078,15 +1113,16 @@ class WikiPluginCached extends WikiPlugin * @param until string expected output filename * @return boolean error status; true=ok; false=error */ - function execute($cmd, $until = false) { + function execute($cmd, $until = false) + { // cmd must redirect stderr to stdout though! $errstr = exec($cmd); //, $outarr, $returnval); // normally 127 //$errstr = join('',$outarr); $ok = empty($errstr); if (!$ok) { - trigger_error("\n".$cmd." failed: $errstr", E_USER_WARNING); + trigger_error("\n" . $cmd . " failed: $errstr", E_USER_WARNING); } elseif ($GLOBALS['request']->getArg('debug')) - trigger_error("\n".$cmd.": success\n", E_USER_NOTICE); + trigger_error("\n" . $cmd . ": success\n", E_USER_NOTICE); if (!isWindows()) { if ($until) { $loop = 100000; diff --git a/lib/WikiTheme.php b/lib/WikiTheme.php index 208cf4a8a..7af1e6b6c 100644 --- a/lib/WikiTheme.php +++ b/lib/WikiTheme.php @@ -51,7 +51,8 @@ * * @return XmlContent The link */ -function WikiLink ($page_or_rev, $type = 'known', $label = false) { +function WikiLink($page_or_rev, $type = 'known', $label = false) +{ global $WikiTheme, $request; if ($type == 'button') { @@ -68,19 +69,16 @@ function WikiLink ($page_or_rev, $type = 'known', $label = false) { $pagename = $page->getName(); $wikipage = $pagename; $exists = true; - } - elseif (isa($page_or_rev, 'WikiDB_Page')) { + } elseif (isa($page_or_rev, 'WikiDB_Page')) { $page = $page_or_rev; $pagename = $page->getName(); $wikipage = $pagename; - } - elseif (isa($page_or_rev, 'WikiPageName')) { + } elseif (isa($page_or_rev, 'WikiPageName')) { $wikipage = $page_or_rev; $pagename = $wikipage->name; if (!$wikipage->isValid('strict')) return $WikiTheme->linkBadWikiWord($wikipage, $label); - } - else { + } else { $wikipage = new WikiPageName($page_or_rev, $request->getPage()); $pagename = $wikipage->name; if (!$wikipage->isValid('strict')) @@ -90,16 +88,13 @@ function WikiLink ($page_or_rev, $type = 'known', $label = false) { if ($type == 'auto' or $type == 'if_known') { if (isset($page)) { $exists = $page->exists(); - } - else { - $dbi =& $request->_dbi; + } else { + $dbi =& $request->_dbi; $exists = $dbi->isWikiPage($wikipage->name); } - } - elseif ($type == 'unknown') { + } elseif ($type == 'unknown') { $exists = false; - } - else { + } else { $exists = true; } @@ -108,9 +103,9 @@ function WikiLink ($page_or_rev, $type = 'known', $label = false) { // (I think that the fancy split links are just confusing.) // Todo: test external ImageLinks http://some/images/next.gif if (isa($wikipage, 'WikiPageName') and - ! $label and - strchr(substr($wikipage->shortName,1), SUBPAGE_SEPARATOR)) - { + !$label and + strchr(substr($wikipage->shortName, 1), SUBPAGE_SEPARATOR) + ) { $parts = explode(SUBPAGE_SEPARATOR, $wikipage->shortName); $last_part = array_pop($parts); $sep = ''; @@ -123,11 +118,11 @@ function WikiLink ($page_or_rev, $type = 'known', $label = false) { if ($part) $link->pushContent($WikiTheme->linkExistingWikiWord($parent, $sep . $part)); $sep = $WikiTheme->_autosplitWikiWords - ? ' ' . SUBPAGE_SEPARATOR : SUBPAGE_SEPARATOR; + ? ' ' . SUBPAGE_SEPARATOR : SUBPAGE_SEPARATOR; } if ($exists) $link->pushContent($WikiTheme->linkExistingWikiWord($wikipage, $sep . $last_part, - $version)); + $version)); else $link->pushContent($WikiTheme->linkUnknownWikiWord($wikipage, $sep . $last_part)); return $link; @@ -135,13 +130,11 @@ function WikiLink ($page_or_rev, $type = 'known', $label = false) { if ($exists) { return $WikiTheme->linkExistingWikiWord($wikipage, $label, $version); - } - elseif ($type == 'if_known') { + } elseif ($type == 'if_known') { if (!$label && isa($wikipage, 'WikiPageName')) $label = $wikipage->shortName; return HTML($label ? $label : $pagename); - } - else { + } else { return $WikiTheme->linkUnknownWikiWord($wikipage, $label); } } @@ -175,7 +168,8 @@ function WikiLink ($page_or_rev, $type = 'known', $label = false) { * * ($Page_or_rev is ignored for submit buttons.) */ -function Button ($action, $label = false, $page_or_rev = false, $options = false) { +function Button($action, $label = false, $page_or_rev = false, $options = false) +{ global $WikiTheme; if (!is_array($action) && preg_match('/^submit:(.*)/', $action, $m)) @@ -184,17 +178,19 @@ function Button ($action, $label = false, $page_or_rev = false, $options = false return $WikiTheme->makeActionButton($action, $label, $page_or_rev, $options); } -class WikiTheme { +class WikiTheme +{ var $HTML_DUMP_SUFFIX = ''; var $DUMP_MODE = false, $dumped_images, $dumped_css; /** * noinit: Do not initialize unnecessary items in default_theme fallback twice. */ - function WikiTheme ($theme_name = 'default', $noinit = false) { + function WikiTheme($theme_name = 'default', $noinit = false) + { $this->_name = $theme_name; $this->_themes_dir = NormalizeLocalFileName("themes"); - $this->_path = defined('PHPWIKI_DIR') ? NormalizeLocalFileName("") : ""; + $this->_path = defined('PHPWIKI_DIR') ? NormalizeLocalFileName("") : ""; $this->_theme = "themes/$theme_name"; $this->_parents = array(); @@ -207,7 +203,7 @@ class WikiTheme { $this->_parents[] = $this->_default_theme; } elseif ($parent) { $this->_parents[] = new WikiTheme - (preg_replace("/^WikiTheme_/i", "", $parent), true); + (preg_replace("/^WikiTheme_/i", "", $parent), true); } } } @@ -218,15 +214,16 @@ class WikiTheme { if (count($this->_parents) > 1) { return; } - $this->addMoreHeaders(JavaScript('',array('src' => $this->_findData("wikicommon.js")))); + $this->addMoreHeaders(JavaScript('', array('src' => $this->_findData("wikicommon.js")))); if (!FUSIONFORGE) { // FusionForge already loads this - $this->addMoreHeaders(JavaScript('',array('src' => $this->_findData("sortable.js")))); + $this->addMoreHeaders(JavaScript('', array('src' => $this->_findData("sortable.js")))); } // by pixels if ((is_object($GLOBALS['request']) // guard against unittests - and $GLOBALS['request']->getPref('doubleClickEdit')) - or ENABLE_DOUBLECLICKEDIT) + and $GLOBALS['request']->getPref('doubleClickEdit')) + or ENABLE_DOUBLECLICKEDIT + ) $this->initDoubleClickEdit(); // will be replaced by acDropDown @@ -238,15 +235,17 @@ class WikiTheme { if (ENABLE_ACDROPDOWN or ENABLE_AJAX) { $this->initMoAcDropDown(); if (ENABLE_AJAX and DEBUG) // minified all together - $this->addMoreHeaders(JavaScript('',array('src' => $this->_findData("ajax.js")))); + $this->addMoreHeaders(JavaScript('', array('src' => $this->_findData("ajax.js")))); } } - function file ($file) { + function file($file) + { return $this->_path . "$this->_theme/$file"; - } + } - function _findFile ($file, $missing_okay = false) { + function _findFile($file, $missing_okay = false) + { if (file_exists($this->file($file))) return "$this->_theme/$file"; @@ -258,7 +257,7 @@ class WikiTheme { /* Derived classes should search all parent classes */ foreach ($this->_parents as $parent) { - $path = $parent->_findFile($file, 1); + $path = $parent->_findFile($file, 1); if ($path) { return $path; } elseif (0 and DEBUG & (_DEBUG_VERBOSE + _DEBUG_REMOTE)) { @@ -267,8 +266,7 @@ class WikiTheme { } if (isset($this->_default_theme)) { return $this->_default_theme->_findFile($file, $missing_okay); - } - else if (!$missing_okay) { + } else if (!$missing_okay) { trigger_error("$this->_theme/$file: not found", E_USER_NOTICE); if (DEBUG & _DEBUG_TRACE) { echo "
    ", printSimpleTrace(debug_backtrace()), "
    \n"; @@ -277,7 +275,8 @@ class WikiTheme { return false; } - function _findData ($file, $missing_okay = false) { + function _findData($file, $missing_okay = false) + { if (!string_starts_with($file, "themes")) { // common case $path = $this->_findFile($file, $missing_okay); } else { @@ -285,7 +284,8 @@ class WikiTheme { if (file_exists($file)) { $path = $file; } elseif (defined('DATA_PATH') - and file_exists(DATA_PATH . "/$file")) { + and file_exists(DATA_PATH . "/$file") + ) { $path = $file; } else { // fallback for buttons in parent themes $path = $this->_findFile($file, $missing_okay); @@ -329,7 +329,8 @@ class WikiTheme { * are included in the messages generated by getLastModifiedMessage(), * otherwise, only the date of last modification will be shown. */ - function setDateFormat ($fs, $show_mod_time = true) { + function setDateFormat($fs, $show_mod_time = true) + { $this->_dateFormat = $fs; $this->_showModTime = $show_mod_time; } @@ -339,7 +340,8 @@ class WikiTheme { * * @param $fs string Format string for times. */ - function setTimeFormat ($fs) { + function setTimeFormat($fs) + { $this->_timeFormat = $fs; } @@ -353,14 +355,15 @@ class WikiTheme { * * @return string The date. */ - function formatDate ($time_t) { + function formatDate($time_t) + { global $request; $offset_time = $time_t + 3600 * $request->getPref('timeOffset'); // strip leading zeros from date elements (ie space followed by zero // or leading 0 as in French "09 mai 2009") return preg_replace('/ 0/', ' ', preg_replace('/^0/', ' ', - strftime($this->_dateFormat, $offset_time))); + strftime($this->_dateFormat, $offset_time))); } /** @@ -373,12 +376,13 @@ class WikiTheme { * * @return string The time. */ - function formatTime ($time_t) { + function formatTime($time_t) + { //FIXME: make 24-hour mode configurable? global $request; $offset_time = $time_t + 3600 * $request->getPref('timeOffset'); return preg_replace('/^0/', ' ', - strtolower(strftime($this->_timeFormat, $offset_time))); + strtolower(strftime($this->_timeFormat, $offset_time))); } /** @@ -391,7 +395,8 @@ class WikiTheme { * * @return string The date and time. */ - function formatDateTime ($time_t) { + function formatDateTime($time_t) + { if ($time_t == 0) { // Do not display "01 January 1970 1:00" for nonexistent pages return ""; @@ -413,7 +418,8 @@ class WikiTheme { * * @return string The day. */ - function getDay ($time_t) { + function getDay($time_t) + { global $request; if ($request->getPref('relativeDates') && ($date = $this->_relativeDay($time_t))) { @@ -434,12 +440,13 @@ class WikiTheme { * * @return string The "last modified" message. */ - function getLastModifiedMessage ($revision, $show_version = 'auto') { + function getLastModifiedMessage($revision, $show_version = 'auto') + { global $request; if (!$revision) return ''; // dates >= this are considered invalid. - if (! defined('EPOCH')) + if (!defined('EPOCH')) define('EPOCH', 0); // seconds since ~ January 1 1970 $mtime = $revision->get('mtime'); @@ -451,8 +458,8 @@ class WikiTheme { if ($request->getPref('relativeDates') && ($date = $this->_relativeDay($mtime))) { if ($this->_showModTime) - $date = sprintf(_("%s at %s"), - $date, $this->formatTime($mtime)); + $date = sprintf(_("%s at %s"), + $date, $this->formatTime($mtime)); if ($show_version) return fmt("Version %s, saved on %s", $revision->getVersion(), $date); @@ -471,13 +478,14 @@ class WikiTheme { return fmt("Last edited on %s", $date); } - function _relativeDay ($time_t) { + function _relativeDay($time_t) + { global $request; if (is_numeric($request->getPref('timeOffset'))) - $offset = 3600 * $request->getPref('timeOffset'); + $offset = 3600 * $request->getPref('timeOffset'); else - $offset = 0; + $offset = 0; $now = time() + $offset; $today = localtime($now, true); @@ -490,7 +498,8 @@ class WikiTheme { // 24 hours is not guaranteed to be yesterday. $yesterday = localtime($now - (12 + $today['tm_hour']) * 3600, true); if ($time['tm_yday'] == $yesterday['tm_yday'] - and $time['tm_year'] == $yesterday['tm_year']) + and $time['tm_year'] == $yesterday['tm_year'] + ) return _("yesterday"); return false; @@ -499,7 +508,8 @@ class WikiTheme { /** * Format the "Author" and "Owner" messages for a page revision. */ - function getOwnerMessage ($page) { + function getOwnerMessage($page) + { if (!ENABLE_PAGEPERM or !class_exists("PagePermission")) return ''; $dbi =& $GLOBALS['request']->_dbi; @@ -511,25 +521,26 @@ class WikiTheme { 's' => $page->getName()), $owner, $page)); */ - if ( $dbi->isWikiPage($owner) ) + if ($dbi->isWikiPage($owner)) return fmt("Owner: %s", WikiLink($owner)); else - return fmt("Owner: %s", '"'.$owner.'"'); + return fmt("Owner: %s", '"' . $owner . '"'); } } /* New behaviour: (by Matt Brown) Prefer author (name) over internal author_id (IP) */ - function getAuthorMessage ($revision) { + function getAuthorMessage($revision) + { if (!$revision) return ''; $dbi =& $GLOBALS['request']->_dbi; $author = $revision->get('author'); if (!$author) $author = $revision->get('author_id'); - if (!$author) return ''; - if ( $dbi->isWikiPage($author) ) { - return fmt("by %s", WikiLink($author)); + if (!$author) return ''; + if ($dbi->isWikiPage($author)) { + return fmt("by %s", WikiLink($author)); } else { - return fmt("by %s", '"'.$author.'"'); + return fmt("by %s", '"' . $author . '"'); } } @@ -543,7 +554,8 @@ class WikiTheme { //lib/WikiTheme.php:84: Notice[8]: The call_user_method() function is deprecated, //use the call_user_func variety with the array(&$obj, "method") syntax instead - function getFormatter ($type, $format) { + function getFormatter($type, $format) + { $method = strtolower("get${type}Formatter"); if (method_exists($this, $method)) return $this->{$method}($format); @@ -557,11 +569,14 @@ class WikiTheme { //////////////////////////////////////////////////////////////// var $_autosplitWikiWords = false; - function setAutosplitWikiWords($autosplit=true) { + + function setAutosplitWikiWords($autosplit = true) + { $this->_autosplitWikiWords = $autosplit ? true : false; } - function maybeSplitWikiWord ($wikiword) { + function maybeSplitWikiWord($wikiword) + { if ($this->_autosplitWikiWords) return SplitPagename($wikiword); else @@ -569,11 +584,14 @@ class WikiTheme { } var $_anonEditUnknownLinks = true; - function setAnonEditUnknownLinks($anonedit=true) { + + function setAnonEditUnknownLinks($anonedit = true) + { $this->_anonEditUnknownLinks = $anonedit ? true : false; } - function linkExistingWikiWord($wikiword, $linktext = '', $version = false) { + function linkExistingWikiWord($wikiword, $linktext = '', $version = false) + { global $request; if ($version !== false and !$this->HTML_DUMP_SUFFIX) @@ -589,16 +607,15 @@ class WikiTheme { $link = HTML::a(array('href' => $url)); if (isa($wikiword, 'WikiPageName')) - $default_text = $wikiword->shortName; - else - $default_text = $wikiword; + $default_text = $wikiword->shortName; + else + $default_text = $wikiword; if (!empty($linktext)) { $link->pushContent($linktext); $link->setAttr('class', 'named-wiki'); $link->setAttr('title', $this->maybeSplitWikiWord($default_text)); - } - else { + } else { $link->pushContent($this->maybeSplitWikiWord($default_text)); $link->setAttr('class', 'wiki'); } @@ -607,31 +624,31 @@ class WikiTheme { return $link; } - function linkUnknownWikiWord($wikiword, $linktext = '') { + function linkUnknownWikiWord($wikiword, $linktext = '') + { global $request; // Get rid of anchors on unknown wikiwords if (isa($wikiword, 'WikiPageName')) { $default_text = $wikiword->shortName; $wikiword = $wikiword->name; - } - else { + } else { $default_text = $wikiword; } if ($this->DUMP_MODE) { // HTML, PDF or XML - $link = HTML::span( empty($linktext) ? $wikiword : $linktext); + $link = HTML::span(empty($linktext) ? $wikiword : $linktext); $link->setAttr('style', 'text-decoration: underline'); $link->addTooltip(sprintf(_("Empty link to: %s"), $wikiword)); $link->setAttr('class', empty($linktext) ? 'wikiunknown' : 'named-wikiunknown'); return $link; } else { // if AnonEditUnknownLinks show "?" only users which are allowed to edit this page - if (! $this->_anonEditUnknownLinks and - ( ! $request->_user->isSignedIn() - or ! mayAccessPage('edit', $request->getArg('pagename')))) - { - $text = HTML::span( empty($linktext) ? $wikiword : $linktext); + if (!$this->_anonEditUnknownLinks and + (!$request->_user->isSignedIn() + or !mayAccessPage('edit', $request->getArg('pagename'))) + ) { + $text = HTML::span(empty($linktext) ? $wikiword : $linktext); $text->setAttr('class', empty($linktext) ? 'wikiunknown' : 'named-wikiunknown'); return $text; } else { @@ -646,8 +663,7 @@ class WikiTheme { $link->pushContent(HTML::span($linktext)); $link->setAttr('style', 'text-decoration: underline'); $link->setAttr('class', 'named-wikiunknown'); - } - else { + } else { $link->pushContent(HTML::span($this->maybeSplitWikiWord($default_text))); $link->setAttr('style', 'text-decoration: underline'); $link->setAttr('class', 'wikiunknown'); @@ -657,7 +673,7 @@ class WikiTheme { $link->pushContent($button); if ($request->getPref('googleLink')) { $gbutton = $this->makeButton('G', "http://www.google.com/search?q=" - . urlencode($wikiword)); + . urlencode($wikiword)); $gbutton->addTooltip(sprintf(_("Google:%s"), $wikiword)); $link->pushContent($gbutton); } @@ -667,16 +683,15 @@ class WikiTheme { return $link; } - function linkBadWikiWord($wikiword, $linktext = '') { + function linkBadWikiWord($wikiword, $linktext = '') + { global $ErrorManager; if ($linktext) { $text = $linktext; - } - elseif (isa($wikiword, 'WikiPageName')) { + } elseif (isa($wikiword, 'WikiPageName')) { $text = $wikiword->shortName; - } - else { + } else { $text = $wikiword; } @@ -700,15 +715,18 @@ class WikiTheme { * * (To disable an image, alias the image to false. */ - function addImageAlias ($alias, $image_name) { + function addImageAlias($alias, $image_name) + { // fall back to the PhpWiki-supplied image if not found - if ((empty($this->_imageAliases[$alias]) - and $this->_findFile("images/$image_name", true)) - or $image_name === false) + if ((empty($this->_imageAliases[$alias]) + and $this->_findFile("images/$image_name", true)) + or $image_name === false + ) $this->_imageAliases[$alias] = $image_name; } - function getImageURL ($image) { + function getImageURL($image) + { $aliases = &$this->_imageAliases; if (isset($aliases[$image])) { @@ -731,21 +749,23 @@ class WikiTheme { if ($this->DUMP_MODE) { if (empty($this->dumped_images)) $this->dumped_images = array(); - $path = "images/". basename($path); - if (!in_array($path,$this->dumped_images)) + $path = "images/" . basename($path); + if (!in_array($path, $this->dumped_images)) $this->dumped_images[] = $path; } return $path; } - function setLinkIcon($proto, $image = false) { + function setLinkIcon($proto, $image = false) + { if (!$image) $image = $proto; $this->_linkIcons[$proto] = $image; } - function getLinkIconURL ($proto) { + function getLinkIconURL($proto) + { $icons = &$this->_linkIcons; if (!empty($icons[$proto])) return $this->getImageURL($icons[$proto]); @@ -758,25 +778,29 @@ class WikiTheme { // maybe also 'spanall': there is a scheme currently in effect with front, which // spans the icon only to the first, to let the next words wrap on line breaks // see stdlib.php:PossiblyGlueIconToText() - function getLinkIconAttr () { + function getLinkIconAttr() + { return $this->_linkIcon; } - function setLinkIconAttr ($where) { + + function setLinkIconAttr($where) + { $this->_linkIcon = $where; } - function addButtonAlias ($text, $alias = false) { + function addButtonAlias($text, $alias = false) + { $aliases = &$this->_buttonAliases; if (is_array($text)) $aliases = array_merge($aliases, $text); elseif ($alias === false) - unset($aliases[$text]); - else + unset($aliases[$text]); else $aliases[$text] = $alias; } - function getButtonURL ($text) { + function getButtonURL($text) + { $aliases = &$this->_buttonAliases; if (isset($aliases[$text])) $text = $aliases[$text]; @@ -786,8 +810,8 @@ class WikiTheme { if ($url && strstr($url, '%')) { $url = preg_replace('|([^/]+)$|e', 'urlencode("\\1")', $url); } - if (!$url) {// Jeff complained about png not supported everywhere. - // This was not PC until 2005. + if (!$url) { // Jeff complained about png not supported everywhere. + // This was not PC until 2005. $url = $this->_findButton("$qtext.gif"); if ($url && strstr($url, '%')) { $url = preg_replace('|([^/]+)$|e', 'urlencode("\\1")', $url); @@ -797,15 +821,16 @@ class WikiTheme { if (empty($this->dumped_buttons)) $this->dumped_buttons = array(); $file = $url; if (defined('DATA_PATH')) - $file = substr($url,strlen(DATA_PATH)+1); - $url = "images/buttons/".basename($file); + $file = substr($url, strlen(DATA_PATH) + 1); + $url = "images/buttons/" . basename($file); if (!array_key_exists($text, $this->dumped_buttons)) $this->dumped_buttons[$text] = $file; } return $url; } - function _findButton ($button_file) { + function _findButton($button_file) + { if (empty($this->_button_path)) $this->_button_path = $this->_getButtonPath(); @@ -816,7 +841,8 @@ class WikiTheme { return false; } - function _getButtonPath () { + function _getButtonPath() + { $button_dir = $this->_findFile("buttons"); $path_dir = $this->_path . $button_dir; if (!file_exists($path_dir) || !is_dir($path_dir)) @@ -856,7 +882,8 @@ class WikiTheme { // //////////////////////////////////////////////////////////////// - function makeButton ($text, $url, $class = false, $options = false) { + function makeButton($text, $url, $class = false, $options = false) + { // FIXME: don't always try for image button? // Special case: URLs like 'submit:preview' generate form @@ -870,14 +897,15 @@ class WikiTheme { $imgurl = $text; if ($imgurl) return new ImageButton($text, $url, - in_array($class,array("wikiaction","wikiadmin"))?"wikibutton":$class, - $imgurl, $options); + in_array($class, array("wikiaction", "wikiadmin")) ? "wikibutton" : $class, + $imgurl, $options); else return new Button($this->maybeSplitWikiWord($text), $url, - $class, $options); + $class, $options); } - function makeSubmitButton ($text, $name, $class = false, $options = false) { + function makeSubmitButton($text, $name, $class = false, $options = false) + { $imgurl = $this->getButtonURL($text); if ($imgurl) @@ -910,20 +938,19 @@ class WikiTheme { * * @return object A Button object. */ - function makeActionButton ($action, $label = false, - $page_or_rev = false, $options = false) + function makeActionButton($action, $label = false, + $page_or_rev = false, $options = false) { extract($this->_get_name_and_rev($page_or_rev)); if (is_array($action)) { $attr = $action; $action = isset($attr['action']) ? $attr['action'] : 'browse'; - } - else + } else $attr['action'] = $action; $class = is_safe_action($action) ? 'wikiaction' : 'wikiadmin'; - if ( !$label ) + if (!$label) $label = $this->_labelForAction($action); if ($version) @@ -937,30 +964,31 @@ class WikiTheme { return $this->makeButton($label, WikiURL($pagename, $attr), $class, $options); } - function tooltipAccessKeyPrefix() { - static $tooltipAccessKeyPrefix = null; - if ($tooltipAccessKeyPrefix) return $tooltipAccessKeyPrefix; + function tooltipAccessKeyPrefix() + { + static $tooltipAccessKeyPrefix = null; + if ($tooltipAccessKeyPrefix) return $tooltipAccessKeyPrefix; $tooltipAccessKeyPrefix = 'alt'; - if (isBrowserOpera()) $tooltipAccessKeyPrefix = 'shift-esc'; - elseif (isBrowserSafari() or browserDetect("Mac") or isBrowserKonqueror()) - $tooltipAccessKeyPrefix = 'ctrl'; - // ff2 win and x11 only - elseif ((browserDetect("firefox/2") or browserDetect("minefield/3") or browserDetect("SeaMonkey/1.1")) - and ((browserDetect("windows") or browserDetect("x11")))) - $tooltipAccessKeyPrefix = 'alt-shift'; - return $tooltipAccessKeyPrefix; + if (isBrowserOpera()) $tooltipAccessKeyPrefix = 'shift-esc'; + elseif (isBrowserSafari() or browserDetect("Mac") or isBrowserKonqueror()) + $tooltipAccessKeyPrefix = 'ctrl'; // ff2 win and x11 only + elseif ((browserDetect("firefox/2") or browserDetect("minefield/3") or browserDetect("SeaMonkey/1.1")) + and ((browserDetect("windows") or browserDetect("x11"))) + ) + $tooltipAccessKeyPrefix = 'alt-shift'; + return $tooltipAccessKeyPrefix; } /** Define the accesskey in the title only, with ending [p] or [alt-p]. * This fixes the prefix in the title and sets the accesskey. */ - function fixAccesskey($attrs) { - if (!empty($attrs['title']) and preg_match("/\[(alt-)?(.)\]$/", $attrs['title'], $m)) - { + function fixAccesskey($attrs) + { + if (!empty($attrs['title']) and preg_match("/\[(alt-)?(.)\]$/", $attrs['title'], $m)) { if (empty($attrs['accesskey'])) $attrs['accesskey'] = $m[2]; // firefox 'alt-shift', MSIE: 'alt', ... see wikibits.js - $attrs['title'] = preg_replace("/\[(alt-)?(.)\]$/", "[".$this->tooltipAccessKeyPrefix()."-\\2]", $attrs['title']); + $attrs['title'] = preg_replace("/\[(alt-)?(.)\]$/", "[" . $this->tooltipAccessKeyPrefix() . "-\\2]", $attrs['title']); } return $attrs; } @@ -985,52 +1013,61 @@ class WikiTheme { * * @return object A Button object. */ - function makeLinkButton ($page_or_rev, $label = false, $action = false) { + function makeLinkButton($page_or_rev, $label = false, $action = false) + { extract($this->_get_name_and_rev($page_or_rev)); $args = $version ? array('version' => $version) : false; if ($action) $args['action'] = $action; return $this->makeButton($label ? $label : $pagename, - WikiURL($pagename, $args), 'wiki'); + WikiURL($pagename, $args), 'wiki'); } - function _get_name_and_rev ($page_or_rev) { + function _get_name_and_rev($page_or_rev) + { $version = false; if (empty($page_or_rev)) { global $request; $pagename = $request->getArg("pagename"); $version = $request->getArg("version"); - } - elseif (is_object($page_or_rev)) { + } elseif (is_object($page_or_rev)) { if (isa($page_or_rev, 'WikiDB_PageRevision')) { $rev = $page_or_rev; $page = $rev->getPage(); if (!$rev->isCurrent()) $version = $rev->getVersion(); - } - else { + } else { $page = $page_or_rev; } $pagename = $page->getName(); - } - else { - $pagename = (string) $page_or_rev; + } else { + $pagename = (string)$page_or_rev; } return compact('pagename', 'version'); } - function _labelForAction ($action) { + function _labelForAction($action) + { switch ($action) { - case 'edit': return _("Edit"); - case 'diff': return _("Diff"); - case 'logout': return _("Sign Out"); - case 'login': return _("Sign In"); - case 'rename': return _("Rename Page"); - case 'lock': return _("Lock Page"); - case 'unlock': return _("Unlock Page"); - case 'remove': return _("Remove Page"); - case 'purge': return _("Purge Page"); + case 'edit': + return _("Edit"); + case 'diff': + return _("Diff"); + case 'logout': + return _("Sign Out"); + case 'login': + return _("Sign In"); + case 'rename': + return _("Rename Page"); + case 'lock': + return _("Lock Page"); + case 'unlock': + return _("Unlock Page"); + case 'remove': + return _("Remove Page"); + case 'purge': + return _("Purge Page"); default: // I don't think the rest of these actually get used. // 'setprefs' @@ -1043,11 +1080,13 @@ class WikiTheme { //---------------------------------------------------------------- var $_buttonSeparator = "\n | "; - function setButtonSeparator($separator) { + function setButtonSeparator($separator) + { $this->_buttonSeparator = $separator; } - function getButtonSeparator() { + function getButtonSeparator() + { return $this->_buttonSeparator; } @@ -1092,15 +1131,16 @@ class WikiTheme { // //////////////////////////////////////////////////////////////// - function _CSSlink($title, $css_file, $media, $is_alt = false) { + function _CSSlink($title, $css_file, $media, $is_alt = false) + { // Don't set title on default style. This makes it clear to // the user which is the default (i.e. most supported) style. if ($is_alt and isBrowserKonqueror()) return HTML(); - $link = HTML::link(array('rel' => $is_alt ? 'alternate stylesheet' : 'stylesheet', - 'type' => 'text/css', - 'charset' => $GLOBALS['charset'], - 'href' => $this->_findData($css_file))); + $link = HTML::link(array('rel' => $is_alt ? 'alternate stylesheet' : 'stylesheet', + 'type' => 'text/css', + 'charset' => $GLOBALS['charset'], + 'href' => $this->_findData($css_file))); if ($is_alt) $link->setAttr('title', $title); @@ -1108,7 +1148,7 @@ class WikiTheme { $link->setAttr('media', $media); if ($this->DUMP_MODE) { if (empty($this->dumped_css)) $this->dumped_css = array(); - if (!in_array($css_file,$this->dumped_css)) $this->dumped_css[] = $css_file; + if (!in_array($css_file, $this->dumped_css)) $this->dumped_css[] = $css_file; $link->setAttr('href', basename($link->getAttr('href'))); } @@ -1135,7 +1175,8 @@ class WikiTheme { * between media types and CSS file names. Use a key of '' (the empty string) * to set the default CSS for non-specified media. (See above for an example.) */ - function setDefaultCSS ($title, $css_files) { + function setDefaultCSS($title, $css_files) + { if (!is_array($css_files)) $css_files = array('' => $css_files); // Add to the front of $this->_css @@ -1148,7 +1189,8 @@ class WikiTheme { * @param string $title Name of style. * @param string $css_files Name of CSS file. */ - function addAlternateCSS ($title, $css_files) { + function addAlternateCSS($title, $css_files) + { if (!is_array($css_files)) $css_files = array('' => $css_files); $this->_css[$title] = $css_files; @@ -1157,18 +1199,19 @@ class WikiTheme { /** * @return string HTML for CSS. */ - function getCSS () { + function getCSS() + { $css = array(); $is_alt = false; foreach ($this->_css as $title => $css_files) { ksort($css_files); // move $css_files[''] to front. foreach ($css_files as $media => $css_file) { - if (!empty($this->DUMP_MODE)) { - if ($media == 'print') - $css[] = $this->_CSSlink($title, $css_file, '', $is_alt); - } else { - $css[] = $this->_CSSlink($title, $css_file, $media, $is_alt); - } + if (!empty($this->DUMP_MODE)) { + if ($media == 'print') + $css[] = $this->_CSSlink($title, $css_file, '', $is_alt); + } else { + $css[] = $this->_CSSlink($title, $css_file, $media, $is_alt); + } if ($is_alt) break; } $is_alt = true; @@ -1176,7 +1219,8 @@ class WikiTheme { return HTML($css); } - function findTemplate ($name) { + function findTemplate($name) + { if ($tmp = $this->_findFile("templates/$name.tmpl", 1)) return $this->_path . $tmp; else { @@ -1196,19 +1240,21 @@ class WikiTheme { * or use an optional type argument, and seperate it within _MoreHeaders[] */ //$GLOBALS['request']->_MoreHeaders = array(); - function addMoreHeaders ($element) { + function addMoreHeaders($element) + { $GLOBALS['request']->_MoreHeaders[] = $element; if (!empty($this->_headers_printed) and $this->_headers_printed) { - trigger_error(_("Some action(page) wanted to add more headers, but they were already printed.") - ."\n". $element->asXML(), - E_USER_NOTICE); + trigger_error(_("Some action(page) wanted to add more headers, but they were already printed.") + . "\n" . $element->asXML(), + E_USER_NOTICE); } } /** - * Singleton. Only called once, by the head template. See the warning above. - */ - function getMoreHeaders () { + * Singleton. Only called once, by the head template. See the warning above. + */ + function getMoreHeaders() + { global $request; // actionpages cannot add headers, because recursive template expansion // already expanded the head template before. @@ -1243,11 +1289,12 @@ else window.onload = downloadJSAtOnload;'); //$GLOBALS['request']->_MoreAttr = array(); // new arg: named elements to be able to remove them. such as DoubleClickEdit for htmldumps - function addMoreAttr ($tag, $name, $element) { + function addMoreAttr($tag, $name, $element) + { global $request; // protect from duplicate attr (body jscript: themes, prefs, ...) static $_attr_cache = array(); - $hash = md5($tag."/".$element); + $hash = md5($tag . "/" . $element); if (!empty($_attr_cache[$hash])) return; $_attr_cache[$hash] = 1; @@ -1257,7 +1304,8 @@ else window.onload = downloadJSAtOnload;'); $request->_MoreAttr[$tag][$name] = $element; } - function getMoreAttr ($tag) { + function getMoreAttr($tag) + { global $request; if (empty($request->_MoreAttr[$tag])) return ''; @@ -1280,120 +1328,121 @@ else window.onload = downloadJSAtOnload;'); * This is run only once for the selected theme, and not for the parent themes. * Without this you would not be able to derive from other themes. */ - function load() { + function load() + { $this->initGlobals(); - // CSS file defines fonts, colors and background images for this - // style. The companion '*-heavy.css' file isn't defined, it's just - // expected to be in the same directory that the base style is in. - - // This should result in phpwiki-printer.css being used when - // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. - $this->setDefaultCSS('PhpWiki', - array('' => 'phpwiki.css', - 'print' => 'phpwiki-printer.css')); - - // This allows one to manually select "Printer" style (when browsing page) - // to see what the printer style looks like. - $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); - $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css'); - $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); - - if (isBrowserIE()) { - $this->addMoreHeaders($this->_CSSlink(0, - $this->_findFile('IEFixes.css'),'all')); - $this->addMoreHeaders("\n"); - } - - /** - * The logo image appears on every page and links to the HomePage. - */ - $this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); + // CSS file defines fonts, colors and background images for this + // style. The companion '*-heavy.css' file isn't defined, it's just + // expected to be in the same directory that the base style is in. - $this->addImageAlias('search', 'search.png'); + // This should result in phpwiki-printer.css being used when + // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. + $this->setDefaultCSS('PhpWiki', + array('' => 'phpwiki.css', + 'print' => 'phpwiki-printer.css')); - /** - * The Signature image is shown after saving an edited page. If this - * is set to false then the "Thank you for editing..." screen will - * be omitted. - */ + // This allows one to manually select "Printer" style (when browsing page) + // to see what the printer style looks like. + $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); + $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css'); + $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); - $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); - // Uncomment this next line to disable the signature. - //$this->addImageAlias('signature', false); + if (isBrowserIE()) { + $this->addMoreHeaders($this->_CSSlink(0, + $this->_findFile('IEFixes.css'), 'all')); + $this->addMoreHeaders("\n"); + } - /* - * Link icons. - */ - $this->setLinkIcon('http'); - $this->setLinkIcon('https'); - $this->setLinkIcon('ftp'); - $this->setLinkIcon('mailto'); - $this->setLinkIcon('interwiki'); - $this->setLinkIcon('wikiuser'); - $this->setLinkIcon('*', 'url'); + /** + * The logo image appears on every page and links to the HomePage. + */ + $this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); - $this->setButtonSeparator("\n | "); + $this->addImageAlias('search', 'search.png'); - /** - * WikiWords can automatically be split by inserting spaces between - * the words. The default is to leave WordsSmashedTogetherLikeSo. - */ - $this->setAutosplitWikiWords(false); + /** + * The Signature image is shown after saving an edited page. If this + * is set to false then the "Thank you for editing..." screen will + * be omitted. + */ - /** - * Layout improvement with dangling links for mostly closed wiki's: - * If false, only users with edit permissions will be presented the - * special wikiunknown class with "?" and Tooltip. - * If true (default), any user will see the ?, but will be presented - * the PrintLoginForm on a click. - */ - //$this->setAnonEditUnknownLinks(false); - - /* - * You may adjust the formats used for formatting dates and times - * below. (These examples give the default formats.) - * Formats are given as format strings to PHP strftime() function See - * http://www.php.net/manual/en/function.strftime.php for details. - * Do not include the server's zone (%Z), times are converted to the - * user's time zone. - * - * Suggestion for french: - * $this->setDateFormat("%A %e %B %Y"); - * $this->setTimeFormat("%H:%M:%S"); - * Suggestion for capable php versions, using the server locale: - * $this->setDateFormat("%x"); - * $this->setTimeFormat("%X"); - */ - //$this->setDateFormat("%B %d, %Y"); - //$this->setTimeFormat("%I:%M %p"); + $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); + // Uncomment this next line to disable the signature. + //$this->addImageAlias('signature', false); - /* - * To suppress times in the "Last edited on" messages, give a - * give a second argument of false: - */ - //$this->setDateFormat("%B %d, %Y", false); + /* + * Link icons. + */ + $this->setLinkIcon('http'); + $this->setLinkIcon('https'); + $this->setLinkIcon('ftp'); + $this->setLinkIcon('mailto'); + $this->setLinkIcon('interwiki'); + $this->setLinkIcon('wikiuser'); + $this->setLinkIcon('*', 'url'); + + $this->setButtonSeparator("\n | "); + + /** + * WikiWords can automatically be split by inserting spaces between + * the words. The default is to leave WordsSmashedTogetherLikeSo. + */ + $this->setAutosplitWikiWords(false); + + /** + * Layout improvement with dangling links for mostly closed wiki's: + * If false, only users with edit permissions will be presented the + * special wikiunknown class with "?" and Tooltip. + * If true (default), any user will see the ?, but will be presented + * the PrintLoginForm on a click. + */ + //$this->setAnonEditUnknownLinks(false); - /** - * Custom UserPreferences: - * A list of name => _UserPreference class pairs. - * Rationale: Certain themes should be able to extend the predefined list - * of preferences. Display/editing is done in the theme specific userprefs.tmpl - * but storage/sanification/update/... must be extended to the Get/SetPreferences methods. - * See themes/wikilens/themeinfo.php - */ - //$this->customUserPreference(); + /* + * You may adjust the formats used for formatting dates and times + * below. (These examples give the default formats.) + * Formats are given as format strings to PHP strftime() function See + * http://www.php.net/manual/en/function.strftime.php for details. + * Do not include the server's zone (%Z), times are converted to the + * user's time zone. + * + * Suggestion for french: + * $this->setDateFormat("%A %e %B %Y"); + * $this->setTimeFormat("%H:%M:%S"); + * Suggestion for capable php versions, using the server locale: + * $this->setDateFormat("%x"); + * $this->setTimeFormat("%X"); + */ + //$this->setDateFormat("%B %d, %Y"); + //$this->setTimeFormat("%I:%M %p"); - /** - * Register custom PageList type and define custom PageList classes. - * Rationale: Certain themes should be able to extend the predefined list - * of pagelist types. E.g. certain plugins, like MostPopular might use - * info=pagename,hits,rating - * which displays the rating column whenever the wikilens theme is active. - * See themes/wikilens/themeinfo.php - */ - //$this->addPageListColumn(); + /* + * To suppress times in the "Last edited on" messages, give a + * give a second argument of false: + */ + //$this->setDateFormat("%B %d, %Y", false); + + /** + * Custom UserPreferences: + * A list of name => _UserPreference class pairs. + * Rationale: Certain themes should be able to extend the predefined list + * of preferences. Display/editing is done in the theme specific userprefs.tmpl + * but storage/sanification/update/... must be extended to the Get/SetPreferences methods. + * See themes/wikilens/themeinfo.php + */ + //$this->customUserPreference(); + + /** + * Register custom PageList type and define custom PageList classes. + * Rationale: Certain themes should be able to extend the predefined list + * of pagelist types. E.g. certain plugins, like MostPopular might use + * info=pagename,hits,rating + * which displays the rating column whenever the wikilens theme is active. + * See themes/wikilens/themeinfo.php + */ + //$this->addPageListColumn(); } // end of load @@ -1405,7 +1454,8 @@ else window.onload = downloadJSAtOnload;'); * but storage/sanification/update/... must be extended to the Get/SetPreferences methods. * These values are just ignored if another theme is used. */ - function customUserPreferences($array) { + function customUserPreferences($array) + { global $customUserPreferenceColumns; // FIXME: really a global? if (empty($customUserPreferenceColumns)) $customUserPreferenceColumns = array(); //array('wikilens' => new _UserPreference_wikilens()); @@ -1418,7 +1468,8 @@ else window.onload = downloadJSAtOnload;'); * Register custom PageList types for special themes, like * 'rating' for wikilens */ - function addPageListColumn ($array) { + function addPageListColumn($array) + { global $customPageListColumns; if (empty($customPageListColumns)) $customPageListColumns = array(); foreach ($array as $column => $obj) { @@ -1426,31 +1477,33 @@ else window.onload = downloadJSAtOnload;'); } } - function initGlobals() { + function initGlobals() + { global $request; - static $already = 0; + static $already = 0; if (!$already) { $script_url = deduce_script_name(); if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug'])) - $script_url .= ("?start_debug=".$_GET['start_debug']); + $script_url .= ("?start_debug=" . $_GET['start_debug']); $folderArrowPath = dirname($this->_findData('images/folderArrowLoading.gif')); $pagename = $request->getArg('pagename'); - $js = "var data_path = '". javascript_quote_string(DATA_PATH) ."';\n" + $js = "var data_path = '" . javascript_quote_string(DATA_PATH) . "';\n" // XSS warning with pagename - ."var pagename = '". javascript_quote_string($pagename) ."';\n" - ."var script_url= '". javascript_quote_string($script_url) ."';\n" - ."var stylepath = data_path+'/".javascript_quote_string($this->_theme)."/';\n" - ."var folderArrowPath = '".javascript_quote_string($folderArrowPath)."';\n" - ."var use_path_info = " . (USE_PATH_INFO ? "true" : "false") .";\n"; + . "var pagename = '" . javascript_quote_string($pagename) . "';\n" + . "var script_url= '" . javascript_quote_string($script_url) . "';\n" + . "var stylepath = data_path+'/" . javascript_quote_string($this->_theme) . "/';\n" + . "var folderArrowPath = '" . javascript_quote_string($folderArrowPath) . "';\n" + . "var use_path_info = " . (USE_PATH_INFO ? "true" : "false") . ";\n"; $this->addMoreHeaders(JavaScript($js)); - $already = 1; + $already = 1; } } // Works only on action=browse. Patch #970004 by pixels // Usage: call $WikiTheme->initDoubleClickEdit() from theme init or // define ENABLE_DOUBLECLICKEDIT - function initDoubleClickEdit() { + function initDoubleClickEdit() + { if (!$this->HTML_DUMP_SUFFIX) $this->addMoreAttr('body', 'DoubleClickEdit', HTML::Raw(" ondblclick=\"url = document.URL; url2 = url; if (url.indexOf('?') != -1) url2 = url.slice(0, url.indexOf('?')); if ((url.indexOf('action') == -1) || (url.indexOf('action=browse') != -1)) document.location = url2 + '?action=edit';\"")); } @@ -1458,25 +1511,27 @@ else window.onload = downloadJSAtOnload;'); // Immediate title search results via XMLHTML(HttpRequest) // by Bitflux GmbH, bitflux.ch. You need to install the livesearch.js seperately. // Google's or acdropdown is better. - function initLiveSearch() { - //subclasses of Sidebar will init this twice - static $already = 0; + function initLiveSearch() + { + //subclasses of Sidebar will init this twice + static $already = 0; if (!$this->HTML_DUMP_SUFFIX and !$already) { $this->addMoreAttr('body', 'LiveSearch', - HTML::Raw(" onload=\"liveSearchInit()")); + HTML::Raw(" onload=\"liveSearchInit()")); $this->addMoreHeaders(JavaScript('var liveSearchURI="' - .WikiURL(_("TitleSearch"),false,true).'";')); + . WikiURL(_("TitleSearch"), false, true) . '";')); $this->addMoreHeaders(JavaScript('', array - ('src' => $this->_findData('livesearch.js')))); - $already = 1; + ('src' => $this->_findData('livesearch.js')))); + $already = 1; } } // Immediate title search results via XMLHttpRequest // using the shipped moacdropdown js-lib - function initMoAcDropDown() { - //subclasses of Sidebar will init this twice - static $already = 0; + function initMoAcDropDown() + { + //subclasses of Sidebar will init this twice + static $already = 0; if (!$this->HTML_DUMP_SUFFIX and !$already) { $dir = $this->_findData('moacdropdown'); if (!DEBUG and ($css = $this->_findFile('moacdropdown/css/dropdown-min.css'))) { @@ -1485,85 +1540,87 @@ else window.onload = downloadJSAtOnload;'); $this->addMoreHeaders(HTML::style(array('type' => 'text/css'), " @import url( $dir/css/dropdown.css );\n")); } // if autocomplete_remote is used: (getobject2 also for calc. the showlist width) - if (DEBUG) { - foreach (array("mobrowser.js","modomevent3.js","modomt.js", - "modomext.js","getobject2.js","xmlextras.js") as $js) - { - $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/$js"))); - } - $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/acdropdown.js"))); - } else { + if (DEBUG) { + foreach (array("mobrowser.js", "modomevent3.js", "modomt.js", + "modomext.js", "getobject2.js", "xmlextras.js") as $js) { + $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/$js"))); + } + $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/acdropdown.js"))); + } else { // already in wikicommon-min.js - ; //$this->addMoreHeaders(JavaScript('', array('src' => DATA_PATH . "/themes/default/moacdropdown.js"))); - } - /* - // for local xmlrpc requests - $xmlrpc_url = deduce_script_name(); - //if (1 or DATABASE_TYPE == 'dba') - $xmlrpc_url = DATA_PATH . "/RPC2.php"; - if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug'])) - $xmlrpc_url .= ("?start_debug=".$_GET['start_debug']); - $this->addMoreHeaders(JavaScript("var xmlrpc_url = '$xmlrpc_url'")); - */ - $already = 1; + ; //$this->addMoreHeaders(JavaScript('', array('src' => DATA_PATH . "/themes/default/moacdropdown.js"))); + } + /* + // for local xmlrpc requests + $xmlrpc_url = deduce_script_name(); + //if (1 or DATABASE_TYPE == 'dba') + $xmlrpc_url = DATA_PATH . "/RPC2.php"; + if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug'])) + $xmlrpc_url .= ("?start_debug=".$_GET['start_debug']); + $this->addMoreHeaders(JavaScript("var xmlrpc_url = '$xmlrpc_url'")); + */ + $already = 1; } } - function calendarLink($date = false) { + function calendarLink($date = false) + { return $this->calendarBase() . SUBPAGE_SEPARATOR . - strftime("%Y-%m-%d", $date ? $date : time()); + strftime("%Y-%m-%d", $date ? $date : time()); } - function calendarBase() { + function calendarBase() + { static $UserCalPageTitle = false; global $request; if (!$UserCalPageTitle) $UserCalPageTitle = $request->_user->getId() . - SUBPAGE_SEPARATOR . _("Calendar"); + SUBPAGE_SEPARATOR . _("Calendar"); if (!$UserCalPageTitle) $UserCalPageTitle = (BLOG_EMPTY_DEFAULT_PREFIX ? '' - : ($request->_user->getId() . SUBPAGE_SEPARATOR)) . "Blog"; + : ($request->_user->getId() . SUBPAGE_SEPARATOR)) . "Blog"; return $UserCalPageTitle; } - function calendarInit($force = false) { + function calendarInit($force = false) + { $dbi = $GLOBALS['request']->getDbh(); // display flat calender dhtml in the sidebar if ($force or $dbi->isWikiPage($this->calendarBase())) { $jslang = @$GLOBALS['LANG']; $this->addMoreHeaders - ( - $this->_CSSlink(0, - $this->_findFile('jscalendar/calendar-phpwiki.css'), 'all')); + ( + $this->_CSSlink(0, + $this->_findFile('jscalendar/calendar-phpwiki.css'), 'all')); $this->addMoreHeaders - (JavaScript('', - array('src' => $this->_findData('jscalendar/calendar'.(DEBUG?'':'_stripped').'.js')))); + (JavaScript('', + array('src' => $this->_findData('jscalendar/calendar' . (DEBUG ? '' : '_stripped') . '.js')))); if (!($langfile = $this->_findData("jscalendar/lang/calendar-$jslang.js"))) $langfile = $this->_findData("jscalendar/lang/calendar-en.js"); - $this->addMoreHeaders(JavaScript('',array('src' => $langfile))); + $this->addMoreHeaders(JavaScript('', array('src' => $langfile))); $this->addMoreHeaders - (JavaScript('', - array('src' => - $this->_findData('jscalendar/calendar-setup'.(DEBUG?'':'_stripped').'.js')))); + (JavaScript('', + array('src' => + $this->_findData('jscalendar/calendar-setup' . (DEBUG ? '' : '_stripped') . '.js')))); // Get existing date entries for the current user require_once 'lib/TextSearchQuery.php'; - $iter = $dbi->titleSearch(new TextSearchQuery("^".$this->calendarBase().SUBPAGE_SEPARATOR, true, "auto")); + $iter = $dbi->titleSearch(new TextSearchQuery("^" . $this->calendarBase() . SUBPAGE_SEPARATOR, true, "auto")); $existing = array(); while ($page = $iter->next()) { if ($page->exists()) $existing[] = basename($page->_pagename); } if (!empty($existing)) { - $js_exist = '{"'.join('":1,"',$existing).'":1}'; + $js_exist = '{"' . join('":1,"', $existing) . '":1}'; //var SPECIAL_DAYS = {"2004-05-11":1,"2004-05-12":1,"2004-06-01":1} $this->addMoreHeaders(JavaScript(' /* This table holds the existing calender entries for the current user * calculated from the database */ -var SPECIAL_DAYS = '.javascript_quote_string($js_exist).'; +var SPECIAL_DAYS = ' . javascript_quote_string($js_exist) . '; /* This function returns true if the date exists in SPECIAL_DAYS */ function dateExists(date, y, m, d) { @@ -1584,8 +1641,7 @@ function dateStatusFunc(date, y, m, d) { else return false; } ')); - } - else { + } else { $this->addMoreHeaders(JavaScript(' function dateStatusFunc(date, y, m, d) { return false;}')); } @@ -1600,16 +1656,18 @@ function dateStatusFunc(date, y, m, d) { return false;}')); /** CbUserLogin (&$request, $userid) * Callback when a user logs in - */ - function CbUserLogin (&$request, $userid) { - ; // do nothing + */ + function CbUserLogin(&$request, $userid) + { + ; // do nothing } /** CbNewUserEdit (&$request, $userid) * Callback when a new user creates or edits a page */ - function CbNewUserEdit (&$request, $userid) { - ; // i.e. create homepage with Template/UserPage + function CbNewUserEdit(&$request, $userid) + { + ; // i.e. create homepage with Template/UserPage } /** CbNewUserLogin (&$request, $userid) @@ -1618,18 +1676,22 @@ function dateStatusFunc(date, y, m, d) { return false;}')); * Should we track user actions? * Let's say a new user is a user without homepage. */ - function CbNewUserLogin (&$request, $userid) { - ; // do nothing + function CbNewUserLogin(&$request, $userid) + { + ; // do nothing } /** CbUserLogout (&$request, $userid) * Callback when a user logs out */ - function CbUserLogout (&$request, $userid) { - ; // do nothing + function CbUserLogout(&$request, $userid) + { + ; // do nothing } -}; +} + +; /** * A class representing a clickable "button". @@ -1637,7 +1699,8 @@ function dateStatusFunc(date, y, m, d) { return false;}')); * In it's simplest (default) form, a "button" is just a link associated * with some sort of wiki-action. */ -class Button extends HtmlElement { +class Button extends HtmlElement +{ /** Constructor * * @param $text string The text for the button. @@ -1645,7 +1708,8 @@ class Button extends HtmlElement { * @param $class string The CSS class for the button. * @param $options array Additional attributes for the <input> tag. */ - function Button ($text, $url, $class=false, $options=false) { + function Button($text, $url, $class = false, $options = false) + { global $request; //php5 workaround if (check_php_version(5)) { @@ -1662,19 +1726,23 @@ class Button extends HtmlElement { $this->setAttr($key, $val); } // Google honors this - if (in_array(strtolower($text), array('edit','create','diff','pdf')) - and !$request->_user->isAuthenticated()) + if (in_array(strtolower($text), array('edit', 'create', 'diff', 'pdf')) + and !$request->_user->isAuthenticated() + ) $this->setAttr('rel', 'nofollow'); $this->pushContent($GLOBALS['WikiTheme']->maybeSplitWikiWord($text)); } -}; +} + +; /** * A clickable image button. */ -class ImageButton extends Button { +class ImageButton extends Button +{ /** Constructor * * @param $text string The text for the button. @@ -1683,13 +1751,15 @@ class ImageButton extends Button { * @param $img_url string URL for button's image. * @param $img_attr array Additional attributes for the <img> tag. */ - function ImageButton ($text, $url, $class, $img_url, $img_attr=false) { + function ImageButton($text, $url, $class, $img_url, $img_attr = false) + { $this->__construct('a', array('href' => $url)); if ($class) $this->setAttr('class', $class); // Google honors this - if (in_array(strtolower($text), array('edit','create','diff','pdf')) - and !$GLOBALS['request']->_user->isAuthenticated()) + if (in_array(strtolower($text), array('edit', 'create', 'diff', 'pdf')) + and !$GLOBALS['request']->_user->isAuthenticated() + ) $this->setAttr('rel', 'nofollow'); if (!is_array($img_attr)) @@ -1699,12 +1769,15 @@ class ImageButton extends Button { $img_attr['class'] = 'wiki-button'; $this->pushContent(HTML::img($img_attr)); } -}; +} + +; /** * A class representing a form submit button. */ -class SubmitButton extends HtmlElement { +class SubmitButton extends HtmlElement +{ /** Constructor * * @param $text string The text for the button. @@ -1712,9 +1785,10 @@ class SubmitButton extends HtmlElement { * @param $class string The CSS class for the button. * @param $options array Additional attributes for the <input> tag. */ - function SubmitButton ($text, $name=false, $class=false, $options=false) { + function SubmitButton($text, $name = false, $class = false, $options = false) + { $this->__construct('input', array('type' => 'submit', - 'value' => $text)); + 'value' => $text)); if ($name) $this->setAttr('name', $name); if ($class) @@ -1725,12 +1799,15 @@ class SubmitButton extends HtmlElement { } } -}; +} + +; /** * A class representing an image form submit button. */ -class SubmitImageButton extends SubmitButton { +class SubmitImageButton extends SubmitButton +{ /** Constructor * * @param $text string The text for the button. @@ -1739,11 +1816,12 @@ class SubmitImageButton extends SubmitButton { * @param $img_url string URL for button's image. * @param $img_attr array Additional attributes for the <img> tag. */ - function SubmitImageButton ($text, $name=false, $class=false, $img_url, $img_attr=false) { - $this->__construct('input', array('type' => 'image', - 'src' => $img_url, - 'value' => $text, - 'alt' => $text)); + function SubmitImageButton($text, $name = false, $class = false, $img_url, $img_attr = false) + { + $this->__construct('input', array('type' => 'image', + 'src' => $img_url, + 'value' => $text, + 'alt' => $text)); if ($name) $this->setAttr('name', $name); if ($class) @@ -1754,7 +1832,9 @@ class SubmitImageButton extends SubmitButton { } } -}; +} + +; /** * A sidebar box with title and body, narrow fixed-width. @@ -1769,14 +1849,18 @@ class SubmitImageButton extends SubmitButton { * $menu = SidebarBox("Menu",HTML::dl(HTML::dt(...))); $menu->format(); * $menu = PluginSidebarBox("RecentChanges",array('limit'=>10)); $menu->format(); */ -class SidebarBox { +class SidebarBox +{ - function SidebarBox($title, $body) { + function SidebarBox($title, $body) + { require_once 'lib/WikiPlugin.php'; $this->title = $title; $this->body = $body; } - function format() { + + function format() + { return WikiPlugin::makeBox($this->title, $this->body); } } @@ -1786,38 +1870,44 @@ class SidebarBox { * Any plugin may provide a box($args=false, $request=false, $basepage=false) * method, with the help of WikiPlugin::makeBox() */ -class PluginSidebarBox extends SidebarBox { +class PluginSidebarBox extends SidebarBox +{ var $_plugin, $_args = false, $_basepage = false; - function PluginSidebarBox($name, $args = false, $basepage = false) { - require_once 'lib/WikiPlugin.php'; + function PluginSidebarBox($name, $args = false, $basepage = false) + { + require_once 'lib/WikiPlugin.php'; $loader = new WikiPluginLoader(); $plugin = $loader->getPlugin($name); if (!$plugin) { return $loader->_error(sprintf(_("Plugin %s: undefined"), - $name)); - }/* - if (!method_exists($plugin, 'box')) { - return $loader->_error(sprintf(_("%s: has no box method"), - get_class($plugin))); - }*/ - $this->_plugin =& $plugin; - $this->_args = $args ? $args : array(); + $name)); + } + /* + if (!method_exists($plugin, 'box')) { + return $loader->_error(sprintf(_("%s: has no box method"), + get_class($plugin))); + }*/ + $this->_plugin =& $plugin; + $this->_args = $args ? $args : array(); $this->_basepage = $basepage; } - function format($args = false) { + function format($args = false) + { return $this->_plugin->box($args ? array_merge($this->_args, $args) : $this->_args, - $GLOBALS['request'], - $this->_basepage); + $GLOBALS['request'], + $this->_basepage); } } // Various boxes which are no plugins -class RelatedLinksBox extends SidebarBox { - function RelatedLinksBox($title = false, $body = '', $limit = 20) { +class RelatedLinksBox extends SidebarBox +{ + function RelatedLinksBox($title = false, $body = '', $limit = 20) + { global $request; $this->title = $title ? $title : _("Related Links"); $this->body = HTML($body); @@ -1837,8 +1927,10 @@ class RelatedLinksBox extends SidebarBox { } } -class RelatedExternalLinksBox extends SidebarBox { - function RelatedExternalLinksBox($title = false, $body = '', $limit = 20) { +class RelatedExternalLinksBox extends SidebarBox +{ + function RelatedExternalLinksBox($title = false, $body = '', $limit = 20) + { global $request; $this->title = $title ? $title : _("External Links"); $this->body = HTML($body); @@ -1857,17 +1949,18 @@ class RelatedExternalLinksBox extends SidebarBox { } } -function listAvailableThemes() { +function listAvailableThemes() +{ $available_themes = array(); $dir_root = 'themes'; if (defined('PHPWIKI_DIR')) $dir_root = PHPWIKI_DIR . "/$dir_root"; $dir = dir($dir_root); if ($dir) { - while($entry = $dir->read()) { - if (is_dir($dir_root.'/'.$entry) - and file_exists($dir_root.'/'.$entry.'/themeinfo.php')) - { + while ($entry = $dir->read()) { + if (is_dir($dir_root . '/' . $entry) + and file_exists($dir_root . '/' . $entry . '/themeinfo.php') + ) { array_push($available_themes, $entry); } } @@ -1876,15 +1969,15 @@ function listAvailableThemes() { return $available_themes; } -function listAvailableLanguages() { +function listAvailableLanguages() +{ $available_languages = array('en'); $dir_root = 'locale'; if (defined('PHPWIKI_DIR')) $dir_root = PHPWIKI_DIR . "/$dir_root"; if ($dir = dir($dir_root)) { - while($entry = $dir->read()) { - if (is_dir($dir_root."/".$entry) and is_dir($dir_root.'/'.$entry.'/LC_MESSAGES')) - { + while ($entry = $dir->read()) { + if (is_dir($dir_root . "/" . $entry) and is_dir($dir_root . '/' . $entry . '/LC_MESSAGES')) { array_push($available_languages, $entry); } } diff --git a/lib/WikiUser.php b/lib/WikiUser.php index 517b396c3..575afb5b0 100644 --- a/lib/WikiUser.php +++ b/lib/WikiUser.php @@ -16,38 +16,40 @@ define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed. define('WIKIAUTH_ANON', 0); -define('WIKIAUTH_BOGO', 1); // any valid WikiWord is enough -define('WIKIAUTH_USER', 2); // real auth from a database/file/server. +define('WIKIAUTH_BOGO', 1); // any valid WikiWord is enough +define('WIKIAUTH_USER', 2); // real auth from a database/file/server. -define('WIKIAUTH_ADMIN', 10); // Wiki Admin -define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve +define('WIKIAUTH_ADMIN', 10); // Wiki Admin +define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365); -if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/'); +if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/'); $UserPreferences = array( - 'userid' => new _UserPreference(''), // really store this also? - 'passwd' => new _UserPreference(''), - 'email' => new _UserPreference(''), - 'emailVerified' => new _UserPreference_bool(), - 'notifyPages' => new _UserPreference(''), - 'theme' => new _UserPreference_theme(THEME), - 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE), - 'editWidth' => new _UserPreference_int(80, 30, 150), - 'noLinkIcons' => new _UserPreference_bool(), - 'editHeight' => new _UserPreference_int(22, 5, 80), - 'timeOffset' => new _UserPreference_numeric(0, -26, 26), - 'relativeDates' => new _UserPreference_bool(), - 'googleLink' => new _UserPreference_bool(), // 1.3.10 - 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11 - ); - -function WikiUserClassname() { + 'userid' => new _UserPreference(''), // really store this also? + 'passwd' => new _UserPreference(''), + 'email' => new _UserPreference(''), + 'emailVerified' => new _UserPreference_bool(), + 'notifyPages' => new _UserPreference(''), + 'theme' => new _UserPreference_theme(THEME), + 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE), + 'editWidth' => new _UserPreference_int(80, 30, 150), + 'noLinkIcons' => new _UserPreference_bool(), + 'editHeight' => new _UserPreference_int(22, 5, 80), + 'timeOffset' => new _UserPreference_numeric(0, -26, 26), + 'relativeDates' => new _UserPreference_bool(), + 'googleLink' => new _UserPreference_bool(), // 1.3.10 + 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11 +); + +function WikiUserClassname() +{ return 'WikiUser'; } -function UpgradeUser ($olduser, $user) { - if (isa($user,'WikiUser') and isa($olduser,'WikiUser')) { +function UpgradeUser($olduser, $user) +{ + if (isa($user, 'WikiUser') and isa($olduser, 'WikiUser')) { // populate the upgraded class with the values from the old object foreach (get_object_vars($olduser) as $k => $v) { $user->$k = $v; @@ -60,11 +62,12 @@ function UpgradeUser ($olduser, $user) { } /** -* -*/ -class WikiUser { + * + */ +class WikiUser +{ var $_userid = false; - var $_level = false; + var $_level = false; var $_request, $_dbi, $_authdbi, $_homepage; var $_authmethod = '', $_authhow = ''; @@ -76,15 +79,15 @@ class WikiUser { * @param mixed $userid String of username or WikiUser object. * @param integer $authlevel Authorization level. */ - function WikiUser (&$request, $userid = false, $authlevel = false) { + function WikiUser(&$request, $userid = false, $authlevel = false) + { $this->_request =& $request; $this->_dbi =& $this->_request->getDbh(); if (isa($userid, 'WikiUser')) { - $this->_userid = $userid->_userid; - $this->_level = $userid->_level; - } - else { + $this->_userid = $userid->_userid; + $this->_level = $userid->_level; + } else { $this->_userid = $userid; $this->_level = $authlevel; } @@ -101,13 +104,14 @@ class WikiUser { } /** - * Get the string indicating how the user was authenticated. - * - * Get the string indicating how the user was authenticated. - * Does not seem to be set - jbw - * @return string The method of authentication. - */ - function auth_how() { + * Get the string indicating how the user was authenticated. + * + * Get the string indicating how the user was authenticated. + * Does not seem to be set - jbw + * @return string The method of authentication. + */ + function auth_how() + { return $this->_authhow; } @@ -118,66 +122,77 @@ class WikiUser { * userid is a string returns true, else false. * @return boolean If valid level and username string true, else false */ - function _ok () { + function _ok() + { if ((in_array($this->_level, array(WIKIAUTH_BOGO, - WIKIAUTH_USER, - WIKIAUTH_ADMIN)) + WIKIAUTH_USER, + WIKIAUTH_ADMIN)) && - (is_string($this->_userid)))) { + (is_string($this->_userid))) + ) { return true; } return false; } - function UserName() { + function UserName() + { return $this->_userid; } - function getId () { + function getId() + { if ($this->_userid) return $this->_userid; if (!empty($this->_request)) return $this->_request->get('REMOTE_ADDR'); if (empty($this->_request)) return Request::get('REMOTE_ADDR'); - return ( $this->isSignedIn() - ? $this->_userid - : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals + return ($this->isSignedIn() + ? $this->_userid + : $this->_request->get('REMOTE_ADDR')); // FIXME: globals } - function getAuthenticatedId() { + function getAuthenticatedId() + { //assert($this->_request); - return ( $this->isAuthenticated() - ? $this->_userid - : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals + return ($this->isAuthenticated() + ? $this->_userid + : $this->_request->get('REMOTE_ADDR')); // FIXME: globals } - function isSignedIn () { + function isSignedIn() + { return $this->_level >= WIKIAUTH_BOGO; } - function isAuthenticated () { + function isAuthenticated() + { return $this->_level >= WIKIAUTH_BOGO; } - function isAdmin () { + function isAdmin() + { return $this->_level == WIKIAUTH_ADMIN; } - function hasAuthority ($require_level) { + function hasAuthority($require_level) + { return $this->_level >= $require_level; } - function isValidName ($userid = false) { + function isValidName($userid = false) + { if (!$userid) $userid = $this->_userid; - return preg_match("/^[\w\.@\-]+$/",$userid) and strlen($userid) < 32; + return preg_match("/^[\w\.@\-]+$/", $userid) and strlen($userid) < 32; } - function AuthCheck ($postargs) { + function AuthCheck($postargs) + { // Normalize args, and extract. $keys = array('userid', 'passwd', 'require_level', 'login', 'logout', - 'cancel'); + 'cancel'); foreach ($keys as $key) $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false; extract($args); @@ -186,9 +201,9 @@ class WikiUser { if ($logout) return new WikiUser($this->_request); // Log out elseif ($cancel) - return false; // User hit cancel button. + return false; // User hit cancel button. elseif (!$login && !$userid) - return false; // Nothing to do? + return false; // Nothing to do? if (!$this->isValidName($userid)) return _("Invalid username."); @@ -204,8 +219,9 @@ class WikiUser { return $user; } - function PrintLoginForm (&$request, $args, $fail_message = false, - $seperate_page = true) { + function PrintLoginForm(&$request, $args, $fail_message = false, + $seperate_page = true) + { include_once 'lib/Template.php'; // Call update_locale in case the system's default language is not 'en'. // (We have no user pref for lang at this point yet, no one is logged in.) @@ -218,13 +234,13 @@ class WikiUser { $pagename = $request->getArg('pagename'); $login = new Template('login', $request, - compact('pagename', 'userid', 'require_level', - 'fail_message', 'pass_required')); + compact('pagename', 'userid', 'require_level', + 'fail_message', 'pass_required')); if ($seperate_page) { $request->discardOutput(); $page = $request->getPage($pagename); $revision = $page->getCurrentRevision(); - return GeneratePage($login,_("Sign In"),$revision); + return GeneratePage($login, _("Sign In"), $revision); } else { return $login; } @@ -233,33 +249,35 @@ class WikiUser { /** * Check password. */ - function _pwcheck ($userid, $passwd) { + function _pwcheck($userid, $passwd) + { global $WikiNameRegexp; if (!empty($userid) && $userid == ADMIN_USER) { // $this->_authmethod = 'pagedata'; if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) - if ( !empty($passwd) - && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD ) + if (!empty($passwd) + && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD + ) return WIKIAUTH_ADMIN; else return false; if (!empty($passwd)) { if ($passwd == ADMIN_PASSWD) - return WIKIAUTH_ADMIN; + return WIKIAUTH_ADMIN; else { // maybe we forgot to enable ENCRYPTED_PASSWD? - if ( function_exists('crypt') - && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD ) { + if (function_exists('crypt') + && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD + ) { trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your config/config.ini"), - E_USER_WARNING); + E_USER_WARNING); return WIKIAUTH_ADMIN; } } } return false; - } - // HTTP Authentication + } // HTTP Authentication elseif (ALLOW_HTTP_AUTH_LOGIN && !empty($PHP_AUTH_USER)) { // if he ignored the password field, because he is already // authenticated try the previously given password. @@ -281,13 +299,13 @@ class WikiUser { return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false; } else { // else try others such as LDAP authentication: - if (ALLOW_LDAP_LOGIN && defined(LDAP_AUTH_HOST) && !empty($passwd) && !strstr($userid,'*')) { + if (ALLOW_LDAP_LOGIN && defined(LDAP_AUTH_HOST) && !empty($passwd) && !strstr($userid, '*')) { if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server! $r = @ldap_bind($ldap); // this is an anonymous bind $st_search = "uid=$userid"; // Need to set the right root search information. see ../index.php $sr = ldap_search($ldap, LDAP_BASE_DN, - "$st_search"); + "$st_search"); $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every for ($i = 0; $i < $info["count"]; $i++) { $dn = $info[$i]["dn"]; @@ -301,14 +319,14 @@ class WikiUser { } } else { trigger_error("Unable to connect to LDAP server " - . LDAP_AUTH_HOST, E_USER_WARNING); + . LDAP_AUTH_HOST, E_USER_WARNING); } } // imap authentication. added by limako if (ALLOW_IMAP_LOGIN && !empty($passwd)) { - $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}INBOX", - $userid, $passwd, OP_HALFOPEN ); - if($mbox) { + $mbox = @imap_open("{" . IMAP_AUTH_HOST . "}INBOX", + $userid, $passwd, OP_HALFOPEN); + if ($mbox) { imap_close($mbox); $this->_authmethod = 'IMAP'; return WIKIAUTH_USER; @@ -316,8 +334,9 @@ class WikiUser { } } } - if ( ALLOW_BOGO_LOGIN - && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid) ) { + if (ALLOW_BOGO_LOGIN + && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid) + ) { $this->_authmethod = 'BOGO'; return WIKIAUTH_BOGO; } @@ -325,14 +344,15 @@ class WikiUser { } // Todo: try our WikiDB backends. - function getPreferences() { + function getPreferences() + { // Restore saved preferences. // I'd rather prefer only to store the UserId in the cookie or // session, and get the preferences from the db or page. if (isset($this->_request)) { - if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2'))) - $prefs = $this->_request->getSessionVar('wiki_prefs'); + if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2'))) + $prefs = $this->_request->getSessionVar('wiki_prefs'); } //if (!$this->_userid && !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) { @@ -355,7 +375,8 @@ class WikiUser { // but not persistent. Get persistency with a homepage or DB Prefs // // Return the number of changed entries - function setPreferences($prefs, $id_only = false) { + function setPreferences($prefs, $id_only = false) + { if (!is_object($prefs)) { $prefs = new UserPreferences($prefs); } @@ -367,7 +388,7 @@ class WikiUser { // We must ensure that any password is encrypted. // We don't need any plaintext password. - if (! $id_only ) { + if (!$id_only) { if ($this->isSignedIn()) { if ($this->isAdmin()) $prefs->set('passwd', ''); @@ -375,16 +396,14 @@ class WikiUser { // plaintext! well oh well if ($homepage = $this->homePage()) { // check for page revision 0 - if (! $this->_dbi->isWikiPage($this->_userid)) { + if (!$this->_dbi->isWikiPage($this->_userid)) { trigger_error(_("Your home page has not been created yet so your preferences cannot not be saved."), - E_USER_WARNING); - } - else { + E_USER_WARNING); + } else { if ($this->isAdmin() || !$homepage->get('locked')) { $homepage->set('pref', serialize($prefs->_prefs)); return sizeof($prefs->_prefs); - } - else { + } else { // An "empty" page could still be // intentionally locked by admin to // prevent its creation. @@ -394,13 +413,13 @@ class WikiUser { // once the new WikiUser code has been // implemented. trigger_error(_("Your home page is locked so your preferences cannot not be saved.") - . " " . _("Please contact your PhpWiki administrator for assistance."), - E_USER_WARNING); + . " " . _("Please contact your PhpWiki administrator for assistance."), + E_USER_WARNING); } } } else { trigger_error("No homepage for user found. Creating one...", - E_USER_WARNING); + E_USER_WARNING); $this->createHomepage($prefs); //$homepage->set('pref', serialize($prefs->_prefs)); return sizeof($prefs->_prefs); @@ -414,14 +433,16 @@ class WikiUser { // check for homepage with user flag. // can be overriden from the auth backends - function exists() { + function exists() + { $homepage = $this->homePage(); return ($this->_userid && $homepage && $homepage->get('pref')); } // doesn't check for existance!!! hmm. // how to store metadata in not existing pages? how about versions? - function homePage() { + function homePage() + { if (!$this->_userid) return false; if (!empty($this->_homepage)) { @@ -436,12 +457,14 @@ class WikiUser { } } - function hasHomePage() { + function hasHomePage() + { return !$this->homePage(); } // create user by checking his homepage - function createUser ($pref, $createDefaultHomepage = true) { + function createUser($pref, $createDefaultHomepage = true) + { if ($this->exists()) return; if ($createDefaultHomepage) { @@ -450,87 +473,92 @@ class WikiUser { // empty page include 'lib/loadsave.php'; $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)), - 'versiondata' => array('author' => $this->_userid), - 'pagename' => $this->_userid, - 'content' => _('CategoryHomepage')); - SavePage ($this->_request, $pageinfo, false, false); + 'versiondata' => array('author' => $this->_userid), + 'pagename' => $this->_userid, + 'content' => _('CategoryHomepage')); + SavePage($this->_request, $pageinfo, false, false); } $this->setPreferences($pref); } // create user and default user homepage - function createHomepage ($pref) { + function createHomepage($pref) + { $pagename = $this->_userid; include 'lib/loadsave.php'; // create default homepage: // properly expanded template and the pref metadata $template = Template('homepage.tmpl', $this->_request); - $text = $template->getExpansion(); + $text = $template->getExpansion(); $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)), - 'versiondata' => array('author' => $this->_userid), - 'pagename' => $pagename, - 'content' => $text); - SavePage ($this->_request, $pageinfo, false, false); + 'versiondata' => array('author' => $this->_userid), + 'pagename' => $pagename, + 'content' => $text); + SavePage($this->_request, $pageinfo, false, false); // create Calendar $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Calendar'); - if (! isWikiPage($pagename)) { + if (!isWikiPage($pagename)) { $pageinfo = array('pagedata' => array(), - 'versiondata' => array('author' => $this->_userid), - 'pagename' => $pagename, - 'content' => "\n"); - SavePage ($this->_request, $pageinfo, false, false); + 'versiondata' => array('author' => $this->_userid), + 'pagename' => $pagename, + 'content' => "\n"); + SavePage($this->_request, $pageinfo, false, false); } // create Preferences $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences'); - if (! isWikiPage($pagename)) { + if (!isWikiPage($pagename)) { $pageinfo = array('pagedata' => array(), - 'versiondata' => array('author' => $this->_userid), - 'pagename' => $pagename, - 'content' => "\n"); - SavePage ($this->_request, $pageinfo, false, false); + 'versiondata' => array('author' => $this->_userid), + 'pagename' => $pagename, + 'content' => "\n"); + SavePage($this->_request, $pageinfo, false, false); } } - function tryAuthBackends() { + function tryAuthBackends() + { return ''; // crypt('') will never be '' } // Auth backends must store the crypted password where? // Not in the preferences. - function checkPassword($passwd) { + function checkPassword($passwd) + { $prefs = $this->getPreferences(); $stored_passwd = $prefs->get('passwd'); // crypted - if (empty($prefs->_prefs['passwd'])) // not stored in the page + if (empty($prefs->_prefs['passwd'])) // not stored in the page // allow empty passwords? At least store a '*' then. // try other backend. hmm. $stored_passwd = $this->tryAuthBackends($this->_userid); if (empty($stored_passwd)) { trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."), - $this->_userid), E_USER_NOTICE); - $prefs->set('passwd','*'); + $this->_userid), E_USER_NOTICE); + $prefs->set('passwd', '*'); return true; } if ($stored_passwd == '*') return true; - if ( !empty($passwd) - && crypt($passwd, $stored_passwd) == $stored_passwd ) + if (!empty($passwd) + && crypt($passwd, $stored_passwd) == $stored_passwd + ) return true; else return false; } - function changePassword($newpasswd, $passwd2 = false) { - if (! $this->mayChangePass() ) { + function changePassword($newpasswd, $passwd2 = false) + { + if (!$this->mayChangePass()) { trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!", - $this->_userid), E_USER_ERROR); + $this->_userid), E_USER_ERROR); return false; } if ($passwd2 && $passwd2 != $newpasswd) { trigger_error("The second password must be the same as the first to change it", - E_USER_ERROR); + E_USER_ERROR); return false; } if (!$this->isAuthenticated()) return false; @@ -544,7 +572,8 @@ class WikiUser { return true; } - function mayChangePass() { + function mayChangePass() + { // on external DBAuth maybe. on IMAP or LDAP not // on internal DBAuth yes if (in_array($this->_authmethod, array('IMAP', 'LDAP'))) @@ -556,7 +585,7 @@ class WikiUser { if ($this->_authmethod == 'authdb') return true; } - } +} // create user and default user homepage // FIXME: delete this, not used? @@ -570,29 +599,34 @@ function createUser ($userid, $pref) { class _UserPreference { - function _UserPreference ($default_value) { + function _UserPreference($default_value) + { $this->default_value = $default_value; } - function sanify ($value) { + function sanify($value) + { return (string)$value; } - function update ($value) { + function update($value) + { } } class _UserPreference_numeric -extends _UserPreference + extends _UserPreference { - function _UserPreference_numeric ($default, $minval = false, - $maxval = false) { + function _UserPreference_numeric($default, $minval = false, + $maxval = false) + { $this->_UserPreference((double)$default); $this->_minval = (double)$minval; $this->_maxval = (double)$maxval; } - function sanify ($value) { + function sanify($value) + { $value = (double)$value; if ($this->_minval !== false && $value < $this->_minval) $value = $this->_minval; @@ -603,26 +637,30 @@ extends _UserPreference } class _UserPreference_int -extends _UserPreference_numeric + extends _UserPreference_numeric { - function _UserPreference_int ($default, $minval = false, $maxval = false) { + function _UserPreference_int($default, $minval = false, $maxval = false) + { $this->_UserPreference_numeric((int)$default, (int)$minval, - (int)$maxval); + (int)$maxval); } - function sanify ($value) { + function sanify($value) + { return (int)parent::sanify((int)$value); } } class _UserPreference_bool -extends _UserPreference + extends _UserPreference { - function _UserPreference_bool ($default = false) { + function _UserPreference_bool($default = false) + { $this->_UserPreference((bool)$default); } - function sanify ($value) { + function sanify($value) + { if (is_array($value)) { /* This allows for constructs like: * @@ -639,56 +677,64 @@ extends _UserPreference } return false; } - return (bool) $value; + return (bool)$value; } } class _UserPreference_language -extends _UserPreference + extends _UserPreference { - function _UserPreference_language ($default = DEFAULT_LANGUAGE) { + function _UserPreference_language($default = DEFAULT_LANGUAGE) + { $this->_UserPreference($default); } // FIXME: check for valid locale - function sanify ($value) { + function sanify($value) + { // Revert to DEFAULT_LANGUAGE if user does not specify // language in UserPreferences or chooses . if ($value == '' or empty($value)) $value = DEFAULT_LANGUAGE; - return (string) $value; + return (string)$value; } } class _UserPreference_theme -extends _UserPreference + extends _UserPreference { - function _UserPreference_theme ($default = THEME) { + function _UserPreference_theme($default = THEME) + { $this->_UserPreference($default); } - function sanify ($value) { + function sanify($value) + { if (findFile($this->_themefile($value), true)) return $value; return $this->default_value; } - function update ($newvalue) { + function update($newvalue) + { global $WikiTheme; include_once($this->_themefile($newvalue)); if (empty($WikiTheme)) include_once($this->_themefile(THEME)); } - function _themefile ($theme) { + function _themefile($theme) + { return "themes/$theme/themeinfo.php"; } } // don't save default preferences for efficiency. -class UserPreferences { - function UserPreferences ($saved_prefs = false) { +class UserPreferences +{ + function UserPreferences($saved_prefs = false) + { $this->_prefs = array(); if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) { @@ -700,7 +746,8 @@ class UserPreferences { } } - function _getPref ($name) { + function _getPref($name) + { global $UserPreferences; if (!isset($UserPreferences[$name])) { if ($name == 'passwd2') return false; @@ -710,7 +757,8 @@ class UserPreferences { return $UserPreferences[$name]; } - function get ($name) { + function get($name) + { if (isset($this->_prefs[$name])) return $this->_prefs[$name]; if (!($pref = $this->_getPref($name))) @@ -718,7 +766,8 @@ class UserPreferences { return $pref->default_value; } - function set ($name, $value) { + function set($name, $value) + { if (!($pref = $this->_getPref($name))) return false; @@ -737,13 +786,16 @@ class UserPreferences { $this->_prefs[$name] = $newvalue; } - function pack ($nonpacked) { + function pack($nonpacked) + { return serialize($nonpacked); } - function unpack ($packed) { + + function unpack($packed) + { if (!$packed) return false; - if (substr($packed,0,2) == "O:") { + if (substr($packed, 0, 2) == "O:") { // Looks like a serialized object return unserialize($packed); } @@ -752,7 +804,8 @@ class UserPreferences { return false; } - function hash () { + function hash() + { return wikihash($this->_prefs); } } diff --git a/lib/WikiUser/AdoDb.php b/lib/WikiUser/AdoDb.php index dd41ce008..15867082e 100644 --- a/lib/WikiUser/AdoDb.php +++ b/lib/WikiUser/AdoDb.php @@ -23,28 +23,30 @@ include_once 'lib/WikiUser/Db.php'; class _AdoDbPassUser -extends _DbPassUser -/** - * ADODB methods - * Simple sprintf, no prepare. - * - * Warning: Since we use FETCH_MODE_ASSOC (string hash) and not the also faster - * FETCH_MODE_ROW (numeric), we have to use the correct aliases in auth_* sql statements! - * - * TODO: Change FETCH_MODE in adodb WikiDB sublasses. - * - * @tables: user - */ + extends _DbPassUser + /** + * ADODB methods + * Simple sprintf, no prepare. + * + * Warning: Since we use FETCH_MODE_ASSOC (string hash) and not the also faster + * FETCH_MODE_ROW (numeric), we have to use the correct aliases in auth_* sql statements! + * + * TODO: Change FETCH_MODE in adodb WikiDB sublasses. + * + * @tables: user + */ { var $_authmethod = 'AdoDb'; - function _AdoDbPassUser($UserName='',$prefs=false) { - if (!$this->_prefs and isa($this,"_AdoDbPassUser")) { + + function _AdoDbPassUser($UserName = '', $prefs = false) + { + if (!$this->_prefs and isa($this, "_AdoDbPassUser")) { if ($prefs) $this->_prefs = $prefs; if (!isset($this->_prefs->_method)) - _PassUser::_PassUser($UserName); + _PassUser::_PassUser($UserName); } if (!$this->isValidName($UserName)) { - trigger_error(_("Invalid username."),E_USER_WARNING); + trigger_error(_("Invalid username."), E_USER_WARNING); return false; } $this->_userid = $UserName; @@ -54,7 +56,8 @@ extends _DbPassUser return $this; } - function getPreferences() { + function getPreferences() + { // override the generic slow method here for efficiency _AnonUser::getPreferences(); $this->getAuthDbh(); @@ -75,7 +78,8 @@ extends _DbPassUser } if (!empty($this->_HomePagehandle)) { if ($restored_from_page = $this->_prefs->retrieve - ($this->_HomePagehandle->get('pref'))) { + ($this->_HomePagehandle->get('pref')) + ) { $updated = $this->_prefs->updatePrefs($restored_from_page); //$this->_prefs = new UserPreferences($restored_from_page); return $this->_prefs; @@ -84,7 +88,8 @@ extends _DbPassUser return $this->_prefs; } - function setPreferences($prefs, $id_only=false) { + function setPreferences($prefs, $id_only = false) + { // if the prefs are changed if (_AnonUser::setPreferences($prefs, 1)) { global $request; @@ -105,16 +110,16 @@ extends _DbPassUser } if ($prefs_blob) { $db_result = $dbh->Execute(sprintf($this->_prefs->_update, - $dbh->qstr($packed), - $dbh->qstr($this->_userid))); + $dbh->qstr($packed), + $dbh->qstr($this->_userid))); } else { // Otherwise, insert a record for them and set it to the defaults. $dbi = $request->getDbh(); $this->_prefs->_insert = $this->prepare($dbi->getAuthParam('pref_insert'), - array("pref_blob", "userid")); + array("pref_blob", "userid")); $db_result = $dbh->Execute(sprintf($this->_prefs->_insert, - $dbh->qstr($packed), - $dbh->qstr($this->_userid))); + $dbh->qstr($packed), + $dbh->qstr($this->_userid))); } $db_result->Close(); // delete pageprefs: @@ -130,7 +135,8 @@ extends _DbPassUser return 0; } - function userExists() { + function userExists() + { $this->getAuthDbh(); $dbh = &$this->_auth_dbi; if (!$dbh) { // needed? @@ -143,13 +149,13 @@ extends _DbPassUser // Prepare the configured auth statements if ($dbi->getAuthParam('auth_check') and empty($this->_authselect)) { $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'), - array("password", "userid")); + array("password", "userid")); } //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed - if ( !$dbi->getAuthParam('auth_user_exists') - and $this->_auth_crypt_method == 'crypt' - and $this->_authselect) - { + if (!$dbi->getAuthParam('auth_user_exists') + and $this->_auth_crypt_method == 'crypt' + and $this->_authselect + ) { $rs = $dbh->Execute(sprintf($this->_authselect, $dbh->qstr($this->_userid))); if (!$rs->EOF) { $rs->Close(); @@ -157,13 +163,12 @@ extends _DbPassUser } else { $rs->Close(); } - } - else { - if (! $dbi->getAuthParam('auth_user_exists')) + } else { + if (!$dbi->getAuthParam('auth_user_exists')) trigger_error(fmt("%s is missing", 'DBAUTH_AUTH_USER_EXISTS'), - E_USER_WARNING); + E_USER_WARNING); $this->_authcheck = $this->prepare($dbi->getAuthParam('auth_user_exists'), - 'userid'); + 'userid'); $rs = $dbh->Execute(sprintf($this->_authcheck, $dbh->qstr($this->_userid))); if (!$rs->EOF) { $rs->Close(); @@ -178,30 +183,31 @@ extends _DbPassUser // reasons if (empty($this->_authcreate) and $dbi->getAuthParam('auth_create')) { $this->_authcreate = $this->prepare($dbi->getAuthParam('auth_create'), - array("password", "userid")); + array("password", "userid")); } if (!empty($this->_authcreate) and isset($GLOBALS['HTTP_POST_VARS']['auth']) and - isset($GLOBALS['HTTP_POST_VARS']['auth']['passwd'])) - { + isset($GLOBALS['HTTP_POST_VARS']['auth']['passwd']) + ) { $passwd = $GLOBALS['HTTP_POST_VARS']['auth']['passwd']; $dbh->Execute(sprintf($this->_authcreate, - $dbh->qstr($passwd), - $dbh->qstr($this->_userid))); + $dbh->qstr($passwd), + $dbh->qstr($this->_userid))); return true; } return $this->_tryNextUser(); } - function checkPass($submitted_password) { + function checkPass($submitted_password) + { //global $DBAuthParams; $this->getAuthDbh(); - if (!$this->_auth_dbi) { // needed? + if (!$this->_auth_dbi) { // needed? return $this->_tryNextPass($submitted_password); } if (!$this->isValidName()) { - trigger_error(_("Invalid username."),E_USER_WARNING); + trigger_error(_("Invalid username."), E_USER_WARNING); return $this->_tryNextPass($submitted_password); } if (!$this->_checkPassLength($submitted_password)) { @@ -211,18 +217,18 @@ extends _DbPassUser $dbi =& $GLOBALS['request']->_dbi; if (empty($this->_authselect) and $dbi->getAuthParam('auth_check')) { $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'), - array("password", "userid")); + array("password", "userid")); } if (!isset($this->_authselect)) $this->userExists(); if (!isset($this->_authselect)) trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'", - 'DBAUTH_AUTH_CHECK', 'ADODB'), - E_USER_WARNING); + 'DBAUTH_AUTH_CHECK', 'ADODB'), + E_USER_WARNING); //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set if ($this->_auth_crypt_method == 'crypt') { $rs = $dbh->Execute(sprintf($this->_authselect, - $dbh->qstr($this->_userid))); + $dbh->qstr($this->_userid))); if (!$rs->EOF) { $stored_password = $rs->fields['password']; $rs->Close(); @@ -233,13 +239,12 @@ extends _DbPassUser } } else { $rs = $dbh->Execute(sprintf($this->_authselect, - $dbh->qstr($submitted_password), - $dbh->qstr($this->_userid))); + $dbh->qstr($submitted_password), + $dbh->qstr($this->_userid))); if (isset($rs->fields['ok'])) $okay = $rs->fields['ok']; elseif (isset($rs->fields[0])) - $okay = $rs->fields[0]; - else { + $okay = $rs->fields[0]; else { if (is_array($rs->fields)) $okay = reset($rs->fields); else @@ -260,22 +265,24 @@ extends _DbPassUser } } - function mayChangePass() { + function mayChangePass() + { return $GLOBALS['request']->_dbi->getAuthParam('auth_update'); } - function storePass($submitted_password) { + function storePass($submitted_password) + { $this->getAuthDbh(); $dbh = &$this->_auth_dbi; $dbi =& $GLOBALS['request']->_dbi; if ($dbi->getAuthParam('auth_update') and empty($this->_authupdate)) { $this->_authupdate = $this->prepare($dbi->getAuthParam('auth_update'), - array("password", "userid")); + array("password", "userid")); } if (!isset($this->_authupdate)) { trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'", - 'DBAUTH_AUTH_UPDATE', 'ADODB'), - E_USER_WARNING); + 'DBAUTH_AUTH_UPDATE', 'ADODB'), + E_USER_WARNING); return false; } @@ -284,9 +291,9 @@ extends _DbPassUser $submitted_password = crypt($submitted_password); } $rs = $dbh->Execute(sprintf($this->_authupdate, - $dbh->qstr($submitted_password), - $dbh->qstr($this->_userid) - )); + $dbh->qstr($submitted_password), + $dbh->qstr($this->_userid) + )); $rs->Close(); return $rs; } diff --git a/lib/WikiUser/BogoLogin.php b/lib/WikiUser/BogoLogin.php index 190cc37ff..d53effdd8 100644 --- a/lib/WikiUser/BogoLogin.php +++ b/lib/WikiUser/BogoLogin.php @@ -23,11 +23,13 @@ /** Without stored password. A _BogoLoginPassUser with password * is automatically upgraded to a PersonalPagePassUser. */ -class _BogoLoginPassUser extends _PassUser { +class _BogoLoginPassUser extends _PassUser +{ var $_authmethod = 'BogoLogin'; - function userExists() { + function userExists() + { if (isWikiWord($this->_userid)) { $this->_level = WIKIAUTH_BOGO; return true; @@ -40,7 +42,8 @@ class _BogoLoginPassUser extends _PassUser { /** A BogoLoginUser requires no password at all * But if there's one stored, we override it with the PersonalPagePassUser instead */ - function checkPass($submitted_password) { + function checkPass($submitted_password) + { if ($this->_prefs->get('passwd')) { if (isset($this->_prefs->_method) and $this->_prefs->_method == 'HomePage') { $user = new _PersonalPagePassUser($this->_userid, $this->_prefs); diff --git a/lib/WikiUser/Db.php b/lib/WikiUser/Db.php index 9172f7649..976f8eb35 100644 --- a/lib/WikiUser/Db.php +++ b/lib/WikiUser/Db.php @@ -43,20 +43,21 @@ * Flat files auth is handled by the auth method "File". */ class _DbPassUser -extends _PassUser + extends _PassUser { var $_authselect, $_authupdate, $_authcreate; // This can only be called from _PassUser, because the parent class // sets the auth_dbi and pref methods, before this class is initialized. - function _DbPassUser($UserName='',$prefs=false) { + function _DbPassUser($UserName = '', $prefs = false) + { if (!$this->_prefs) { if ($prefs) $this->_prefs = $prefs; } if (!isset($this->_prefs->_method)) - _PassUser::_PassUser($UserName); + _PassUser::_PassUser($UserName); elseif (!$this->isValidName($UserName)) { - trigger_error(_("Invalid username."),E_USER_WARNING); + trigger_error(_("Invalid username."), E_USER_WARNING); return false; } $this->_authmethod = 'Db'; @@ -67,29 +68,27 @@ extends _PassUser if ($dbtype == 'ADODB') { include_once 'lib/WikiUser/AdoDb.php'; if (check_php_version(5)) - return new _AdoDbPassUser($UserName,$this->_prefs); + return new _AdoDbPassUser($UserName, $this->_prefs); else { - $user = new _AdoDbPassUser($UserName,$this->_prefs); + $user = new _AdoDbPassUser($UserName, $this->_prefs); eval("\$this = \$user;"); return $user; } - } - elseif ($dbtype == 'SQL') { + } elseif ($dbtype == 'SQL') { include_once 'lib/WikiUser/PearDb.php'; if (check_php_version(5)) - return new _PearDbPassUser($UserName,$this->_prefs); + return new _PearDbPassUser($UserName, $this->_prefs); else { - $user = new _PearDbPassUser($UserName,$this->_prefs); + $user = new _PearDbPassUser($UserName, $this->_prefs); eval("\$this = \$user;"); return $user; } - } - elseif ($dbtype == 'PDO') { + } elseif ($dbtype == 'PDO') { include_once 'lib/WikiUser/PdoDb.php'; if (check_php_version(5)) - return new _PdoDbPassUser($UserName,$this->_prefs); + return new _PdoDbPassUser($UserName, $this->_prefs); else { - $user = new _PdoDbPassUser($UserName,$this->_prefs); + $user = new _PdoDbPassUser($UserName, $this->_prefs); eval("\$this = \$user;"); return $user; } @@ -100,14 +99,16 @@ extends _PassUser /* Since we properly quote the username, we allow most chars here. Just " ; and ' is forbidden, max length: 48 as defined in the schema. */ - function isValidName ($userid = false) { + function isValidName($userid = false) + { if (!$userid) $userid = $this->_userid; if (strcspn($userid, ";'\"") != strlen($userid)) return false; if (strlen($userid) > 48) return false; return true; } - function mayChangePass() { + function mayChangePass() + { return !isset($this->_authupdate); } diff --git a/lib/WikiUser/EMailConfirm.php b/lib/WikiUser/EMailConfirm.php index 84da1e3f4..4485fde8f 100644 --- a/lib/WikiUser/EMailConfirm.php +++ b/lib/WikiUser/EMailConfirm.php @@ -21,30 +21,32 @@ */ class _EMailConfirmPassUser -extends _PassUser -/** - * Unconfirmed users have ANON access, - * confirmed users are equal to passusers WIKIAUTH_USER. - * - * Users give their email at registration, phpwiki sends a link per email, - * user clicks on url link to verify, user is confirmed. - * - * Preferences are handled in _PassUser - */ + extends _PassUser + /** + * Unconfirmed users have ANON access, + * confirmed users are equal to passusers WIKIAUTH_USER. + * + * Users give their email at registration, phpwiki sends a link per email, + * user clicks on url link to verify, user is confirmed. + * + * Preferences are handled in _PassUser + */ { // This can only be called from _PassUser, because the parent class // sets the pref methods, before this class is initialized. - function _EMailConfirmPassUser($UserName='', $prefs=false, $file='') { + function _EMailConfirmPassUser($UserName = '', $prefs = false, $file = '') + { if (!$this->_prefs and isa($this, "_EMailPassUser")) { if ($prefs) $this->_prefs = $prefs; if (!isset($this->_prefs->_method)) - _PassUser::_PassUser($UserName); + _PassUser::_PassUser($UserName); } $this->_userid = $UserName; return $this; } - function userExists() { + function userExists() + { if (!$this->isValidName($this->_userid)) { return $this->_tryNextUser(); } diff --git a/lib/WikiUser/Facebook.php b/lib/WikiUser/Facebook.php index 5b78658e9..325770122 100644 --- a/lib/WikiUser/Facebook.php +++ b/lib/WikiUser/Facebook.php @@ -28,17 +28,19 @@ require_once 'lib/HttpClient.php'; class _FacebookPassUser -extends _PassUser { + extends _PassUser +{ /** * Preferences are handled in _PassUser */ - function checkPass($password) { + function checkPass($password) + { $userid = $this->_userid; if (!loadPhpExtension('openssl')) { trigger_error( sprintf(_("The PECL %s extension cannot be loaded."), "openssl") - . sprintf(_(" %s AUTH ignored."), 'Facebook'), - E_USER_WARNING); + . sprintf(_(" %s AUTH ignored."), 'Facebook'), + E_USER_WARNING); return $this->_tryNextUser(); } $web = new HttpClient("www.facebook.com", 80); @@ -50,21 +52,21 @@ extends _PassUser { if (!$firstlogin) { if (DEBUG & (_DEBUG_LOGIN | _DEBUG_VERBOSE)) trigger_error(sprintf(_("Facebook connect failed with %d %s"), - $web->status, $web->errormsg), - E_USER_WARNING); + $web->status, $web->errormsg), + E_USER_WARNING); } // Switch from http to https://login.facebook.com/login.php $web->port = 443; $web->host = 'login.facebook.com'; - if (!($retval = $web->post("/login.php", array('user'=>$userid, 'pass'=>$password)))) { + if (!($retval = $web->post("/login.php", array('user' => $userid, 'pass' => $password)))) { if (DEBUG & (_DEBUG_LOGIN | _DEBUG_VERBOSE)) trigger_error(sprintf(_("Facebook login failed with %d %s"), - $web->status, $web->errormsg), - E_USER_WARNING); + $web->status, $web->errormsg), + E_USER_WARNING); } $this->_authmethod = 'Facebook'; - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::checkPass => $retval", - E_USER_WARNING); + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::checkPass => $retval", + E_USER_WARNING); if ($retval) { $this->_level = WIKIAUTH_USER; } else { @@ -74,16 +76,17 @@ extends _PassUser { } // TODO: msearch facebook for the username - function userExists() { + function userExists() + { if (!loadPhpExtension('openssl')) { trigger_error( sprintf(_("The PECL %s extension cannot be loaded."), "openssl") - . sprintf(_(" %s AUTH ignored."), 'Facebook'), - E_USER_WARNING); + . sprintf(_(" %s AUTH ignored."), 'Facebook'), + E_USER_WARNING); return $this->_tryNextUser(); } if (DEBUG & _DEBUG_LOGIN) - trigger_error(get_class($this)."::userExists => true (dummy)", E_USER_WARNING); + trigger_error(get_class($this) . "::userExists => true (dummy)", E_USER_WARNING); return true; } } diff --git a/lib/WikiUser/File.php b/lib/WikiUser/File.php index b6db5b59f..c2e18f475 100644 --- a/lib/WikiUser/File.php +++ b/lib/WikiUser/File.php @@ -21,23 +21,24 @@ */ class _FilePassUser -extends _PassUser -/** - * Check users defined in a .htaccess style file - * username:crypt\n... - * - * Preferences are handled in _PassUser - */ + extends _PassUser + /** + * Check users defined in a .htaccess style file + * username:crypt\n... + * + * Preferences are handled in _PassUser + */ { var $_file, $_may_change; // This can only be called from _PassUser, because the parent class // sets the pref methods, before this class is initialized. - function _FilePassUser($UserName='', $prefs=false, $file='') { + function _FilePassUser($UserName = '', $prefs = false, $file = '') + { if (!$this->_prefs and isa($this, "_FilePassUser")) { if ($prefs) $this->_prefs = $prefs; if (!isset($this->_prefs->_method)) - _PassUser::_PassUser($UserName); + _PassUser::_PassUser($UserName); } $this->_userid = $UserName; // read the .htaccess style file. We use our own copy of the standard pear class. @@ -45,20 +46,22 @@ extends _PassUser if (empty($file) and defined('AUTH_USER_FILE')) $file = AUTH_USER_FILE; // same style as in main.php - include_once(dirname(__FILE__)."/../pear/File_Passwd.php"); + include_once(dirname(__FILE__) . "/../pear/File_Passwd.php"); // "__PHP_Incomplete_Class" if (!empty($file) or empty($this->_file) or !isa($this->_file, "File_Passwd")) - $this->_file = new File_Passwd($file, false, $file.'.lock'); + $this->_file = new File_Passwd($file, false, $file . '.lock'); else return false; return $this; } - function mayChangePass() { + function mayChangePass() + { return $this->_may_change; } - function userExists() { + function userExists() + { if (!$this->isValidName()) { return $this->_tryNextUser(); } @@ -69,9 +72,10 @@ extends _PassUser return $this->_tryNextUser(); } - function checkPass($submitted_password) { + function checkPass($submitted_password) + { if (!$this->isValidName()) { - trigger_error(_("Invalid username."),E_USER_WARNING); + trigger_error(_("Invalid username."), E_USER_WARNING); return $this->_tryNextPass($submitted_password); } if (!$this->_checkPassLength($submitted_password)) { @@ -89,13 +93,14 @@ extends _PassUser return $this->_tryNextPass($submitted_password); } - function storePass($submitted_password) { + function storePass($submitted_password) + { if (!$this->isValidName()) { return false; } if ($this->_may_change) { $this->_file = new File_Passwd($this->_file->filename, true, - $this->_file->filename.'.lock'); + $this->_file->filename . '.lock'); $result = $this->_file->modUser($this->_userid, $submitted_password); $this->_file->close(); $this->_file = new File_Passwd($this->_file->filename, false); diff --git a/lib/WikiUser/Forbidden.php b/lib/WikiUser/Forbidden.php index 4f9e9616b..2f3787f24 100644 --- a/lib/WikiUser/Forbidden.php +++ b/lib/WikiUser/Forbidden.php @@ -25,9 +25,10 @@ * That's why this class is empty, but must exist. */ class _ForbiddenPassUser -extends _ForbiddenUser + extends _ForbiddenUser { - function dummy() { + function dummy() + { return; } } diff --git a/lib/WikiUser/FusionForge.php b/lib/WikiUser/FusionForge.php index dd468f354..e31b6bd2a 100644 --- a/lib/WikiUser/FusionForge.php +++ b/lib/WikiUser/FusionForge.php @@ -23,14 +23,16 @@ /** Call the FusionForge functions to get the username * */ -class _FusionForgePassUser extends _PassUser { +class _FusionForgePassUser extends _PassUser +{ var $_is_external = 0; - function _FusionForgePassUser($UserName='',$prefs=false) { + function _FusionForgePassUser($UserName = '', $prefs = false) + { if ($prefs) $this->_prefs = $prefs; if (!isset($this->_prefs->_method)) - _PassUser::_PassUser($UserName); + _PassUser::_PassUser($UserName); if ($UserName) $this->_userid = $UserName; $this->_authmethod = 'FusionForge'; @@ -42,7 +44,8 @@ class _FusionForgePassUser extends _PassUser { return $GLOBALS['ForbiddenUser']; } - function userExists() { + function userExists() + { global $group_id; // Mapping (PhpWiki vs FusionForge) performed is: @@ -62,7 +65,7 @@ class _FusionForgePassUser extends _PassUser { return false; } - $member = false ; + $member = false; $user = session_get_user(); $perm =& $project->getPermission(); if (!$perm || !is_object($perm)) { @@ -87,13 +90,15 @@ class _FusionForgePassUser extends _PassUser { return false; } - function checkPass($submitted_password) { + function checkPass($submitted_password) + { return $this->userExists() ? ($this->isAdmin() ? WIKIAUTH_ADMIN : WIKIAUTH_USER) : WIKIAUTH_ANON; } - function mayChangePass() { + function mayChangePass() + { return false; } } diff --git a/lib/WikiUser/HttpAuth.php b/lib/WikiUser/HttpAuth.php index 28359dd61..700e586af 100644 --- a/lib/WikiUser/HttpAuth.php +++ b/lib/WikiUser/HttpAuth.php @@ -33,12 +33,13 @@ * header('Authorization: Basic '.base64_encode("$userid:$passwd")."\r\n"; */ class _HttpAuthPassUser -extends _PassUser + extends _PassUser { - function _HttpAuthPassUser($UserName='', $prefs=false) { + function _HttpAuthPassUser($UserName = '', $prefs = false) + { if ($prefs) $this->_prefs = $prefs; if (!isset($this->_prefs->_method)) - _PassUser::_PassUser($UserName); + _PassUser::_PassUser($UserName); if ($UserName) $this->_userid = $UserName; $this->_authmethod = 'HttpAuth'; @@ -53,11 +54,12 @@ extends _PassUser // FIXME! This doesn't work yet! // Allow httpauth by other method: Admin for now only - function _fake_auth($userid, $passwd) { - return false; + function _fake_auth($userid, $passwd) + { + return false; - header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"'); - header("Authorization: Basic ".base64_encode($userid.":".$passwd)); + header('WWW-Authenticate: Basic realm="' . WIKI_NAME . '"'); + header("Authorization: Basic " . base64_encode($userid . ":" . $passwd)); if (!isset($_SERVER)) $_SERVER =& $GLOBALS['HTTP_SERVER_VARS']; $GLOBALS['REMOTE_USER'] = $userid; @@ -66,14 +68,15 @@ extends _PassUser //$GLOBALS['request']->setStatus(200); } - function logout() { + function logout() + { if (!isset($_SERVER)) $_SERVER =& $GLOBALS['HTTP_SERVER_VARS']; // Maybe we should random the realm to really force a logout. // But the next login will fail. // better_srand(); $realm = microtime().rand(); // TODO: On AUTH_TYPE=NTLM this will fail. Only Basic supported so far. - header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"'); + header('WWW-Authenticate: Basic realm="' . WIKI_NAME . '"'); if (strstr(php_sapi_name(), 'apache')) header('HTTP/1.0 401 Unauthorized'); else @@ -83,7 +86,8 @@ extends _PassUser unset($_SERVER['PHP_AUTH_PW']); } - function _http_username() { + function _http_username() + { if (!isset($_SERVER)) $_SERVER =& $GLOBALS['HTTP_SERVER_VARS']; if (!empty($_SERVER['PHP_AUTH_USER'])) @@ -104,14 +108,15 @@ extends _PassUser } // force http auth authorization - function userExists() { + function userExists() + { if (!isset($_SERVER)) $_SERVER =& $GLOBALS['HTTP_SERVER_VARS']; $username = $this->_http_username(); if (strstr($username, "\\") and isset($_SERVER['AUTH_TYPE']) - and $_SERVER['AUTH_TYPE'] == 'NTLM') - { + and $_SERVER['AUTH_TYPE'] == 'NTLM' + ) { // allow domain\user, change userid to domain/user $username = str_ireplace("\\\\", "\\", $username); // php bug with _SERVER $username = str_ireplace("\\", SUBPAGE_SEPARATOR, $username); @@ -119,11 +124,11 @@ extends _PassUser } // FIXME: if AUTH_TYPE = NTLM there's a domain\\name <> domain\name mismatch if (empty($username) - or strtolower($username) != strtolower($this->_userid)) - { + or strtolower($username) != strtolower($this->_userid) + ) { $this->logout(); $user = $GLOBALS['ForbiddenUser']; - $user->_userid = $this->_userid = ""; + $user->_userid = $this->_userid = ""; $this->_level = WIKIAUTH_FORBIDDEN; return $user; //exit; @@ -138,13 +143,15 @@ extends _PassUser } // ignore password, this is checked by the webservers http auth. - function checkPass($submitted_password) { + function checkPass($submitted_password) + { return $this->userExists() ? ($this->isAdmin() ? WIKIAUTH_ADMIN : WIKIAUTH_USER) : WIKIAUTH_ANON; } - function mayChangePass() { + function mayChangePass() + { return false; } } diff --git a/lib/WikiUser/HttpAuthUpper.php b/lib/WikiUser/HttpAuthUpper.php index 6ede05f7c..3df0fd174 100644 --- a/lib/WikiUser/HttpAuthUpper.php +++ b/lib/WikiUser/HttpAuthUpper.php @@ -34,12 +34,13 @@ * header('Authorization: Basic '.base64_encode("$userid:$passwd")."\r\n"; */ class _HttpAuthUpperPassUser -extends _PassUser + extends _PassUser { - function _HttpAuthUpperPassUser($UserName='', $prefs=false) { + function _HttpAuthUpperPassUser($UserName = '', $prefs = false) + { if ($prefs) $this->_prefs = $prefs; if (!isset($this->_prefs->_method)) - _PassUser::_PassUser($UserName); + _PassUser::_PassUser($UserName); if ($UserName) $this->_userid = $UserName; $this->_authmethod = 'HttpAuthUpper'; @@ -55,11 +56,12 @@ extends _PassUser // FIXME! This doesn't work yet! // Allow httpauth by other method: Admin for now only - function _fake_auth($userid, $passwd) { - return false; + function _fake_auth($userid, $passwd) + { + return false; - header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"'); - header("Authorization: Basic ".base64_encode($userid.":".$passwd)); + header('WWW-Authenticate: Basic realm="' . WIKI_NAME . '"'); + header("Authorization: Basic " . base64_encode($userid . ":" . $passwd)); if (!isset($_SERVER)) $_SERVER =& $GLOBALS['HTTP_SERVER_VARS']; $GLOBALS['REMOTE_USER'] = $userid; @@ -68,14 +70,15 @@ extends _PassUser //$GLOBALS['request']->setStatus(200); } - function logout() { + function logout() + { if (!isset($_SERVER)) $_SERVER =& $GLOBALS['HTTP_SERVER_VARS']; // Maybe we should random the realm to really force a logout. // But the next login will fail. // better_srand(); $realm = microtime().rand(); // TODO: On AUTH_TYPE=NTLM this will fail. Only Basic supported so far. - header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"'); + header('WWW-Authenticate: Basic realm="' . WIKI_NAME . '"'); if (strstr(php_sapi_name(), 'apache')) header('HTTP/1.0 401 Unauthorized'); else @@ -85,7 +88,8 @@ extends _PassUser unset($_SERVER['PHP_AUTH_PW']); } - function _http_username() { + function _http_username() + { if (!isset($_SERVER)) $_SERVER =& $GLOBALS['HTTP_SERVER_VARS']; if (!empty($_SERVER['PHP_AUTH_USER'])) @@ -106,7 +110,8 @@ extends _PassUser } // special: force upcase username - function UserName() { + function UserName() + { if (!empty($this->_userid)) { $this->_userid = strtoupper($this->_userid); return strtoupper($this->_userid); @@ -114,14 +119,15 @@ extends _PassUser } // force http auth authorization - function userExists() { + function userExists() + { if (!isset($_SERVER)) $_SERVER =& $GLOBALS['HTTP_SERVER_VARS']; $username = strtoupper($this->_http_username()); if (strstr($username, "\\") and isset($_SERVER['AUTH_TYPE']) - and $_SERVER['AUTH_TYPE'] == 'NTLM') - { + and $_SERVER['AUTH_TYPE'] == 'NTLM' + ) { // allow domain\user, change userid to domain/user $username = str_ireplace("\\\\", "\\", $username); // php bug with _SERVER $username = str_ireplace("\\", SUBPAGE_SEPARATOR, $username); @@ -129,11 +135,11 @@ extends _PassUser } // FIXME: if AUTH_TYPE = NTLM there's a domain\\name <> domain\name mismatch if (empty($username) - or strtolower($username) != strtolower($this->_userid)) - { + or strtolower($username) != strtolower($this->_userid) + ) { $this->logout(); $user = $GLOBALS['ForbiddenUser']; - $user->_userid = $this->_userid = ""; + $user->_userid = $this->_userid = ""; $this->_level = WIKIAUTH_FORBIDDEN; return $user; //exit; @@ -148,13 +154,15 @@ extends _PassUser } // ignore password, this is checked by the webservers http auth. - function checkPass($submitted_password) { + function checkPass($submitted_password) + { return $this->userExists() ? ($this->isAdmin() ? WIKIAUTH_ADMIN : WIKIAUTH_USER) : WIKIAUTH_ANON; } - function mayChangePass() { + function mayChangePass() + { return false; } } diff --git a/lib/WikiUser/IMAP.php b/lib/WikiUser/IMAP.php index 3dcd93d50..03a82f704 100644 --- a/lib/WikiUser/IMAP.php +++ b/lib/WikiUser/IMAP.php @@ -21,57 +21,60 @@ */ class _IMAPPassUser -extends _PassUser -/** - * Define the var IMAP_AUTH_HOST in config/config.ini (with port probably) - * - * Preferences are handled in _PassUser - */ + extends _PassUser + /** + * Define the var IMAP_AUTH_HOST in config/config.ini (with port probably) + * + * Preferences are handled in _PassUser + */ { - function checkPass($submitted_password) { + function checkPass($submitted_password) + { if (!$this->isValidName()) { - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::checkPass => failed isValidName", E_USER_WARNING); - trigger_error(_("Invalid username."),E_USER_WARNING); + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::checkPass => failed isValidName", E_USER_WARNING); + trigger_error(_("Invalid username."), E_USER_WARNING); return $this->_tryNextPass($submitted_password); } if (!$this->_checkPassLength($submitted_password)) { - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::checkPass => failed checkPassLength", E_USER_WARNING); + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::checkPass => failed checkPassLength", E_USER_WARNING); return WIKIAUTH_FORBIDDEN; } $userid = $this->_userid; - $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}", - $userid, $submitted_password, OP_HALFOPEN ); + $mbox = @imap_open("{" . IMAP_AUTH_HOST . "}", + $userid, $submitted_password, OP_HALFOPEN); if ($mbox) { imap_close($mbox); $this->_authmethod = 'IMAP'; - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::checkPass => ok", E_USER_WARNING); + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::checkPass => ok", E_USER_WARNING); $this->_level = WIKIAUTH_USER; return $this->_level; } else { if ($submitted_password != "") { // if LENGTH 0 is allowed - trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, - E_USER_WARNING); + trigger_error(_("Unable to connect to IMAP server ") . IMAP_AUTH_HOST, + E_USER_WARNING); } } - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::checkPass => wrong", E_USER_WARNING); + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::checkPass => wrong", E_USER_WARNING); return $this->_tryNextPass($submitted_password); } //CHECKME: this will not be okay for the auth policy strict - function userExists() { + function userExists() + { return true; if ($this->checkPass($this->_prefs->get('passwd'))) { - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::userExists => true (pass ok)", E_USER_WARNING); + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::userExists => true (pass ok)", E_USER_WARNING); return true; } - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::userExists => false (pass wrong)", E_USER_WARNING); + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::userExists => false (pass wrong)", E_USER_WARNING); return $this->_tryNextUser(); } - function mayChangePass() { - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::mayChangePass => false", E_USER_WARNING); + function mayChangePass() + { + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::mayChangePass => false", E_USER_WARNING); return false; } } diff --git a/lib/WikiUser/LDAP.php b/lib/WikiUser/LDAP.php index c5cecc391..12fdf9dbf 100644 --- a/lib/WikiUser/LDAP.php +++ b/lib/WikiUser/LDAP.php @@ -21,18 +21,19 @@ */ class _LDAPPassUser -extends _PassUser -/** - * Define the vars LDAP_AUTH_HOST and LDAP_BASE_DN in config/config.ini - * - * Preferences are handled in _PassUser - */ + extends _PassUser + /** + * Define the vars LDAP_AUTH_HOST and LDAP_BASE_DN in config/config.ini + * + * Preferences are handled in _PassUser + */ { /** * ->_init() * connect and bind to the LDAP host */ - function _init() { + function _init() + { if ($this->_ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server! global $LDAP_SET_OPTION; if (!empty($LDAP_SET_OPTION)) { @@ -53,8 +54,8 @@ extends _PassUser if (!$r) { $this->_free(); trigger_error(sprintf(_("Unable to bind LDAP server %s using %s %s"), - LDAP_AUTH_HOST, LDAP_AUTH_USER, LDAP_AUTH_PASSWORD), - E_USER_WARNING); + LDAP_AUTH_HOST, LDAP_AUTH_USER, LDAP_AUTH_PASSWORD), + E_USER_WARNING); return false; } return $this->_ldap; @@ -66,8 +67,9 @@ extends _PassUser /** * free and close the bound ressources */ - function _free() { - if (isset($this->_sr) and is_resource($this->_sr)) ldap_free_result($this->_sr); + function _free() + { + if (isset($this->_sr) and is_resource($this->_sr)) ldap_free_result($this->_sr); if (isset($this->_ldap) and is_resource($this->_ldap)) ldap_close($this->_ldap); unset($this->_sr); unset($this->_ldap); @@ -82,15 +84,16 @@ extends _PassUser * * @see http://www.faqs.org/rfcs/rfc4514.html LDAP String Representation of Distinguished Names */ - function _stringEscape($name) { + function _stringEscape($name) + { $name = strtr(utf8_encode($name), - array("*" => "\\2a", - "?" => "\\3f", - "(" => "\\28", - ")" => "\\29", - "\\" => "\\5c", - '"' => '\"', - "\0" => "\\00")); + array("*" => "\\2a", + "?" => "\\3f", + "(" => "\\28", + ")" => "\\29", + "\\" => "\\5c", + '"' => '\"', + "\0" => "\\00")); return $name; } @@ -98,7 +101,8 @@ extends _PassUser * LDAP names may contain every utf-8 character. However we restrict them a bit for convenience. * @see _stringEscape() */ - function isValidName ($userid = false) { + function isValidName($userid = false) + { if (!$userid) $userid = $this->_userid; // We are more restrictive here, but must allow explitly utf-8 return preg_match("/^[\-\w_\.@ ]+$/u", $userid) and strlen($userid) < 64; @@ -113,14 +117,15 @@ extends _PassUser * @return string The 3rd argument to ldap_search() * @see http://www.faqs.org/rfcs/rfc4514.html LDAP String Representation of Distinguished Names */ - function _searchparam($userid) { + function _searchparam($userid) + { $euserid = $this->_stringEscape($userid); // Need to set the right root search information. See config/config.ini if (LDAP_SEARCH_FILTER) { $st_search = str_replace("\$userid", $euserid, LDAP_SEARCH_FILTER); } else { $st_search = LDAP_SEARCH_FIELD - ? LDAP_SEARCH_FIELD."=$euserid" + ? LDAP_SEARCH_FIELD . "=$euserid" : "uid=$euserid"; } return $st_search; @@ -132,7 +137,8 @@ extends _PassUser * @see http://www.faqs.org/rfcs/rfc4514.html LDAP String Representation of Distinguished Names * @see http://www.faqs.org/rfcs/rfc3454.html stringprep */ - function checkPass($submitted_password) { + function checkPass($submitted_password) + { $this->_authmethod = 'LDAP'; $this->_userid = trim($this->_userid); @@ -164,14 +170,14 @@ extends _PassUser $st_search = $this->_searchparam($userid); if (!$this->_sr = ldap_search($ldap, LDAP_BASE_DN, $st_search)) { trigger_error(_("Could not search in LDAP"), E_USER_WARNING); - $this->_free(); + $this->_free(); return $this->_tryNextPass($submitted_password); } $info = ldap_get_entries($ldap, $this->_sr); if (empty($info["count"])) { if (DEBUG) trigger_error(_("User not found in LDAP"), E_USER_WARNING); - $this->_free(); + $this->_free(); return $this->_tryNextPass($submitted_password); } // There may be more hits with this userid. @@ -189,7 +195,7 @@ extends _PassUser if (!empty($info[$i]["mail"][0])) { $this->_prefs->_prefs['email']->default_value = $info[$i]["mail"][0]; } - $this->_free(); + $this->_free(); $this->_level = WIKIAUTH_USER; return $this->_level; } else { @@ -206,8 +212,8 @@ extends _PassUser } if (DEBUG) trigger_error(_("Wrong password: ") . - str_repeat("*", strlen($submitted_password)), - E_USER_WARNING); + str_repeat("*", strlen($submitted_password)), + E_USER_WARNING); $this->_free(); } else { $this->_free(); @@ -218,34 +224,36 @@ extends _PassUser } - function userExists() { + function userExists() + { $this->_userid = trim($this->_userid); $userid = $this->_userid; if (strstr($userid, '*')) { trigger_error(fmt("Invalid username '%s' for LDAP Auth", $userid), - E_USER_WARNING); + E_USER_WARNING); return false; } if ($ldap = $this->_init()) { // Need to set the right root search information. see ../index.php $st_search = $this->_searchparam($userid); if (!$this->_sr = ldap_search($ldap, LDAP_BASE_DN, $st_search)) { - $this->_free(); + $this->_free(); return $this->_tryNextUser(); } $info = ldap_get_entries($ldap, $this->_sr); if ($info["count"] > 0) { - $this->_free(); + $this->_free(); UpgradeUser($GLOBALS['ForbiddenUser'], $this); return true; } } - $this->_free(); + $this->_free(); return $this->_tryNextUser(); } - function mayChangePass() { + function mayChangePass() + { return false; } diff --git a/lib/WikiUser/LdapUpper.php b/lib/WikiUser/LdapUpper.php index 533a747e7..092a9d2bc 100644 --- a/lib/WikiUser/LdapUpper.php +++ b/lib/WikiUser/LdapUpper.php @@ -28,14 +28,16 @@ include_once 'lib/WikiUser/LDAP.php'; * Preferences are handled in _PassUser */ class _LdapUpperPassUser -extends _LDAPPassUser + extends _LDAPPassUser { - function checkPass($submitted_password) { + function checkPass($submitted_password) + { return parent::checkPass($submitted_password); } - function UserName() { + function UserName() + { if (!empty($this->_userid)) { $this->_userid = trim(strtoupper($this->_userid)); if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) @@ -44,7 +46,8 @@ extends _LDAPPassUser } } - function userExists() { + function userExists() + { // lowercase check and uppercase visibility $this->_userid = trim(strtoupper($this->_userid)); return parent::userExists(); diff --git a/lib/WikiUser/OpenID.php b/lib/WikiUser/OpenID.php index 1dbd0d133..bec996b62 100644 --- a/lib/WikiUser/OpenID.php +++ b/lib/WikiUser/OpenID.php @@ -30,10 +30,10 @@ require_once 'lib/HttpClient.php'; class _OpenIDPassUser -extends _PassUser -/** - * Preferences are handled in _PassUser - */ + extends _PassUser + /** + * Preferences are handled in _PassUser + */ { /** * Verifies authentication response from OpenID server. @@ -48,16 +48,18 @@ extends _PassUser * @param mixed $extensions extension object or array of extensions objects * @return bool */ - function verify($params, &$identity = "", $extensions = null) { + function verify($params, &$identity = "", $extensions = null) + { $version = 1.1; $this->_setError(""); if (isset($params['openid_ns']) && - $params['openid_ns'] == $NS_2_0) { // global session var + $params['openid_ns'] == $NS_2_0 + ) { // global session var $version = 2.0; } if (isset($params["openid_claimed_id"])) { $identity = $params["openid_claimed_id"]; - } elseif (isset($params["openid_identity"])){ + } elseif (isset($params["openid_identity"])) { $identity = $params["openid_identity"]; } else { $identity = ""; @@ -90,7 +92,7 @@ extends _PassUser return false; } if ($params['openid_mode'] != 'id_res') { - $this->_setError("Wrong openid.mode '".$params['openid_mode']."' != 'id_res'"); + $this->_setError("Wrong openid.mode '" . $params['openid_mode'] . "' != 'id_res'"); return false; } if (empty($params['openid_assoc_handle'])) { @@ -115,8 +117,9 @@ extends _PassUser * object to perform HTTP or HTML form redirection * @return bool */ - function _checkId($immediate, $id, $returnTo=null, $root=null, - $extensions=null, $response = null) { + function _checkId($immediate, $id, $returnTo = null, $root = null, + $extensions = null, $response = null) + { $this->_setError(''); /*if (!Zend_OpenId::normalize($id)) { @@ -134,11 +137,12 @@ extends _PassUser return false; } if (!$this->_getAssociation( - $server, - $handle, - $macFunc, - $secret, - $expires)) { + $server, + $handle, + $macFunc, + $secret, + $expires) + ) { /* Use dumb mode */ unset($handle); unset($macFunc); @@ -177,7 +181,7 @@ extends _PassUser if (empty($root)) { //$root = Zend_OpenId::selfUrl(); - if ($root[strlen($root)-1] != '/') { + if ($root[strlen($root) - 1] != '/') { $root = dirname($root); } } @@ -197,24 +201,26 @@ extends _PassUser return true; } - function _setError($message) { + function _setError($message) + { $this->_error = $message; } - function checkPass($password) { + function checkPass($password) + { $userid = $this->_userid; if (!loadPhpExtension('openssl')) { trigger_error( sprintf(_("The PECL %s extension cannot be loaded."), "openssl") - . sprintf(_(" %s AUTH ignored."), 'OpenID'), - E_USER_WARNING); + . sprintf(_(" %s AUTH ignored."), 'OpenID'), + E_USER_WARNING); return $this->_tryNextUser(); } $retval = $this->_checkId(false, $id, $returnTo, $root, $extensions, $response); $this->_authmethod = 'OpenID'; - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::checkPass => $retval", - E_USER_WARNING); + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::checkPass => $retval", + E_USER_WARNING); if ($retval) { $this->_level = WIKIAUTH_USER; } else { @@ -224,24 +230,26 @@ extends _PassUser } /* do nothing. the login/redirect is done in checkPass */ - function userExists() { + function userExists() + { if (!$this->isValidName($this->_userid)) { return $this->_tryNextUser(); } if (!loadPhpExtension('openssl')) { trigger_error - (sprintf(_("The PECL %s extension cannot be loaded."), "openssl") - . sprintf(_(" %s AUTH ignored."), 'OpenID'), - E_USER_WARNING); + (sprintf(_("The PECL %s extension cannot be loaded."), "openssl") + . sprintf(_(" %s AUTH ignored."), 'OpenID'), + E_USER_WARNING); return $this->_tryNextUser(); } if (DEBUG & _DEBUG_LOGIN) - trigger_error(get_class($this)."::userExists => true (dummy)", E_USER_WARNING); + trigger_error(get_class($this) . "::userExists => true (dummy)", E_USER_WARNING); return true; } // no quotes and shorter than 128 - function isValidName() { + function isValidName() + { if (!$this->_userid) return false; return !preg_match('/[\"\']/', $this->_userid) and strlen($this->_userid) < 128; } diff --git a/lib/WikiUser/POP3.php b/lib/WikiUser/POP3.php index 39b7a36ca..20f06c87d 100644 --- a/lib/WikiUser/POP3.php +++ b/lib/WikiUser/POP3.php @@ -23,19 +23,21 @@ require_once 'lib/WikiUser/IMAP.php'; class _POP3PassUser -extends _IMAPPassUser { -/** - * Define the var POP3_AUTH_HOST in config/config.ini - * Preferences are handled in _PassUser - */ - function checkPass($submitted_password) { + extends _IMAPPassUser +{ + /** + * Define the var POP3_AUTH_HOST in config/config.ini + * Preferences are handled in _PassUser + */ + function checkPass($submitted_password) + { if (!$this->isValidName()) { trigger_error(_("Invalid username."), E_USER_WARNING); - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::checkPass => failed isValidName", E_USER_WARNING); + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::checkPass => failed isValidName", E_USER_WARNING); return $this->_tryNextPass($submitted_password); } if (!$this->_checkPassLength($submitted_password)) { - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::checkPass => failed checkPassLength", E_USER_WARNING); + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::checkPass => failed checkPassLength", E_USER_WARNING); return WIKIAUTH_FORBIDDEN; } $userid = $this->_userid; @@ -43,8 +45,8 @@ extends _IMAPPassUser { $host = defined('POP3_AUTH_HOST') ? POP3_AUTH_HOST : 'localhost:110'; if (defined('POP3_AUTH_PORT')) $port = POP3_AUTH_PORT; - elseif (strstr($host,':')) { - list(,$port) = explode(':', $host); + elseif (strstr($host, ':')) { + list(, $port) = explode(':', $host); } else { $port = 110; } @@ -53,17 +55,17 @@ extends _IMAPPassUser { if ($fp) { // Get welcome string $line = fgets($fp, 1024); - if (! strncmp("+OK", $line, 3)) { + if (!strncmp("+OK", $line, 3)) { // Send user name fputs($fp, "user $userid\n"); // Get response $line = fgets($fp, 1024); - if (! strncmp("+OK", $line, 3)) { + if (!strncmp("+OK", $line, 3)) { // Send password fputs($fp, "pass $pass\n"); // Get response $line = fgets($fp, 1024); - if (! strncmp("+OK", $line, 3)) { + if (!strncmp("+OK", $line, 3)) { $retval = true; } } @@ -74,11 +76,11 @@ extends _IMAPPassUser { $line = fgets($fp, 1024); fclose($fp); } else { - trigger_error(_("Couldn't connect to %s","POP3_AUTH_HOST ".$host.':'.$port), - E_USER_WARNING); + trigger_error(_("Couldn't connect to %s", "POP3_AUTH_HOST " . $host . ':' . $port), + E_USER_WARNING); } $this->_authmethod = 'POP3'; - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::checkPass => $retval", E_USER_WARNING); + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::checkPass => $retval", E_USER_WARNING); if ($retval) { $this->_level = WIKIAUTH_USER; } else { @@ -87,8 +89,9 @@ extends _IMAPPassUser { return $this->_level; } - function __userExists() { - if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this)."::userExists => true (dummy)", E_USER_WARNING); + function __userExists() + { + if (DEBUG & _DEBUG_LOGIN) trigger_error(get_class($this) . "::userExists => true (dummy)", E_USER_WARNING); return true; } } diff --git a/lib/WikiUser/PdoDb.php b/lib/WikiUser/PdoDb.php index 2bdeaa4e3..5a547ce04 100644 --- a/lib/WikiUser/PdoDb.php +++ b/lib/WikiUser/PdoDb.php @@ -23,21 +23,22 @@ include_once 'lib/WikiUser/Db.php'; class _PdoDbPassUser -extends _DbPassUser -/** - * PDO DB methods (PHP5) - * prepare, bind, execute. - * We use numrical FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements. - * - * @tables: user - * @tables: pref - */ + extends _DbPassUser + /** + * PDO DB methods (PHP5) + * prepare, bind, execute. + * We use numrical FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements. + * + * @tables: user + * @tables: pref + */ { var $_authmethod = 'PDODb'; - function _PdoDbPassUser($UserName='', $prefs=false) { + function _PdoDbPassUser($UserName = '', $prefs = false) + { - if (!$this->_prefs and isa($this,"_PdoDbPassUser")) { + if (!$this->_prefs and isa($this, "_PdoDbPassUser")) { if ($prefs) $this->_prefs = $prefs; } if (!isset($this->_prefs->_method)) @@ -53,7 +54,8 @@ extends _DbPassUser return $this; } - function getPreferences() { + function getPreferences() + { // override the generic slow method here for efficiency and not to // clutter the homepage metadata with prefs. _AnonUser::getPreferences(); @@ -72,7 +74,8 @@ extends _DbPassUser } if ($this->_HomePagehandle) { if ($restored_from_page = $this->_prefs->retrieve - ($this->_HomePagehandle->get('pref'))) { + ($this->_HomePagehandle->get('pref')) + ) { $updated = $this->_prefs->updatePrefs($restored_from_page); //$this->_prefs = new UserPreferences($restored_from_page); return $this->_prefs; @@ -81,7 +84,8 @@ extends _DbPassUser return $this->_prefs; } - function setPreferences($prefs, $id_only=false) { + function setPreferences($prefs, $id_only = false) + { // if the prefs are changed if ($count = _AnonUser::setPreferences($prefs, 1)) { $this->getAuthDbh(); @@ -91,11 +95,10 @@ extends _DbPassUser try { $sth = $dbh->prepare($this->_prefs->_update); $sth->bindParam("prefs", $packed); - $sth->bindParam("user", $this->_userid); + $sth->bindParam("user", $this->_userid); $sth->execute(); - } - catch (PDOException $e) { - trigger_error("SQL Error: ".$e->getMessage(), E_USER_WARNING); + } catch (PDOException $e) { + trigger_error("SQL Error: " . $e->getMessage(), E_USER_WARNING); return false; } //delete pageprefs: @@ -111,46 +114,44 @@ extends _DbPassUser return 0; } - function userExists() { + function userExists() + { $this->getAuthDbh(); $dbh = &$this->_auth_dbi; if (!$dbh) { // needed? return $this->_tryNextUser(); } if (!$this->isValidName()) { - trigger_error(_("Invalid username."),E_USER_WARNING); + trigger_error(_("Invalid username."), E_USER_WARNING); return $this->_tryNextUser(); } $dbi =& $GLOBALS['request']->_dbi; if ($dbi->getAuthParam('auth_check') and empty($this->_authselect)) { try { $this->_authselect = $dbh->prepare($dbi->getAuthParam('auth_check')); - } - catch (PDOException $e) { - trigger_error("SQL Error: ".$e->getMessage(), E_USER_WARNING); + } catch (PDOException $e) { + trigger_error("SQL Error: " . $e->getMessage(), E_USER_WARNING); return false; } } //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed - if ( !$dbi->getAuthParam('auth_user_exists') - and $this->_auth_crypt_method == 'crypt' - and $this->_authselect) - { + if (!$dbi->getAuthParam('auth_user_exists') + and $this->_auth_crypt_method == 'crypt' + and $this->_authselect + ) { try { - $this->_authselect->bindParam("userid", $this->_userid, PDO_PARAM_STR, 48); + $this->_authselect->bindParam("userid", $this->_userid, PDO_PARAM_STR, 48); $this->_authselect->execute(); - } - catch (PDOException $e) { - trigger_error("SQL Error: ".$e->getMessage(), E_USER_WARNING); + } catch (PDOException $e) { + trigger_error("SQL Error: " . $e->getMessage(), E_USER_WARNING); return false; } if ($this->_authselect->fetchSingle()) return true; - } - else { - if (! $dbi->getAuthParam('auth_user_exists')) + } else { + if (!$dbi->getAuthParam('auth_user_exists')) trigger_error(fmt("%s is missing", 'DBAUTH_AUTH_USER_EXISTS'), - E_USER_WARNING); + E_USER_WARNING); $this->_authcheck = $dbh->prepare($dbi->getAuthParam('auth_check')); $this->_authcheck->bindParam("userid", $this->_userid, PDO_PARAM_STR, 48); $this->_authcheck->execute(); @@ -164,24 +165,22 @@ extends _DbPassUser if (empty($this->_authcreate) and $dbi->getAuthParam('auth_create')) { try { $this->_authcreate = $dbh->prepare($dbi->getAuthParam('auth_create')); - } - catch (PDOException $e) { - trigger_error("SQL Error: ".$e->getMessage(), E_USER_WARNING); + } catch (PDOException $e) { + trigger_error("SQL Error: " . $e->getMessage(), E_USER_WARNING); return false; } } if (!empty($this->_authcreate) and isset($GLOBALS['HTTP_POST_VARS']['auth']) and - isset($GLOBALS['HTTP_POST_VARS']['auth']['passwd'])) - { + isset($GLOBALS['HTTP_POST_VARS']['auth']['passwd']) + ) { $passwd = $GLOBALS['HTTP_POST_VARS']['auth']['passwd']; try { $this->_authcreate->bindParam("userid", $this->_userid, PDO_PARAM_STR, 48); $this->_authcreate->bindParam("password", $passwd, PDO_PARAM_STR, 48); $rs = $this->_authselect->execute(); - } - catch (PDOException $e) { - trigger_error("SQL Error: ".$e->getMessage(), E_USER_WARNING); + } catch (PDOException $e) { + trigger_error("SQL Error: " . $e->getMessage(), E_USER_WARNING); return false; } if ($rs) @@ -190,10 +189,11 @@ extends _DbPassUser return $this->_tryNextUser(); } - function checkPass($submitted_password) { + function checkPass($submitted_password) + { //global $DBAuthParams; $this->getAuthDbh(); - if (!$this->_auth_dbi) { // needed? + if (!$this->_auth_dbi) { // needed? return $this->_tryNextPass($submitted_password); } if (!$this->isValidName()) { @@ -206,8 +206,8 @@ extends _DbPassUser $this->userExists(); if (!isset($this->_authselect)) trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'", - 'DBAUTH_AUTH_CHECK', 'SQL'), - E_USER_WARNING); + 'DBAUTH_AUTH_CHECK', 'SQL'), + E_USER_WARNING); //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set $dbh = &$this->_auth_dbi; @@ -216,9 +216,8 @@ extends _DbPassUser $this->_authselect->bindParam("userid", $this->_userid, PDO_PARAM_STR, 48); $this->_authselect->execute(); $rs = $this->_authselect->fetch(PDO_FETCH_BOTH); - } - catch (PDOException $e) { - trigger_error("SQL Error: ".$e->getMessage(), E_USER_WARNING); + } catch (PDOException $e) { + trigger_error("SQL Error: " . $e->getMessage(), E_USER_WARNING); return false; } $stored_password = @$rs[0]; @@ -229,9 +228,8 @@ extends _DbPassUser $this->_authselect->bindParam("userid", $this->_userid, PDO_PARAM_STR, 48); $this->_authselect->execute(); $rs = $this->_authselect->fetch(PDO_FETCH_BOTH); - } - catch (PDOException $e) { - trigger_error("SQL Error: ".$e->getMessage(), E_USER_WARNING); + } catch (PDOException $e) { + trigger_error("SQL Error: " . $e->getMessage(), E_USER_WARNING); return false; } $okay = @$rs[0]; @@ -249,11 +247,13 @@ extends _DbPassUser } } - function mayChangePass() { + function mayChangePass() + { return $GLOBALS['request']->_dbi->getAuthParam('auth_update'); } - function storePass($submitted_password) { + function storePass($submitted_password) + { if (!$this->isValidName()) { return false; } @@ -263,16 +263,15 @@ extends _DbPassUser if ($dbi->getAuthParam('auth_update') and empty($this->_authupdate)) { try { $this->_authupdate = $dbh->prepare($dbi->getAuthParam('auth_update')); - } - catch (PDOException $e) { - trigger_error("SQL Error: ".$e->getMessage(), E_USER_WARNING); + } catch (PDOException $e) { + trigger_error("SQL Error: " . $e->getMessage(), E_USER_WARNING); return false; } } if (empty($this->_authupdate)) { trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'", - 'DBAUTH_AUTH_UPDATE','SQL'), - E_USER_WARNING); + 'DBAUTH_AUTH_UPDATE', 'SQL'), + E_USER_WARNING); return false; } @@ -284,9 +283,8 @@ extends _DbPassUser $this->_authupdate->bindParam("password", $submitted_password, PDO_PARAM_STR, 48); $this->_authupdate->bindParam("userid", $this->_userid, PDO_PARAM_STR, 48); $this->_authupdate->execute(); - } - catch (PDOException $e) { - trigger_error("SQL Error: ".$e->getMessage(), E_USER_WARNING); + } catch (PDOException $e) { + trigger_error("SQL Error: " . $e->getMessage(), E_USER_WARNING); return false; } return true; diff --git a/lib/WikiUser/PearDb.php b/lib/WikiUser/PearDb.php index 2a966b91a..be97b72dd 100644 --- a/lib/WikiUser/PearDb.php +++ b/lib/WikiUser/PearDb.php @@ -22,19 +22,21 @@ include_once 'lib/WikiUser/Db.php'; class _PearDbPassUser -extends _DbPassUser -/** - * Pear DB methods - * Now optimized not to use prepare, ...query(sprintf($sql,quote())) instead. - * We use FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements. - * - * @tables: pref - */ + extends _DbPassUser + /** + * Pear DB methods + * Now optimized not to use prepare, ...query(sprintf($sql,quote())) instead. + * We use FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements. + * + * @tables: pref + */ { var $_authmethod = 'PearDb'; - function _PearDbPassUser($UserName='',$prefs=false) { + + function _PearDbPassUser($UserName = '', $prefs = false) + { //global $DBAuthParams; - if (!$this->_prefs and isa($this,"_PearDbPassUser")) { + if (!$this->_prefs and isa($this, "_PearDbPassUser")) { if ($prefs) $this->_prefs = $prefs; } if (!isset($this->_prefs->_method)) @@ -50,7 +52,8 @@ extends _DbPassUser return $this; } - function getPreferences() { + function getPreferences() + { // override the generic slow method here for efficiency and not to // clutter the homepage metadata with prefs. _AnonUser::getPreferences(); @@ -69,7 +72,8 @@ extends _DbPassUser } if (isset($this->_HomePagehandle) && $this->_HomePagehandle) { if ($restored_from_page = $this->_prefs->retrieve - ($this->_HomePagehandle->get('pref'))) { + ($this->_HomePagehandle->get('pref')) + ) { $updated = $this->_prefs->updatePrefs($restored_from_page); //$this->_prefs = new UserPreferences($restored_from_page); return $this->_prefs; @@ -78,7 +82,8 @@ extends _DbPassUser return $this->_prefs; } - function setPreferences($prefs, $id_only=false) { + function setPreferences($prefs, $id_only = false) + { // if the prefs are changed if ($count = _AnonUser::setPreferences($prefs, 1)) { //global $request; @@ -92,22 +97,22 @@ extends _DbPassUser $dbh = &$this->_auth_dbi; // check if the user already exists (not needed with mysql REPLACE) $db_result = $dbh->query(sprintf($this->_prefs->_select, - $dbh->quote($this->_userid))); + $dbh->quote($this->_userid))); $prefs = $db_result->fetchRow(); $prefs_blob = @$prefs["prefs"]; // If there are prefs for the user, update them. - if($prefs_blob != "" ){ + if ($prefs_blob != "") { $dbh->simpleQuery(sprintf($this->_prefs->_update, - $dbh->quote($packed), - $dbh->quote($this->_userid))); + $dbh->quote($packed), + $dbh->quote($this->_userid))); } else { // Otherwise, insert a record for them and set it to the defaults. // johst@deakin.edu.au $dbi = $GLOBALS['request']->getDbh(); $this->_prefs->_insert = $this->prepare($dbi->getAuthParam('pref_insert'), - array("pref_blob", "userid")); + array("pref_blob", "userid")); $dbh->simpleQuery(sprintf($this->_prefs->_insert, - $dbh->quote($packed), $dbh->quote($this->_userid))); + $dbh->quote($packed), $dbh->quote($this->_userid))); } //delete pageprefs: if (isset($this->_HomePagehandle) && $this->_HomePagehandle and $this->_HomePagehandle->get('pref')) @@ -122,7 +127,8 @@ extends _DbPassUser return 0; } - function userExists() { + function userExists() + { //global $DBAuthParams; $this->getAuthDbh(); $dbh = &$this->_auth_dbi; @@ -130,28 +136,27 @@ extends _DbPassUser return $this->_tryNextUser(); } if (!$this->isValidName()) { - trigger_error(_("Invalid username."),E_USER_WARNING); + trigger_error(_("Invalid username."), E_USER_WARNING); return $this->_tryNextUser(); } $dbi =& $GLOBALS['request']->_dbi; // Prepare the configured auth statements if ($dbi->getAuthParam('auth_check') and empty($this->_authselect)) { $this->_authselect = $this->prepare($dbi->getAuthParam('auth_check'), - array("password", "userid")); + array("password", "userid")); } //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed if (!$dbi->getAuthParam('auth_user_exists') and $this->_auth_crypt_method == 'crypt' - and $this->_authselect) - { + and $this->_authselect + ) { $rs = $dbh->query(sprintf($this->_authselect, $dbh->quote($this->_userid))); if ($rs->numRows()) return true; - } - else { - if (! $dbi->getAuthParam('auth_user_exists')) + } else { + if (!$dbi->getAuthParam('auth_user_exists')) trigger_error(fmt("%s is missing", 'DBAUTH_AUTH_USER_EXISTS'), - E_USER_WARNING); + E_USER_WARNING); $this->_authcheck = $this->prepare($dbi->getAuthParam('auth_user_exists'), "userid"); $rs = $dbh->query(sprintf($this->_authcheck, $dbh->quote($this->_userid))); if ($rs->numRows()) @@ -163,25 +168,26 @@ extends _DbPassUser // reasons if (empty($this->_authcreate) and $dbi->getAuthParam('auth_create')) { $this->_authcreate = $this->prepare($dbi->getAuthParam('auth_create'), - array("password", "userid")); + array("password", "userid")); } if (!empty($this->_authcreate) and isset($GLOBALS['HTTP_POST_VARS']['auth']) and - isset($GLOBALS['HTTP_POST_VARS']['auth']['passwd'])) - { + isset($GLOBALS['HTTP_POST_VARS']['auth']['passwd']) + ) { $passwd = $GLOBALS['HTTP_POST_VARS']['auth']['passwd']; $dbh->simpleQuery(sprintf($this->_authcreate, - $dbh->quote($passwd), - $dbh->quote($this->_userid))); + $dbh->quote($passwd), + $dbh->quote($this->_userid))); return true; } return $this->_tryNextUser(); } - function checkPass($submitted_password) { + function checkPass($submitted_password) + { //global $DBAuthParams; $this->getAuthDbh(); - if (!$this->_auth_dbi) { // needed? + if (!$this->_auth_dbi) { // needed? return $this->_tryNextPass($submitted_password); } if (!$this->isValidName()) { @@ -194,8 +200,8 @@ extends _DbPassUser $this->userExists(); if (!isset($this->_authselect)) trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'", - 'DBAUTH_AUTH_CHECK', 'SQL'), - E_USER_WARNING); + 'DBAUTH_AUTH_CHECK', 'SQL'), + E_USER_WARNING); //NOTE: for auth_crypt_method='crypt' defined('ENCRYPTED_PASSWD',true) must be set $dbh = &$this->_auth_dbi; @@ -205,8 +211,8 @@ extends _DbPassUser } else { // be position independent $okay = $dbh->getOne(sprintf($this->_authselect, - $dbh->quote($submitted_password), - $dbh->quote($this->_userid))); + $dbh->quote($submitted_password), + $dbh->quote($this->_userid))); $result = !empty($okay); } @@ -221,11 +227,13 @@ extends _DbPassUser } } - function mayChangePass() { + function mayChangePass() + { return $GLOBALS['request']->_dbi->getAuthParam('auth_update'); } - function storePass($submitted_password) { + function storePass($submitted_password) + { if (!$this->isValidName()) { return false; } @@ -234,12 +242,12 @@ extends _DbPassUser $dbi =& $GLOBALS['request']->_dbi; if ($dbi->getAuthParam('auth_update') and empty($this->_authupdate)) { $this->_authupdate = $this->prepare($dbi->getAuthParam('auth_update'), - array("password", "userid")); + array("password", "userid")); } if (empty($this->_authupdate)) { trigger_error(fmt("Either %s is missing or DATABASE_TYPE != '%s'", - 'DBAUTH_AUTH_UPDATE','SQL'), - E_USER_WARNING); + 'DBAUTH_AUTH_UPDATE', 'SQL'), + E_USER_WARNING); return false; } @@ -248,7 +256,7 @@ extends _DbPassUser $submitted_password = crypt($submitted_password); } $dbh->simpleQuery(sprintf($this->_authupdate, - $dbh->quote($submitted_password), $dbh->quote($this->_userid))); + $dbh->quote($submitted_password), $dbh->quote($this->_userid))); return true; } } diff --git a/lib/WikiUser/PersonalPage.php b/lib/WikiUser/PersonalPage.php index 73938f49f..793cedd11 100644 --- a/lib/WikiUser/PersonalPage.php +++ b/lib/WikiUser/PersonalPage.php @@ -25,20 +25,22 @@ * It inherits almost all all methods from _PassUser. */ class _PersonalPagePassUser -extends _PassUser + extends _PassUser { var $_authmethod = 'PersonalPage'; /* Very loose checking, since we properly quote the PageName. Just trim spaces, ... See lib/stdlib.php */ - function isValidName ($userid = false) { + function isValidName($userid = false) + { if (!$userid) $userid = $this->_userid; $WikiPageName = new WikiPageName($userid); return $WikiPageName->isValid() and ($userid === $WikiPageName->name); } - function userExists() { + function userExists() + { return $this->_HomePagehandle and $this->_HomePagehandle->exists(); } @@ -46,28 +48,29 @@ extends _PassUser * BUT if the user already has a homepage with an empty password * stored, allow login but warn him to change it. */ - function checkPass($submitted_password) { + function checkPass($submitted_password) + { if ($this->userExists()) { $stored_password = $this->_prefs->get('passwd'); if (empty($stored_password)) { - if (PASSWORD_LENGTH_MINIMUM > 0) { - trigger_error(sprintf( - _("PersonalPage login method:")."\n". - _("You stored an empty password in your '%s' page.")."\n". - _("Your access permissions are only for a BogoUser.")."\n". - _("Please set a password in UserPreferences."), - $this->_userid), E_USER_WARNING); - $this->_level = WIKIAUTH_BOGO; - } else { - if (!empty($submitted_password)) + if (PASSWORD_LENGTH_MINIMUM > 0) { trigger_error(sprintf( - _("PersonalPage login method:")."\n". - _("You stored an empty password in your '%s' page.")."\n". - _("Given password ignored.")."\n". - _("Please set a password in UserPreferences."), - $this->_userid), E_USER_WARNING); - $this->_level = WIKIAUTH_USER; - } + _("PersonalPage login method:") . "\n" . + _("You stored an empty password in your '%s' page.") . "\n" . + _("Your access permissions are only for a BogoUser.") . "\n" . + _("Please set a password in UserPreferences."), + $this->_userid), E_USER_WARNING); + $this->_level = WIKIAUTH_BOGO; + } else { + if (!empty($submitted_password)) + trigger_error(sprintf( + _("PersonalPage login method:") . "\n" . + _("You stored an empty password in your '%s' page.") . "\n" . + _("Given password ignored.") . "\n" . + _("Please set a password in UserPreferences."), + $this->_userid), E_USER_WARNING); + $this->_level = WIKIAUTH_USER; + } return $this->_level; } if ($this->_checkPass($submitted_password, $stored_password)) diff --git a/lib/WikiUser/Session.php b/lib/WikiUser/Session.php index 71757f14e..7d93a75a8 100644 --- a/lib/WikiUser/Session.php +++ b/lib/WikiUser/Session.php @@ -28,9 +28,10 @@ * define('AUTH_SESS_LEVEL',2); */ class _SessionPassUser -extends _PassUser + extends _PassUser { - function _SessionPassUser($UserName='',$prefs=false) { + function _SessionPassUser($UserName = '', $prefs = false) + { if ($prefs) $this->_prefs = $prefs; if (!defined("AUTH_SESS_USER") or !defined("AUTH_SESS_LEVEL")) { trigger_error( @@ -40,33 +41,39 @@ extends _PassUser } $sess =& $GLOBALS['HTTP_SESSION_VARS']; // user hash: "[user][userid]" or object "user->id" - if (strstr(AUTH_SESS_USER,"][")) { + if (strstr(AUTH_SESS_USER, "][")) { $sess = $GLOBALS['HTTP_SESSION_VARS']; // recurse into hashes: "[user][userid]", sess = sess[user] => sess = sess[userid] foreach (explode("][", AUTH_SESS_USER) as $v) { - $v = str_replace(array("[","]"),'',$v); + $v = str_replace(array("[", "]"), '', $v); $sess = $sess[$v]; } $this->_userid = $sess; - } elseif (strstr(AUTH_SESS_USER,"->")) { + } elseif (strstr(AUTH_SESS_USER, "->")) { // object "user->id" (no objects inside hashes supported!) - list($obj,$key) = explode("->", AUTH_SESS_USER); + list($obj, $key) = explode("->", AUTH_SESS_USER); $this->_userid = $sess[$obj]->$key; } else { $this->_userid = $sess[AUTH_SESS_USER]; } if (!isset($this->_prefs->_method)) - _PassUser::_PassUser($this->_userid); + _PassUser::_PassUser($this->_userid); $this->_level = AUTH_SESS_LEVEL; $this->_authmethod = 'Session'; } - function userExists() { + + function userExists() + { return !empty($this->_userid); } - function checkPass($submitted_password) { + + function checkPass($submitted_password) + { return $this->userExists() and $this->_level > -1; } - function mayChangePass() { + + function mayChangePass() + { return false; } } diff --git a/lib/WikiUserNew.php b/lib/WikiUserNew.php index 21965b274..b6a33bf6b 100644 --- a/lib/WikiUserNew.php +++ b/lib/WikiUserNew.php @@ -99,24 +99,24 @@ */ define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed. -define('WIKIAUTH_ANON', 0); // Not signed in. -define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough. -define('WIKIAUTH_USER', 2); // Bogo user with a password. -define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER. -define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve +define('WIKIAUTH_ANON', 0); // Not signed in. +define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough. +define('WIKIAUTH_USER', 2); // Bogo user with a password. +define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER. +define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve //if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365); //if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/'); -if (!defined('EDITWIDTH_MIN_COLS')) define('EDITWIDTH_MIN_COLS', 30); -if (!defined('EDITWIDTH_MAX_COLS')) define('EDITWIDTH_MAX_COLS', 150); +if (!defined('EDITWIDTH_MIN_COLS')) define('EDITWIDTH_MIN_COLS', 30); +if (!defined('EDITWIDTH_MAX_COLS')) define('EDITWIDTH_MAX_COLS', 150); if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80); -if (!defined('EDITHEIGHT_MIN_ROWS')) define('EDITHEIGHT_MIN_ROWS', 5); -if (!defined('EDITHEIGHT_MAX_ROWS')) define('EDITHEIGHT_MAX_ROWS', 80); +if (!defined('EDITHEIGHT_MIN_ROWS')) define('EDITHEIGHT_MIN_ROWS', 5); +if (!defined('EDITHEIGHT_MAX_ROWS')) define('EDITHEIGHT_MAX_ROWS', 80); if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22); define('TIMEOFFSET_MIN_HOURS', -26); -define('TIMEOFFSET_MAX_HOURS', 26); +define('TIMEOFFSET_MAX_HOURS', 26); if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0); /* EMAIL VERIFICATION @@ -162,18 +162,24 @@ else $USER_AUTH_ORDER[] = "Forbidden"; // Local convenience functions. -function _isAnonUserAllowed() { +function _isAnonUserAllowed() +{ return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER); } -function _isBogoUserAllowed() { + +function _isBogoUserAllowed() +{ return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN); } -function _isUserPasswordsAllowed() { + +function _isUserPasswordsAllowed() +{ return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS); } // Possibly upgrade userobject functions. -function _determineAdminUserOrOtherUser($UserName) { +function _determineAdminUserOrOtherUser($UserName) +{ // Sanity check. User name is a condition of the definition of the // _AdminUser, _BogoUser and _passuser. if (!$UserName) @@ -191,7 +197,8 @@ function _determineAdminUserOrOtherUser($UserName) { return _determineBogoUserOrPassUser($UserName); } -function _determineBogoUserOrPassUser($UserName) { +function _determineBogoUserOrPassUser($UserName) +{ global $ForbiddenUser; // Sanity check. User name is a condition of the definition of @@ -210,21 +217,22 @@ function _determineBogoUserOrPassUser($UserName) { if (_isUserPasswordsAllowed()) { // PassUsers override BogoUsers if a password is stored if (isset($_BogoUser) and isset($_BogoUser->_prefs) - and $_BogoUser->_prefs->get('passwd')) + and $_BogoUser->_prefs->get('passwd') + ) return new _PassUser($UserName, $_BogoUser->_prefs); else { $_PassUser = new _PassUser($UserName, - isset($_BogoUser) ? $_BogoUser->_prefs : false); + isset($_BogoUser) ? $_BogoUser->_prefs : false); if ($_PassUser->userExists() or $GLOBALS['request']->getArg('auth')) { if (isset($GLOBALS['request']->_user_class)) - $class = $GLOBALS['request']->_user_class; + $class = $GLOBALS['request']->_user_class; elseif (strtolower(get_class($_PassUser)) == "_passuser") - $class = $_PassUser->nextClass(); - else - $class = get_class($_PassUser); - if ($user = new $class($UserName, $_PassUser->_prefs) - and $user->_userid) { - return $user; + $class = $_PassUser->nextClass(); else + $class = get_class($_PassUser); + if ($user = new $class($UserName, $_PassUser->_prefs) + and $user->_userid + ) { + return $user; } else { return $_PassUser; } @@ -251,7 +259,8 @@ function _determineBogoUserOrPassUser($UserName) { * is returned. (was previously false) * */ -function WikiUser ($UserName = '') { +function WikiUser($UserName = '') +{ global $ForbiddenUser, $HTTP_SESSION_VARS; //Maybe: Check sessionvar for username & save username into @@ -260,13 +269,11 @@ function WikiUser ($UserName = '') { $ForbiddenUser = new _ForbiddenUser($UserName); // Found a user name. return _determineAdminUserOrOtherUser($UserName); - } - elseif (!empty($HTTP_SESSION_VARS['userid'])) { + } elseif (!empty($HTTP_SESSION_VARS['userid'])) { // Found a user name. $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']); return _determineAdminUserOrOtherUser($_SESSION['userid']); - } - else { + } else { // Check for autologin pref in cookie and possibly upgrade // user object to another type. $_AnonUser = new _AnonUser(); @@ -274,14 +281,13 @@ function WikiUser ($UserName = '') { // Found a user name. $ForbiddenUser = new _ForbiddenUser($UserName); return _determineAdminUserOrOtherUser($UserName); - } - else { + } else { $ForbiddenUser = new _ForbiddenUser(); if (_isAnonUserAllowed()) return $_AnonUser; return $ForbiddenUser; // User must sign in to browse pages. } - return $ForbiddenUser; // User must sign in with a password. + return $ForbiddenUser; // User must sign in with a password. } /* trigger_error("DEBUG: Note: End of function reached in WikiUser." . " " @@ -293,7 +299,8 @@ function WikiUser ($UserName = '') { /** * WikiUser.php use the name 'WikiUser' */ -function WikiUserClassname() { +function WikiUserClassname() +{ return '_WikiUser'; } @@ -303,21 +310,24 @@ function WikiUserClassname() { * (on php4 it works ok, on php5 it's currently disallowed on the parser level) * that's why try it the hard way. */ -function UpgradeUser ($user, $newuser) { - if (isa($user,'_WikiUser') and isa($newuser,'_WikiUser')) { +function UpgradeUser($user, $newuser) +{ + if (isa($user, '_WikiUser') and isa($newuser, '_WikiUser')) { // populate the upgraded class $newuser with the values from the current user object //only _auth_level, _current_method, _current_index, if (!empty($user->_level) and - $user->_level > $newuser->_level) + $user->_level > $newuser->_level + ) $newuser->_level = $user->_level; if (!empty($user->_current_index) and - $user->_current_index > $newuser->_current_index) { + $user->_current_index > $newuser->_current_index + ) { $newuser->_current_index = $user->_current_index; $newuser->_current_method = $user->_current_method; } if (!empty($user->_authmethod)) $newuser->_authmethod = $user->_authmethod; - $GLOBALS['request']->_user_class = get_class($newuser); + $GLOBALS['request']->_user_class = get_class($newuser); /* foreach (get_object_vars($user) as $k => $v) { if (!empty($v)) $olduser->$k = $v; @@ -335,7 +345,8 @@ function UpgradeUser ($user, $newuser) { * Probably not needed, since we use the various user objects methods so far. * Anyway, here it is, looping through all available objects. */ -function UserExists ($UserName) { +function UserExists($UserName) +{ global $request; if (!($user = $request->getUser())) $user = WikiUser($UserName); @@ -345,8 +356,8 @@ function UserExists ($UserName) { $request->_user = $user; return true; } - if (isa($user,'_BogoUser')) - $user = new _PassUser($UserName,$user->_prefs); + if (isa($user, '_BogoUser')) + $user = new _PassUser($UserName, $user->_prefs); $class = $user->nextClass(); if ($user = new $class($UserName, $user->_prefs)) { return $user->userExists($UserName); @@ -362,13 +373,14 @@ function UserExists ($UserName) { */ class _WikiUser { - var $_userid = ''; - var $_level = WIKIAUTH_ANON; - var $_prefs = false; - var $_HomePagehandle = false; + var $_userid = ''; + var $_level = WIKIAUTH_ANON; + var $_prefs = false; + var $_HomePagehandle = false; // constructor - function _WikiUser($UserName='', $prefs=false) { + function _WikiUser($UserName = '', $prefs = false) + { $this->_userid = $UserName; $this->_HomePagehandle = false; @@ -381,43 +393,48 @@ class _WikiUser } } - function UserName() { + function UserName() + { if (!empty($this->_userid)) return $this->_userid; } - function getPreferences() { + function getPreferences() + { trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " " - . "New subclasses of _WikiUser must override this function."); + . "New subclasses of _WikiUser must override this function."); return false; } - function setPreferences($prefs, $id_only) { + function setPreferences($prefs, $id_only) + { trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." - . " " - . "New subclasses of _WikiUser must override this function."); + . " " + . "New subclasses of _WikiUser must override this function."); return false; } - function userExists() { + function userExists() + { return $this->hasHomePage(); } - function checkPass($submitted_password) { + function checkPass($submitted_password) + { // By definition, an undefined user class cannot sign in. trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." - . " " - . "New subclasses of _WikiUser must override this function."); + . " " + . "New subclasses of _WikiUser must override this function."); return false; } // returns page_handle to user's home page or false if none - function hasHomePage() { + function hasHomePage() + { if ($this->_userid) { if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) { return $this->_HomePagehandle->exists(); - } - else { + } else { // check db again (maybe someone else created it since // we logged in.) global $request; @@ -429,18 +446,20 @@ class _WikiUser return false; } - function createHomePage() { + function createHomePage() + { global $request; $versiondata = array('author' => ADMIN_USER); - $request->_dbi->save(_("Automatically created user homepage to be able to store UserPreferences."). - "\n{{Template/UserPage}}", - 1, $versiondata); + $request->_dbi->save(_("Automatically created user homepage to be able to store UserPreferences.") . + "\n{{Template/UserPage}}", + 1, $versiondata); $request->_dbi->touch(); $this->_HomePagehandle = $request->getPage($this->_userid); } // innocent helper: case-insensitive position in _auth_methods - function array_position ($string, $array) { + function array_position($string, $array) + { $string = strtolower($string); for ($found = 0; $found < count($array); $found++) { if (strtolower($array[$found]) == $string) @@ -449,14 +468,15 @@ class _WikiUser return false; } - function nextAuthMethodIndex() { + function nextAuthMethodIndex() + { if (empty($this->_auth_methods)) $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER']; if (empty($this->_current_index)) { if (strtolower(get_class($this)) != '_passuser') { - $this->_current_method = substr(get_class($this),1,-8); + $this->_current_method = substr(get_class($this), 1, -8); $this->_current_index = $this->array_position($this->_current_method, - $this->_auth_methods); + $this->_auth_methods); } else { $this->_current_index = -1; } @@ -468,22 +488,25 @@ class _WikiUser return $this->_current_index; } - function AuthMethod($index = false) { - return $this->_auth_methods[ $index === false - ? count($this->_auth_methods)-1 - : $index]; + function AuthMethod($index = false) + { + return $this->_auth_methods[$index === false + ? count($this->_auth_methods) - 1 + : $index]; } // upgrade the user object - function nextClass() { + function nextClass() + { $method = $this->AuthMethod($this->nextAuthMethodIndex()); include_once("lib/WikiUser/$method.php"); - return "_".$method."PassUser"; + return "_" . $method . "PassUser"; } //Fixme: for _HttpAuthPassUser - function PrintLoginForm (&$request, $args, $fail_message = false, - $seperate_page = false) { + function PrintLoginForm(&$request, $args, $fail_message = false, + $seperate_page = false) + { include_once 'lib/Template.php'; // Call update_locale in case the system's default language is not 'en'. // (We have no user pref for lang at this point yet, no one is logged in.) @@ -498,14 +521,14 @@ class _WikiUser $pagename = $request->getArg('pagename'); $nocache = 1; $login = Template('login', - compact('pagename', 'userid', 'require_level', - 'fail_message', 'pass_required', 'nocache')); + compact('pagename', 'userid', 'require_level', + 'fail_message', 'pass_required', 'nocache')); // check if the html template was already processed $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html'); if ($seperate_page) { $page = $request->getPage($pagename); $revision = $page->getCurrentRevision(); - return GeneratePage($login,_("Sign In"), $revision); + return GeneratePage($login, _("Sign In"), $revision); } else { return $login->printExpansion(); } @@ -513,19 +536,22 @@ class _WikiUser /** Signed in but not password checked or empty password. */ - function isSignedIn() { - return (isa($this,'_BogoUser') or isa($this,'_PassUser')); + function isSignedIn() + { + return (isa($this, '_BogoUser') or isa($this, '_PassUser')); } /** This is password checked for sure. */ - function isAuthenticated() { + function isAuthenticated() + { //return isa($this,'_PassUser'); //return isa($this,'_BogoUser') || isa($this,'_PassUser'); return $this->_level >= WIKIAUTH_BOGO; } - function isAdmin () { + function isAdmin() + { static $group; if ($this->_level == WIKIAUTH_ADMIN) return true; if (!$this->isSignedIn()) return false; @@ -537,21 +563,24 @@ class _WikiUser /** Name or IP for a signed user. UserName could come from a cookie e.g. */ - function getId () { - return ( $this->UserName() - ? $this->UserName() - : $GLOBALS['request']->get('REMOTE_ADDR') ); + function getId() + { + return ($this->UserName() + ? $this->UserName() + : $GLOBALS['request']->get('REMOTE_ADDR')); } /** Name for an authenticated user. No IP here. */ - function getAuthenticatedId() { - return ( $this->isAuthenticated() - ? $this->_userid - : ''); //$GLOBALS['request']->get('REMOTE_ADDR') ); + function getAuthenticatedId() + { + return ($this->isAuthenticated() + ? $this->_userid + : ''); //$GLOBALS['request']->get('REMOTE_ADDR') ); } - function hasAuthority ($require_level) { + function hasAuthority($require_level) + { return $this->_level >= $require_level; } @@ -559,7 +588,8 @@ class _WikiUser Any word char (A-Za-z0-9_), " ", ".", "@" and "-" The backends may loosen or tighten this. */ - function isValidName ($userid = false) { + function isValidName($userid = false) + { if (!$userid) $userid = $this->_userid; if (!$userid) return false; if (FUSIONFORGE) { @@ -572,86 +602,82 @@ class _WikiUser * Called on an auth_args POST request, such as login, logout or signin. * TODO: Check BogoLogin users with empty password. (self-signed users) */ - function AuthCheck ($postargs) { + function AuthCheck($postargs) + { // Normalize args, and extract. $keys = array('userid', 'passwd', 'require_level', 'login', 'logout', - 'cancel'); + 'cancel'); foreach ($keys as $key) $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false; extract($args); $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level)); if ($logout) { // Log out - if (LOGIN_LOG and is_writeable(LOGIN_LOG)) { - global $request; - $zone_offset = Request_AccessLogEntry::_zone_offset(); - $ncsa_time = date("d/M/Y:H:i:s", time()); - $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"', - (string) $request->get('REMOTE_HOST'), - (string) $request->_user->_userid, - $ncsa_time, $zone_offset, - "logout ".get_class($request->_user), - "401", - (string) $request->get('HTTP_REFERER'), - (string) $request->get('HTTP_USER_AGENT') - ); - if (($fp = fopen(LOGIN_LOG, "a"))) { - flock($fp, LOCK_EX); - fputs($fp, "$entry\n"); - fclose($fp); - } - //error_log("$entry\n", 3, LOGIN_LOG); - } + if (LOGIN_LOG and is_writeable(LOGIN_LOG)) { + global $request; + $zone_offset = Request_AccessLogEntry::_zone_offset(); + $ncsa_time = date("d/M/Y:H:i:s", time()); + $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"', + (string)$request->get('REMOTE_HOST'), + (string)$request->_user->_userid, + $ncsa_time, $zone_offset, + "logout " . get_class($request->_user), + "401", + (string)$request->get('HTTP_REFERER'), + (string)$request->get('HTTP_USER_AGENT') + ); + if (($fp = fopen(LOGIN_LOG, "a"))) { + flock($fp, LOCK_EX); + fputs($fp, "$entry\n"); + fclose($fp); + } + //error_log("$entry\n", 3, LOGIN_LOG); + } if (method_exists($GLOBALS['request']->_user, "logout")) { //_HttpAuthPassUser - $GLOBALS['request']->_user->logout(); + $GLOBALS['request']->_user->logout(); } $user = new _AnonUser(); $user->_userid = ''; $user->_level = WIKIAUTH_ANON; return $user; } elseif ($cancel) - return false; // User hit cancel button. + return false; // User hit cancel button. elseif (!$login && !$userid) - return false; // Nothing to do? + return false; // Nothing to do? if (!$this->isValidName($userid)) - return _("Invalid username.");; + return _("Invalid username."); + ; $authlevel = $this->checkPass($passwd === false ? '' : $passwd); - if (LOGIN_LOG and is_writeable(LOGIN_LOG)) { - global $request; - $zone_offset = Request_AccessLogEntry::_zone_offset(); - $ncsa_time = date("d/M/Y:H:i:s", time()); - $manglepasswd = $passwd; - for ($i=0; $i= 127) $manglepasswd[$i] = ">"; - } + if (LOGIN_LOG and is_writeable(LOGIN_LOG)) { + global $request; + $zone_offset = Request_AccessLogEntry::_zone_offset(); + $ncsa_time = date("d/M/Y:H:i:s", time()); + $manglepasswd = $passwd; + for ($i = 0; $i < strlen($manglepasswd); $i++) { + $c = substr($manglepasswd, $i, 1); + if (ord($c) < 32) $manglepasswd[$i] = "<"; + elseif ($c == '*') $manglepasswd[$i] = "*"; elseif ($c == '?') $manglepasswd[$i] = "?"; elseif ($c == '(') $manglepasswd[$i] = "("; elseif ($c == ')') $manglepasswd[$i] = ")"; elseif ($c == "\\") $manglepasswd[$i] = "\\"; elseif (ord($c) < 127) $manglepasswd[$i] = "x"; elseif (ord($c) >= 127) $manglepasswd[$i] = ">"; + } if ((DEBUG & _DEBUG_LOGIN) and $authlevel <= 0) $manglepasswd = $passwd; - $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"', - $request->get('REMOTE_HOST'), - (string) $request->_user->_userid, - $ncsa_time, $zone_offset, - "login $userid/$manglepasswd => $authlevel ".get_class($request->_user), - $authlevel > 0 ? "200" : "403", - (string) $request->get('HTTP_REFERER'), - (string) $request->get('HTTP_USER_AGENT') - ); - if (($fp = fopen(LOGIN_LOG, "a"))) { - flock($fp, LOCK_EX); - fputs($fp, "$entry\n"); - fclose($fp); - } - //error_log("$entry\n", 3, LOGIN_LOG); - } + $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"', + $request->get('REMOTE_HOST'), + (string)$request->_user->_userid, + $ncsa_time, $zone_offset, + "login $userid/$manglepasswd => $authlevel " . get_class($request->_user), + $authlevel > 0 ? "200" : "403", + (string)$request->get('HTTP_REFERER'), + (string)$request->get('HTTP_USER_AGENT') + ); + if (($fp = fopen(LOGIN_LOG, "a"))) { + flock($fp, LOCK_EX); + fputs($fp, "$entry\n"); + fclose($fp); + } + //error_log("$entry\n", 3, LOGIN_LOG); + } if ($authlevel <= 0) { // anon or forbidden if ($passwd) @@ -659,12 +685,11 @@ class _WikiUser else return _("Invalid password or userid."); } elseif ($authlevel < $require_level) { // auth ok, but not enough - if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser') - { + if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser') { // upgrade class $class = "_" . $this->_current_method . "PassUser"; - include_once 'lib/WikiUser/'.$this->_current_method.'.php'; - $user = new $class($userid,$this->_prefs); + include_once 'lib/WikiUser/' . $this->_current_method . '.php'; + $user = new $class($userid, $this->_prefs); if (!check_php_version(5)) eval("\$this = \$user;"); // /*PHP5 patch*/$this = $user; @@ -679,11 +704,11 @@ class _WikiUser // Successful login. //$user = $GLOBALS['request']->_user; if (!empty($this->_current_method) and - strtolower(get_class($this)) == '_passuser') - { + strtolower(get_class($this)) == '_passuser' + ) { // upgrade class $class = "_" . $this->_current_method . "PassUser"; - include_once 'lib/WikiUser/'.$this->_current_method.'.php'; + include_once 'lib/WikiUser/' . $this->_current_method . '.php'; $user = new $class($userid, $this->_prefs); if (!check_php_version(5)) eval("\$this = \$user;"); @@ -703,13 +728,14 @@ class _WikiUser * prefs are stored in cookies, but only the userid. */ class _AnonUser -extends _WikiUser + extends _WikiUser { - var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated + var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated /** Anon only gets to load and save prefs in a cookie, that's it. */ - function getPreferences() { + function getPreferences() + { global $request; if (empty($this->_prefs)) @@ -718,13 +744,13 @@ extends _WikiUser // Try to read deprecated 1.3.x style cookies if ($cookie = $request->cookies->get_old(WIKI_NAME)) { - if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) { + if (!$unboxedcookie = $this->_prefs->retrieve($cookie)) { trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.") - . "\n" - . sprintf("%s='%s'", WIKI_NAME, $cookie) - . "\n" - . _("Default preferences will be used."), - E_USER_NOTICE); + . "\n" + . sprintf("%s='%s'", WIKI_NAME, $cookie) + . "\n" + . _("Default preferences will be used."), + E_USER_NOTICE); } /** * Only set if it matches the UserName who is @@ -732,11 +758,11 @@ extends _WikiUser * username). (Remember, _BogoUser and higher inherit this * function too!). */ - if (! $UserName || $UserName == @$unboxedcookie['userid']) { + if (!$UserName || $UserName == @$unboxedcookie['userid']) { $updated = $this->_prefs->updatePrefs($unboxedcookie); //$this->_prefs = new UserPreferences($unboxedcookie); $UserName = @$unboxedcookie['userid']; - if (is_string($UserName) and (substr($UserName,0,2) != 's:')) + if (is_string($UserName) and (substr($UserName, 0, 2) != 's:')) $this->_userid = $UserName; else $UserName = false; @@ -746,13 +772,13 @@ extends _WikiUser $request->deleteCookieVar(WIKI_NAME); } // Try to read deprecated 1.3.4 style cookies - if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) { - if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) { - if (! $UserName || $UserName == $unboxedcookie['userid']) { + if (!$UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) { + if (!$unboxedcookie = $this->_prefs->retrieve($cookie)) { + if (!$UserName || $UserName == $unboxedcookie['userid']) { $updated = $this->_prefs->updatePrefs($unboxedcookie); //$this->_prefs = new UserPreferences($unboxedcookie); $UserName = $unboxedcookie['userid']; - if (is_string($UserName) and (substr($UserName,0,2) != 's:')) + if (is_string($UserName) and (substr($UserName, 0, 2) != 's:')) $this->_userid = $UserName; else $UserName = false; @@ -761,15 +787,15 @@ extends _WikiUser $request->deleteCookieVar("WIKI_PREF2"); } } - if (! $UserName ) { + if (!$UserName) { // Try reading userid from old PhpWiki cookie formats: if ($cookie = $request->cookies->get_old(getCookieName())) { - if (is_string($cookie) and (substr($cookie,0,2) != 's:')) + if (is_string($cookie) and (substr($cookie, 0, 2) != 's:')) $UserName = $cookie; elseif (is_array($cookie) and !empty($cookie['userid'])) $UserName = $cookie['userid']; } - if (! $UserName and !headers_sent()) + if (!$UserName and !headers_sent()) $request->deleteCookieVar(getCookieName()); else $this->_userid = $UserName; @@ -792,7 +818,8 @@ extends _WikiUser * user. In that case stricter error checking will be needed * when loading the cookie. */ - function setPreferences($prefs, $id_only=false) { + function setPreferences($prefs, $id_only = false) + { if (!is_object($prefs)) { if (is_object($this->_prefs)) { $updated = $this->_prefs->updatePrefs($prefs); @@ -816,7 +843,7 @@ extends _WikiUser // the pre 1.3.x versions. // prefs should be stored besides the session in the homepagehandle or in a db. $request->setCookieVar(getCookieName(), $this->_userid, - COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN); + COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN); //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')), // COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN); } @@ -825,7 +852,7 @@ extends _WikiUser $packed = $prefs->store(); $unpacked = $prefs->unpack($packed); if (count($unpacked)) { - foreach (array('_method','_select','_update','_insert') as $param) { + foreach (array('_method', '_select', '_update', '_insert') as $param) { if (!empty($this->_prefs->{$param})) $prefs->{$param} = $this->_prefs->{$param}; } @@ -835,19 +862,21 @@ extends _WikiUser return $updated; } - function userExists() { + function userExists() + { return true; } - function checkPass($submitted_password) { + function checkPass($submitted_password) + { return false; // this might happen on a old-style signin button. // By definition, the _AnonUser does not HAVE a password // (compared to _BogoUser, who has an EMPTY password). trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " " - . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " " - . "New subclasses of _WikiUser must override this function."); + . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " " + . "New subclasses of _WikiUser must override this function."); return false; } @@ -858,15 +887,17 @@ extends _WikiUser * This is added automatically to USER_AUTH_ORDER. */ class _ForbiddenUser -extends _AnonUser + extends _AnonUser { var $_level = WIKIAUTH_FORBIDDEN; - function checkPass($submitted_password) { + function checkPass($submitted_password) + { return WIKIAUTH_FORBIDDEN; } - function userExists() { + function userExists() + { if ($this->_HomePagehandle) return true; return false; } @@ -881,9 +912,10 @@ extends _AnonUser * Note: This class is not called anymore by WikiUser() */ class _BogoUser -extends _AnonUser + extends _AnonUser { - function userExists() { + function userExists() + { if (isWikiWord($this->_userid)) { $this->_level = WIKIAUTH_BOGO; return true; @@ -893,7 +925,8 @@ extends _AnonUser } } - function checkPass($submitted_password) { + function checkPass($submitted_password) + { // By definition, BogoUser has an empty password. $this->userExists(); return $this->_level; @@ -901,27 +934,28 @@ extends _AnonUser } class _PassUser -extends _AnonUser -/** - * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed. - * - * The classes for all subsequent auth methods extend from this class. - * This handles the auth method type dispatcher according $USER_AUTH_ORDER, - * the three auth method policies first-only, strict and stacked - * and the two methods for prefs: homepage or database, - * if $DBAuthParams['pref_select'] is defined. - * - * Default is PersonalPage auth and prefs. - * - * @author: Reini Urban - * @tables: pref - */ + extends _AnonUser + /** + * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed. + * + * The classes for all subsequent auth methods extend from this class. + * This handles the auth method type dispatcher according $USER_AUTH_ORDER, + * the three auth method policies first-only, strict and stacked + * and the two methods for prefs: homepage or database, + * if $DBAuthParams['pref_select'] is defined. + * + * Default is PersonalPage auth and prefs. + * + * @author: Reini Urban + * @tables: pref + */ { var $_auth_dbi, $_prefs; var $_current_method, $_current_index; // check and prepare the auth and pref methods only once - function _PassUser($UserName='', $prefs=false) { + function _PassUser($UserName = '', $prefs = false) + { //global $DBAuthParams, $DBParams; if ($UserName) { /*if (!$this->isValidName($UserName)) @@ -930,17 +964,17 @@ extends _AnonUser if ($this->hasHomePage()) $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid); } - $this->_authmethod = substr(get_class($this),1,-8); + $this->_authmethod = substr(get_class($this), 1, -8); if ($this->_authmethod == 'a') $this->_authmethod = 'admin'; // Check the configured Prefs methods $dbi = $this->getAuthDbh(); $dbh = $GLOBALS['request']->getDbh(); - if ( $dbi - and !$dbh->readonly - and !isset($this->_prefs->_select) - and $dbh->getAuthParam('pref_select')) - { + if ($dbi + and !$dbh->readonly + and !isset($this->_prefs->_select) + and $dbh->getAuthParam('pref_select') + ) { if (!$this->_prefs) { $this->_prefs = new UserPreferences(); $need_pref = true; @@ -948,9 +982,9 @@ extends _AnonUser $this->_prefs->_method = $dbh->getParam('dbtype'); $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid"); // read-only prefs? - if ( !isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) { + if (!isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) { $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'), - array("userid", "pref_blob")); + array("userid", "pref_blob")); } } else { if (!$this->_prefs) { @@ -960,13 +994,13 @@ extends _AnonUser $this->_prefs->_method = 'HomePage'; } - if (! $this->_prefs or isset($need_pref) ) { + if (!$this->_prefs or isset($need_pref)) { if ($prefs) $this->_prefs = $prefs; else $this->getPreferences(); } // Upgrade to the next parent _PassUser class. Avoid recursion. - if ( strtolower(get_class($this)) === '_passuser' ) { + if (strtolower(get_class($this)) === '_passuser') { //auth policy: Check the order of the configured auth methods // 1. first-only: Upgrade the class here in the constructor // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as @@ -979,9 +1013,8 @@ extends _AnonUser // policy 1: only pre-define one method for all users if (USER_AUTH_POLICY === 'first-only') { $class = $this->nextClass(); - return new $class($UserName,$this->_prefs); - } - // Use the default behaviour from the previous versions: + return new $class($UserName, $this->_prefs); + } // Use the default behaviour from the previous versions: elseif (USER_AUTH_POLICY === 'old') { // Default: try to be smart // On php5 we can directly return and upgrade the Object, @@ -989,49 +1022,53 @@ extends _AnonUser if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) { include_once 'lib/WikiUser/HttpAuth.php'; if (check_php_version(5)) - return new _HttpAuthPassUser($UserName,$this->_prefs); + return new _HttpAuthPassUser($UserName, $this->_prefs); else { - $user = new _HttpAuthPassUser($UserName,$this->_prefs); + $user = new _HttpAuthPassUser($UserName, $this->_prefs); eval("\$this = \$user;"); // /*PHP5 patch*/$this = $user; return $user; } } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and - $dbh->getAuthParam('auth_check') and - ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))) { + $dbh->getAuthParam('auth_check') and + ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn')) + ) { if (check_php_version(5)) - return new _DbPassUser($UserName,$this->_prefs); + return new _DbPassUser($UserName, $this->_prefs); else { - $user = new _DbPassUser($UserName,$this->_prefs); + $user = new _DbPassUser($UserName, $this->_prefs); eval("\$this = \$user;"); // /*PHP5 patch*/$this = $user; return $user; } } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and - defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and - function_exists('ldap_connect')) { + defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and + function_exists('ldap_connect') + ) { include_once 'lib/WikiUser/LDAP.php'; if (check_php_version(5)) - return new _LDAPPassUser($UserName,$this->_prefs); + return new _LDAPPassUser($UserName, $this->_prefs); else { - $user = new _LDAPPassUser($UserName,$this->_prefs); + $user = new _LDAPPassUser($UserName, $this->_prefs); eval("\$this = \$user;"); // /*PHP5 patch*/$this = $user; return $user; } } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and - defined('IMAP_AUTH_HOST') and function_exists('imap_open')) { + defined('IMAP_AUTH_HOST') and function_exists('imap_open') + ) { include_once 'lib/WikiUser/IMAP.php'; if (check_php_version(5)) - return new _IMAPPassUser($UserName,$this->_prefs); + return new _IMAPPassUser($UserName, $this->_prefs); else { - $user = new _IMAPPassUser($UserName,$this->_prefs); + $user = new _IMAPPassUser($UserName, $this->_prefs); eval("\$this = \$user;"); // /*PHP5 patch*/$this = $user; return $user; } } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and - defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)) { + defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE) + ) { include_once 'lib/WikiUser/File.php'; if (check_php_version(5)) return new _FilePassUser($UserName, $this->_prefs); @@ -1044,23 +1081,23 @@ extends _AnonUser } else { include_once 'lib/WikiUser/PersonalPage.php'; if (check_php_version(5)) - return new _PersonalPagePassUser($UserName,$this->_prefs); + return new _PersonalPagePassUser($UserName, $this->_prefs); else { - $user = new _PersonalPagePassUser($UserName,$this->_prefs); + $user = new _PersonalPagePassUser($UserName, $this->_prefs); eval("\$this = \$user;"); // /*PHP5 patch*/$this = $user; return $user; } } - } - else + } else // else use the page methods defined in _PassUser. return $this; } } } - function getAuthDbh () { + function getAuthDbh() + { global $request; //, $DBParams, $DBAuthParams; $dbh = $request->getDbh(); @@ -1075,7 +1112,8 @@ extends _AnonUser if (empty($this->_auth_dbi)) { if ($dbh->getParam('dbtype') != 'SQL' and $dbh->getParam('dbtype') != 'ADODB' - and $dbh->getParam('dbtype') != 'PDO') + and $dbh->getParam('dbtype') != 'PDO' + ) return false; if (empty($GLOBALS['DBAuthParams'])) return false; @@ -1084,7 +1122,7 @@ extends _AnonUser } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) { $dbh = $request->getDbh(); // same phpwiki database } else { // use another external database handle. needs PHP >= 4.1 - $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']); + $local_params = array_merge($GLOBALS['DBParams'], $GLOBALS['DBAuthParams']); $local_params['dsn'] = $local_params['auth_dsn']; $dbh = WikiDB::open($local_params); } @@ -1093,16 +1131,17 @@ extends _AnonUser return $this->_auth_dbi; } - function _normalize_stmt_var($var, $oldstyle = false) { - static $valid_variables = array('userid','password','pref_blob','groupname'); + function _normalize_stmt_var($var, $oldstyle = false) + { + static $valid_variables = array('userid', 'password', 'pref_blob', 'groupname'); // old-style: "'$userid'" // new-style: '"\$userid"' or just "userid" - $new = str_replace(array("'",'"','\$','$'),'',$var); + $new = str_replace(array("'", '"', '\$', '$'), '', $var); if (!in_array($new, $valid_variables)) { - trigger_error("Unknown DBAuthParam statement variable: ". $new, E_USER_ERROR); + trigger_error("Unknown DBAuthParam statement variable: " . $new, E_USER_ERROR); return false; } - return !$oldstyle ? "'$".$new."'" : '\$'.$new; + return !$oldstyle ? "'$" . $new . "'" : '\$' . $new; } // TODO: use it again for the auth and member tables @@ -1110,7 +1149,8 @@ extends _AnonUser // multiple vars should be executed via prepare(?,?)+execute, // single vars with execute(sprintf(quote(var))) // help with position independency - function prepare ($stmt, $variables, $oldstyle = false, $sprintfstyle = true) { + function prepare($stmt, $variables, $oldstyle = false, $sprintfstyle = true) + { global $request; $dbi = $request->getDbh(); $this->getAuthDbh(); @@ -1120,15 +1160,15 @@ extends _AnonUser $new = array(); if (is_array($variables)) { //$sprintfstyle = false; - for ($i=0; $i < count($variables); $i++) { + for ($i = 0; $i < count($variables); $i++) { $var = $this->_normalize_stmt_var($variables[$i], $oldstyle); if (!$var) trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s", - $variables[$i], $stmt), E_USER_WARNING); + $variables[$i], $stmt), E_USER_WARNING); $variables[$i] = $var; if (!$var) $new[] = ''; else { - $s = "%" . ($i+1) . "s"; + $s = "%" . ($i + 1) . "s"; $new[] = $sprintfstyle ? $s : "?"; } } @@ -1136,7 +1176,7 @@ extends _AnonUser $var = $this->_normalize_stmt_var($variables, $oldstyle); if (!$var) trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s", - $variables, $stmt), E_USER_WARNING); + $variables, $stmt), E_USER_WARNING); $variables = $var; if (!$var) $new = ''; else $new = $sprintfstyle ? '%s' : "?"; @@ -1144,17 +1184,17 @@ extends _AnonUser $prefix = $dbi->getParam('prefix'); // probably prefix table names if in same database if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and - ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn'))) - { + ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn')) + ) { if (!stristr($stmt, $prefix)) { $oldstmt = $stmt; - $stmt = str_replace(array(" user "," pref "," member "), - array(" ".$prefix."user ", - " ".$prefix."pref ", - " ".$prefix."member "), $stmt); + $stmt = str_replace(array(" user ", " pref ", " member "), + array(" " . $prefix . "user ", + " " . $prefix . "pref ", + " " . $prefix . "member "), $stmt); //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have trigger_error("Need to prefix the DBAUTH tablename in config/config.ini:\n $oldstmt \n=> $stmt", - E_USER_WARNING); + E_USER_WARNING); } } // Preparate the SELECT statement, for ADODB and PearDB (MDB not). @@ -1163,17 +1203,18 @@ extends _AnonUser if ($new_stmt == $stmt) { if ($oldstyle) { trigger_error(sprintf("DbAuthParams: Invalid statement in %s", - $stmt), E_USER_WARNING); + $stmt), E_USER_WARNING); } else { trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s", - $stmt), E_USER_WARNING); + $stmt), E_USER_WARNING); $new_stmt = $this->prepare($stmt, $variables, 'oldstyle'); } } return $new_stmt; } - function getPreferences() { + function getPreferences() + { if (!empty($this->_prefs->_method)) { if ($this->_prefs->_method == 'ADODB') { // FIXME: strange why this should be needed... @@ -1199,8 +1240,9 @@ extends _AnonUser // PersonalPage if there is one. if (!empty($this->_HomePagehandle)) { if ($restored_from_page = $this->_prefs->retrieve - ($this->_HomePagehandle->get('pref'))) { - $updated = $this->_prefs->updatePrefs($restored_from_page,'init'); + ($this->_HomePagehandle->get('pref')) + ) { + $updated = $this->_prefs->updatePrefs($restored_from_page, 'init'); //$this->_prefs = new UserPreferences($restored_from_page); return $this->_prefs; } @@ -1208,20 +1250,19 @@ extends _AnonUser return $this->_prefs; } - function setPreferences($prefs, $id_only=false) { + function setPreferences($prefs, $id_only = false) + { if (!empty($this->_prefs->_method)) { if ($this->_prefs->_method == 'ADODB') { // FIXME: strange why this should be needed... include_once 'lib/WikiUser/Db.php'; include_once 'lib/WikiUser/AdoDb.php'; return _AdoDbPassUser::setPreferences($prefs, $id_only); - } - elseif ($this->_prefs->_method == 'SQL') { + } elseif ($this->_prefs->_method == 'SQL') { include_once 'lib/WikiUser/Db.php'; include_once 'lib/WikiUser/PearDb.php'; return _PearDbPassUser::setPreferences($prefs, $id_only); - } - elseif ($this->_prefs->_method == 'PDO') { + } elseif ($this->_prefs->_method == 'PDO') { include_once 'lib/WikiUser/Db.php'; include_once 'lib/WikiUser/PdoDb.php'; return _PdoDbPassUser::setPreferences($prefs, $id_only); @@ -1229,27 +1270,29 @@ extends _AnonUser } if ($updated = _AnonUser::setPreferences($prefs, $id_only)) { // Encode only the _prefs array of the UserPreference object - // If no DB method exists to store the prefs we must store it in the page, not in the cookies. + // If no DB method exists to store the prefs we must store it in the page, not in the cookies. if (empty($this->_HomePagehandle)) { $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid); - } - if (! $this->_HomePagehandle->exists() ) { + } + if (!$this->_HomePagehandle->exists()) { $this->createHomePage(); } - if (!empty($this->_HomePagehandle) and !$id_only) { + if (!empty($this->_HomePagehandle) and !$id_only) { $this->_HomePagehandle->set('pref', $this->_prefs->store()); } } return $updated; } - function mayChangePass() { + function mayChangePass() + { return true; } //The default method is getting the password from prefs. // child methods obtain $stored_password from external auth. - function userExists() { + function userExists() + { //if ($this->_HomePagehandle) return true; if (strtolower(get_class($this)) == "_passuser") { $class = $this->nextClass(); @@ -1277,7 +1320,8 @@ extends _AnonUser //The default method is getting the password from prefs. // child methods obtain $stored_password from external auth. - function checkPass($submitted_password) { + function checkPass($submitted_password) + { $stored_password = $this->_prefs->get('passwd'); if ($this->_checkPass($submitted_password, $stored_password)) { $this->_level = WIKIAUTH_USER; @@ -1292,7 +1336,8 @@ extends _AnonUser } - function _checkPassLength($submitted_password) { + function _checkPassLength($submitted_password) + { if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) { trigger_error(_("The length of the password is shorter than the system policy allows.")); return false; @@ -1315,7 +1360,8 @@ extends _AnonUser * * TODO: remove crypt() function check from config.php:396 ?? */ - function _checkPass($submitted_password, $stored_password) { + function _checkPass($submitted_password, $stored_password) + { if (!empty($submitted_password)) { // This works only on plaintext passwords. if (!ENCRYPTED_PASSWD and (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM)) { @@ -1329,19 +1375,17 @@ extends _AnonUser if (ENCRYPTED_PASSWD) { // Verify against encrypted password. if (function_exists('crypt')) { - if (crypt($submitted_password, $stored_password) == $stored_password ) + if (crypt($submitted_password, $stored_password) == $stored_password) return true; // matches encrypted password else return false; - } - else { + } else { trigger_error(_("The crypt function is not available in this version of PHP.") . " " - . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."), - E_USER_WARNING); + . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."), + E_USER_WARNING); return false; } - } - else { + } else { // Verify against cleartext password. if ($submitted_password == $stored_password) return true; @@ -1350,7 +1394,7 @@ extends _AnonUser if (function_exists('crypt')) { if (crypt($submitted_password, $stored_password) == $stored_password) { trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."), - E_USER_WARNING); + E_USER_WARNING); return true; } } @@ -1365,7 +1409,8 @@ extends _AnonUser * must be explicitly enabled. * This may be called by plugin/UserPreferences or by ->SetPreferences() */ - function changePass($submitted_password) { + function changePass($submitted_password) + { $stored_password = $this->_prefs->get('passwd'); // check if authenticated if (!$this->isAuthenticated()) return false; @@ -1385,15 +1430,16 @@ extends _AnonUser return ENCRYPTED_PASSWD ? true : false; } - function _tryNextPass($submitted_password) { + function _tryNextPass($submitted_password) + { if (DEBUG & _DEBUG_LOGIN) { $class = strtolower(get_class($this)); - if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser"; + if (substr($class, -10) == "dbpassuser") $class = "_dbpassuser"; $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass'; } if (USER_AUTH_POLICY === 'strict') { $class = $this->nextClass(); - if ($user = new $class($this->_userid,$this->_prefs)) { + if ($user = new $class($this->_userid, $this->_prefs)) { if ($user->userExists()) { return $user->checkPass($submitted_password); } @@ -1401,25 +1447,27 @@ extends _AnonUser } if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') { $class = $this->nextClass(); - if ($user = new $class($this->_userid,$this->_prefs)) + if ($user = new $class($this->_userid, $this->_prefs)) return $user->checkPass($submitted_password); } return $this->_level; } - function _tryNextUser() { + function _tryNextUser() + { if (DEBUG & _DEBUG_LOGIN) { $class = strtolower(get_class($this)); - if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser"; + if (substr($class, -10) == "dbpassuser") $class = "_dbpassuser"; $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser'; } if (USER_AUTH_POLICY === 'strict' - or USER_AUTH_POLICY === 'stacked') { + or USER_AUTH_POLICY === 'stacked' + ) { $class = $this->nextClass(); while ($user = new $class($this->_userid, $this->_prefs)) { if (!check_php_version(5)) eval("\$this = \$user;"); - $user = UpgradeUser($this, $user); + $user = UpgradeUser($this, $user); if ($user->userExists()) { $user = UpgradeUser($this, $user); return true; @@ -1451,12 +1499,15 @@ extends _AnonUser * storage methods. */ class _AdminUser -extends _PassUser + extends _PassUser { - function mayChangePass() { + function mayChangePass() + { return false; } - function checkPass($submitted_password) { + + function checkPass($submitted_password) + { if ($this->_userid == ADMIN_USER) $stored_password = ADMIN_PASSWD; else { @@ -1479,7 +1530,8 @@ extends _PassUser } } - function storePass($submitted_password) { + function storePass($submitted_password) + { if ($this->_userid == ADMIN_USER) return false; else { @@ -1495,42 +1547,47 @@ extends _PassUser * to support get, set, sanify (range checking, ...) * update() will do the neccessary side-effects if a * setting gets changed (theme, language, ...) -*/ + */ class _UserPreference { var $default_value; - function _UserPreference ($default_value) { + function _UserPreference($default_value) + { $this->default_value = $default_value; } - function sanify ($value) { + function sanify($value) + { return (string)$value; } - function get ($name) { + function get($name) + { if (isset($this->{$name})) - return $this->{$name}; + return $this->{$name}; else return $this->default_value; } - function getraw ($name) { + function getraw($name) + { if (!empty($this->{$name})) - return $this->{$name}; + return $this->{$name}; } // stores the value as $this->$name, and not as $this->value (clever?) - function set ($name, $value) { + function set($name, $value) + { $return = 0; $value = $this->sanify($value); - if ($this->get($name) != $value) { - $this->update($value); - $return = 1; - } - if ($value != $this->default_value) { - $this->{$name} = $value; + if ($this->get($name) != $value) { + $this->update($value); + $return = 1; + } + if ($value != $this->default_value) { + $this->{$name} = $value; } else { unset($this->{$name}); } @@ -1538,22 +1595,25 @@ class _UserPreference } // default: no side-effects - function update ($value) { + function update($value) + { ; } } class _UserPreference_numeric -extends _UserPreference + extends _UserPreference { - function _UserPreference_numeric ($default, $minval = false, - $maxval = false) { + function _UserPreference_numeric($default, $minval = false, + $maxval = false) + { $this->_UserPreference((double)$default); $this->_minval = (double)$minval; $this->_maxval = (double)$maxval; } - function sanify ($value) { + function sanify($value) + { $value = (double)$value; if ($this->_minval !== false && $value < $this->_minval) $value = $this->_minval; @@ -1564,25 +1624,29 @@ extends _UserPreference } class _UserPreference_int -extends _UserPreference_numeric + extends _UserPreference_numeric { - function _UserPreference_int ($default, $minval = false, $maxval = false) { + function _UserPreference_int($default, $minval = false, $maxval = false) + { $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval); } - function sanify ($value) { + function sanify($value) + { return (int)parent::sanify((int)$value); } } class _UserPreference_bool -extends _UserPreference + extends _UserPreference { - function _UserPreference_bool ($default = false) { + function _UserPreference_bool($default = false) + { $this->_UserPreference((bool)$default); } - function sanify ($value) { + function sanify($value) + { if (is_array($value)) { /* This allows for constructs like: * @@ -1599,29 +1663,32 @@ extends _UserPreference } return false; } - return (bool) $value; + return (bool)$value; } } class _UserPreference_language -extends _UserPreference + extends _UserPreference { - function _UserPreference_language ($default = DEFAULT_LANGUAGE) { + function _UserPreference_language($default = DEFAULT_LANGUAGE) + { $this->_UserPreference($default); } // FIXME: check for valid locale - function sanify ($value) { + function sanify($value) + { // Revert to DEFAULT_LANGUAGE if user does not specify // language in UserPreferences or chooses . if ($value == '' or empty($value)) $value = DEFAULT_LANGUAGE; - return (string) $value; + return (string)$value; } - function update ($newvalue) { - if (! $this->_init ) { + function update($newvalue) + { + if (!$this->_init) { // invalidate etag to force fresh output $GLOBALS['request']->setValidators(array('%mtime' => false)); update_locale($newvalue ? $newvalue : $GLOBALS['LANG']); @@ -1630,22 +1697,25 @@ extends _UserPreference } class _UserPreference_theme -extends _UserPreference + extends _UserPreference { - function _UserPreference_theme ($default = THEME) { + function _UserPreference_theme($default = THEME) + { $this->_UserPreference($default); } - function sanify ($value) { + function sanify($value) + { if (!empty($value) and FindFile($this->_themefile($value))) return $value; return $this->default_value; } - function update ($newvalue) { + function update($newvalue) + { global $WikiTheme; // invalidate etag to force fresh output - if (! $this->_init ) + if (!$this->_init) $GLOBALS['request']->setValidators(array('%mtime' => false)); if ($newvalue) include_once($this->_themefile($newvalue)); @@ -1653,15 +1723,17 @@ extends _UserPreference include_once($this->_themefile(THEME)); } - function _themefile ($theme) { + function _themefile($theme) + { return "themes/$theme/themeinfo.php"; } } class _UserPreference_notify -extends _UserPreference + extends _UserPreference { - function sanify ($value) { + function sanify($value) + { if (!empty($value)) return $value; else @@ -1675,7 +1747,8 @@ extends _UserPreference * ...), * ...); */ - function update ($value) { + function update($value) + { if (!empty($this->_init)) return; $dbh = $GLOBALS['request']->getDbh(); $notify = $dbh->get('notify'); @@ -1688,10 +1761,10 @@ extends _UserPreference $pages = $this->_page_split($value); // Limitation: only current user. $user = $GLOBALS['request']->getUser(); - if (!$user or !method_exists($user,'UserName')) return; + if (!$user or !method_exists($user, 'UserName')) return; // This fails with php5 and a WIKI_ID cookie: $userid = $user->UserName(); - $email = $user->_prefs->get('email'); + $email = $user->_prefs->get('email'); $verified = $user->_prefs->_prefs['email']->getraw('emailVerified'); // check existing notify hash and possibly delete pages for email if (!empty($data)) { @@ -1713,7 +1786,7 @@ extends _UserPreference // check it dynamically at every page->save? if ($verified) { $data[$page][$userid] = array('email' => $email, - 'verified' => $verified); + 'verified' => $verified); } else { $data[$page][$userid] = array('email' => $email); } @@ -1721,21 +1794,23 @@ extends _UserPreference } } // store users changes - $dbh->set('notify',$data); + $dbh->set('notify', $data); } /** split the user-given comma or whitespace delimited pagenames * to array */ - function _page_split($value) { - return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY); + function _page_split($value) + { + return preg_split('/[\s,]+/', $value, -1, PREG_SPLIT_NO_EMPTY); } } class _UserPreference_email -extends _UserPreference + extends _UserPreference { - function get($name) { + function get($name) + { // get e-mail address from FusionForge if (FUSIONFORGE && session_loggedin()) { $user = session_get_user(); @@ -1745,7 +1820,8 @@ extends _UserPreference } } - function sanify($value) { + function sanify($value) + { // e-mail address is already checked by FusionForge if (FUSIONFORGE) return $value; // check for valid email address @@ -1754,11 +1830,11 @@ extends _UserPreference // hack! if ($value == 1 or $value === true) return $value; - list($ok,$msg) = ValidateMail($value,'noconnect'); + list($ok, $msg) = ValidateMail($value, 'noconnect'); if ($ok) { return $value; } else { - trigger_error("E-mail Validation Error: ".$msg, E_USER_WARNING); + trigger_error("E-mail Validation Error: " . $msg, E_USER_WARNING); return $this->default_value; } } @@ -1767,7 +1843,8 @@ extends _UserPreference * Send a verification mail or for now just a notification email. * For true verification (value = 2), we'd need a mailserver hook. */ - function update($value) { + function update($value) + { // e-mail address is already checked by FusionForge if (FUSIONFORGE) return $value; if (!empty($this->_init)) return; @@ -1776,11 +1853,12 @@ extends _UserPreference if (($value == 1 or $value === true) and $verified) return; if (!empty($value) and !$verified) { - list($ok,$msg) = ValidateMail($value); - if ($ok and mail($value,"[".WIKI_NAME ."] "._("E-mail address confirmation"), - sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"), - WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true)))) { - $this->set('emailVerified',1); + list($ok, $msg) = ValidateMail($value); + if ($ok and mail($value, "[" . WIKI_NAME . "] " . _("E-mail address confirmation"), + sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"), + WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'), '', true))) + ) { + $this->set('emailVerified', 1); } else { trigger_error($msg, E_USER_WARNING); } @@ -1789,10 +1867,11 @@ extends _UserPreference } /** Check for valid email address - fixed version from http://www.zend.com/zend/spotlight/ev12apr.php - Note: too strict, Bug #1053681 +fixed version from http://www.zend.com/zend/spotlight/ev12apr.php +Note: too strict, Bug #1053681 */ -function ValidateMail($email, $noconnect=false) { +function ValidateMail($email, $noconnect = false) +{ global $EMailHosts; $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST'); @@ -1833,7 +1912,7 @@ function ValidateMail($email, $noconnect=false) { $rfc822re = "/$lwsp*$mailbox/"; unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart, - $atom, $word, $quoted_string); + $atom, $word, $quoted_string); unset($dtext, $controls, $specials, $lwsp, $domain_literal); if (!preg_match($rfc822re, $email)) { @@ -1842,51 +1921,51 @@ function ValidateMail($email, $noconnect=false) { return $result; } if ($noconnect) - return array(true, sprintf(_("E-mail address '%s' is properly formatted"), $email)); + return array(true, sprintf(_("E-mail address '%s' is properly formatted"), $email)); - list ( $Username, $Domain ) = explode("@", $email); + list ($Username, $Domain) = explode("@", $email); //Todo: getmxrr workaround on windows or manual input field to verify it manually if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows. $ConnectAddress = $MXHost[0]; } else { $ConnectAddress = $Domain; - if (isset($EMailHosts[ $Domain ])) { - $ConnectAddress = $EMailHosts[ $Domain ]; + if (isset($EMailHosts[$Domain])) { + $ConnectAddress = $EMailHosts[$Domain]; } } - $Connect = @fsockopen ( $ConnectAddress, 25 ); + $Connect = @fsockopen($ConnectAddress, 25); if ($Connect) { if (ereg("^220", $Out = fgets($Connect, 1024))) { - fputs ($Connect, "HELO $HTTP_HOST\r\n"); - $Out = fgets ( $Connect, 1024 ); - fputs ($Connect, "MAIL FROM: <".$email.">\r\n"); - $From = fgets ( $Connect, 1024 ); - fputs ($Connect, "RCPT TO: <".$email.">\r\n"); - $To = fgets ($Connect, 1024); - fputs ($Connect, "QUIT\r\n"); + fputs($Connect, "HELO $HTTP_HOST\r\n"); + $Out = fgets($Connect, 1024); + fputs($Connect, "MAIL FROM: <" . $email . ">\r\n"); + $From = fgets($Connect, 1024); + fputs($Connect, "RCPT TO: <" . $email . ">\r\n"); + $To = fgets($Connect, 1024); + fputs($Connect, "QUIT\r\n"); fclose($Connect); - if (!ereg ("^250", $From)) { - $result[0]=false; - $result[1]="Server rejected address: ". $From; + if (!ereg("^250", $From)) { + $result[0] = false; + $result[1] = "Server rejected address: " . $From; return $result; } - if (!ereg ( "^250", $To )) { - $result[0]=false; - $result[1]="Server rejected address: ". $To; + if (!ereg("^250", $To)) { + $result[0] = false; + $result[1] = "Server rejected address: " . $To; return $result; } } else { $result[0] = false; $result[1] = "No response from server"; return $result; - } - } else { - $result[0]=false; - $result[1]="Cannot connect e-mail server."; + } + } else { + $result[0] = false; + $result[1] = "Cannot connect e-mail server."; return $result; } - $result[0]=true; - $result[1]="E-mail address '$email' appears to be valid."; + $result[0] = true; + $result[1] = "E-mail address '$email' appears to be valid."; return $result; } // end of function @@ -1907,7 +1986,8 @@ class UserPreferences { var $notifyPagesAll; - function UserPreferences($saved_prefs = false) { + function UserPreferences($saved_prefs = false) + { // userid stored too, to ensure the prefs are being loaded for // the correct (currently signing in) userid if stored in a // cookie. @@ -1916,53 +1996,53 @@ class UserPreferences // if some app needs prefs from different users, different from current user. $this->_prefs = array( - 'userid' => new _UserPreference(''), - 'passwd' => new _UserPreference(''), - 'autologin' => new _UserPreference_bool(), - //'emailVerified' => new _UserPreference_emailVerified(), - //fixed: store emailVerified as email parameter, 1.3.8 - 'email' => new _UserPreference_email(''), - 'notifyPages' => new _UserPreference_notify(''), // 1.3.8 - 'theme' => new _UserPreference_theme(THEME), - 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE), - 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS, - EDITWIDTH_MIN_COLS, - EDITWIDTH_MAX_COLS), - 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8 - 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS, - EDITHEIGHT_MIN_ROWS, - EDITHEIGHT_MAX_ROWS), - 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS, - TIMEOFFSET_MIN_HOURS, - TIMEOFFSET_MAX_HOURS), - 'ownModifications' => new _UserPreference_bool(), - 'majorModificationsOnly' => new _UserPreference_bool(), - 'relativeDates' => new _UserPreference_bool(), - 'googleLink' => new _UserPreference_bool(), // 1.3.10 - 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11 - ); + 'userid' => new _UserPreference(''), + 'passwd' => new _UserPreference(''), + 'autologin' => new _UserPreference_bool(), + //'emailVerified' => new _UserPreference_emailVerified(), + //fixed: store emailVerified as email parameter, 1.3.8 + 'email' => new _UserPreference_email(''), + 'notifyPages' => new _UserPreference_notify(''), // 1.3.8 + 'theme' => new _UserPreference_theme(THEME), + 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE), + 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS, + EDITWIDTH_MIN_COLS, + EDITWIDTH_MAX_COLS), + 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8 + 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS, + EDITHEIGHT_MIN_ROWS, + EDITHEIGHT_MAX_ROWS), + 'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS, + TIMEOFFSET_MIN_HOURS, + TIMEOFFSET_MAX_HOURS), + 'ownModifications' => new _UserPreference_bool(), + 'majorModificationsOnly' => new _UserPreference_bool(), + 'relativeDates' => new _UserPreference_bool(), + 'googleLink' => new _UserPreference_bool(), // 1.3.10 + 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11 + ); // This should be probably be done with $customUserPreferenceColumns // For now, we use FUSIONFORGE define if (FUSIONFORGE) { $fusionforgeprefs = array( - 'pageTrail' => new _UserPreference_bool(), - 'diffMenuItem' => new _UserPreference_bool(), - 'pageInfoMenuItem' => new _UserPreference_bool(), - 'pdfMenuItem' => new _UserPreference_bool(), - 'lockMenuItem' => new _UserPreference_bool(), - 'chownMenuItem' => new _UserPreference_bool(), - 'setaclMenuItem' => new _UserPreference_bool(), - 'removeMenuItem' => new _UserPreference_bool(), - 'renameMenuItem' => new _UserPreference_bool(), - 'revertMenuItem' => new _UserPreference_bool(), - 'backLinksMenuItem' => new _UserPreference_bool(), - 'watchPageMenuItem' => new _UserPreference_bool(), - 'recentChangesMenuItem' => new _UserPreference_bool(), - 'randomPageMenuItem' => new _UserPreference_bool(), - 'likePagesMenuItem' => new _UserPreference_bool(), - 'specialPagesMenuItem' => new _UserPreference_bool(), - ); + 'pageTrail' => new _UserPreference_bool(), + 'diffMenuItem' => new _UserPreference_bool(), + 'pageInfoMenuItem' => new _UserPreference_bool(), + 'pdfMenuItem' => new _UserPreference_bool(), + 'lockMenuItem' => new _UserPreference_bool(), + 'chownMenuItem' => new _UserPreference_bool(), + 'setaclMenuItem' => new _UserPreference_bool(), + 'removeMenuItem' => new _UserPreference_bool(), + 'renameMenuItem' => new _UserPreference_bool(), + 'revertMenuItem' => new _UserPreference_bool(), + 'backLinksMenuItem' => new _UserPreference_bool(), + 'watchPageMenuItem' => new _UserPreference_bool(), + 'recentChangesMenuItem' => new _UserPreference_bool(), + 'randomPageMenuItem' => new _UserPreference_bool(), + 'likePagesMenuItem' => new _UserPreference_bool(), + 'specialPagesMenuItem' => new _UserPreference_bool(), + ); $this->_prefs = array_merge($this->_prefs, $fusionforgeprefs); } @@ -1971,19 +2051,20 @@ class UserPreferences // We will silently ignore this. if (!empty($customUserPreferenceColumns)) $this->_prefs = array_merge($this->_prefs, $customUserPreferenceColumns); -/* - if (isset($this->_method) and $this->_method == 'SQL') { - //unset($this->_prefs['userid']); - unset($this->_prefs['passwd']); - } -*/ + /* + if (isset($this->_method) and $this->_method == 'SQL') { + //unset($this->_prefs['userid']); + unset($this->_prefs['passwd']); + } + */ if (is_array($saved_prefs)) { foreach ($saved_prefs as $name => $value) $this->set($name, $value); } } - function __clone() { + function __clone() + { foreach ($this as $key => $val) { if (is_object($val) || (is_array($val))) { $this->{$key} = unserialize(serialize($val)); @@ -1991,7 +2072,8 @@ class UserPreferences } } - function _getPref($name) { + function _getPref($name) + { if ($name == 'emailVerified') $name = 'email'; if (!isset($this->_prefs[$name])) { @@ -2004,7 +2086,8 @@ class UserPreferences } // get the value or default_value of the subobject - function get($name) { + function get($name) + { if ($_pref = $this->_getPref($name)) if ($name == 'emailVerified') return $_pref->getraw($name); @@ -2015,7 +2098,8 @@ class UserPreferences } // check and set the new value in the subobject - function set($name, $value) { + function set($name, $value) + { $pref = $this->_getPref($name); if ($pref === false) return false; @@ -2023,7 +2107,8 @@ class UserPreferences /* do it here or outside? */ if ($name == 'passwd' and defined('PASSWORD_LENGTH_MINIMUM') and - strlen($value) <= PASSWORD_LENGTH_MINIMUM ) { + strlen($value) <= PASSWORD_LENGTH_MINIMUM + ) { //TODO: How to notify the user? return false; } @@ -2034,23 +2119,26 @@ class UserPreferences // Fix Fatal error for undefined value. Thanks to Jim Ford and Joel Schaubert if ((!$value and $pref->default_value) or ($value and !isset($pref->{$name})) // bug #1355533 - or ($value and ($pref->{$name} != $pref->default_value))) - { + or ($value and ($pref->{$name} != $pref->default_value)) + ) { if ($name == 'emailVerified') $newvalue = $value; else $newvalue = $pref->sanify($value); - $pref->set($name, $newvalue); + $pref->set($name, $newvalue); } $this->_prefs[$name] =& $pref; return true; } + /** * use init to avoid update on set */ - function updatePrefs($prefs, $init = false) { + function updatePrefs($prefs, $init = false) + { $count = 0; if ($init) $this->_init = $init; if (is_object($prefs)) { - $type = 'emailVerified'; $obj =& $this->_prefs['email']; + $type = 'emailVerified'; + $obj =& $this->_prefs['email']; $obj->_init = $init; if ($obj->get($type) !== $prefs->get($type)) { if ($obj->set($type, $prefs->get($type))) @@ -2062,9 +2150,11 @@ class UserPreferences if ($prefs->get($type) !== $obj->get($type)) { // special systemdefault prefs: (probably not needed) if ($type == 'theme' and $prefs->get($type) == '' and - $obj->get($type) == THEME) continue; + $obj->get($type) == THEME + ) continue; if ($type == 'lang' and $prefs->get($type) == '' and - $obj->get($type) == DEFAULT_LANGUAGE) continue; + $obj->get($type) == DEFAULT_LANGUAGE + ) continue; if ($this->_prefs[$type]->set($type, $prefs->get($type))) $count++; } @@ -2077,27 +2167,30 @@ class UserPreferences unset($this->_prefs['passwd']); } */ - // emailVerified at first, the rest later - $type = 'emailVerified'; $obj =& $this->_prefs['email']; + // emailVerified at first, the rest later + $type = 'emailVerified'; + $obj =& $this->_prefs['email']; $obj->_init = $init; if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) { - if ($obj->set($type,$prefs[$type])) + if ($obj->set($type, $prefs[$type])) $count++; } foreach (array_keys($this->_prefs) as $type) { $obj =& $this->_prefs[$type]; $obj->_init = $init; - if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool")) + if (!isset($prefs[$type]) and isa($obj, "_UserPreference_bool")) $prefs[$type] = false; - if (isset($prefs[$type]) and isa($obj,"_UserPreference_int")) - $prefs[$type] = (int) $prefs[$type]; + if (isset($prefs[$type]) and isa($obj, "_UserPreference_int")) + $prefs[$type] = (int)$prefs[$type]; if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) { // special systemdefault prefs: if ($type == 'theme' and $prefs[$type] == '' and - $obj->get($type) == THEME) continue; + $obj->get($type) == THEME + ) continue; if ($type == 'lang' and $prefs[$type] == '' and - $obj->get($type) == DEFAULT_LANGUAGE) continue; - if ($obj->set($type,$prefs[$type])) + $obj->get($type) == DEFAULT_LANGUAGE + ) continue; + if ($obj->set($type, $prefs[$type])) $count++; } } @@ -2107,7 +2200,8 @@ class UserPreferences // For now convert just array of objects => array of values // Todo: the specialized subobjects must override this. - function store() { + function store() + { $prefs = array(); foreach ($this->_prefs as $name => $object) { if ($value = $object->getraw($name)) @@ -2137,7 +2231,8 @@ class UserPreferences // packed string or array of values => array of values // Todo: the specialized subobjects must override this. - function retrieve($packed) { + function retrieve($packed) + { if (is_string($packed) and (substr($packed, 0, 2) == "a:")) $packed = unserialize($packed); if (!is_array($packed)) return false; @@ -2145,19 +2240,19 @@ class UserPreferences foreach ($packed as $name => $packed_pref) { if (is_string($packed_pref) and isSerialized($packed_pref) - and substr($packed_pref, 0, 2) == "O:") - { + and substr($packed_pref, 0, 2) == "O:" + ) { //legacy: check if it's an old array of objects // Looks like a serialized object. // This might fail if the object definition does not exist anymore. // object with ->$name and ->default_value vars. - $pref = @unserialize($packed_pref); + $pref = @unserialize($packed_pref); if (is_object($pref)) $prefs[$name] = $pref->get($name); - // fix old-style prefs + // fix old-style prefs } elseif (is_numeric($name) and is_array($packed_pref)) { if (count($packed_pref) == 1) { - list($name,$value) = each($packed_pref); + list($name, $value) = each($packed_pref); $prefs[$name] = $value; } } else { @@ -2191,7 +2286,8 @@ class UserPreferences /** * Check if the given prefs object is different from the current prefs object */ - function isChanged($other) { + function isChanged($other) + { foreach ($this->_prefs as $type => $obj) { if ($obj->get($type) !== $other->get($type)) return true; @@ -2199,7 +2295,8 @@ class UserPreferences return false; } - function defaultPreferences() { + function defaultPreferences() + { $prefs = array(); foreach ($this->_prefs as $key => $obj) { $prefs[$key] = $obj->default_value; @@ -2208,15 +2305,18 @@ class UserPreferences } // array of objects - function getAll() { + function getAll() + { return $this->_prefs; } - function pack($nonpacked) { + function pack($nonpacked) + { return serialize($nonpacked); } - function unpack($packed) { + function unpack($packed) + { if (!$packed) return false; //$packed = base64_decode($packed); @@ -2232,7 +2332,8 @@ class UserPreferences return false; } - function hash () { + function hash() + { return wikihash($this->_prefs); } } diff --git a/lib/WysiwygEdit.php b/lib/WysiwygEdit.php index baa3ec595..1ee24d8b9 100644 --- a/lib/WysiwygEdit.php +++ b/lib/WysiwygEdit.php @@ -23,18 +23,22 @@ require_once 'lib/InlineParser.php'; -class WysiwygEdit { +class WysiwygEdit +{ - function WysiwygEdit() { + function WysiwygEdit() + { $this->_transformer_tags = false; } - function Head($name='edit[content]') { + function Head($name = 'edit[content]') + { trigger_error("virtual", E_USER_ERROR); } // to be called after - function Textarea($textarea,$wikitext,$name='edit[content]') { + function Textarea($textarea, $wikitext, $name = 'edit[content]') + { trigger_error("virtual", E_USER_ERROR); } @@ -43,7 +47,8 @@ class WysiwygEdit { * This will be converted back by WysiwygEdit_ConvertAfter if required. * *text* => 'text' */ - function ConvertBefore($text) { + function ConvertBefore($text) + { require_once 'lib/BlockParser.php'; $xml = TransformText($text, 2.0, $GLOBALS['request']->getArg('pagename')); return $xml->AsXML(); @@ -56,7 +61,8 @@ class WysiwygEdit { * * TODO: Switch over to HtmlParser */ - function ConvertAfter($text) { + function ConvertAfter($text) + { static $trfm; if (empty($trfm)) { $trfm = new HtmlTransformer($this->_transformer_tags); @@ -68,24 +74,28 @@ class WysiwygEdit { // re-use these classes for the regexp's. // just output strings instead of XmlObjects -class Markup_html_br extends Markup_linebreak { - function markup ($match) { +class Markup_html_br extends Markup_linebreak +{ + function markup($match) + { return $match; } } -class Markup_html_simple_tag extends Markup_html_emphasis { - function markup ($match, $body) { +class Markup_html_simple_tag extends Markup_html_emphasis +{ + function markup($match, $body) + { $tag = substr($match, 1, -1); switch ($tag) { - case 'b': - case 'strong': - return "*".$body."*"; - case 'big': - return "".$body.""; - case 'i': - case 'em': - return "_".$body."_"; + case 'b': + case 'strong': + return "*" . $body . "*"; + case 'big': + return "" . $body . ""; + case 'i': + case 'em': + return "_" . $body . "_"; } } } @@ -94,11 +104,14 @@ class Markup_html_p extends BalancedMarkup { var $_start_regexp = "<(?:p|P)( class=\".*\")?>"; - function getEndRegexp ($match) { + function getEndRegexp($match) + { return "<\\/" . substr($match, 1); } - function markup ($match, $body) { - return $body."\n"; + + function markup($match, $body) + { + return $body . "\n"; } } @@ -107,21 +120,25 @@ class Markup_html_spanbold extends BalancedMarkup { var $_start_regexp = "<(?:span|SPAN) style=\"FONT-WEIGHT: bold\">"; - function getEndRegexp ($match) { + function getEndRegexp($match) + { return "<\\/" . substr($match, 1); } - function markup ($match, $body) { + + function markup($match, $body) + { //Todo: convert style formatting to simplier nested tags - return "*".$body."*"; + return "*" . $body . "*"; } } class HtmlTransformer extends InlineTransformer { - function HtmlTransformer ($tags = false) { + function HtmlTransformer($tags = false) + { if (!$tags) $tags = - array('escape','html_br','html_spanbold','html_simple_tag', - 'html_p',); + array('escape', 'html_br', 'html_spanbold', 'html_simple_tag', + 'html_p',); /* 'html_a','html_span','html_div', 'html_table','html_hr','html_pre', diff --git a/lib/WysiwygEdit/FCKeditor.php b/lib/WysiwygEdit/FCKeditor.php index 427e90316..0ad4ae68d 100644 --- a/lib/WysiwygEdit/FCKeditor.php +++ b/lib/WysiwygEdit/FCKeditor.php @@ -15,13 +15,15 @@ require_once 'lib/WysiwygEdit.php'; -class WysiwygEdit_FCKeditor extends WysiwygEdit { +class WysiwygEdit_FCKeditor extends WysiwygEdit +{ - function WysiwygEdit_FCKeditor() { + function WysiwygEdit_FCKeditor() + { global $LANG; $this->_transformer_tags = false; - $this->BasePath = DATA_PATH.'/themes/default/FCKeditor/'; - $this->_htmltextid = "edit-content"; // FCKEditor1; + $this->BasePath = DATA_PATH . '/themes/default/FCKeditor/'; + $this->_htmltextid = "edit-content"; // FCKEditor1; $this->_wikitextid = "editareawiki"; $this->_jsdefault = " oFCKeditor.BasePath = '$this->BasePath'; @@ -35,73 +37,78 @@ oFCKeditor.Config.ImageBrowserURL = oFCKeditor.BasePath + 'editor/filemanager/br $this->_jsdefault = "\noFCKeditor.Config.Debug = true;"; } - function Head($name='edit[content]') { + function Head($name = 'edit[content]') + { global $WikiTheme; $WikiTheme->addMoreHeaders - (Javascript('', array('src' => $this->BasePath . 'fckeditor.js', - 'language' => 'JavaScript'))); - return JavaScript(" + (Javascript('', array('src' => $this->BasePath . 'fckeditor.js', + 'language' => 'JavaScript'))); + return JavaScript(" window.onload = function() { var oFCKeditor = new FCKeditor( '$this->_htmltextid' ) ;" -. $this->_jsdefault . " + . $this->_jsdefault . " // force textarea in favor of iFrame? // oFCKeditor._IsCompatibleBrowser = function() { return false; } oFCKeditor.ReplaceTextarea(); }"); } - function Textarea ($textarea, $wikitext, $name='edit[content]') { + function Textarea($textarea, $wikitext, $name = 'edit[content]') + { return $this->Textarea_Replace($textarea, $wikitext, $name); } /* either iframe or textarea */ - function Textarea_Create ($textarea, $wikitext, $name='edit[content]') { + function Textarea_Create($textarea, $wikitext, $name = 'edit[content]') + { $htmltextid = $name; $out = HTML( JavaScript(" var oFCKeditor = new FCKeditor( '$htmltextid' ) ; oFCKeditor.Value = '" . $textarea->_content[0]->asXML() . "';" -. $this->_jsdefault . " + . $this->_jsdefault . " oFCKeditor.Create();"), - HTML::div(array("id" => $this->_wikitextid, + HTML::div(array("id" => $this->_wikitextid, 'style' => 'display:none'), - $wikitext), + $wikitext), "\n"); - return $out; + return $out; } /* textarea only */ - function Textarea_Replace ($textarea, $wikitext, $name='edit[content]') { + function Textarea_Replace($textarea, $wikitext, $name = 'edit[content]') + { $htmltextid = $this->_htmltextid; $textarea->SetAttr('id', $htmltextid); $out = HTML($textarea, - HTML::div(array("id" => $this->_wikitextid, + HTML::div(array("id" => $this->_wikitextid, 'style' => 'display:none'), - $wikitext), + $wikitext), "\n"); - return $out; + return $out; } /* via the PHP object */ - function Textarea_PHP ($textarea, $wikitext, $name='edit[content]') { + function Textarea_PHP($textarea, $wikitext, $name = 'edit[content]') + { global $LANG; - $this->FilePath = realpath(PHPWIKI_DIR.'/themes/default/FCKeditor') . "/"; + $this->FilePath = realpath(PHPWIKI_DIR . '/themes/default/FCKeditor') . "/"; $htmltextid = "edit-content"; - include_once($this->FilePath . 'fckeditor.php'); - $this->oFCKeditor = new FCKeditor($htmltextid) ; - $this->oFCKeditor->BasePath = $this->BasePath; - $this->oFCKeditor->Value = $textarea->_content[0]->asXML(); + include_once($this->FilePath . 'fckeditor.php'); + $this->oFCKeditor = new FCKeditor($htmltextid); + $this->oFCKeditor->BasePath = $this->BasePath; + $this->oFCKeditor->Value = $textarea->_content[0]->asXML(); - $this->oFCKeditor->Config['AutoDetectLanguage'] = true ; - $this->oFCKeditor->Config['DefaultLanguage'] = $LANG; - $this->oFCKeditor->Create(); + $this->oFCKeditor->Config['AutoDetectLanguage'] = true; + $this->oFCKeditor->Config['DefaultLanguage'] = $LANG; + $this->oFCKeditor->Create(); - return HTML::div(array("id" => $this->_wikitextid, - 'style' => 'display:none'), - $wikitext); + return HTML::div(array("id" => $this->_wikitextid, + 'style' => 'display:none'), + $wikitext); } } diff --git a/lib/WysiwygEdit/Wikiwyg.php b/lib/WysiwygEdit/Wikiwyg.php index 8cc371e18..1e9fb7b08 100644 --- a/lib/WysiwygEdit/Wikiwyg.php +++ b/lib/WysiwygEdit/Wikiwyg.php @@ -15,32 +15,35 @@ require_once 'lib/WysiwygEdit.php'; -class WysiwygEdit_Wikiwyg extends WysiwygEdit { +class WysiwygEdit_Wikiwyg extends WysiwygEdit +{ - function WysiwygEdit_Wikiwyg() { + function WysiwygEdit_Wikiwyg() + { global $request, $LANG; $this->_transformer_tags = false; - $this->BasePath = DATA_PATH.'/themes/default/Wikiwyg'; - $this->_htmltextid = "edit-content"; + $this->BasePath = DATA_PATH . '/themes/default/Wikiwyg'; + $this->_htmltextid = "edit-content"; $this->_wikitextid = "editareawiki"; - $script_url = deduce_script_name(); - if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug'])) - $script_url .= ("?start_debug=".$_GET['start_debug']); + $script_url = deduce_script_name(); + if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug'])) + $script_url .= ("?start_debug=" . $_GET['start_debug']); $this->_jsdefault = ""; } - function Head($name='edit[content]') { + function Head($name = 'edit[content]') + { global $WikiTheme; - foreach (array("Wikiwyg.js","Wikiwyg/Toolbar.js","Wikiwyg/Preview.js","Wikiwyg/Wikitext.js", - "Wikiwyg/Wysiwyg.js","Wikiwyg/Phpwiki.js","Wikiwyg/HTML.js", - "Wikiwyg/Toolbar.js") as $js) { + foreach (array("Wikiwyg.js", "Wikiwyg/Toolbar.js", "Wikiwyg/Preview.js", "Wikiwyg/Wikitext.js", + "Wikiwyg/Wysiwyg.js", "Wikiwyg/Phpwiki.js", "Wikiwyg/HTML.js", + "Wikiwyg/Toolbar.js") as $js) { $WikiTheme->addMoreHeaders - (Javascript('', array('src' => $this->BasePath . '/' . $js, - 'language' => 'JavaScript'))); + (Javascript('', array('src' => $this->BasePath . '/' . $js, + 'language' => 'JavaScript'))); } $doubleClickToEdit = ($GLOBALS['request']->getPref('doubleClickEdit') or ENABLE_DOUBLECLICKEDIT) ? 'true' : 'false'; - if ($GLOBALS['request']->getArg('mode') && $GLOBALS['request']->getArg('mode') == 'wysiwyg'){ + if ($GLOBALS['request']->getArg('mode') && $GLOBALS['request']->getArg('mode') == 'wysiwyg') { return JavaScript($this->_jsdefault . " window.onload = function() { var wikiwyg = new Wikiwyg.Phpwiki(); @@ -66,18 +69,18 @@ class WysiwygEdit_Wikiwyg extends WysiwygEdit { 'label', 'p', 'h2', 'h3', 'h4', 'pre' ], controlLabels: { - save: '"._("Apply changes")."', - cancel: '"._("Exit toolbar")."', - h2: '"._("Title 1")."', - h3: '"._("Title 2")."', - h4: '"._("Title 3")."', - verbatim: '"._("Verbatim")."', - toc: '"._("Table of Contents")."', - wikitext: '"._("Insert Wikitext section")."', - sup: '"._("Sup")."', - sub: '"._("Sub")."', - preview: '"._("Preview")."', - save_button:'"._("Save")."' + save: '" . _("Apply changes") . "', + cancel: '" . _("Exit toolbar") . "', + h2: '" . _("Title 1") . "', + h3: '" . _("Title 2") . "', + h4: '" . _("Title 3") . "', + verbatim: '" . _("Verbatim") . "', + toc: '" . _("Table of Contents") . "', + wikitext: '" . _("Insert Wikitext section") . "', + sup: '" . _("Sup") . "', + sub: '" . _("Sub") . "', + preview: '" . _("Preview") . "', + save_button:'" . _("Save") . "' } }, wysiwyg: { @@ -91,26 +94,27 @@ class WysiwygEdit_Wikiwyg extends WysiwygEdit { wikiwyg.createWikiwygArea(div, config); wikiwyg_divs.push(wikiwyg); wikiwyg.editMode();}" - ); + ); } } - function Textarea ($textarea, $wikitext, $name='edit[content]') { + function Textarea($textarea, $wikitext, $name = 'edit[content]') + { global $request; $htmltextid = $this->_htmltextid; $textarea->SetAttr('id', $htmltextid); $iframe0 = new RawXml(''); - if ($request->getArg('mode') and $request->getArg('mode') == 'wysiwyg'){ - $out = HTML(HTML::div(array('class' => 'hint'), - _("Warning: This Wikiwyg editor has only Beta quality!")), - $textarea, - $iframe0, + if ($request->getArg('mode') and $request->getArg('mode') == 'wysiwyg') { + $out = HTML(HTML::div(array('class' => 'hint'), + _("Warning: This Wikiwyg editor has only Beta quality!")), + $textarea, + $iframe0, "\n"); - } else { - $out = HTML($textarea, $iframe0, "\n"); - } - return $out; + } else { + $out = HTML($textarea, $iframe0, "\n"); + } + return $out; } /** @@ -118,7 +122,8 @@ class WysiwygEdit_Wikiwyg extends WysiwygEdit { * This will be converted back by WysiwygEdit_ConvertAfter if required. * *text* => 'text' */ - function ConvertBefore($text) { + function ConvertBefore($text) + { return $text; } @@ -126,94 +131,103 @@ class WysiwygEdit_Wikiwyg extends WysiwygEdit { * No special PHP HTML->Wikitext conversion needed. This is done in js thanksfully. * Avoided in editpage.php: PageEditor->getContent */ - function ConvertAfter($text) { + function ConvertAfter($text) + { return TransformInline($text); } } -class WikiToHtml { - function WikiToHtml ($wikitext, &$request) { +class WikiToHtml +{ + function WikiToHtml($wikitext, &$request) + { $this->_wikitext = $wikitext; - $this->_request =& $request; - $this->_html = ""; - $this->html_content = ""; + $this->_request =& $request; + $this->_html = ""; + $this->html_content = ""; } - function send() { + function send() + { $this->convert(); - echo $this->html_content; + echo $this->html_content; } - function convert() { + function convert() + { require_once 'lib/BlockParser.php'; - $xmlcontent = TransformText($this->_wikitext, 2.0, $this->_request->getArg('pagename')); - $this->_html = $xmlcontent->AsXML(); + $xmlcontent = TransformText($this->_wikitext, 2.0, $this->_request->getArg('pagename')); + $this->_html = $xmlcontent->AsXML(); - $this->replace_inside_html(); + $this->replace_inside_html(); } - function replace_inside_html() { - global $charset; + function replace_inside_html() + { + global $charset; - $this->clean_links(); + $this->clean_links(); $this->clean_plugin_name(); $this->replace_known_plugins(); $this->replace_unknown_plugins(); - // $this->replace_tags(); - $this->clean_plugin(); + // $this->replace_tags(); + $this->clean_plugin(); - if ($charset != 'utf-8') { - if ($charset == 'iso-8959-1') { - $this->_html = utf8_decode($this->_html); - } else { + if ($charset != 'utf-8') { + if ($charset == 'iso-8959-1') { + $this->_html = utf8_decode($this->_html); + } else { // check for iconv support loadPhpExtension("iconv"); - $this->_html = iconv("UTF-8", $charset, $this->_html); - } + $this->_html = iconv("UTF-8", $charset, $this->_html); + } } - $this->html_content = $this->_html; + $this->html_content = $this->_html; } // Draft function to replace RichTable // by a html table // Works only on one plugin for the moment - function replace_known_plugins() { - // If match a plugin - $pattern = '/\<\;\?plugin\s+RichTable(.*)\?\>\;/Umsi'; - $replace_string = "replace_rich_table"; - $this->_html = preg_replace_callback($pattern, - $replace_string, - $this->_html); + function replace_known_plugins() + { + // If match a plugin + $pattern = '/\<\;\?plugin\s+RichTable(.*)\?\>\;/Umsi'; + $replace_string = "replace_rich_table"; + $this->_html = preg_replace_callback($pattern, + $replace_string, + $this->_html); } // Replace unknown plugins by keyword Wikitext { tag } - function replace_unknown_plugins() { + function replace_unknown_plugins() + { $pattern = '/(\<\;\?plugin[^?]*\?\>\;)/Usi'; - $replace_string = - '

    Wikitext { + $replace_string = + '

    Wikitext {
    \1
    }

    '; - $this->_html = preg_replace($pattern, - $replace_string, - $this->_html); + $this->_html = preg_replace($pattern, + $replace_string, + $this->_html); } // Clean links to keep only name - function clean_links() { + function clean_links() + { // Existing links // FIXME: use VIRTUAL_PATH $pattern = '/\])*\>/Umsi'; $replace_string = ''; $this->_html = preg_replace($pattern, - $replace_string, - $this->_html) ; + $replace_string, + $this->_html); // Non existing links $pattern = '/\])*\>/Umsi'; $replace_string = ''; $this->_html = preg_replace($pattern, - $replace_string, - $this->_html) ; + $replace_string, + $this->_html); // Clean underline $pattern = '/\(.*)\<\/u\>(\.*\<\/a\>/Umsi'; @@ -221,12 +235,13 @@ class WikiToHtml { '\2" style="color:blue;">\1'; $this->_html = preg_replace($pattern, - $replace_string, - $this->_html) ; + $replace_string, + $this->_html); } // Put unknown tags in Wikitext {} - function replace_tags() { + function replace_tags() + { // Replace old table format ( non plugin ) $pattern = '/(\ {0,4}(?:\S.*)?\|\S+\s*$.*?\<\/p\>)/ms'; $replace_string = @@ -234,67 +249,70 @@ class WikiToHtml {
    \1
    }

    '; $this->_html = preg_replace($pattern, - $replace_string, - $this->_html); -} + $replace_string, + $this->_html); + } // Replace \n by
    only in // tag to keep formatting - function clean_plugin() { + function clean_plugin() + { $pattern = '/(\<\;\?plugin.*\?\>\;)/Umsei'; - $replace_string = 'preg_replace("/\n/Ums","
    ","\1")'; + $replace_string = 'preg_replace("/\n/Ums","
    ","\1")'; - $this->_html = preg_replace($pattern, - $replace_string, - $this->_html) ; + $this->_html = preg_replace($pattern, + $replace_string, + $this->_html); } - function clean_plugin_name() { - // Remove plugin name converted in a link - $pattern = '/(\<\;\?plugin\s)\\\(\w+)\<\/a\><\/span\><\/span>([^?]*\?\>\;)/Umsi'; - $replace_string = '\1 \2 \3'; - $this->_html = preg_replace($pattern, - $replace_string, - $this->_html) ; + function clean_plugin_name() + { + // Remove plugin name converted in a link + $pattern = '/(\<\;\?plugin\s)\\\(\w+)\<\/a\><\/span\><\/span>([^?]*\?\>\;)/Umsi'; + $replace_string = '\1 \2 \3'; + $this->_html = preg_replace($pattern, + $replace_string, + $this->_html); } } // This is called to replace the RichTable plugin by an html table // $matched contains html

    tags so // they are deleted before the conversion. -function replace_rich_table($matched) { +function replace_rich_table($matched) +{ $plugin = $matched[1]; $unknown_options = "/colspan|rowspan|width|height/"; // if the plugin contains one of the options bellow // it won't be converted - if (preg_match($unknown_options,$plugin)) - return $matched[0]."\n"; + if (preg_match($unknown_options, $plugin)) + return $matched[0] . "\n"; else { //Replace unused $pattern = '/\/Umsi'; $replace_string = ""; $plugin = preg_replace($pattern, - $replace_string, - $plugin) ; + $replace_string, + $plugin); //replace unused

    by \n $pattern = '/\<\/p\>/Umsi'; $replace_string = "\n"; $plugin = preg_replace($pattern, - $replace_string, - $plugin) ; + $replace_string, + $plugin); - $plugin = ""; + $plugin = ""; require_once 'lib/BlockParser.php'; $xmlcontent = TransformText($plugin, 2.0, $GLOBALS['request']->getArg('pagename')); return $xmlcontent->AsXML(); - } + } } // Local Variables: diff --git a/lib/WysiwygEdit/htmlarea2.php b/lib/WysiwygEdit/htmlarea2.php index c0bbb1cfa..a4e6631c0 100644 --- a/lib/WysiwygEdit/htmlarea2.php +++ b/lib/WysiwygEdit/htmlarea2.php @@ -13,11 +13,13 @@ require_once 'lib/WysiwygEdit.php'; -class WysiwygEdit_htmlarea2 extends WysiwygEdit { +class WysiwygEdit_htmlarea2 extends WysiwygEdit +{ - function Head($name='edit[content]') { + function Head($name = 'edit[content]') + { return JavaScript(" -_editor_url = \"".DATA_PATH."/themes/default/htmlarea2/\"; +_editor_url = \"" . DATA_PATH . "/themes/default/htmlarea2/\"; var win_ie_ver = parseFloat(navigator.appVersion.split(\"MSIE\")[1]); if (navigator.userAgent.indexOf('Mac') >= 0) { win_ie_ver = 0; } if (navigator.userAgent.indexOf('Windows CE') >= 0) { win_ie_ver = 0; } @@ -30,16 +32,17 @@ if (win_ie_ver >= 5.5) { } ", array('version' => 'JavaScript1.2', - 'type' => 'text/javascript')); + 'type' => 'text/javascript')); } // to be called after // version 2 - function Textarea($textarea,$wikitext,$name='edit[content]') { + function Textarea($textarea, $wikitext, $name = 'edit[content]') + { $out = HTML($textarea); - $out->pushContent(JavaScript("editor_generate('".$name."');", - array('version' => 'JavaScript1.2', - 'defer' => 1))); + $out->pushContent(JavaScript("editor_generate('" . $name . "');", + array('version' => 'JavaScript1.2', + 'defer' => 1))); return $out; } } diff --git a/lib/WysiwygEdit/htmlarea3.php b/lib/WysiwygEdit/htmlarea3.php index 338125062..6bc09e420 100644 --- a/lib/WysiwygEdit/htmlarea3.php +++ b/lib/WysiwygEdit/htmlarea3.php @@ -10,24 +10,26 @@ require_once 'lib/WysiwygEdit.php'; -class WysiwygEdit_htmlarea3 extends WysiwygEdit { +class WysiwygEdit_htmlarea3 extends WysiwygEdit +{ - function Head($name='edit[content]') { + function Head($name = 'edit[content]') + { global $WikiTheme; - $WikiTheme->addMoreAttr('body'," onload='initEditor()'"); + $WikiTheme->addMoreAttr('body', " onload='initEditor()'"); //Todo: language selection from available lang/*.js files return new RawXml(' - - - + + + - + +Alpha Channel Test + + + \n"); +while ($fileName = readdir($dir)) + if (!(strcmp(substr($fileName, -4), ".png"))) + print("\"$fileName\"\n"); ?>
    bgcolor:
    - + + diff --git a/themes/MacOSX/lib/RecentChanges.php b/themes/MacOSX/lib/RecentChanges.php index 073b1808d..a97548edc 100644 --- a/themes/MacOSX/lib/RecentChanges.php +++ b/themes/MacOSX/lib/RecentChanges.php @@ -6,45 +6,49 @@ require_once 'lib/plugin/RecentChanges.php'; require_once 'lib/plugin/PageHistory.php'; -function MacOSX_RC_revision_formatter (&$fmt, &$rev) { +function MacOSX_RC_revision_formatter(&$fmt, &$rev) +{ $class = 'rc-' . $fmt->importance($rev); return HTML::li(array('class' => $class), - $fmt->diffLink($rev), ' ', - $fmt->pageLink($rev), ' ', - $rev->get('is_minor_edit') ? $fmt->time($rev) : HTML::strong($fmt->time($rev)), - ' . . . ', - $fmt->summaryAsHTML($rev), - ' -- ', - $fmt->authorLink($rev)); + $fmt->diffLink($rev), ' ', + $fmt->pageLink($rev), ' ', + $rev->get('is_minor_edit') ? $fmt->time($rev) : HTML::strong($fmt->time($rev)), + ' . . . ', + $fmt->summaryAsHTML($rev), + ' -- ', + $fmt->authorLink($rev)); } -function MacOSX_PH_revision_formatter (&$fmt, &$rev) { +function MacOSX_PH_revision_formatter(&$fmt, &$rev) +{ $class = 'rc-' . $fmt->importance($rev); return HTML::li(array('class' => $class), - $fmt->diffLink($rev), ' ', - $fmt->pageLink($rev), ' ', - $rev->get('is_minor_edit') ? $fmt->time($rev) : HTML::strong($fmt->time($rev)), - ' . . . ', - $fmt->summaryAsHTML($rev), - ' -- ', - $fmt->authorLink($rev), - $rev->get('is_minor_edit') ? HTML::em(" (" . _("minor edit") . ")") : ''); + $fmt->diffLink($rev), ' ', + $fmt->pageLink($rev), ' ', + $rev->get('is_minor_edit') ? $fmt->time($rev) : HTML::strong($fmt->time($rev)), + ' . . . ', + $fmt->summaryAsHTML($rev), + ' -- ', + $fmt->authorLink($rev), + $rev->get('is_minor_edit') ? HTML::em(" (" . _("minor edit") . ")") : ''); } class _MacOSX_RecentChanges_Formatter -extends _RecentChanges_HtmlFormatter + extends _RecentChanges_HtmlFormatter { - function format_revision (&$rev) { + function format_revision(&$rev) + { return MacOSX_RC_revision_formatter($this, $rev); } } class _MacOSX_PageHistory_Formatter -extends _PageHistory_HtmlFormatter + extends _PageHistory_HtmlFormatter { - function format_revision (&$rev) { + function format_revision(&$rev) + { return MacOSX_PH_revision_formatter($this, $rev); } } diff --git a/themes/MacOSX/themeinfo.php b/themes/MacOSX/themeinfo.php index 26aa4a15d..ff6529ef9 100644 --- a/themes/MacOSX/themeinfo.php +++ b/themes/MacOSX/themeinfo.php @@ -31,42 +31,46 @@ if (!defined('PHPWIKI_VERSION')) { require_once 'lib/WikiTheme.php'; -class WikiTheme_MacOSX extends WikiTheme { - function getCSS() { +class WikiTheme_MacOSX extends WikiTheme +{ + function getCSS() + { // FIXME: this is a hack which will not be needed once // we have dynamic CSS. $css = WikiTheme::getCSS(); $css->pushcontent(HTML::style(array('type' => 'text/css'), - new RawXml(sprintf("\n", - $this->getImageURL('bgpaper8'))))); - //for non-browse pages, like former editpage, message etc. - //$this->getImageURL('bggranular'))); + new RawXml(sprintf("\n", + $this->getImageURL('bgpaper8'))))); + //for non-browse pages, like former editpage, message etc. + //$this->getImageURL('bggranular'))); return $css; } - function getRecentChangesFormatter ($format) { + function getRecentChangesFormatter($format) + { include_once($this->file('lib/RecentChanges.php')); if (preg_match('/^rss|^sidebar/', $format)) - return false; // use default + return false; // use default return '_MacOSX_RecentChanges_Formatter'; } - function getPageHistoryFormatter ($format) { + function getPageHistoryFormatter($format) + { include_once($this->file('lib/RecentChanges.php')); if (preg_match('/^rss|^sidebar/', $format)) - return false; // use default + return false; // use default return '_MacOSX_PageHistory_Formatter'; } - function linkUnknownWikiWord($wikiword, $linktext = '') { + function linkUnknownWikiWord($wikiword, $linktext = '') + { global $request; // Get rid of anchors on unknown wikiwords if (isa($wikiword, 'WikiPageName')) { $default_text = $wikiword->shortName; $wikiword = $wikiword->name; - } - else { + } else { $default_text = $wikiword; } @@ -80,8 +84,7 @@ class WikiTheme_MacOSX extends WikiTheme { if (!empty($linktext)) { $link->unshiftContent(HTML::u($linktext)); $link->setAttr('class', 'named-wikiunknown'); - } - else { + } else { $link->unshiftContent(HTML::u($this->maybeSplitWikiWord($default_text))); $link->setAttr('class', 'wikiunknown'); } @@ -89,69 +92,70 @@ class WikiTheme_MacOSX extends WikiTheme { return $link; } - function load() { - // CSS file defines fonts, colors and background images for this - // style. The companion '*-heavy.css' file isn't defined, it's just - // expected to be in the same directory that the base style is in. - - // This should result in phpwiki-printer.css being used when - // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. - $this->setDefaultCSS('MacOSX', array('' => 'MacOSX.css', 'print' => 'phpwiki-printer.css')); - - // This allows one to manually select "Printer" style (when browsing page) - // to see what the printer style looks like. - $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); - $this->addAlternateCSS(_("Top & bottom toolbars"), 'MacOSX-topbottombars.css'); - - /** - * The logo image appears on every page and links to the HomePage. - */ - $this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); - - /** - * The Signature image is shown after saving an edited page. If this - * is set to false then the "Thank you for editing..." screen will - * be omitted. - */ - $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); - // Uncomment this next line to disable the signature. - //$this->addImageAlias('signature', false); - - /* - * Link icons. - */ - $this->setLinkIcon('http'); - $this->setLinkIcon('https'); - $this->setLinkIcon('ftp'); - $this->setLinkIcon('mailto'); - $this->setLinkIcon('interwiki'); - $this->setLinkIcon('wikiuser'); - $this->setLinkIcon('*', 'url'); - - $this->setButtonSeparator(""); //use no separator instead of default - - $this->addButtonAlias('?', 'uww'); - $this->addButtonAlias(_("Lock Page"), "Lock Page"); - $this->addButtonAlias(_("Unlock Page"), "Unlock Page"); - $this->addButtonAlias(_("Page Locked"), "Page Locked"); - $this->addButtonAlias("...", "alltime"); - - /** - * WikiWords can automatically be split by inserting spaces between - * the words. The default is to leave WordsSmashedTogetherLikeSo. - */ - //$this->setAutosplitWikiWords(false); - - /* - * You may adjust the formats used for formatting dates and times - * below. (These examples give the default formats.) - * Formats are given as format strings to PHP strftime() function See - * http://www.php.net/manual/en/function.strftime.php for details. - * Do not include the server's zone (%Z), times are converted to the - * user's time zone. - */ - $this->setDateFormat("%A, %B %d, %Y"); // must not contain time - $this->setTimeFormat("%I:%M:%S %p"); + function load() + { + // CSS file defines fonts, colors and background images for this + // style. The companion '*-heavy.css' file isn't defined, it's just + // expected to be in the same directory that the base style is in. + + // This should result in phpwiki-printer.css being used when + // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. + $this->setDefaultCSS('MacOSX', array('' => 'MacOSX.css', 'print' => 'phpwiki-printer.css')); + + // This allows one to manually select "Printer" style (when browsing page) + // to see what the printer style looks like. + $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); + $this->addAlternateCSS(_("Top & bottom toolbars"), 'MacOSX-topbottombars.css'); + + /** + * The logo image appears on every page and links to the HomePage. + */ + $this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); + + /** + * The Signature image is shown after saving an edited page. If this + * is set to false then the "Thank you for editing..." screen will + * be omitted. + */ + $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); + // Uncomment this next line to disable the signature. + //$this->addImageAlias('signature', false); + + /* + * Link icons. + */ + $this->setLinkIcon('http'); + $this->setLinkIcon('https'); + $this->setLinkIcon('ftp'); + $this->setLinkIcon('mailto'); + $this->setLinkIcon('interwiki'); + $this->setLinkIcon('wikiuser'); + $this->setLinkIcon('*', 'url'); + + $this->setButtonSeparator(""); //use no separator instead of default + + $this->addButtonAlias('?', 'uww'); + $this->addButtonAlias(_("Lock Page"), "Lock Page"); + $this->addButtonAlias(_("Unlock Page"), "Unlock Page"); + $this->addButtonAlias(_("Page Locked"), "Page Locked"); + $this->addButtonAlias("...", "alltime"); + + /** + * WikiWords can automatically be split by inserting spaces between + * the words. The default is to leave WordsSmashedTogetherLikeSo. + */ + //$this->setAutosplitWikiWords(false); + + /* + * You may adjust the formats used for formatting dates and times + * below. (These examples give the default formats.) + * Formats are given as format strings to PHP strftime() function See + * http://www.php.net/manual/en/function.strftime.php for details. + * Do not include the server's zone (%Z), times are converted to the + * user's time zone. + */ + $this->setDateFormat("%A, %B %d, %Y"); // must not contain time + $this->setTimeFormat("%I:%M:%S %p"); } } diff --git a/themes/MonoBook/themeinfo.php b/themes/MonoBook/themeinfo.php index d43250b23..4871e8fdd 100644 --- a/themes/MonoBook/themeinfo.php +++ b/themes/MonoBook/themeinfo.php @@ -18,7 +18,8 @@ if (!defined('PHPWIKI_VERSION')) { require_once 'lib/WikiTheme.php'; require_once 'themes/wikilens/themeinfo.php'; -function ActionButton ($action, $label = false, $page_or_rev = false, $options = false) { +function ActionButton($action, $label = false, $page_or_rev = false, $options = false) +{ global $WikiTheme; global $request; if (is_array($action)) { @@ -33,34 +34,35 @@ function ActionButton ($action, $label = false, $page_or_rev = false, $options = $class = "selected $class"; if (!empty($options['class'])) { if ($curract == 'browse') - $class = "$class ".$options['class']; + $class = "$class " . $options['class']; else $class = $options['class']; } return HTML::li(array('class' => $class), - $WikiTheme->makeActionButton($action, $label, $page_or_rev, $options)); + $WikiTheme->makeActionButton($action, $label, $page_or_rev, $options)); } class WikiTheme_MonoBook extends WikiTheme_Wikilens { /* this adds selected to the class */ - function makeActionButton ($action, $label=false, $page_or_rev=false, $options=false) { + function makeActionButton($action, $label = false, $page_or_rev = false, $options = false) + { extract($this->_get_name_and_rev($page_or_rev)); if (is_array($action)) { $attr = $action; $action = isset($attr['action']) ? $attr['action'] : 'browse'; - } - else + } else $attr['action'] = $action; - $class = is_safe_action($action) ? /*'named-wiki'*/'new' : 'wikiadmin'; + $class = is_safe_action($action) ? /*'named-wiki'*/ + 'new' : 'wikiadmin'; /* if selected action is current then prepend selected */ global $request; if ($request->getArg("action") == $action) $class = "selected $class"; - //$class = "selected"; + //$class = "selected"; if (!empty($options['class'])) $class = $options['class']; if (!$label) @@ -76,91 +78,92 @@ class WikiTheme_MonoBook extends WikiTheme_Wikilens return $this->makeButton($label, WikiURL($pagename, $attr), $class, $options); } - function load() { - $this->addMoreHeaders(JavaScript("var ta;\nvar skin = '".$this->_name."';\n")); - $this->addMoreHeaders(JavaScript('',array('src' => $this->_findData("wikibits.js")))); - if (isBrowserIE()) { - $ver = browserVersion(); - if ($ver > 5.5 and $ver < 7.0) - $this->addMoreHeaders($this->_CSSlink(0,$this->_findFile('IE60Fixes.css'),'all')); - elseif ($ver >= 7.0) - $this->addMoreHeaders($this->_CSSlink(0,$this->_findFile('IE70Fixes.css'),'all')); - unset($ver); - $this->addMoreHeaders("\n"); - $this->addMoreHeaders(JavaScript('',array('src' => $this->_findData("IEFixes.js")))); - $this->addMoreHeaders("\n"); - $this->addMoreHeaders(HTML::Raw('')); - } - $this->addMoreAttr('body', "class-ns-0", HTML::Raw('class="ns-0"')); - - // CSS file defines fonts, colors and background images for this - // style. The companion '*-heavy.css' file isn't defined, it's just - // expected to be in the same directory that the base style is in. - - // This should result in phpwiki-printer.css being used when - // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. - $this->setDefaultCSS('PhpWiki', - array('' => 'monobook.css', - 'print' => 'commonPrint.css')); - - // This allows one to manually select "Printer" style (when browsing page) - // to see what the printer style looks like. - $this->addAlternateCSS(_("Printer"), 'commonPrint.css', 'print, screen'); - $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css'); - $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); - - /** - * The logo image appears on every page and links to the HomePage. - */ - $this->addImageAlias('logo', 'MonoBook-Logo.png'); - //$this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); - - /** - * The Signature image is shown after saving an edited page. If this - * is set to false then the "Thank you for editing..." screen will - * be omitted. - */ - - $this->addImageAlias('signature', "Signature.png"); - // Uncomment this next line to disable the signature. - $this->addImageAlias('signature', false); - - /* - * Link icons. - */ - $this->setLinkIcon('wikiuser'); - - /** - * WikiWords can automatically be split by inserting spaces between - * the words. The default is to leave WordsSmashedTogetherLikeSo. - */ - //$this->setAutosplitWikiWords(false); - - /** - * Layout improvement with dangling links for mostly closed wiki's: - * If false, only users with edit permissions will be presented the - * special wikiunknown class with "?" and Tooltip. - * If true (default), any user will see the ?, but will be presented - * the PrintLoginForm on a click. - */ - $this->setAnonEditUnknownLinks(false); - - /* - * You may adjust the formats used for formatting dates and times - * below. (These examples give the default formats.) - * Formats are given as format strings to PHP strftime() function See - * http://www.php.net/manual/en/function.strftime.php for details. - * Do not include the server's zone (%Z), times are converted to the - * user's time zone. - */ - $this->setDateFormat("%B %d, %Y"); - $this->setTimeFormat("%H:%M"); - - /* - * To suppress times in the "Last edited on" messages, give a - * give a second argument of false: - */ - //$this->setDateFormat("%B %d, %Y", false); + function load() + { + $this->addMoreHeaders(JavaScript("var ta;\nvar skin = '" . $this->_name . "';\n")); + $this->addMoreHeaders(JavaScript('', array('src' => $this->_findData("wikibits.js")))); + if (isBrowserIE()) { + $ver = browserVersion(); + if ($ver > 5.5 and $ver < 7.0) + $this->addMoreHeaders($this->_CSSlink(0, $this->_findFile('IE60Fixes.css'), 'all')); + elseif ($ver >= 7.0) + $this->addMoreHeaders($this->_CSSlink(0, $this->_findFile('IE70Fixes.css'), 'all')); + unset($ver); + $this->addMoreHeaders("\n"); + $this->addMoreHeaders(JavaScript('', array('src' => $this->_findData("IEFixes.js")))); + $this->addMoreHeaders("\n"); + $this->addMoreHeaders(HTML::Raw('')); + } + $this->addMoreAttr('body', "class-ns-0", HTML::Raw('class="ns-0"')); + + // CSS file defines fonts, colors and background images for this + // style. The companion '*-heavy.css' file isn't defined, it's just + // expected to be in the same directory that the base style is in. + + // This should result in phpwiki-printer.css being used when + // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. + $this->setDefaultCSS('PhpWiki', + array('' => 'monobook.css', + 'print' => 'commonPrint.css')); + + // This allows one to manually select "Printer" style (when browsing page) + // to see what the printer style looks like. + $this->addAlternateCSS(_("Printer"), 'commonPrint.css', 'print, screen'); + $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css'); + $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); + + /** + * The logo image appears on every page and links to the HomePage. + */ + $this->addImageAlias('logo', 'MonoBook-Logo.png'); + //$this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); + + /** + * The Signature image is shown after saving an edited page. If this + * is set to false then the "Thank you for editing..." screen will + * be omitted. + */ + + $this->addImageAlias('signature', "Signature.png"); + // Uncomment this next line to disable the signature. + $this->addImageAlias('signature', false); + + /* + * Link icons. + */ + $this->setLinkIcon('wikiuser'); + + /** + * WikiWords can automatically be split by inserting spaces between + * the words. The default is to leave WordsSmashedTogetherLikeSo. + */ + //$this->setAutosplitWikiWords(false); + + /** + * Layout improvement with dangling links for mostly closed wiki's: + * If false, only users with edit permissions will be presented the + * special wikiunknown class with "?" and Tooltip. + * If true (default), any user will see the ?, but will be presented + * the PrintLoginForm on a click. + */ + $this->setAnonEditUnknownLinks(false); + + /* + * You may adjust the formats used for formatting dates and times + * below. (These examples give the default formats.) + * Formats are given as format strings to PHP strftime() function See + * http://www.php.net/manual/en/function.strftime.php for details. + * Do not include the server's zone (%Z), times are converted to the + * user's time zone. + */ + $this->setDateFormat("%B %d, %Y"); + $this->setTimeFormat("%H:%M"); + + /* + * To suppress times in the "Last edited on" messages, give a + * give a second argument of false: + */ + //$this->setDateFormat("%B %d, %Y", false); } } diff --git a/themes/Portland/lib/RecentChanges.php b/themes/Portland/lib/RecentChanges.php index 3971f2b70..f0fde4be4 100644 --- a/themes/Portland/lib/RecentChanges.php +++ b/themes/Portland/lib/RecentChanges.php @@ -6,57 +6,63 @@ require_once 'lib/plugin/RecentChanges.php'; require_once 'lib/plugin/PageHistory.php'; -function Portland_RC_revision_formatter (&$fmt, &$rev) { - $class = 'rc-' . $fmt->importance($rev); - $time = $fmt->time($rev); - if ($rev->get('is_minor_edit')) { - $minor_flag = HTML::small("(" . _("minor edit") . ")"); - } - else { - $time = HTML::strong($time); - $minor_flag = ''; - } - - return HTML::li(array('class' => $class), - $fmt->diffLink($rev), ' ', - $fmt->pageLink($rev), ' ', - $time, ' ', - $minor_flag, ' ', - " . . . ", $fmt->summaryAsHTML($rev), ' ', - " . . . ", - $fmt->authorLink($rev) - ); +function Portland_RC_revision_formatter(&$fmt, &$rev) +{ + $class = 'rc-' . $fmt->importance($rev); + $time = $fmt->time($rev); + if ($rev->get('is_minor_edit')) { + $minor_flag = HTML::small("(" . _("minor edit") . ")"); + } else { + $time = HTML::strong($time); + $minor_flag = ''; } + return HTML::li(array('class' => $class), + $fmt->diffLink($rev), ' ', + $fmt->pageLink($rev), ' ', + $time, ' ', + $minor_flag, ' ', + " . . . ", $fmt->summaryAsHTML($rev), ' ', + " . . . ", + $fmt->authorLink($rev) + ); +} + class _Portland_RecentChanges_Formatter -extends _RecentChanges_HtmlFormatter + extends _RecentChanges_HtmlFormatter { - function format_revision (&$rev) { + function format_revision(&$rev) + { return Portland_RC_revision_formatter($this, $rev); } - function summaryAsHTML ($rev) { - if ( !($summary = $this->summary($rev)) ) + + function summaryAsHTML($rev) + { + if (!($summary = $this->summary($rev))) return ''; - return HTML::strong( array('class' => 'wiki-summary'), - "(", - TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), - ")"); + return HTML::strong(array('class' => 'wiki-summary'), + "(", + TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), + ")"); } } class _Portland_PageHistory_Formatter -extends _PageHistory_HtmlFormatter + extends _PageHistory_HtmlFormatter { - function format_revision (&$rev) { + function format_revision(&$rev) + { return Portland_RC_revision_formatter($this, $rev); } - function summaryAsHTML ($rev) { - if ( !($summary = $this->summary($rev)) ) + + function summaryAsHTML($rev) + { + if (!($summary = $this->summary($rev))) return ''; - return HTML::strong( array('class' => 'wiki-summary'), - "(", - TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), - ")"); + return HTML::strong(array('class' => 'wiki-summary'), + "(", + TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), + ")"); } } diff --git a/themes/Portland/themeinfo.php b/themes/Portland/themeinfo.php index 8e7dbd3c6..c1ab2a185 100644 --- a/themes/Portland/themeinfo.php +++ b/themes/Portland/themeinfo.php @@ -12,15 +12,16 @@ if (!defined('PHPWIKI_VERSION')) { require_once 'lib/WikiTheme.php'; -class WikiTheme_Portland extends WikiTheme { +class WikiTheme_Portland extends WikiTheme +{ - function linkUnknownWikiWord($wikiword, $linktext = '') { + function linkUnknownWikiWord($wikiword, $linktext = '') + { global $request; if (isa($wikiword, 'WikiPageName')) { $default_text = $wikiword->shortName; $wikiword = $wikiword->name; - } - else { + } else { $default_text = $wikiword; } @@ -30,73 +31,76 @@ class WikiTheme_Portland extends WikiTheme { if (!empty($linktext)) { $link->unshiftContent(HTML::u($linktext)); $link->setAttr('class', 'named-wikiunknown'); - } - else { + } else { $link->unshiftContent(HTML::u($this->maybeSplitWikiWord($default_text))); $link->setAttr('class', 'wikiunknown'); } return $link; } - function getRecentChangesFormatter ($format) { + + function getRecentChangesFormatter($format) + { include_once($this->file('lib/RecentChanges.php')); if (preg_match('/^rss|^sidebar/', $format)) - return false; // use default + return false; // use default return '_Portland_RecentChanges_Formatter'; } - function getPageHistoryFormatter ($format) { + function getPageHistoryFormatter($format) + { include_once($this->file('lib/RecentChanges.php')); if (preg_match('/^rss|^sidebar/', $format)) - return false; // use default + return false; // use default return '_Portland_PageHistory_Formatter'; } - function load() { - // CSS file defines fonts, colors and background images for this - // style. The companion '*-heavy.css' file isn't defined, it's just - // expected to be in the same directory that the base style is in. - - $this->setDefaultCSS('Portland', 'portland.css'); - $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); - $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); - $this->addAlternateCSS('PhpWiki', 'phpwiki.css'); - - /** - * The logo image appears on every page and links to the HomePage. - */ - $this->addImageAlias('logo', WIKI_NAME . 'logo.png'); - - /** - * The Signature image is shown after saving an edited page. If this - * is set to false then the "Thank you for editing..." screen will - * be omitted. - */ - $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); - // Uncomment this next line to disable the signature. - //$this->addImageAlias('signature', false); - - /* - * Link icons. - */ - - $this->setButtonSeparator(' '); - - /** - * WikiWords can automatically be split by inserting spaces between - * the words. The default is to leave WordsSmashedTogetherLikeSo. - */ - $this->setAutosplitWikiWords(false); - - /* - * You may adjust the formats used for formatting dates and times - * below. (These examples give the default formats.) - * Formats are given as format strings to PHP strftime() function See - * http://www.php.net/manual/en/function.strftime.php for details. - * Do not include the server's zone (%Z), times are converted to the - * user's time zone. - */ - $this->setDateFormat("%B %d, %Y", false); + function load() + { + // CSS file defines fonts, colors and background images for this + // style. The companion '*-heavy.css' file isn't defined, it's just + // expected to be in the same directory that the base style is in. + + $this->setDefaultCSS('Portland', 'portland.css'); + $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); + $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); + $this->addAlternateCSS('PhpWiki', 'phpwiki.css'); + + /** + * The logo image appears on every page and links to the HomePage. + */ + $this->addImageAlias('logo', WIKI_NAME . 'logo.png'); + + /** + * The Signature image is shown after saving an edited page. If this + * is set to false then the "Thank you for editing..." screen will + * be omitted. + */ + $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); + // Uncomment this next line to disable the signature. + //$this->addImageAlias('signature', false); + + /* + * Link icons. + */ + + $this->setButtonSeparator(' '); + + /** + * WikiWords can automatically be split by inserting spaces between + * the words. The default is to leave WordsSmashedTogetherLikeSo. + */ + $this->setAutosplitWikiWords(false); + + /* + * You may adjust the formats used for formatting dates and times + * below. (These examples give the default formats.) + * Formats are given as format strings to PHP strftime() function See + * http://www.php.net/manual/en/function.strftime.php for details. + * Do not include the server's zone (%Z), times are converted to the + * user's time zone. + */ + $this->setDateFormat("%B %d, %Y", false); } } diff --git a/themes/Sidebar/clock.php b/themes/Sidebar/clock.php index 810e33cf8..cdcd9d3f1 100644 --- a/themes/Sidebar/clock.php +++ b/themes/Sidebar/clock.php @@ -1,7 +1,11 @@ _findFile("ora.swf") : "ora.swf"; +$ora = isset($GLOBALS['WikiTheme']) ? DATA_PATH . '/' . $GLOBALS['WikiTheme']->_findFile("ora.swf") : "ora.swf"; ?> - - - + + + + diff --git a/themes/Sidebar/hyperapplet.php b/themes/Sidebar/hyperapplet.php index 5f64ccfe1..c86238640 100644 --- a/themes/Sidebar/hyperapplet.php +++ b/themes/Sidebar/hyperapplet.php @@ -12,10 +12,10 @@ global $WikiTheme; " width="160" height="360"> - - - - " /> - - + + + + "/> + + diff --git a/themes/Sidebar/hyperwiki.php b/themes/Sidebar/hyperwiki.php index 6059c7c01..1a120c3f4 100644 --- a/themes/Sidebar/hyperwiki.php +++ b/themes/Sidebar/hyperwiki.php @@ -1,16 +1,16 @@ " width="162" height="240"> - - " /> - + + "/> + diff --git a/themes/Sidebar/themeinfo.php b/themes/Sidebar/themeinfo.php index 0df2245ee..5db22074e 100644 --- a/themes/Sidebar/themeinfo.php +++ b/themes/Sidebar/themeinfo.php @@ -23,44 +23,48 @@ if (!defined('PHPWIKI_VERSION')) { */ if (!defined("CLAMDSCAN_PATH")) - define("CLAMDSCAN_PATH","/usr/local/bin/clamdscan"); + define("CLAMDSCAN_PATH", "/usr/local/bin/clamdscan"); if (!defined("CLAMDSCAN_VIRUS")) - define("CLAMDSCAN_VIRUS","/var/www/virus-found"); + define("CLAMDSCAN_VIRUS", "/var/www/virus-found"); require_once 'lib/WikiTheme.php'; require_once 'lib/WikiPlugin.php'; require_once 'themes/MonoBook/themeinfo.php'; -class WikiTheme_Sidebar extends WikiTheme_MonoBook { +class WikiTheme_Sidebar extends WikiTheme_MonoBook +{ - function WikiTheme_Sidebar ($theme_name='Sidebar') { + function WikiTheme_Sidebar($theme_name = 'Sidebar') + { $this->WikiTheme($theme_name); //$this->calendarInit(true); } /* Display up/down button with persistent state */ /* persistent state per block in cookie for 30 days */ - function folderArrow ($id, $init='Open') { + function folderArrow($id, $init = 'Open') + { global $request; - if ($cookie = $request->cookies->get("folder_".$id)) { + if ($cookie = $request->cookies->get("folder_" . $id)) { $init = $cookie; - } + } if ($init == 'Open' or $init == 'Closed') - $png = $this->_findData('images/folderArrow'.$init.'.png'); + $png = $this->_findData('images/folderArrow' . $init . '.png'); else $png = $this->_findData('images/folderArrowOpen.png'); - return HTML::img(array('id' => $id.'-img', - 'src' => $png, - //'align' => 'right', - 'onclick' => "showHideFolder('$id')", - 'alt' => _("Click to hide/show"), - 'title' => _("Click to hide/show"))); + return HTML::img(array('id' => $id . '-img', + 'src' => $png, + //'align' => 'right', + 'onclick' => "showHideFolder('$id')", + 'alt' => _("Click to hide/show"), + 'title' => _("Click to hide/show"))); } /* Callback when a new user creates or edits a page */ - function CbNewUserEdit (&$request, $userid) { + function CbNewUserEdit(&$request, $userid) + { $userid = strtoupper($userid); - $content = "{{Template/UserPage}}"; + $content = "{{Template/UserPage}}"; $dbi =& $request->_dbi; $page = $dbi->getPage($userid); $page->save($content, WIKIDB_FORCE_CREATE, array('author' => $userid)); @@ -78,24 +82,26 @@ class WikiTheme_Sidebar extends WikiTheme_MonoBook { * if (!$WikiTheme->CbUpload($request, $file_dir . $userfile_name)) * unlink($file_dir . $userfile_name); */ - function CbUpload (&$request, $pathname) { + function CbUpload(&$request, $pathname) + { $cmdline = CLAMDSCAN_PATH . " --nosummary --move=" . CLAMDSCAN_VIRUS; - $report = `$cmdline "$pathname"`; - if (!$report) { - trigger_error("clamdscan failed", E_USER_WARNING); - return true; - } - if (!preg_match("/: OK$/", $report)) { - //preg_match("/: (.+)$/", $report, $m); - trigger_error("Upload failed. virus-scanner: $report", E_USER_WARNING); - return false; - } else { - return true; - } + $report = `$cmdline "$pathname"`; + if (!$report) { + trigger_error("clamdscan failed", E_USER_WARNING); + return true; + } + if (!preg_match("/: OK$/", $report)) { + //preg_match("/: (.+)$/", $report, $m); + trigger_error("Upload failed. virus-scanner: $report", E_USER_WARNING); + return false; + } else { + return true; + } } - function findTemplate ($name) { + function findTemplate($name) + { // hack for navbar.tmpl to hide the buttonseparator if ($name == "navbar") { $this->setButtonSeparator(HTML::Raw("
    \n · ")); @@ -106,105 +112,106 @@ class WikiTheme_Sidebar extends WikiTheme_MonoBook { return parent::findTemplate($name); } - function load() { + function load() + { $this->initGlobals(); - // CSS file defines fonts, colors and background images for this - // style. The companion '*-heavy.css' file isn't defined, it's just - // expected to be in the same directory that the base style is in. - - $this->setDefaultCSS(_("Sidebar"), array('' => 'sidebar.css', - 'print' => 'phpwiki-printer.css')); - $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); - $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); - - /** - * The logo image appears on every page and links to the HomePage. - */ - //$this->addImageAlias('logo', 'logo.png'); - - /** - * The Signature image is shown after saving an edited page. If this - * is not set, any signature defined in index.php will be used. If it - * is not defined by index.php or in here then the "Thank you for - * editing..." screen will be omitted. - */ - - // Comment this next line out to enable signature. - $this->addImageAlias('signature', false); - - $this->addImageAlias('search', 'search.png'); - - /* - * Link icons. - */ - $this->setLinkIcon('http'); - $this->setLinkIcon('https'); - $this->setLinkIcon('ftp'); - $this->setLinkIcon('mailto'); - $this->setLinkIcon('interwiki'); - $this->setLinkIcon('*', 'url'); - - //$this->setButtonSeparator(' | '); - - /** - * WikiWords can automatically be split by inserting spaces between - * the words. The default is to leave WordsSmashedTogetherLikeSo. - */ - //$this->setAutosplitWikiWords(true); - - /** - * If true (default) show create '?' buttons on not existing pages, even if the - * user is not signed in. - * If false, anon users get no links and it looks cleaner, but then they - * cannot easily fix missing pages. - */ - $this->setAnonEditUnknownLinks(false); - - /* - * You may adjust the formats used for formatting dates and times - * below. (These examples give the default formats.) - * Formats are given as format strings to PHP strftime() function See - * http://www.php.net/manual/en/function.strftime.php for details. - * Do not include the server's zone (%Z), times are converted to the - * user's time zone. - */ - //$this->setDateFormat("%B %d, %Y"); - - /** - * Custom UserPreferences: - * A list of name => _UserPreference class pairs. - * Rationale: Certain themes should be able to extend the predefined list - * of preferences. Display/editing is done in the theme specific userprefs.tmpl - * but storage/sanification/update/... must be extended to the Get/SetPreferences methods. - * See themes/wikilens/themeinfo.php - */ - //$this->customUserPreference(); - - /** - * Register custom PageList type and define custom PageList classes. - * Rationale: Certain themes should be able to extend the predefined list - * of pagelist types. E.g. certain plugins, like MostPopular might use - * info=pagename,hits,rating - * which displays the rating column whenever the wikilens theme is active. - * See themes/wikilens/themeinfo.php - */ - //$this->addPageListColumn(); + // CSS file defines fonts, colors and background images for this + // style. The companion '*-heavy.css' file isn't defined, it's just + // expected to be in the same directory that the base style is in. + + $this->setDefaultCSS(_("Sidebar"), array('' => 'sidebar.css', + 'print' => 'phpwiki-printer.css')); + $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); + $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); + + /** + * The logo image appears on every page and links to the HomePage. + */ + //$this->addImageAlias('logo', 'logo.png'); + + /** + * The Signature image is shown after saving an edited page. If this + * is not set, any signature defined in index.php will be used. If it + * is not defined by index.php or in here then the "Thank you for + * editing..." screen will be omitted. + */ + + // Comment this next line out to enable signature. + $this->addImageAlias('signature', false); + + $this->addImageAlias('search', 'search.png'); + + /* + * Link icons. + */ + $this->setLinkIcon('http'); + $this->setLinkIcon('https'); + $this->setLinkIcon('ftp'); + $this->setLinkIcon('mailto'); + $this->setLinkIcon('interwiki'); + $this->setLinkIcon('*', 'url'); + + //$this->setButtonSeparator(' | '); + + /** + * WikiWords can automatically be split by inserting spaces between + * the words. The default is to leave WordsSmashedTogetherLikeSo. + */ + //$this->setAutosplitWikiWords(true); + + /** + * If true (default) show create '?' buttons on not existing pages, even if the + * user is not signed in. + * If false, anon users get no links and it looks cleaner, but then they + * cannot easily fix missing pages. + */ + $this->setAnonEditUnknownLinks(false); + + /* + * You may adjust the formats used for formatting dates and times + * below. (These examples give the default formats.) + * Formats are given as format strings to PHP strftime() function See + * http://www.php.net/manual/en/function.strftime.php for details. + * Do not include the server's zone (%Z), times are converted to the + * user's time zone. + */ + //$this->setDateFormat("%B %d, %Y"); + + /** + * Custom UserPreferences: + * A list of name => _UserPreference class pairs. + * Rationale: Certain themes should be able to extend the predefined list + * of preferences. Display/editing is done in the theme specific userprefs.tmpl + * but storage/sanification/update/... must be extended to the Get/SetPreferences methods. + * See themes/wikilens/themeinfo.php + */ + //$this->customUserPreference(); + + /** + * Register custom PageList type and define custom PageList classes. + * Rationale: Certain themes should be able to extend the predefined list + * of pagelist types. E.g. certain plugins, like MostPopular might use + * info=pagename,hits,rating + * which displays the rating column whenever the wikilens theme is active. + * See themes/wikilens/themeinfo.php + */ + //$this->addPageListColumn(); } } $WikiTheme = new WikiTheme_Sidebar('Sidebar'); if (ENABLE_RATEIT) { - require_once 'lib/wikilens/CustomPrefs.php'; - require_once 'lib/wikilens/PageListColumns.php'; - //require_once("lib/plugin/RateIt.php"); - $plugin = new WikiPlugin_RateIt; - // add parent to current theme to find the RateIt images - // $WikiTheme->addParent('wikilens', 'noinit'); - $WikiTheme->_parents[] = new WikiTheme('wikilens', 'noinit'); - $plugin->head(); + require_once 'lib/wikilens/CustomPrefs.php'; + require_once 'lib/wikilens/PageListColumns.php'; + //require_once("lib/plugin/RateIt.php"); + $plugin = new WikiPlugin_RateIt; + // add parent to current theme to find the RateIt images + // $WikiTheme->addParent('wikilens', 'noinit'); + $WikiTheme->_parents[] = new WikiTheme('wikilens', 'noinit'); + $plugin->head(); } // Local Variables: diff --git a/themes/SpaceWiki/lib/RecentChanges.php b/themes/SpaceWiki/lib/RecentChanges.php index 963bc12c6..5305800d6 100644 --- a/themes/SpaceWiki/lib/RecentChanges.php +++ b/themes/SpaceWiki/lib/RecentChanges.php @@ -6,50 +6,56 @@ require_once 'lib/plugin/RecentChanges.php'; require_once 'lib/plugin/PageHistory.php'; -function SpaceWiki_RC_revision_formatter (&$fmt, &$rev) { +function SpaceWiki_RC_revision_formatter(&$fmt, &$rev) +{ $class = 'rc-' . $fmt->importance($rev); return HTML::li(array('class' => $class), - $fmt->diffLink($rev), ' ', - $fmt->pageLink($rev), ' ', - ' . ', - $rev->get('is_minor_edit') ? $fmt->time($rev) : HTML::strong($fmt->time($rev)), ' ', - ' . . . ', - $fmt->summaryAsHTML($rev), - ' . . . ', - $fmt->authorLink($rev)); + $fmt->diffLink($rev), ' ', + $fmt->pageLink($rev), ' ', + ' . ', + $rev->get('is_minor_edit') ? $fmt->time($rev) : HTML::strong($fmt->time($rev)), ' ', + ' . . . ', + $fmt->summaryAsHTML($rev), + ' . . . ', + $fmt->authorLink($rev)); } -function SpaceWiki_PH_revision_formatter (&$fmt, &$rev) { +function SpaceWiki_PH_revision_formatter(&$fmt, &$rev) +{ $class = 'rc-' . $fmt->importance($rev); return HTML::li(array('class' => $class), - $fmt->diffLink($rev), ' ', - $fmt->pageLink($rev), ' ', - $rev->get('is_minor_edit') ? $fmt->time($rev) : HTML::strong($fmt->time($rev)), ' ', - ' . . . ', - $fmt->summaryAsHTML($rev), - ' . . . ', - $fmt->authorLink($rev), - ($fmt->importance($rev)=='minor') ? HTML::small(" (" . _("minor edit") . ")") : ''); + $fmt->diffLink($rev), ' ', + $fmt->pageLink($rev), ' ', + $rev->get('is_minor_edit') ? $fmt->time($rev) : HTML::strong($fmt->time($rev)), ' ', + ' . . . ', + $fmt->summaryAsHTML($rev), + ' . . . ', + $fmt->authorLink($rev), + ($fmt->importance($rev) == 'minor') ? HTML::small(" (" . _("minor edit") . ")") : ''); } class _SpaceWiki_RecentChanges_Formatter -extends _RecentChanges_HtmlFormatter + extends _RecentChanges_HtmlFormatter { - function format_revision (&$rev) { + function format_revision(&$rev) + { return SpaceWiki_RC_revision_formatter($this, $rev); } - function summaryAsHTML ($rev) { - if ( !($summary = $this->summary($rev)) ) + + function summaryAsHTML($rev) + { + if (!($summary = $this->summary($rev))) return ''; - return HTML::strong( array('class' => 'wiki-summary'), - " ", - TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), - " "); + return HTML::strong(array('class' => 'wiki-summary'), + " ", + TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), + " "); } - function diffLink ($rev) { + function diffLink($rev) + { global $WikiTheme; return $WikiTheme->makeButton(_("diff"), $this->diffURL($rev), 'wiki-rc-action'); } @@ -57,18 +63,21 @@ extends _RecentChanges_HtmlFormatter } class _SpaceWiki_PageHistory_Formatter -extends _PageHistory_HtmlFormatter + extends _PageHistory_HtmlFormatter { - function format_revision (&$rev) { + function format_revision(&$rev) + { return SpaceWiki_PH_revision_formatter($this, $rev); } - function summaryAsHTML ($rev) { - if ( !($summary = $this->summary($rev)) ) + + function summaryAsHTML($rev) + { + if (!($summary = $this->summary($rev))) return ''; - return HTML::strong( array('class' => 'wiki-summary'), - " ", - TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), - " "); + return HTML::strong(array('class' => 'wiki-summary'), + " ", + TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), + " "); } } diff --git a/themes/SpaceWiki/themeinfo.php b/themes/SpaceWiki/themeinfo.php index c5c65d0b5..599690002 100644 --- a/themes/SpaceWiki/themeinfo.php +++ b/themes/SpaceWiki/themeinfo.php @@ -19,66 +19,70 @@ if (!defined('PHPWIKI_VERSION')) { require_once 'lib/WikiTheme.php'; -class WikiTheme_SpaceWiki extends WikiTheme { +class WikiTheme_SpaceWiki extends WikiTheme +{ - function getRecentChangesFormatter ($format) { + function getRecentChangesFormatter($format) + { include_once($this->file('lib/RecentChanges.php')); if (preg_match('/^rss|^sidebar/', $format)) - return false; // use default + return false; // use default return '_SpaceWiki_RecentChanges_Formatter'; } - function getPageHistoryFormatter ($format) { + function getPageHistoryFormatter($format) + { include_once($this->file('lib/RecentChanges.php')); if (preg_match('/^rss|^sidebar/', $format)) - return false; // use default + return false; // use default return '_SpaceWiki_PageHistory_Formatter'; } - function load() { - // CSS file defines fonts, colors and background images for this - // style. The companion '*-heavy.css' file isn't defined, it's just - // expected to be in the same directory that the base style is in. - - $this->setDefaultCSS('SpaceWiki', 'SpaceWiki.css'); - $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); - $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); - $this->addAlternateCSS('PhpWiki', 'phpwiki.css'); - - /** - * The logo image appears on every page and links to the HomePage. - */ - //$this->addImageAlias('logo', 'logo.png'); - $this->addImageAlias('logo', 'Ufp-logo.jpg'); - $this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); - - /** - * The Signature image is shown after saving an edited page. If this - * is set to false then the "Thank you for editing..." screen will - * be omitted. - */ - $this->addImageAlias('signature', 'lights.png'); - $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); - // Uncomment this next line to disable the signature. - //$this->addImageAlias('signature', false); - - $this->addImageAlias('hr', 'hr.png'); - - $this->setButtonSeparator(" "); - - /** - * WikiWords can automatically be split by inserting spaces between - * the words. The default is to leave WordsSmashedTogetherLikeSo. - */ - //$this->setAutosplitWikiWords(false); - - /** - * The "stardate" format here is really just metricdate.24hourtime. A - * "real" date2startdate conversion function might be fun but not very - * useful on a wiki. - */ - $this->setTimeFormat("%H%M%S"); - $this->setDateFormat("%Y%m%d"); // must not contain time + function load() + { + // CSS file defines fonts, colors and background images for this + // style. The companion '*-heavy.css' file isn't defined, it's just + // expected to be in the same directory that the base style is in. + + $this->setDefaultCSS('SpaceWiki', 'SpaceWiki.css'); + $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); + $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); + $this->addAlternateCSS('PhpWiki', 'phpwiki.css'); + + /** + * The logo image appears on every page and links to the HomePage. + */ + //$this->addImageAlias('logo', 'logo.png'); + $this->addImageAlias('logo', 'Ufp-logo.jpg'); + $this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); + + /** + * The Signature image is shown after saving an edited page. If this + * is set to false then the "Thank you for editing..." screen will + * be omitted. + */ + $this->addImageAlias('signature', 'lights.png'); + $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); + // Uncomment this next line to disable the signature. + //$this->addImageAlias('signature', false); + + $this->addImageAlias('hr', 'hr.png'); + + $this->setButtonSeparator(" "); + + /** + * WikiWords can automatically be split by inserting spaces between + * the words. The default is to leave WordsSmashedTogetherLikeSo. + */ + //$this->setAutosplitWikiWords(false); + + /** + * The "stardate" format here is really just metricdate.24hourtime. A + * "real" date2startdate conversion function might be fun but not very + * useful on a wiki. + */ + $this->setTimeFormat("%H%M%S"); + $this->setDateFormat("%Y%m%d"); // must not contain time } } diff --git a/themes/Wordpress/lib/RecentChanges.php b/themes/Wordpress/lib/RecentChanges.php index fdcbbb4e5..932d4a043 100644 --- a/themes/Wordpress/lib/RecentChanges.php +++ b/themes/Wordpress/lib/RecentChanges.php @@ -6,57 +6,63 @@ require_once 'lib/plugin/RecentChanges.php'; require_once 'lib/plugin/PageHistory.php'; -function Wordpress_RC_revision_formatter (&$fmt, &$rev) { - $class = 'rc-' . $fmt->importance($rev); - $time = $fmt->time($rev); - if ($rev->get('is_minor_edit')) { - $minor_flag = HTML::small("(" . _("minor edit") . ")"); - } - else { - $time = HTML::strong($time); - $minor_flag = ''; - } +function Wordpress_RC_revision_formatter(&$fmt, &$rev) +{ + $class = 'rc-' . $fmt->importance($rev); + $time = $fmt->time($rev); + if ($rev->get('is_minor_edit')) { + $minor_flag = HTML::small("(" . _("minor edit") . ")"); + } else { + $time = HTML::strong($time); + $minor_flag = ''; + } - return HTML::li(array('class' => $class), - $fmt->diffLink($rev), ' ', - $fmt->pageLink($rev), ' ', - $time, ' ', - $minor_flag, ' ', - " . . . ", $fmt->summaryAsHTML($rev), ' ', - " . . . ", - $fmt->authorLink($rev) - ); + return HTML::li(array('class' => $class), + $fmt->diffLink($rev), ' ', + $fmt->pageLink($rev), ' ', + $time, ' ', + $minor_flag, ' ', + " . . . ", $fmt->summaryAsHTML($rev), ' ', + " . . . ", + $fmt->authorLink($rev) + ); } class _Wordpress_RecentChanges_Formatter -extends _RecentChanges_HtmlFormatter + extends _RecentChanges_HtmlFormatter { - function format_revision (&$rev) { + function format_revision(&$rev) + { return Wordpress_RC_revision_formatter($this, $rev); } - function summaryAsHTML ($rev) { - if ( !($summary = $this->summary($rev)) ) + + function summaryAsHTML($rev) + { + if (!($summary = $this->summary($rev))) return ''; - return HTML::strong( array('class' => 'wiki-summary'), - "(", - TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), - ")"); + return HTML::strong(array('class' => 'wiki-summary'), + "(", + TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), + ")"); } } class _Wordpress_PageHistory_Formatter -extends _PageHistory_HtmlFormatter + extends _PageHistory_HtmlFormatter { - function format_revision (&$rev) { + function format_revision(&$rev) + { return Wordpress_RC_revision_formatter($this, $rev); } - function summaryAsHTML ($rev) { - if ( !($summary = $this->summary($rev)) ) + + function summaryAsHTML($rev) + { + if (!($summary = $this->summary($rev))) return ''; - return HTML::strong( array('class' => 'wiki-summary'), - "(", - TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), - ")"); + return HTML::strong(array('class' => 'wiki-summary'), + "(", + TransformLinks($summary, $rev->get('markup'), $rev->getPageName()), + ")"); } } diff --git a/themes/Wordpress/themeinfo.php b/themes/Wordpress/themeinfo.php index 13f2790f4..0058e3436 100644 --- a/themes/Wordpress/themeinfo.php +++ b/themes/Wordpress/themeinfo.php @@ -14,15 +14,16 @@ if (!defined('PHPWIKI_VERSION')) { require_once 'lib/WikiTheme.php'; -class WikiTheme_Wordpress extends WikiTheme { +class WikiTheme_Wordpress extends WikiTheme +{ - function linkUnknownWikiWord($wikiword, $linktext = '') { + function linkUnknownWikiWord($wikiword, $linktext = '') + { global $request; if (isa($wikiword, 'WikiPageName')) { $default_text = $wikiword->shortName; $wikiword = $wikiword->name; - } - else { + } else { $default_text = $wikiword; } @@ -32,72 +33,75 @@ class WikiTheme_Wordpress extends WikiTheme { if (!empty($linktext)) { $link->unshiftContent(HTML::u($linktext)); $link->setAttr('class', 'named-wikiunknown'); - } - else { + } else { $link->unshiftContent(HTML::u($this->maybeSplitWikiWord($default_text))); $link->setAttr('class', 'wikiunknown'); } return $link; } - function getRecentChangesFormatter ($format) { + + function getRecentChangesFormatter($format) + { include_once($this->file('lib/RecentChanges.php')); if (preg_match('/^rss|^sidebar/', $format)) - return false; // use default + return false; // use default return '_Wordpress_RecentChanges_Formatter'; } - function getPageHistoryFormatter ($format) { + function getPageHistoryFormatter($format) + { include_once($this->file('lib/RecentChanges.php')); if (preg_match('/^rss|^sidebar/', $format)) - return false; // use default + return false; // use default return '_Wordpress_PageHistory_Formatter'; } - function load() { - // CSS file defines fonts, colors and background images for this - // style. The companion '*-heavy.css' file isn't defined, it's just - // expected to be in the same directory that the base style is in. - - $this->setDefaultCSS('Wordpress', 'Wordpress.css'); - $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); - $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); - $this->addAlternateCSS('PhpWiki', 'phpwiki.css'); - - /** - * The logo image appears on every page and links to the HomePage. - */ - //$this->addImageAlias('logo', 'logo.png'); - - /** - * The Signature image is shown after saving an edited page. If this - * is not set, any signature defined in index.php will be used. If it - * is not defined by index.php or in here then the "Thank you for - * editing..." screen will be omitted. - */ - $this->addImageAlias('signature', 'signature.png'); - - /* - * Link icons. - */ - - $this->setButtonSeparator(' '); - - /** - * WikiWords can automatically be split by inserting spaces between - * the words. The default is to leave WordsSmashedTogetherLikeSo. - */ - $this->setAutosplitWikiWords(false); - - /* - * You may adjust the formats used for formatting dates and times - * below. (These examples give the default formats.) - * Formats are given as format strings to PHP strftime() function See - * http://www.php.net/manual/en/function.strftime.php for details. - * Do not include the server's zone (%Z), times are converted to the - * user's time zone. - */ - $this->setDateFormat("%B %d, %Y", false); + function load() + { + // CSS file defines fonts, colors and background images for this + // style. The companion '*-heavy.css' file isn't defined, it's just + // expected to be in the same directory that the base style is in. + + $this->setDefaultCSS('Wordpress', 'Wordpress.css'); + $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); + $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); + $this->addAlternateCSS('PhpWiki', 'phpwiki.css'); + + /** + * The logo image appears on every page and links to the HomePage. + */ + //$this->addImageAlias('logo', 'logo.png'); + + /** + * The Signature image is shown after saving an edited page. If this + * is not set, any signature defined in index.php will be used. If it + * is not defined by index.php or in here then the "Thank you for + * editing..." screen will be omitted. + */ + $this->addImageAlias('signature', 'signature.png'); + + /* + * Link icons. + */ + + $this->setButtonSeparator(' '); + + /** + * WikiWords can automatically be split by inserting spaces between + * the words. The default is to leave WordsSmashedTogetherLikeSo. + */ + $this->setAutosplitWikiWords(false); + + /* + * You may adjust the formats used for formatting dates and times + * below. (These examples give the default formats.) + * Formats are given as format strings to PHP strftime() function See + * http://www.php.net/manual/en/function.strftime.php for details. + * Do not include the server's zone (%Z), times are converted to the + * user's time zone. + */ + $this->setDateFormat("%B %d, %Y", false); } } diff --git a/themes/alphatest.php b/themes/alphatest.php index 9a1810916..3190a0e81 100644 --- a/themes/alphatest.php +++ b/themes/alphatest.php @@ -1,53 +1,58 @@ -Alpha Channel Test - - + +Alpha Channel Test + + +
    bgcolor:

    \n{$current_dir}

    \n"; - $pngs = true; - } - print "\"{$file}\"\n"; +function find_pngs($dir) +{ + $file_list = ''; + $stack[] = $dir; + while ($stack) { + $current_dir = array_pop($stack); + $pngs = false; + if ($dh = opendir($current_dir)) { + while (($file = readdir($dh)) !== false) { + if ($file !== '.' AND $file !== '..') { + $current_file = "{$current_dir}/{$file}"; + if (is_file($current_file)) { + if (!(strcmp(substr($file, -4), ".png"))) { + if (!$pngs) { + print "

    \n{$current_dir}

    \n"; + $pngs = true; + } + print "\"{$file}\"\n"; + } + } elseif (is_dir($current_file)) { + $stack[] = $current_file; + } + } } - } - elseif (is_dir($current_file)) { - $stack[] = $current_file; - } } - } } - } } find_pngs("."); @@ -55,10 +60,12 @@ find_pngs(".");
    bgcolor:
    - + + diff --git a/themes/blog/lib/RecentChanges.php b/themes/blog/lib/RecentChanges.php index 1dc858cd0..524929eb0 100644 --- a/themes/blog/lib/RecentChanges.php +++ b/themes/blog/lib/RecentChanges.php @@ -7,26 +7,28 @@ require_once 'lib/plugin/RecentChanges.php'; //require_once('lib/plugin/PageHistory.php'); class _blog_RecentChanges_BoxFormatter -extends _RecentChanges_BoxFormatter + extends _RecentChanges_BoxFormatter { - function pageLink (&$rev, $link_text=false) { + function pageLink(&$rev, $link_text = false) + { if (!$link_text and $rev->get('pagetype') == 'wikiblog') $link_text = $rev->get('summary'); elseif (preg_match("/\/Blog\b/", $rev->_pagename)) return ''; if ($link_text and strlen($link_text) > 20) - $link_text = substr($link_text,0,20)."..."; - return WikiLink($rev->getPage(),'auto',$link_text); + $link_text = substr($link_text, 0, 20) . "..."; + return WikiLink($rev->getPage(), 'auto', $link_text); } } class _blog_RecentChanges_Formatter -extends _RecentChanges_HtmlFormatter + extends _RecentChanges_HtmlFormatter { - function pageLink (&$rev, $link_text=false) { + function pageLink(&$rev, $link_text = false) + { if (!$link_text and $rev->get('pagetype') == 'wikiblog') $link_text = $rev->get('summary'); - return WikiLink($rev,'auto',$link_text); + return WikiLink($rev, 'auto', $link_text); } } /* diff --git a/themes/blog/themeinfo.php b/themes/blog/themeinfo.php index 01c2635ca..ace866274 100644 --- a/themes/blog/themeinfo.php +++ b/themes/blog/themeinfo.php @@ -43,47 +43,60 @@ liveSearchReq.open("GET", liveSearchURI + "?format=livesearch&paging=none&limit= require_once 'lib/WikiTheme.php'; -class WikiTheme_blog extends WikiTheme { +class WikiTheme_blog extends WikiTheme +{ - function WikiTheme_blog ($theme_name='blog') { + function WikiTheme_blog($theme_name = 'blog') + { $this->WikiTheme($theme_name); $this->calendarInit(true); } /* overload to load from Sidebar */ - function _findFile ($file, $missing_okay=false) { - if (file_exists($this->_path . "themes/".$this->_name."/$file")) - return "themes/".$this->_name."/$file"; + function _findFile($file, $missing_okay = false) + { + if (file_exists($this->_path . "themes/" . $this->_name . "/$file")) + return "themes/" . $this->_name . "/$file"; if (file_exists($this->_path . "themes/Sidebar/$file")) return "themes/Sidebar/$file"; return parent::_findFile($file, $missing_okay); } - function _labelForAction ($action) { + function _labelForAction($action) + { switch ($action) { - case 'edit': return _("Edit"); - case 'diff': return _("Diff"); - case 'logout': return _("Sign Out"); - case 'login': return _("Sign In"); - case 'lock': return _("Lock"); - case 'unlock': return _("Unlock"); - case 'remove': return _("Remove"); + case 'edit': + return _("Edit"); + case 'diff': + return _("Diff"); + case 'logout': + return _("Sign Out"); + case 'login': + return _("Sign In"); + case 'lock': + return _("Lock"); + case 'unlock': + return _("Unlock"); + case 'remove': + return _("Remove"); default: return gettext(ucfirst($action)); } } - function getRecentChangesFormatter ($format) { + function getRecentChangesFormatter($format) + { include_once($this->file('lib/RecentChanges.php')); if (preg_match('/^rss|^sidebar/', $format)) - return false; // use default + return false; // use default if ($format == 'box') return '_blog_RecentChanges_BoxFormatter'; return '_blog_RecentChanges_Formatter'; } /* TODO: use the blog summary as label instead of the pagename */ - function linkExistingWikiWord($wikiword, $linktext = '', $version = false) { + function linkExistingWikiWord($wikiword, $linktext = '', $version = false) + { global $request; if ($version !== false and !$this->HTML_DUMP_SUFFIX) $url = WikiURL($wikiword, array('version' => $version)); @@ -98,16 +111,15 @@ class WikiTheme_blog extends WikiTheme { $link = HTML::a(array('href' => $url)); if (isa($wikiword, 'WikiPageName')) - $default_text = $wikiword->shortName; - else - $default_text = $wikiword; + $default_text = $wikiword->shortName; + else + $default_text = $wikiword; if (!empty($linktext)) { $link->pushContent($linktext); $link->setAttr('class', 'named-wiki'); $link->setAttr('title', $this->maybeSplitWikiWord($default_text)); - } - else { + } else { //TODO: check if wikiblog $link->pushContent($this->maybeSplitWikiWord($default_text)); $link->setAttr('class', 'wiki'); @@ -115,45 +127,46 @@ class WikiTheme_blog extends WikiTheme { return $link; } - function load() { - // CSS file defines fonts, colors and background images for this - // style. + function load() + { + // CSS file defines fonts, colors and background images for this + // style. - // override sidebar definitions: - $this->setDefaultCSS(_("blog"), 'Kubrick.css'); - if (isBrowserIE()) { - $this->addMoreHeaders($this->_CSSlink(0, $this->_findFile('IEFixes.css'),'all')); - } - $this->addButtonAlias(_("(diff)"), "[diff]" ); - $this->addButtonAlias("...", "alltime"); - - $this->setButtonSeparator(""); - - /** - * WikiWords can automatically be split by inserting spaces between - * the words. The default is to leave WordsSmashedTogetherLikeSo. - */ - $this->setAutosplitWikiWords(false); - - /** - * If true (default) show create '?' buttons on not existing pages, even if the - * user is not signed in. - * If false, anon users get no links and it looks cleaner, but then they - * cannot easily fix missing pages. - */ - $this->setAnonEditUnknownLinks(false); - - /* - * You may adjust the formats used for formatting dates and times - * below. (These examples give the default formats.) - * Formats are given as format strings to PHP strftime() function See - * http://www.php.net/manual/en/function.strftime.php for details. - * Do not include the server's zone (%Z), times are converted to the - * user's time zone. - */ - //$this->setDateFormat("%B %d, %Y"); - $this->setDateFormat("%A, %B %e, %Y"); // must not contain time - $this->setTimeFormat("%H:%M:%S"); + // override sidebar definitions: + $this->setDefaultCSS(_("blog"), 'Kubrick.css'); + if (isBrowserIE()) { + $this->addMoreHeaders($this->_CSSlink(0, $this->_findFile('IEFixes.css'), 'all')); + } + $this->addButtonAlias(_("(diff)"), "[diff]"); + $this->addButtonAlias("...", "alltime"); + + $this->setButtonSeparator(""); + + /** + * WikiWords can automatically be split by inserting spaces between + * the words. The default is to leave WordsSmashedTogetherLikeSo. + */ + $this->setAutosplitWikiWords(false); + + /** + * If true (default) show create '?' buttons on not existing pages, even if the + * user is not signed in. + * If false, anon users get no links and it looks cleaner, but then they + * cannot easily fix missing pages. + */ + $this->setAnonEditUnknownLinks(false); + + /* + * You may adjust the formats used for formatting dates and times + * below. (These examples give the default formats.) + * Formats are given as format strings to PHP strftime() function See + * http://www.php.net/manual/en/function.strftime.php for details. + * Do not include the server's zone (%Z), times are converted to the + * user's time zone. + */ + //$this->setDateFormat("%B %d, %Y"); + $this->setDateFormat("%A, %B %e, %Y"); // must not contain time + $this->setTimeFormat("%H:%M:%S"); } } diff --git a/themes/fusionforge/themeinfo.php b/themes/fusionforge/themeinfo.php index 16da8018b..d61643d7b 100644 --- a/themes/fusionforge/themeinfo.php +++ b/themes/fusionforge/themeinfo.php @@ -9,9 +9,11 @@ if (!defined('PHPWIKI_VERSION')) { require_once 'lib/WikiTheme.php'; require_once 'themes/wikilens/themeinfo.php'; -class WikiTheme_fusionforge extends WikiTheme_Wikilens { +class WikiTheme_fusionforge extends WikiTheme_Wikilens +{ - function getCSS () { + function getCSS() + { $css = array(); $css[] = $this->_CSSlink("", "fusionforge.css", ""); $css[] = $this->_CSSlink("", "fusionforge-print.css", "print"); @@ -21,7 +23,8 @@ class WikiTheme_fusionforge extends WikiTheme_Wikilens { return HTML($css); } - function header() { + function header() + { global $HTML, $group_id, $group_public_name, $request, $project; $pagename = $request->getArg('pagename'); @@ -46,20 +49,20 @@ class WikiTheme_fusionforge extends WikiTheme_Wikilens { } $HTML->header(array('h1' => '', - 'title'=> $group_public_name._(": ").htmlspecialchars($pagename), - 'group' => $group_id, - 'toptab' => 'wiki', - 'submenu' => $submenu - ) - ); + 'title' => $group_public_name . _(": ") . htmlspecialchars($pagename), + 'group' => $group_id, + 'toptab' => 'wiki', + 'submenu' => $submenu + ) + ); // Display a warning banner for internal users when the wiki is opened // to external users. if (method_exists($project, 'getIsExternal') && $project->getIsExternal()) { $external_user = false; if (session_loggedin()) { - $user = session_get_user(); - $external_user = $user->getIsExternal(); + $user = session_get_user(); + $external_user = $user->getIsExternal(); } if (!$external_user) { $page = $request->getPage(); @@ -67,15 +70,16 @@ class WikiTheme_fusionforge extends WikiTheme_Wikilens { $external_msg = _("This page is external."); } echo $HTML->information(_("This project is shared with third-party users") . - sprintf(_(" (non %s users)."), forge_get_config('company')) . - (isset($external_msg) ? ' ' . $external_msg : '')); + sprintf(_(" (non %s users)."), forge_get_config('company')) . + (isset($external_msg) ? ' ' . $external_msg : '')); } } textdomain($domain); } } - function footer() { + function footer() + { if (defined('FUSIONFORGE') and FUSIONFORGE) { global $HTML; @@ -89,29 +93,32 @@ class WikiTheme_fusionforge extends WikiTheme_Wikilens { } } - function initGlobals() { + function initGlobals() + { global $request; static $already = 0; if (!$already) { $script_url = deduce_script_name(); - $script_url .= '/'. $GLOBALS['group_name'] ; + $script_url .= '/' . $GLOBALS['group_name']; if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug'])) - $script_url .= ("?start_debug=".$_GET['start_debug']); + $script_url .= ("?start_debug=" . $_GET['start_debug']); $folderArrowPath = dirname($this->_findData('images/folderArrowLoading.gif')); $pagename = $request->getArg('pagename'); $this->addMoreHeaders(JavaScript('', array('src' => $this->_findData("wikilens.js")))); - $js = "var data_path = '". javascript_quote_string(DATA_PATH) ."';\n" - // Temp remove pagename because of XSS warning - // ."var pagename = '". javascript_quote_string($pagename) ."';\n" - ."var script_url= '". javascript_quote_string($script_url) ."';\n" - ."var stylepath = data_path+'/".javascript_quote_string($this->_theme)."/';\n" - ."var folderArrowPath = '".javascript_quote_string($folderArrowPath)."';\n" - ."var use_path_info = " . (USE_PATH_INFO ? "true" : "false") .";\n"; + $js = "var data_path = '" . javascript_quote_string(DATA_PATH) . "';\n" + // Temp remove pagename because of XSS warning + // ."var pagename = '". javascript_quote_string($pagename) ."';\n" + . "var script_url= '" . javascript_quote_string($script_url) . "';\n" + . "var stylepath = data_path+'/" . javascript_quote_string($this->_theme) . "/';\n" + . "var folderArrowPath = '" . javascript_quote_string($folderArrowPath) . "';\n" + . "var use_path_info = " . (USE_PATH_INFO ? "true" : "false") . ";\n"; $this->addMoreHeaders(JavaScript($js)); $already = 1; } } - function load() { + + function load() + { $this->initGlobals(); @@ -163,7 +170,8 @@ class WikiTheme_fusionforge extends WikiTheme_Wikilens { } /* Callback when a new user creates or edits a page */ - function CbNewUserEdit (&$request, $userid) { + function CbNewUserEdit(&$request, $userid) + { $content = "{{Template/UserPage}}\n\n----\n[[CategoryWiki user]]"; $dbi =& $request->_dbi; $page = $dbi->getPage($userid); diff --git a/themes/shamino_com/themeinfo.php b/themes/shamino_com/themeinfo.php index 743de4f32..161b6d99a 100644 --- a/themes/shamino_com/themeinfo.php +++ b/themes/shamino_com/themeinfo.php @@ -19,16 +19,17 @@ if (!defined('PHPWIKI_VERSION')) { require_once 'lib/WikiTheme.php'; -class WikiTheme_shamino_com extends WikiTheme { +class WikiTheme_shamino_com extends WikiTheme +{ - function makeActionButton ($action, $label = false, $page_or_rev = false) { + function makeActionButton($action, $label = false, $page_or_rev = false) + { extract($this->_get_name_and_rev($page_or_rev)); if (is_array($action)) { $attr = $action; $action = isset($attr['action']) ? $attr['action'] : 'browse'; - } - else + } else $attr['action'] = $action; $class = is_safe_action($action) ? 'named-wiki' : 'wikiadmin'; @@ -44,67 +45,68 @@ class WikiTheme_shamino_com extends WikiTheme { return $this->makeButton($label, WikiURL($pagename, $attr), $class); } - function load() { - // CSS file defines fonts, colors and background images for this - // style. The companion '*-heavy.css' file isn't defined, it's just - // expected to be in the same directory that the base style is in. - - // This should result in phpwiki-printer.css being used when - // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. - $this->setDefaultCSS('PhpWiki', array('' => 'shamino_com.css', 'print' => 'phpwiki-printer.css')); - - // This allows one to manually select "Printer" style (when browsing page) - // to see what the printer style looks like. - $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); - $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css'); - $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); - - /** - * The logo image appears on every page and links to the HomePage. - */ - //$this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); - - /** - * The Signature image is shown after saving an edited page. If this - * is set to false then the "Thank you for editing..." screen will - * be omitted. - */ - - //$this->addImageAlias('signature', WIKI_NAME . "Signature.png"); - // Uncomment this next line to disable the signature. - $this->addImageAlias('signature', false); - - /** - * WikiWords can automatically be split by inserting spaces between - * the words. The default is to leave WordsSmashedTogetherLikeSo. - */ - //$this->setAutosplitWikiWords(false); - - /** - * Layout improvement with dangling links for mostly closed wiki's: - * If false, only users with edit permissions will be presented the - * special wikiunknown class with "?" and Tooltip. - * If true (default), any user will see the ?, but will be presented - * the PrintLoginForm on a click. - */ - $this->setAnonEditUnknownLinks(false); - - /* - * You may adjust the formats used for formatting dates and times - * below. (These examples give the default formats.) - * Formats are given as format strings to PHP strftime() function See - * http://www.php.net/manual/en/function.strftime.php for details. - * Do not include the server's zone (%Z), times are converted to the - * user's time zone. - */ - $this->setDateFormat("%B %d, %Y"); - $this->setTimeFormat("%H:%M"); - - /* - * To suppress times in the "Last edited on" messages, give a - * give a second argument of false: - */ - //$this->setDateFormat("%B %d, %Y", false); + function load() + { + // CSS file defines fonts, colors and background images for this + // style. The companion '*-heavy.css' file isn't defined, it's just + // expected to be in the same directory that the base style is in. + + // This should result in phpwiki-printer.css being used when + // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. + $this->setDefaultCSS('PhpWiki', array('' => 'shamino_com.css', 'print' => 'phpwiki-printer.css')); + + // This allows one to manually select "Printer" style (when browsing page) + // to see what the printer style looks like. + $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); + $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css'); + $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); + + /** + * The logo image appears on every page and links to the HomePage. + */ + //$this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); + + /** + * The Signature image is shown after saving an edited page. If this + * is set to false then the "Thank you for editing..." screen will + * be omitted. + */ + + //$this->addImageAlias('signature', WIKI_NAME . "Signature.png"); + // Uncomment this next line to disable the signature. + $this->addImageAlias('signature', false); + + /** + * WikiWords can automatically be split by inserting spaces between + * the words. The default is to leave WordsSmashedTogetherLikeSo. + */ + //$this->setAutosplitWikiWords(false); + + /** + * Layout improvement with dangling links for mostly closed wiki's: + * If false, only users with edit permissions will be presented the + * special wikiunknown class with "?" and Tooltip. + * If true (default), any user will see the ?, but will be presented + * the PrintLoginForm on a click. + */ + $this->setAnonEditUnknownLinks(false); + + /* + * You may adjust the formats used for formatting dates and times + * below. (These examples give the default formats.) + * Formats are given as format strings to PHP strftime() function See + * http://www.php.net/manual/en/function.strftime.php for details. + * Do not include the server's zone (%Z), times are converted to the + * user's time zone. + */ + $this->setDateFormat("%B %d, %Y"); + $this->setTimeFormat("%H:%M"); + + /* + * To suppress times in the "Last edited on" messages, give a + * give a second argument of false: + */ + //$this->setDateFormat("%B %d, %Y", false); } } diff --git a/themes/smaller/themeinfo.php b/themes/smaller/themeinfo.php index 4c924dde6..57eae4bb5 100644 --- a/themes/smaller/themeinfo.php +++ b/themes/smaller/themeinfo.php @@ -15,16 +15,17 @@ if (!defined('PHPWIKI_VERSION')) { require_once 'lib/WikiTheme.php'; -class WikiTheme_smaller extends WikiTheme { +class WikiTheme_smaller extends WikiTheme +{ - function makeActionButton ($action, $label = false, $page_or_rev = false) { + function makeActionButton($action, $label = false, $page_or_rev = false) + { extract($this->_get_name_and_rev($page_or_rev)); if (is_array($action)) { $attr = $action; $action = isset($attr['action']) ? $attr['action'] : 'browse'; - } - else + } else $attr['action'] = $action; $class = is_safe_action($action) ? 'named-wiki' : 'wikiadmin'; diff --git a/themes/wikilens/themeinfo.php b/themes/wikilens/themeinfo.php index 8d5b3229f..10c2a7ea9 100644 --- a/themes/wikilens/themeinfo.php +++ b/themes/wikilens/themeinfo.php @@ -14,80 +14,82 @@ if (!defined('PHPWIKI_VERSION')) { */ require_once 'lib/WikiTheme.php'; -class WikiTheme_Wikilens extends WikiTheme { - - function load() { - // CSS file defines fonts, colors and background images for this - // style. The companion '*-heavy.css' file isn't defined, it's just - // expected to be in the same directory that the base style is in. - - // This should result in phpwiki-printer.css being used when - // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. - $this->setDefaultCSS('PhpWiki', array('' => 'wikilens.css', 'print' => 'phpwiki-printer.css')); - - // This allows one to manually select "Printer" style (when browsing page) - // to see what the printer style looks like. - $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); - $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css'); - $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); - - /** - * The logo image appears on every page and links to the HomePage. - */ - $this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); - - /** - * The Signature image is shown after saving an edited page. If this - * is set to false then the "Thank you for editing..." screen will - * be omitted. - */ - - $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); - // Uncomment this next line to disable the signature. - $this->addImageAlias('signature', false); - - /* - * Link icons. - */ - //$this->setLinkIcon('http'); - $this->setLinkIcon('https'); - $this->setLinkIcon('ftp'); - $this->setLinkIcon('mailto'); - //$this->setLinkIcon('interwiki'); - $this->setLinkIcon('wikiuser'); - //$this->setLinkIcon('*', 'url'); - - /** - * WikiWords can automatically be split by inserting spaces between - * the words. The default is to leave WordsSmashedTogetherLikeSo. - */ - //$this->setAutosplitWikiWords(false); - - /** - * Layout improvement with dangling links for mostly closed wiki's: - * If false, only users with edit permissions will be presented the - * special wikiunknown class with "?" and Tooltip. - * If true (default), any user will see the ?, but will be presented - * the PrintLoginForm on a click. - */ - $this->setAnonEditUnknownLinks(false); - - /* - * You may adjust the formats used for formatting dates and times - * below. (These examples give the default formats.) - * Formats are given as format strings to PHP strftime() function See - * http://www.php.net/manual/en/function.strftime.php for details. - * Do not include the server's zone (%Z), times are converted to the - * user's time zone. - */ - $this->setDateFormat("%B %d, %Y"); - $this->setTimeFormat("%H:%M"); - - /* - * To suppress times in the "Last edited on" messages, give a - * give a second argument of false: - */ - //$this->setDateFormat("%B %d, %Y", false); +class WikiTheme_Wikilens extends WikiTheme +{ + + function load() + { + // CSS file defines fonts, colors and background images for this + // style. The companion '*-heavy.css' file isn't defined, it's just + // expected to be in the same directory that the base style is in. + + // This should result in phpwiki-printer.css being used when + // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. + $this->setDefaultCSS('PhpWiki', array('' => 'wikilens.css', 'print' => 'phpwiki-printer.css')); + + // This allows one to manually select "Printer" style (when browsing page) + // to see what the printer style looks like. + $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); + $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css'); + $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); + + /** + * The logo image appears on every page and links to the HomePage. + */ + $this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); + + /** + * The Signature image is shown after saving an edited page. If this + * is set to false then the "Thank you for editing..." screen will + * be omitted. + */ + + $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); + // Uncomment this next line to disable the signature. + $this->addImageAlias('signature', false); + + /* + * Link icons. + */ + //$this->setLinkIcon('http'); + $this->setLinkIcon('https'); + $this->setLinkIcon('ftp'); + $this->setLinkIcon('mailto'); + //$this->setLinkIcon('interwiki'); + $this->setLinkIcon('wikiuser'); + //$this->setLinkIcon('*', 'url'); + + /** + * WikiWords can automatically be split by inserting spaces between + * the words. The default is to leave WordsSmashedTogetherLikeSo. + */ + //$this->setAutosplitWikiWords(false); + + /** + * Layout improvement with dangling links for mostly closed wiki's: + * If false, only users with edit permissions will be presented the + * special wikiunknown class with "?" and Tooltip. + * If true (default), any user will see the ?, but will be presented + * the PrintLoginForm on a click. + */ + $this->setAnonEditUnknownLinks(false); + + /* + * You may adjust the formats used for formatting dates and times + * below. (These examples give the default formats.) + * Formats are given as format strings to PHP strftime() function See + * http://www.php.net/manual/en/function.strftime.php for details. + * Do not include the server's zone (%Z), times are converted to the + * user's time zone. + */ + $this->setDateFormat("%B %d, %Y"); + $this->setTimeFormat("%H:%M"); + + /* + * To suppress times in the "Last edited on" messages, give a + * give a second argument of false: + */ + //$this->setDateFormat("%B %d, %Y", false); } } diff --git a/uploads/index.php b/uploads/index.php index bc317da18..1e65fa942 100644 --- a/uploads/index.php +++ b/uploads/index.php @@ -1,3 +1,3 @@ getID(); } -if (! isset($group_id) || ! isset($project)) { - exit_no_group(); +if (!isset($group_id) || !isset($project)) { + exit_no_group(); } elseif (!($project->usesPlugin("wiki"))) { - exit_disabled('home'); + exit_disabled('home'); } // If project is private, check membership. if (!$project->isPublic()) { - session_require_perm('project_read', $project->getID()); + session_require_perm('project_read', $project->getID()); } $arr = explode('/', urldecode(getStringFromServer('REQUEST_URI'))); @@ -75,40 +75,40 @@ array_shift($arr); array_shift($arr); $path = join('/', $arr); -$basepath = realpath('/opt/groups/'.$project->getUnixName().'/www/uploads/'); -$filepath = realpath($basepath.'/'.$path); +$basepath = realpath('/opt/groups/' . $project->getUnixName() . '/www/uploads/'); +$filepath = realpath($basepath . '/' . $path); $filename = basename($filepath); if (strncmp($basepath, $filepath, strlen($basepath)) !== 0) { - error_log("DEBUG: basepath=$basepath, filepath=$filepath"); - exit_error('Invalid path: No access'); + error_log("DEBUG: basepath=$basepath, filepath=$filepath"); + exit_error('Invalid path: No access'); } if ($filepath && is_file($filepath)) { - if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) { - # workaround for IE filename bug with multiple periods/ multiple dots in filename - # that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe - $filename = preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1); - } - $filename = str_replace('"', '', $filename); - header('Content-disposition: filename="'.$filename.'"'); - - if (function_exists('finfo_open')) { - $finfo = finfo_open(FILEINFO_MIME_TYPE); - $mimetype = finfo_file($finfo, $filepath); - } else { - $mimetype = 'application/octet-stream'; - } - header("Content-type: $mimetype"); - - $length = filesize($filepath); - header("Content-length: $length"); - - readfile_chunked($filepath); + if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) { + # workaround for IE filename bug with multiple periods/ multiple dots in filename + # that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe + $filename = preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1); + } + $filename = str_replace('"', '', $filename); + header('Content-disposition: filename="' . $filename . '"'); + + if (function_exists('finfo_open')) { + $finfo = finfo_open(FILEINFO_MIME_TYPE); + $mimetype = finfo_file($finfo, $filepath); + } else { + $mimetype = 'application/octet-stream'; + } + header("Content-type: $mimetype"); + + $length = filesize($filepath); + header("Content-length: $length"); + + readfile_chunked($filepath); } else { - header("HTTP/1.0 404 Not Found"); - require_once $gfwww.'404.php'; + header("HTTP/1.0 404 Not Found"); + require_once $gfwww . '404.php'; } // Local Variables: diff --git a/wikiadmin.php b/wikiadmin.php index d766dc9dd..4bdcfe048 100644 --- a/wikiadmin.php +++ b/wikiadmin.php @@ -42,19 +42,19 @@ * ALONE BASIS." */ -require_once dirname(__FILE__)."/../../env.inc.php"; -require_once $gfcommon.'include/pre.php'; -require_once forge_get_config('plugins_path').'wiki/common/WikiPlugin.class.php'; -require_once forge_get_config('plugins_path').'wiki/common/wikiconfig.class.php'; +require_once dirname(__FILE__) . "/../../env.inc.php"; +require_once $gfcommon . 'include/pre.php'; +require_once forge_get_config('plugins_path') . 'wiki/common/WikiPlugin.class.php'; +require_once forge_get_config('plugins_path') . 'wiki/common/wikiconfig.class.php'; $user = session_get_user(); // get the session user if (!$user || !is_object($user)) { - exit_error(_('Invalid User'),'home'); -} elseif ( $user->isError()) { - exit_error($user->getErrorMessage(),'home'); -} elseif ( !$user->isActive()) { - exit_error(_('User not active'),'home'); + exit_error(_('Invalid User'), 'home'); +} elseif ($user->isError()) { + exit_error($user->getErrorMessage(), 'home'); +} elseif (!$user->isActive()) { + exit_error(_('User not active'), 'home'); } $type = getStringFromRequest('type'); @@ -63,29 +63,29 @@ $pluginname = 'wiki'; $config = getArrayFromRequest('config'); if (!$type) { - exit_missing_param('',array(_('No TYPE specified')),'home'); + exit_missing_param('', array(_('No TYPE specified')), 'home'); } elseif (!$group_id) { - exit_missing_param('',array(_('No ID specified')),'home'); + exit_missing_param('', array(_('No ID specified')), 'home'); } else { if ($type == 'admin_post') { $group = group_get_object($group_id); - if ( !$group) { + if (!$group) { exit_no_group(); } if (!($group->usesPlugin($pluginname))) { //check if the group has the wiki plugin active - exit_error(sprintf(_('First activate the %s plugin through the Project\'s Admin Interface'),$pluginname),'home'); + exit_error(sprintf(_('First activate the %s plugin through the Project\'s Admin Interface'), $pluginname), 'home'); } $userperm = $group->getPermission(); //we'll check if the user belongs to the group - if ( !$userperm->IsMember()) { - exit_permission_denied(_('You are not a member of this project'),'home'); + if (!$userperm->IsMember()) { + exit_permission_denied(_('You are not a member of this project'), 'home'); } //only project admin can access here - if ( $userperm->isAdmin() ) { + if ($userperm->isAdmin()) { $wc = new WikiConfig($group_id); foreach ($wc->getWikiConfigNames() as $c) { - if ( ! array_key_exists($c, $config)) { + if (!array_key_exists($c, $config)) { $config[$c] = 0; } } @@ -98,28 +98,28 @@ if (!$type) { $type = 'admin'; $feedback = _('Configuration saved.'); } else { - exit_permission_denied(_('You are not a project Admin'),'home'); + exit_permission_denied(_('You are not a project Admin'), 'home'); } } if ($type == 'admin') { $group = group_get_object($group_id); - if ( !$group) { + if (!$group) { exit_no_group(); } - if ( ! ($group->usesPlugin ($pluginname)) ) {//check if the group has the plugin active - exit_error(sprintf(_('First activate the %s plugin through the Project\'s Admin Interface'),$pluginname),'home'); + if (!($group->usesPlugin($pluginname))) { //check if the group has the plugin active + exit_error(sprintf(_('First activate the %s plugin through the Project\'s Admin Interface'), $pluginname), 'home'); } $userperm = $group->getPermission(); //we'll check if the user belongs to the group - if ( !$userperm->IsMember()) { - exit_permission_denied(_('You are not a member of this project'),'home'); + if (!$userperm->IsMember()) { + exit_permission_denied(_('You are not a member of this project'), 'home'); } //only project admin can access here - if ( $userperm->isAdmin() ) { + if ($userperm->isAdmin()) { site_project_header(array('title' => _("Configuration for your project's wiki"), - 'pagename' => $pluginname, - 'group' => $group_id, - 'toptab' => 'wiki', - 'sectionvals' => array(group_getname($group_id)))); + 'pagename' => $pluginname, + 'group' => $group_id, + 'toptab' => 'wiki', + 'sectionvals' => array(group_getname($group_id)))); $wc = new WikiConfig($group_id); @@ -127,41 +127,41 @@ if (!$type) { print "\n"; print "\n"; print "
    \n"; - print ""._('Wiki Configuration')."\n"; + print "" . _('Wiki Configuration') . "\n"; print "
    \n"; print "\n"; print "\n"; print "\n"; print ''; - print "\n\n\n" . - "\n" . - "\n\n"; + print "\n\n\n" . + "\n" . + "\n\n"; foreach ($wc->getWikiConfigNames() as $c) { $checked = $wc->getWikiConfig($c) ? ' checked="checked"' : ''; $desc = $wc->getWikiConfigDescription($c); print "\n\n" . - "\n" . - "\n"; + "\n" . + "\n"; } print "
    ". - _("Parameter"). - "". - _("Value"). - "
    " . + _("Parameter") . + "" . + _("Value") . + "
    $desc" . - "
    " . + "
    \n"; print "

    "; + _("Save Configuration") . + "\" />

    "; print "
    \n"; print "
    \n"; print "\n"; print "\n"; print "\n"; } else { - exit_permission_denied(_('You are not a project Admin'),'home'); + exit_permission_denied(_('You are not a project Admin'), 'home'); } } } diff --git a/wikilist.php b/wikilist.php index 83051b2b5..8ad8c41fb 100644 --- a/wikilist.php +++ b/wikilist.php @@ -21,22 +21,22 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -require_once dirname(__FILE__)."/../../env.inc.php"; -require_once $gfcommon.'include/pre.php'; -require_once $gfwww.'admin/admin_utils.php'; +require_once dirname(__FILE__) . "/../../env.inc.php"; +require_once $gfcommon . 'include/pre.php'; +require_once $gfwww . 'admin/admin_utils.php'; $title = _('List of active wikis in Forge'); -site_admin_header(array('title'=>$title)); +site_admin_header(array('title' => $title)); $sortorder = getStringFromRequest('sortorder', 'group_name'); -$sortorder = util_ensure_value_in_set ($sortorder, array ('group_name','register_time','unix_group_name','is_public','is_external','members')) ; +$sortorder = util_ensure_value_in_set($sortorder, array('group_name', 'register_time', 'unix_group_name', 'is_public', 'is_external', 'members')); $res = db_query_params('SELECT group_name,register_time,unix_group_name,groups.group_id,is_public,is_external,status, COUNT(user_group.group_id) AS members FROM groups LEFT JOIN user_group ON user_group.group_id=groups.group_id WHERE status=$1 GROUP BY group_name,register_time,unix_group_name,groups.group_id,is_public,is_external,status - ORDER BY '.$sortorder, - array('A')); + ORDER BY ' . $sortorder, + array('A')); $headers = array( _('Project Name'), @@ -70,18 +70,18 @@ while ($grp = db_fetch_array($res)) { if ($project->usesPlugin("wiki")) { $time_display = ""; if ($grp['register_time'] != 0) { - $time_display = date(_('Y-m-d H:i'),$grp['register_time']); + $time_display = date(_('Y-m-d H:i'), $grp['register_time']); } - echo 'boxGetAltRowStyle($i).'>'; - echo ''.$grp['group_name'].''; - echo ''.$time_display.''; - echo ''.$grp['unix_group_name']. ''; - echo ''.$grp['is_public'].''; + echo 'boxGetAltRowStyle($i) . '>'; + echo '' . $grp['group_name'] . ''; + echo '' . $time_display . ''; + echo '' . $grp['unix_group_name'] . ''; + echo '' . $grp['is_public'] . ''; if (isset($sys_intranet) & $sys_intranet) { - echo ''.$grp['is_external'].''; + echo '' . $grp['is_external'] . ''; } - echo ''.$grp['members'].''; - echo ''._("Upgrade").''; + echo '' . $grp['members'] . ''; + echo '' . _("Upgrade") . ''; echo ''; $i++; } -- 2.45.0