Copyright 2003 Carlo Zottmann Copyright 2002, 2003, 2005 David DELON Copyright 2002, 2003, 2004, 2006 Charles NEPOTE Copyright 2002, 2003 Patrick PAUL Copyright 2003 Eric DELORD Copyright 2003 Eric FELDSTEIN Copyright 2004-2006 Jean-Christophe ANDRE Copyright 2005-2006 Didier LOISEAU All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Yes, most of the formatting used in this file is HORRIBLY BAD STYLE. However, most of the action happens outside of this file, and I really wanted the code to look as small as what it does. Basically. Oh, I just suck. :) */ // do not change this line, you fool. In fact, don't change anything! Ever! define("WAKKA_VERSION", "0.1.1"); define("WIKINI_VERSION", "0.5.0"); define("YESWIKI_VERSION", "Cercopitheque"); define("YESWIKI_RELEASE", "2016.01.25"); require 'includes/constants.php'; include 'includes/urlutils.inc.php'; include 'includes/i18n.inc.php'; //error_reporting(E_ALL); // start the compute time list($g_usec, $g_sec) = explode(" ", microtime()); define("t_start", (float) $g_usec + (float) $g_sec); $t_SQL = 0; class Wiki { public $dblink; public $page; public $tag; public $parameter = array(); public $queryLog = array(); public $interWiki = array(); public $VERSION; public $CookiePath = '/'; public $inclusions = array(); /** * an array containing all the actions that are implemented by an object * @access private */ public $actionObjects; // LinkTrackink public $isTrackingLinks = false; public $linktable = array(); public $pageCache = array(); public $_groupsCache = array(); public $_actionsAclsCache = array(); // constructor public function __construct($config) { $this->config = $config; // some host do not allow mysql_pconnect $this->dblink = @mysqli_connect( $this->config["mysql_host"], $this->config["mysql_user"], $this->config["mysql_password"] ); if ($this->dblink) { if (!@mysqli_select_db($this->dblink, $this->config["mysql_database"])) { @mysqli_close($this->dblink); $this->dblink = false; } } $this->VERSION = WAKKA_VERSION; // determine le chemin pour les cookies $a = parse_url($this->GetConfigValue('base_url')); $this->CookiePath = dirname($a['path']); // Fixe la gestion des cookie sous les OS utilisant le \ comme separateur de chemin $this->CookiePath = str_replace("\\", "/", $this->CookiePath); // ajoute un '/' terminal sauf si on est a la racine web if ($this->CookiePath != '/') { $this->CookiePath .= '/'; } } // DATABASE public function Query($query) { if ($this->GetConfigValue("debug")) { $start = $this->GetMicroTime(); } if (!$result = mysqli_query($this->dblink, $query)) { ob_end_clean(); die("Query failed: " . $query . " (" . mysqli_error($this->dblink) . ")"); } if ($this->GetConfigValue("debug")) { $time = $this->GetMicroTime() - $start; $this->queryLog[] = array( "query" => $query, "time" => $time); } return $result; } public function LoadSingle($query) { if ($data = $this->LoadAll($query)) { return $data[0]; } return null; } public function LoadAll($query) { $data = array(); if ($r = $this->Query($query)) { while ($row = mysqli_fetch_assoc($r)) { $data[] = $row; } mysqli_free_result($r); } return $data; } // MISC public function GetMicroTime() { list($usec, $sec) = explode(" ", microtime());return ((float) $usec + (float) $sec); } public function IncludeBuffered($filename, $notfoundText = "", $vars = "", $path = "") { if ($path) { $dirs = explode(":", $path); } else { $dirs = array(""); } foreach ($dirs as $dir) { if ($dir) { $dir .= "/"; } $fullfilename = $dir . $filename; if (file_exists($fullfilename)) { if (is_array($vars)) { extract($vars); } ob_start(); include $fullfilename; $output = ob_get_contents(); ob_end_clean(); return $output; } } if ($notfoundText) { return $notfoundText; } else { return false; } } // VARIABLES public function GetPageTag() {return $this->tag;} public function GetPageTime() {return $this->page["time"];} public function GetMethod() {return $this->method;} public function GetConfigValue($name) {return isset($this->config[$name]) ? trim($this->config[$name]) : '';} public function GetWakkaName() {return $this->GetConfigValue("wakka_name");} public function GetWakkaVersion() {return $this->VERSION;} public function GetWikiNiVersion() {return WIKINI_VERSION;} /** * Retrieves all the triples that match some criteria. * This allows to search triples by their approximate resource or property names. * The allowed operators are the sql LIKE and the sql = * @param string $resource The resource of the triples * @param string $property The property of the triple to retrieve or null * @param string $res_op The operator of comparison between the effective resource and $resource (default: 'LIKE') * @param string $prop_op The operator of comparison between the effective property and $property (default: '=') * @return array The list of all the triples that match the asked criteria */ public function GetMatchingTriples($resource, $property = null, $res_op = 'LIKE', $prop_op = '=') { static $operators = array('=', 'LIKE'); // we might want to add other operators later $res_op = strtoupper($res_op); if (!in_array($res_op, $operators)) { $res_op = '='; } $sql = 'SELECT * FROM ' . $this->GetConfigValue('table_prefix') . 'triples ' . 'WHERE resource ' . $res_op . ' "' . addslashes($resource) . '"'; if ($property !== null) { $prop_op = strtoupper($prop_op); if (!in_array($prop_op, $operators)) { $prop_op = '='; } $sql .= ' AND property ' . $prop_op . ' "' . addslashes($property) . '"'; } return $this->LoadAll($sql); } /** * Retrieves all the values for a given couple (resource, property) * @param string $resource The resource of the triples * @param string $property The property of the triple to retrieve * @param string $re_prefix The prefix to add to $resource (defaults to THISWIKI_PREFIX) * @param string $prop_prefix The prefix to add to $property (defaults to WIKINI_VOC_PREFIX) * @return array An array of the retrieved values, in the form * array( * 0 => array(id = 7 , 'value' => $value1), * 1 => array(id = 34, 'value' => $value2), * ... * ) */ public function GetAllTriplesValues($resource, $property, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX) { $sql = 'SELECT id, value FROM ' . $this->GetConfigValue('table_prefix') . 'triples ' . 'WHERE resource = "' . addslashes($re_prefix . $resource) . '" ' . 'AND property = "' . addslashes($prop_prefix . $property) . '" '; return $this->LoadAll($sql); } /** * Retrieves a single value for a given couple (resource, property) * @param string $resource The resource of the triples * @param string $property The property of the triple to retrieve * @param string $re_prefix The prefix to add to $resource (defaults to THISWIKI_PREFIX) * @param string $prop_prefix The prefix to add to $property (defaults to WIKINI_VOC_PREFIX) * @return string The value corresponding to ($resource, $property) or null if * there is no such couple in the triples table. */ public function GetTripleValue($resource, $property, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX) { $res = $this->GetAllTriplesValues($resource, $property, $re_prefix, $prop_prefix); if ($res) { return $res[0]['value']; } return null; } /** * Checks whether a triple exists or not * @param string $resource The resource of the triple to find * @param string $property The property of the triple to find * @param string $value The value of the triple to find * @param string $re_prefix The prefix to add to $resource (defaults to THISWIKI_PREFIX) * @param string $prop_prefix The prefix to add to $property (defaults to WIKINI_VOC_PREFIX) * @param int The id of the found triple or 0 if there is no such triple. */ public function TripleExists($resource, $property, $value, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX) { $sql = 'SELECT id FROM ' . $this->GetConfigValue('table_prefix') . 'triples ' . 'WHERE resource = "' . addslashes($re_prefix . $resource) . '" ' . 'AND property = "' . addslashes($prop_prefix . $property) . '" ' . 'AND value = "' . addslashes($value) . '"'; $res = $this->LoadSingle($sql); if (!$res) { return 0; } return $res['id']; } /** * Inserts a new triple ($resource, $property, $value) in the triples' table * @param string $resource The resource of the triple to insert * @param string $property The property of the triple to insert * @param string $value The value of the triple to insert * @param string $re_prefix The prefix to add to $resource (defaults to THISWIKI_PREFIX) * @param string $prop_prefix The prefix to add to $property (defaults to WIKINI_VOC_PREFIX) * @return int An error code: 0 (success), 1 (failure) or 3 (already exists) */ public function InsertTriple($resource, $property, $value, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX) { if ($this->TripleExists($resource, $property, $value, $re_prefix, $prop_prefix)) { return 3; } $sql = 'INSERT INTO ' . $this->GetConfigValue('table_prefix') . 'triples (resource, property, value)' . 'VALUES ("' . addslashes($re_prefix . $resource) . '", "' . addslashes($prop_prefix . $property) . '", "' . addslashes($value) . '")'; return $this->Query($sql) ? 0 : 1; } /** * Updates a triple ($resource, $property, $value) in the triples' table * @param string $resource The resource of the triple to update * @param string $property The property of the triple to update * @param string $oldvalue The old value of the triple to update * @param string $newvalue The new value of the triple to update * @param string $re_prefix The prefix to add to $resource (defaults to THISWIKI_PREFIX) * @param string $prop_prefix The prefix to add to $property (defaults to WIKINI_VOC_PREFIX) * @return int An error code: 0 (succ?s), 1 (?chec), * 2 ($resource, $property, $oldvalue does not exist) * or 3 ($resource, $property, $newvalue already exists) */ public function UpdateTriple($resource, $property, $oldvalue, $newvalue, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX) { $id = $this->TripleExists($resource, $property, $oldvalue, $re_prefix, $prop_prefix); if (!$id) { return 2; } if ($this->TripleExists($resource, $property, $newvalue, $re_prefix, $prop_prefix)) { return 3; } $sql = 'UPDATE ' . $this->GetConfigValue('table_prefix') . 'triples ' . 'SET value = "' . addslashes($newvalue) . '" ' . 'WHERE id = ' . $id; return $this->Query($sql) ? 0 : 1; } /** * Deletes a triple ($resource, $property, $value) from the triples' table * @param string $resource The resource of the triple to delete * @param string $property The property of the triple to delete * @param string $value The value of the triple to delete. If set to null, * deletes all the triples corresponding to ($resource, $property). (defaults to null) * @param string $re_prefix The prefix to add to $resource (defaults to THISWIKI_PREFIX) * @param string $prop_prefix The prefix to add to $property (defaults to WIKINI_VOC_PREFIX) */ public function DeleteTriple($resource, $property, $value = null, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX) { $sql = 'DELETE FROM ' . $this->GetConfigValue('table_prefix') . 'triples ' . 'WHERE resource = "' . addslashes($re_prefix . $resource) . '" ' . 'AND property = "' . addslashes($prop_prefix . $property) . '" '; if ($value !== null) { $sql .= 'AND value = "' . addslashes($value) . '"'; } $this->Query($sql); } // inclusions /** * Enregistre une nouvelle inclusion dans la pile d'inclusions. * * @param string $pageTag Le nom de la page qui va etre inclue * @return int Le nombre d'elements dans la pile */ public function RegisterInclusion($pageTag) { return array_unshift($this->inclusions, strtolower(trim($pageTag))); } /** * Retire le dernier element de la pile d'inclusions. * * @return string Le nom de la page dont l'inclusion devrait se terminer. * null s'il n'y a plus d'inclusion dans la pile. */ public function UnregisterLastInclusion() { return array_shift($this->inclusions); } /** * Renvoie le nom de la page en cours d'inclusion. * * @example // dans le cas d'une action comme l'ActionEcrivezMoi * if($inc = $this->CurrentInclusion() && strtolower($this->GetPageTag()) != $inc) * echo 'Cette action ne peut etre appelee depuis une page inclue'; * @return string Le nom (tag) de la page (en minuscules) * false si la pile est vide. */ public function GetCurrentInclusion() { return isset($this->inclusions[0]) ? $this->inclusions[0] : false; } /** * Verifie si on est a l'interieur d'une inclusion par $pageTag (sans tenir compte de la casse) * * @param string $pageTag Le nom de la page a verifier * @return bool True si on est a l'interieur d'une inclusion par $pageTag (false sinon) */ public function IsIncludedBy($pageTag) { return in_array(strtolower($pageTag), $this->inclusions); } /** * * @return array La pile d'inclusions * L'element 0 sera la derniere inclusion, l'element 1 sera son parent et ainsi de suite. */ public function GetAllInclusions() { return $this->inclusions; } /** * Remplace la pile des inclusions par une nouvelle pile (par defaut une pile vide) * Permet de formatter une page sans tenir compte des inclusions precedentes. * * @param array $ La nouvelle pile d'inclusions. * L'element 0 doit representer la derniere inclusion, l'element 1 son parent et ainsi de suite. * @return array L'ancienne pile d'inclusions, avec les noms des pages en minuscules. */ public function SetInclusions($pile = array()) { $temp = $this->inclusions; $this->inclusions = $pile; return $temp; } // PAGES public function LoadPage($tag, $time = "", $cache = 1) { // retrieve from cache if (!$time && $cache && (($cachedPage = $this->GetCachedPage($tag)) !== false)) { $page = $cachedPage; } else // load page { $sql = "SELECT * FROM " . $this->config["table_prefix"] . "pages" . " WHERE tag = '" . mysqli_real_escape_string($this->dblink, $tag) . "' AND " . ($time ? "time = '" . mysqli_real_escape_string($this->dblink, $time) . "'" : "latest = 'Y'") . " LIMIT 1"; $page = $this->LoadSingle($sql); // the database is in ISO-8859-15, it must be converted if (isset($page['body'])) { $page['body'] = _convert($page['body'], "ISO-8859-15"); } // cache result if (!$time) { $this->CachePage($page, $tag); } } return $page; } /** * Retrieves the cached version of a page. * * Notice that this method null or false, use * $this->GetCachedPage($tag) === false * to check if a page is not in the cache. * @return mixed The cached version of a page: * - the page DB line if the page exists and is in cache * - null if the cache knows that the page does not exists * - false is the cache does not know the page */ public function GetCachedPage($tag) {return (array_key_exists($tag, $this->pageCache) ? $this->pageCache[$tag] : false);} /** * Caches a page's DB line. * * @param array $page The page (full) DB line or null if the page does not exists * @param string $pageTag The tag of the page to cache. Defaults to $page['tag'] but is mendatory when $page === null */ public function CachePage($page, $pageTag = null) { if ($pageTag === null) { $pageTag = $page["tag"]; } $this->pageCache[$pageTag] = $page; } public function SetPage($page) { $this->page = $page;if ($this->page["tag"]) { $this->tag = $this->page["tag"]; } } public function LoadPageById($id) {return $this->LoadSingle("select * from " . $this->config["table_prefix"] . "pages where id = '" . mysqli_real_escape_string($this->dblink, $id) . "' limit 1");} public function LoadRevisions($page) {return $this->LoadAll("select * from " . $this->config["table_prefix"] . "pages where tag = '" . mysqli_real_escape_string($this->dblink, $page) . "' order by time desc");} public function LoadPagesLinkingTo($tag) {return $this->LoadAll("select from_tag as tag from " . $this->config["table_prefix"] . "links where to_tag = '" . mysqli_real_escape_string($this->dblink, $tag) . "' order by tag");} public function LoadRecentlyChanged($limit = 50) { $limit = (int) $limit; if ($pages = $this->LoadAll("select id, tag, time, user, owner from " . $this->config["table_prefix"] . "pages where latest = 'Y' and comment_on = '' order by time desc limit $limit")) { foreach ($pages as $page) { $this->CachePage($page); } return $pages; } } public function LoadAllPages() {return $this->LoadAll("select * from " . $this->config["table_prefix"] . "pages where latest = 'Y' order by tag");} public function FullTextSearch($phrase) {return $this->LoadAll("select * from " . $this->config["table_prefix"] . "pages where latest = 'Y' and match(tag, body) against('" . mysqli_real_escape_string($this->dblink, $phrase) . "')");} public function LoadWantedPages() { $p = $this->config["table_prefix"]; $r = "SELECT ${p}links.to_tag AS tag, COUNT(${p}links.from_tag) AS count " . "FROM ${p}links LEFT JOIN ${p}pages ON ${p}links.to_tag = ${p}pages.tag " . "WHERE ${p}pages.tag IS NULL GROUP BY ${p}links.to_tag ORDER BY count DESC, tag ASC"; return $this->LoadAll($r); } public function LoadOrphanedPages() {return $this->LoadAll("select distinct tag from " . $this->config["table_prefix"] . "pages as p left join " . $this->config["table_prefix"] . "links as l on p.tag = l.to_tag where l.to_tag is NULL and p.comment_on = '' and p.latest = 'Y' order by tag");} public function IsOrphanedPage($tag) {return $this->LoadAll("select distinct tag from " . $this->config['table_prefix'] . "pages as p left join " . $this->config['table_prefix'] . "links as l on p.tag = l.to_tag where l.to_tag is NULL and p.latest = 'Y' and tag = '" . mysqli_real_escape_string($this->dblink, $tag) . "'");} public function DeleteOrphanedPage($tag) { $p = $this->config["table_prefix"]; $this->Query("DELETE FROM ${p}pages WHERE tag='" . mysqli_real_escape_string($this->dblink, $tag) . "' OR comment_on='" . mysqli_real_escape_string($this->dblink, $tag) . "'"); $this->Query("DELETE FROM ${p}links WHERE from_tag='" . mysqli_real_escape_string($this->dblink, $tag) . "' "); $this->Query("DELETE FROM ${p}acls WHERE page_tag='" . mysqli_real_escape_string($this->dblink, $tag) . "' "); $this->Query("DELETE FROM ${p}referrers WHERE page_tag='" . mysqli_real_escape_string($this->dblink, $tag) . "' "); } /** * SavePage * Sauvegarde un contenu dans une page donnee * * @param string $body Contenu a sauvegarder dans la page * @param string $tag Nom de la page * @param string $comment_on Indication si c'est un commentaire * @param boolean $bypass_acls Indication si on bypasse les droits d'ecriture * @return int Code d'erreur : 0 (succes), 1 (l'utilisateur n'a pas les droits) */ public function SavePage($tag, $body, $comment_on = "", $bypass_acls = false) { // get current user $user = $this->GetUserName(); // check bypass of rights or write privilege $rights = $bypass_acls || ($comment_on ? $this->HasAccess("comment", $comment_on) : $this->HasAccess("write", $tag)); if ($rights) { // is page new? if (!$oldPage = $this->LoadPage($tag)) { // create default write acl. store empty write ACL for comments. $this->SaveAcl($tag, "write", ($comment_on ? $user : $this->GetConfigValue("default_write_acl"))); // create default read acl $this->SaveAcl($tag, "read", $this->GetConfigValue("default_read_acl")); // create default comment acl. $this->SaveAcl($tag, "comment", ($comment_on ? "" : $this->GetConfigValue("default_comment_acl"))); // current user is owner; if user is logged in! otherwise, no owner. if ($this->GetUser()) { $owner = $user; } else { $owner = ''; } } else { // aha! page isn't new. keep owner! $owner = $oldPage["owner"]; // ...and comment_on, eventualy? if ($comment_on == '') { $comment_on = $oldPage['comment_on']; } } // set all other revisions to old $this->Query("update " . $this->config["table_prefix"] . "pages set latest = 'N' where tag = '" . mysqli_real_escape_string($this->dblink, $tag) . "'"); // add new revision $this->Query("insert into " . $this->config["table_prefix"] . "pages set " . "tag = '" . mysqli_real_escape_string($this->dblink, $tag) . "', " . ($comment_on ? "comment_on = '" . mysqli_real_escape_string($this->dblink, $comment_on) . "', " : "") . "time = now(), " . "owner = '" . mysqli_real_escape_string($this->dblink, $owner) . "', " . "user = '" . mysqli_real_escape_string($this->dblink, $user) . "', " . "latest = 'Y', " . "body = '" . mysqli_real_escape_string($this->dblink, chop($body)) . "', ". "body_r = ''"); unset($this->pageCache[$tag]); return 0; } else { return 1; } } /** * AppendContentToPage * Ajoute du contenu a la fin d'une page * * @param string $content Contenu a ajouter a la page * @param string $page Nom de la page * @param boolean $bypass_acls Bouleen pour savoir s'il faut bypasser les ACLs * @return int Code d'erreur : 0 (succes), 1 (pas de contenu specifie) */ public function AppendContentToPage($content, $page, $bypass_acls = false) { // Si un contenu est specifie if (isset($content)) { // -- Determine quelle est la page : // -- passee en parametre (que se passe-t'il si elle n'existe pas ?) // -- ou la page en cours par defaut $page = isset($page) ? $page : $this->GetPageTag(); // -- Chargement de la page $result = $this->LoadPage($page); $body = $result['body']; // -- Ajout du contenu a la fin de la page $body .= $content; // -- Sauvegarde de la page // TODO : que se passe-t-il si la page est pleine ou si l'utilisateur n'a pas les droits ? $this->SavePage($page, $body, "", $bypass_acls); // now we render it internally so we can write the updated link table. $this->ClearLinkTable(); $this->StartLinkTracking(); $temp = $this->SetInclusions(); $this->RegisterInclusion($this->GetPageTag()); // on simule totalement un affichage normal $this->Format($body); $this->SetInclusions($temp); if ($user = $this->GetUser()) { $this->TrackLinkTo($user['name']); } if ($owner = $this->GetPageOwner()) { $this->TrackLinkTo($owner); } $this->StopLinkTracking(); $this->WriteLinkTable(); $this->ClearLinkTable(); /**/ // Retourne 0 seulement si tout c'est bien passe return 0; } else { return 1; } } /** * LogAdministrativeAction($user, $content, $page = "") * * @param string $user Utilisateur * @param string $content Contenu de l'enregistrement * @param string $page Page de log * * @return int Code d'erreur : 0 (succes), 1 (pas de contenu specifie) */ public function LogAdministrativeAction($user, $content, $page = "") { $order = array("\r\n", "\n", "\r"); $replace = '\\n'; $content = str_replace($order, $replace, $content); $contentToAppend = "\n" . date("Y-m-d H:i:s") . " . . . . " . $user . " . . . . " . $content . "\n"; $page = $page ? $page : "LogDesActionsAdministratives" . date("Ymd"); return $this->AppendContentToPage($contentToAppend, $page, true); } /** * Make the purge of page versions that are older than the last version older than 3 "pages_purge_time" * This method permits to allways keep a version that is older than that period. */ public function PurgePages() { if ($days = $this->GetConfigValue("pages_purge_time")) { // is purge active ? // let's search which pages versions we have to remove // this is necessary beacause even MySQL does not handel multi-tables deletes before version 4.0 $wnPages = $this->GetConfigValue('table_prefix') . 'pages'; $sql = 'SELECT DISTINCT a.id FROM ' . $wnPages . ' a,' . $wnPages . ' b WHERE a.latest = \'N\' AND a.time < date_sub(now(), INTERVAL \'' . addslashes($days) . '\' DAY) AND a.tag = b.tag AND a.time < b.time AND b.time < date_sub(now(), INTERVAL \'' . addslashes($days) . '\' DAY)'; $ids = $this->LoadAll($sql); if (count($ids)) { // there are some versions to remove from DB // let's build one big request, that's better... $sql = 'DELETE FROM ' . $wnPages . ' WHERE id IN ('; foreach ($ids as $key => $line) { $sql .= ($key ? ', ' : '') . $line['id']; // NB.: id is an int, no need of quotes } $sql .= ')'; // ... and send it ! $this->Query($sql); } } } // COOKIES public function SetSessionCookie($name, $value) { SetCookie($name, $value, 0, $this->CookiePath); $_COOKIE[$name] = $value; } public function SetPersistentCookie($name, $value, $remember = 0) { SetCookie($name, $value, time() + ($remember ? 90 * 24 * 60 * 60 : 60 * 60), $this->CookiePath); $_COOKIE[$name] = $value; } public function DeleteCookie($name) { SetCookie($name, "", 1, $this->CookiePath); $_COOKIE[$name] = ""; } public function GetCookie($name) {return $_COOKIE[$name];} // HTTP/REQUEST/LINK RELATED public function SetMessage($message) {$_SESSION["message"] = $message;} public function GetMessage() { if (isset($_SESSION["message"])) { $message = $_SESSION["message"]; } else { $message = ""; } $_SESSION["message"] = ""; return $message; } public function Redirect($url) { header("Location: $url"); exit; } // returns just PageName[/method]. public function MiniHref($method = "", $tag = "") { if (!$tag = trim($tag)) { $tag = $this->tag; } return $tag . ($method ? "/" . $method : ""); } // returns the full url to a page/method. public function Href($method = "", $tag = "", $params = "", $htmlspchars = true) { $href = $this->config["base_url"] . $this->MiniHref($method, $tag); if ($params) { $href .= ($this->config["rewrite_mode"] ? "?" : ($htmlspchars ? "&" : '&')) . $params; } return $href; } public function Link($tag, $method = "", $text = "", $track = 1) { $displayText = $text ? $text : $tag; // is this an interwiki link? if (preg_match('/^' . WN_INTERWIKI_CAPTURE . '$/', $tag, $matches)) { if ($tagInterWiki = $this->GetInterWikiUrl($matches[1], $matches[2])) { return '' . htmlspecialchars($displayText, ENT_COMPAT, YW_CHARSET) . ' (interwiki)'; } else { return '' . htmlspecialchars($displayText, ENT_COMPAT, YW_CHARSET) . ' (interwiki inconnu)'; } } // is this a full link? ie, does it contain non alpha-numeric characters? // Note : [:alnum:] is equivalent [0-9A-Za-z] // [^[:alnum:]] means : some caracters other than [0-9A-Za-z] // For example : "www.adress.com", "mailto:adress@domain.com", "http://www.adress.com" else if (preg_match("/[^[:alnum:]]/", $tag)) { // check for various modifications to perform on $tag if (preg_match("/^[\w.-]+\@[\w.-]+$/", $tag)) { // email addresses $tag = 'mailto:' . $tag; } // Note : in Perl regexp, (?: ... ) is a non-catching cluster else if (preg_match('/^[[:alnum:]][[:alnum:].-]*(?:\/|$)/', $tag)) { // protocol-less URLs $tag = 'http://' . $tag; } // Finally, block script schemes (see RFC 3986 about // schemes) and allow relative link & protocol-full URLs else if (preg_match('/^[a-z0-9.+-]*script[a-z0-9.+-]*:/i', $tag) || !(preg_match('/^\.?\.?\//', $tag) || preg_match('/^[a-z0-9.+-]+:\/\//i', $tag))) { // If does't fit, we can't qualify $tag as an URL. // There is a high risk that $tag is just XSS (bad // javascript: code) or anything nasty. So we must not // produce any link at all. return htmlspecialchars($tag . ($text ? ' ' . $text : ''), ENT_COMPAT, YW_CHARSET); } // Important: Here, we know that $tag is not something bad // and that we must produce a link with it // An inline image? (text!=tag and url ends by png,gif,jpeg) if ($text and preg_match("/\.(gif|jpeg|png|jpg)$/i", $tag)) { return ''; } else { // Even if we know $tag is harmless, we MUST encode it // in HTML with htmlspecialchars() before echoing it. // This is not about being paranoiac. This is about // being compliant to the HTML standard. return '' . htmlspecialchars($displayText, ENT_COMPAT, YW_CHARSET) . ''; } } else { // it's a Wiki link! if (!empty($track)) { $this->TrackLinkTo($tag); } if ($this->LoadPage($tag)) { return '' . htmlspecialchars($displayText, ENT_COMPAT, YW_CHARSET) . ''; } else { return '' . htmlspecialchars($displayText, ENT_COMPAT, YW_CHARSET) . '?'; } } } public function ComposeLinkToPage($tag, $method = "", $text = "", $track = 1) { if (!$text) { $text = $tag; } $text = htmlspecialchars($text, ENT_COMPAT, YW_CHARSET); if ($track) { $this->TrackLinkTo($tag); } return '' . $text . ''; } public function IsWikiName($text) { return preg_match('/^' . WN_CAMEL_CASE . '$/', $text); } // LinkTracking management /** * Tracks the link to a given page (only if the LinkTracking is activated) * @param string $tag The tag (name) of the page to track a link to. */ public function TrackLinkTo($tag) { if ($this->LinkTracking()) { $this->linktable[] = $tag; } } /** * @return array The current link tracking table */ public function GetLinkTable() {return $this->linktable;} /** * Clears the link tracking table */ public function ClearLinkTable() {$this->linktable = array();} /** * Starts the LinkTracking * @return bool The previous state of the link tracking */ public function StartLinkTracking() { return $this->LinkTracking(true); } /** * Stops the LinkTracking * @return bool The previous state of the link tracking */ public function StopLinkTracking() { return $this->LinkTracking(false); } /** * Sets and/or retrieve the state of the LinkTracking * @param bool $newStatus The new status of the LinkTracking * (defaults to null which lets it unchanged) * @return bool The previous state of the link tracking */ public function LinkTracking($newStatus = null) { $old = $this->isTrackingLinks; if ($newStatus !== null) { $this->isTrackingLinks = $newStatus; } return $old; } public function WriteLinkTable() { // delete old link table $this->Query("delete from " . $this->config["table_prefix"] . "links where from_tag = '" . mysqli_real_escape_string($this->dblink, $this->GetPageTag()) . "'"); if ($linktable = $this->GetLinkTable()) { $from_tag = mysqli_real_escape_string($this->dblink, $this->GetPageTag()); foreach ($linktable as $to_tag) { $lower_to_tag = strtolower($to_tag); if (!isset($written[$lower_to_tag])) { $this->Query("insert into " . $this->config["table_prefix"] . "links set from_tag = '" . $from_tag . "', to_tag = '" . mysqli_real_escape_string($this->dblink, $to_tag) . "'"); $written[$lower_to_tag] = 1; } } } } public function Header() { $action = $this->GetConfigValue("header_action"); if (($actionObj = &$this->GetActionObject($action)) && is_object($actionObj)) { return $actionObj->GenerateHeader(); } return $this->Action($action, 1); } public function Footer() { $action = $this->GetConfigValue("footer_action"); if (($actionObj = &$this->GetActionObject($action)) && is_object($actionObj)) { return $actionObj->GenerateFooter(); } return $this->Action($action, 1); } // FORMS public function FormOpen($method = "", $tag = "", $formMethod = "post", $class = "") { $result = "
\n"; } // INTERWIKI STUFF public function ReadInterWikiConfig() { if ($lines = file("interwiki.conf")) { foreach ($lines as $line) { if ($line = trim($line)) { list($wikiName, $wikiUrl) = explode(" ", trim($line)); $this->AddInterWiki($wikiName, $wikiUrl); } } } } public function AddInterWiki($name, $url) { $this->interWiki[strtolower($name)] = $url; } public function GetInterWikiUrl($name, $tag) { if (isset($this->interWiki[strtolower($name)])) { return $this->interWiki[strtolower($name)] . $tag; } else { return false; } } // REFERRERS public function LogReferrer($tag = "", $referrer = "") { // fill values if (!$tag = trim($tag)) { $tag = $this->GetPageTag(); } if (!$referrer = trim($referrer) and isset($_SERVER["HTTP_REFERER"])) { $referrer = $_SERVER["HTTP_REFERER"]; } // check if it's coming from another site if ($referrer && !preg_match("/^" . preg_quote($this->GetConfigValue("base_url"), "/") . "/", $referrer)) { // avoid XSS (with urls like "javascript:alert()" and co) // by forcing http/https prefix // NB.: this does NOT exempt to htmlspecialchars() the collected URIs ! if (!preg_match('`^https?://`', $referrer)) { return; } $this->Query("insert into " . $this->config["table_prefix"] . "referrers set " . "page_tag = '" . mysqli_real_escape_string($this->dblink, $tag) . "', " . "referrer = '" . mysqli_real_escape_string($this->dblink, $referrer) . "', " . "time = now()"); } } public function LoadReferrers($tag = "") { return $this->LoadAll("select referrer, count(referrer) as num from " . $this->config["table_prefix"] . "referrers " . ($tag = trim($tag) ? "where page_tag = '" . mysqli_real_escape_string($this->dblink, $tag) . "'" : "") . " group by referrer order by num desc"); } public function PurgeReferrers() { if ($days = $this->GetConfigValue("referrers_purge_time")) { $this->Query("delete from " . $this->config["table_prefix"] . "referrers where time < date_sub(now(), interval '" . mysqli_real_escape_string($this->dblink, $days) . "' day)"); } } // PLUGINS /** * Exacutes an "action" module and returns the generated output * @param string $action The name of the action and its eventual parameters, * as it appears in the page between "{{" and "}}" * @param boolean $forceLinkTracking By default, the link tracking will be disabled * during the call of an action. Set this value totrue
to allow it.
* @param array $vars An array of additionnal parameters to give to the action, in the form
* array( 'param' => 'value').
* This allows you to call Action() internally, setting $action to the name of the action
* you want to call and it's parameters in an array, wich is more efficient than
* the pattern-matching algorithm used to extract the parameters from $action.
* @return The output generated by the action.
*/
public function Action($action, $forceLinkTracking = 0, $vars = array())
{
$cmd = trim($action);
// extract $action and $vars_temp ("raw" attributes)
if (!preg_match("/^([a-zA-Z-0-9]+)\/?(.*)$/", $cmd, $matches)) {
return '" . _t('INCORRECT_PAGENAME') . "
"; exit; } // create wiki object $wiki = new Wiki($wakkaConfig); // update lang loadpreferredI18n($page); // check for database access if (!$wiki->dblink) { echo "" . _t('DB_CONNECT_FAIL') . "
"; // Log error (useful to find the buggy server in a load balancing platform) trigger_error(_t('LOG_DB_CONNECT_FAIL')); exit; } // go! if (!isset($method)) { $method = ''; } // Security (quick hack) : Check method syntax if (!(preg_match('#^[A-Za-z0-9_]*$#', $method))) { $method = ''; } include 'tools/prepend.php'; $wiki->Run($page, $method);