PageRenderTime 68ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/gforge/plugins/wiki/www/lib/WikiDB.php

https://github.com/neymanna/fusionforge
PHP | 2638 lines | 1285 code | 175 blank | 1178 comment | 253 complexity | 65dd65c437575b0f1b41bac0d39117be MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. <?php //-*-php-*-
  2. rcs_id('$Id: WikiDB.php,v 1.135 2005/09/11 14:19:44 rurban Exp $');
  3. require_once('lib/PageType.php');
  4. /**
  5. * The classes in the file define the interface to the
  6. * page database.
  7. *
  8. * @package WikiDB
  9. * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
  10. * Reini Urban
  11. */
  12. /**
  13. * Force the creation of a new revision.
  14. * @see WikiDB_Page::createRevision()
  15. */
  16. if (!defined('WIKIDB_FORCE_CREATE'))
  17. define('WIKIDB_FORCE_CREATE', -1);
  18. /**
  19. * Abstract base class for the database used by PhpWiki.
  20. *
  21. * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
  22. * turn contain <tt>WikiDB_PageRevision</tt>s.
  23. *
  24. * Conceptually a <tt>WikiDB</tt> contains all possible
  25. * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
  26. * Since all possible pages are already contained in a WikiDB, a call
  27. * to WikiDB::getPage() will never fail (barring bugs and
  28. * e.g. filesystem or SQL database problems.)
  29. *
  30. * Also each <tt>WikiDB_Page</tt> always contains at least one
  31. * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
  32. * [PageName] here."). This default content has a version number of
  33. * zero.
  34. *
  35. * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
  36. * only create new revisions or delete old ones --- one can not modify
  37. * an existing revision.
  38. */
  39. class WikiDB {
  40. /**
  41. * Open a WikiDB database.
  42. *
  43. * This is a static member function. This function inspects its
  44. * arguments to determine the proper subclass of WikiDB to
  45. * instantiate, and then it instantiates it.
  46. *
  47. * @access public
  48. *
  49. * @param hash $dbparams Database configuration parameters.
  50. * Some pertinent paramters are:
  51. * <dl>
  52. * <dt> dbtype
  53. * <dd> The back-end type. Current supported types are:
  54. * <dl>
  55. * <dt> SQL
  56. * <dd> Generic SQL backend based on the PEAR/DB database abstraction
  57. * library. (More stable and conservative)
  58. * <dt> ADODB
  59. * <dd> Another generic SQL backend. (More current features are tested here. Much faster)
  60. * <dt> dba
  61. * <dd> Dba based backend. The default and by far the fastest.
  62. * <dt> cvs
  63. * <dd>
  64. * <dt> file
  65. * <dd> flat files
  66. * </dl>
  67. *
  68. * <dt> dsn
  69. * <dd> (Used by the SQL and ADODB backends.)
  70. * The DSN specifying which database to connect to.
  71. *
  72. * <dt> prefix
  73. * <dd> Prefix to be prepended to database tables (and file names).
  74. *
  75. * <dt> directory
  76. * <dd> (Used by the dba backend.)
  77. * Which directory db files reside in.
  78. *
  79. * <dt> timeout
  80. * <dd> Used only by the dba backend so far.
  81. * And: When optimizing mysql it closes timed out mysql processes.
  82. * otherwise only used for dba: Timeout in seconds for opening (and
  83. * obtaining lock) on the dbm file.
  84. *
  85. * <dt> dba_handler
  86. * <dd> (Used by the dba backend.)
  87. *
  88. * Which dba handler to use. Good choices are probably either
  89. * 'gdbm' or 'db2'.
  90. * </dl>
  91. *
  92. * @return WikiDB A WikiDB object.
  93. **/
  94. function open ($dbparams) {
  95. $dbtype = $dbparams{'dbtype'};
  96. include_once("lib/WikiDB/$dbtype.php");
  97. $class = 'WikiDB_' . $dbtype;
  98. return new $class ($dbparams);
  99. }
  100. /**
  101. * Constructor.
  102. *
  103. * @access private
  104. * @see open()
  105. */
  106. function WikiDB (&$backend, $dbparams) {
  107. $this->_backend = &$backend;
  108. // don't do the following with the auth_dsn!
  109. if (isset($dbparams['auth_dsn'])) return;
  110. $this->_cache = new WikiDB_cache($backend);
  111. if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this;
  112. // If the database doesn't yet have a timestamp, initialize it now.
  113. if ($this->get('_timestamp') === false)
  114. $this->touch();
  115. //FIXME: devel checking.
  116. //$this->_backend->check();
  117. }
  118. /**
  119. * Close database connection.
  120. *
  121. * The database may no longer be used after it is closed.
  122. *
  123. * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
  124. * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
  125. * which have been obtained from it.
  126. *
  127. * @access public
  128. */
  129. function close () {
  130. $this->_backend->close();
  131. $this->_cache->close();
  132. }
  133. /**
  134. * Get a WikiDB_Page from a WikiDB.
  135. *
  136. * A {@link WikiDB} consists of the (infinite) set of all possible pages,
  137. * therefore this method never fails.
  138. *
  139. * @access public
  140. * @param string $pagename Which page to get.
  141. * @return WikiDB_Page The requested WikiDB_Page.
  142. */
  143. function getPage($pagename) {
  144. static $error_displayed = false;
  145. $pagename = (string) $pagename;
  146. if (DEBUG) {
  147. if ($pagename === '') {
  148. if ($error_displayed) return false;
  149. $error_displayed = true;
  150. if (function_exists("xdebug_get_function_stack"))
  151. var_dump(xdebug_get_function_stack());
  152. trigger_error("empty pagename", E_USER_WARNING);
  153. return false;
  154. }
  155. } else {
  156. assert($pagename != '');
  157. }
  158. return new WikiDB_Page($this, $pagename);
  159. }
  160. /**
  161. * Determine whether page exists (in non-default form).
  162. *
  163. * <pre>
  164. * $is_page = $dbi->isWikiPage($pagename);
  165. * </pre>
  166. * is equivalent to
  167. * <pre>
  168. * $page = $dbi->getPage($pagename);
  169. * $current = $page->getCurrentRevision();
  170. * $is_page = ! $current->hasDefaultContents();
  171. * </pre>
  172. * however isWikiPage may be implemented in a more efficient
  173. * manner in certain back-ends.
  174. *
  175. * @access public
  176. *
  177. * @param string $pagename string Which page to check.
  178. *
  179. * @return boolean True if the page actually exists with
  180. * non-default contents in the WikiDataBase.
  181. */
  182. function isWikiPage ($pagename) {
  183. $page = $this->getPage($pagename);
  184. return $page->exists();
  185. }
  186. /**
  187. * Delete page from the WikiDB.
  188. *
  189. * Deletes the page from the WikiDB with the possibility to revert and diff.
  190. * //Also resets all page meta-data to the default values.
  191. *
  192. * Note: purgePage() effectively destroys all revisions of the page from the WikiDB.
  193. *
  194. * @access public
  195. *
  196. * @param string $pagename Name of page to delete.
  197. */
  198. function deletePage($pagename) {
  199. // don't create empty revisions of already purged pages.
  200. if ($this->_backend->get_latest_version($pagename))
  201. $result = $this->_cache->delete_page($pagename);
  202. else
  203. $result = -1;
  204. /* Generate notification emails? */
  205. if (! $this->isWikiPage($pagename) and !isa($GLOBALS['request'],'MockRequest')) {
  206. $notify = $this->get('notify');
  207. if (!empty($notify) and is_array($notify)) {
  208. global $request;
  209. //TODO: deferr it (quite a massive load if you remove some pages).
  210. //TODO: notification class which catches all changes,
  211. // and decides at the end of the request what to mail.
  212. // (type, page, who, what, users, emails)
  213. // could be used for PageModeration and RSS2 Cloud xml-rpc also.
  214. $page = new WikiDB_Page($this, $pagename);
  215. list($emails, $userids) = $page->getPageChangeEmails($notify);
  216. if (!empty($emails)) {
  217. $from = $request->_user->getId();
  218. $editedby = sprintf(_("Removed by: %s"), $from);
  219. $emails = join(',', $emails);
  220. $headers = "From: $from <nobody>\r\n" .
  221. "Bcc: $emails\r\n" .
  222. "MIME-Version: 1.0\r\n" .
  223. "Content-Type: text/plain; charset=".CHARSET."; format=flowed\r\n" .
  224. "Content-Transfer-Encoding: 8bit";
  225. $subject = sprintf(_("Page removed %s"), urlencode($pagename));
  226. if (mail("<undisclosed-recipients>","[".WIKI_NAME."] ".$subject,
  227. $subject."\n".
  228. $editedby."\n\n".
  229. "Deleted $pagename",
  230. $headers))
  231. trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
  232. $pagename, join(',',$userids)), E_USER_NOTICE);
  233. else
  234. trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
  235. $pagename, join(',',$userids)), E_USER_WARNING);
  236. }
  237. }
  238. }
  239. //How to create a RecentChanges entry with explaining summary? Dynamically
  240. /*
  241. $page = $this->getPage($pagename);
  242. $current = $page->getCurrentRevision();
  243. $meta = $current->_data;
  244. $version = $current->getVersion();
  245. $meta['summary'] = _("removed");
  246. $page->save($current->getPackedContent(), $version + 1, $meta);
  247. */
  248. return $result;
  249. }
  250. /**
  251. * Completely remove the page from the WikiDB, without undo possibility.
  252. */
  253. function purgePage($pagename) {
  254. $result = $this->_cache->purge_page($pagename);
  255. $this->deletePage($pagename); // just for the notification
  256. return $result;
  257. }
  258. /**
  259. * Retrieve all pages.
  260. *
  261. * Gets the set of all pages with non-default contents.
  262. *
  263. * @access public
  264. *
  265. * @param boolean $include_defaulted Normally pages whose most
  266. * recent revision has empty content are considered to be
  267. * non-existant. Unless $include_defaulted is set to true, those
  268. * pages will not be returned.
  269. *
  270. * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
  271. * in the WikiDB which have non-default contents.
  272. */
  273. function getAllPages($include_empty=false, $sortby=false, $limit=false,
  274. $exclude=false)
  275. {
  276. // HACK: memory_limit=8M will fail on too large pagesets. old php on unix only!
  277. if (USECACHE) {
  278. $mem = ini_get("memory_limit");
  279. if ($mem and !$limit and !isWindows() and !check_php_version(4,3)) {
  280. $limit = 450;
  281. $GLOBALS['request']->setArg('limit', $limit);
  282. $GLOBALS['request']->setArg('paging', 'auto');
  283. }
  284. }
  285. $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
  286. $exclude);
  287. return new WikiDB_PageIterator($this, $result,
  288. array('include_empty' => $include_empty,
  289. 'exclude' => $exclude,
  290. 'limit' => $limit));
  291. }
  292. /**
  293. * $include_empty = true: include also empty pages
  294. * exclude: comma-seperated list pagenames: TBD: array of pagenames
  295. */
  296. function numPages($include_empty=false, $exclude='') {
  297. if (method_exists($this->_backend, 'numPages'))
  298. // FIXME: currently are all args ignored.
  299. $count = $this->_backend->numPages($include_empty, $exclude);
  300. else {
  301. // FIXME: exclude ignored.
  302. $iter = $this->getAllPages($include_empty, false, false, $exclude);
  303. $count = $iter->count();
  304. $iter->free();
  305. }
  306. return (int)$count;
  307. }
  308. /**
  309. * Title search.
  310. *
  311. * Search for pages containing (or not containing) certain words
  312. * in their names.
  313. *
  314. * Pages are returned in alphabetical order whenever it is
  315. * practical to do so.
  316. *
  317. * FIXME: clarify $search syntax. provide glob=>TextSearchQuery converters
  318. *
  319. * @access public
  320. * @param TextSearchQuery $search A TextSearchQuery object
  321. * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
  322. * @see TextSearchQuery
  323. */
  324. function titleSearch($search, $sortby='pagename', $limit=false, $exclude=false) {
  325. $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
  326. return new WikiDB_PageIterator($this, $result,
  327. array('exclude' => $exclude,
  328. 'limit' => $limit));
  329. }
  330. /**
  331. * Full text search.
  332. *
  333. * Search for pages containing (or not containing) certain words
  334. * in their entire text (this includes the page content and the
  335. * page name).
  336. *
  337. * Pages are returned in alphabetical order whenever it is
  338. * practical to do so.
  339. *
  340. * @access public
  341. *
  342. * @param TextSearchQuery $search A TextSearchQuery object.
  343. * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
  344. * @see TextSearchQuery
  345. */
  346. function fullSearch($search, $sortby='pagename', $limit=false, $exclude=false) {
  347. $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
  348. return new WikiDB_PageIterator($this, $result,
  349. array('exclude' => $exclude,
  350. 'limit' => $limit,
  351. 'stoplisted' => $result->stoplisted
  352. ));
  353. }
  354. /**
  355. * Find the pages with the greatest hit counts.
  356. *
  357. * Pages are returned in reverse order by hit count.
  358. *
  359. * @access public
  360. *
  361. * @param integer $limit The maximum number of pages to return.
  362. * Set $limit to zero to return all pages. If $limit < 0, pages will
  363. * be sorted in decreasing order of popularity.
  364. *
  365. * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
  366. * pages.
  367. */
  368. function mostPopular($limit = 20, $sortby = '-hits') {
  369. $result = $this->_backend->most_popular($limit, $sortby);
  370. return new WikiDB_PageIterator($this, $result);
  371. }
  372. /**
  373. * Find recent page revisions.
  374. *
  375. * Revisions are returned in reverse order by creation time.
  376. *
  377. * @access public
  378. *
  379. * @param hash $params This hash is used to specify various optional
  380. * parameters:
  381. * <dl>
  382. * <dt> limit
  383. * <dd> (integer) At most this many revisions will be returned.
  384. * <dt> since
  385. * <dd> (integer) Only revisions since this time (unix-timestamp) will be returned.
  386. * <dt> include_minor_revisions
  387. * <dd> (boolean) Also include minor revisions. (Default is not to.)
  388. * <dt> exclude_major_revisions
  389. * <dd> (boolean) Don't include non-minor revisions.
  390. * (Exclude_major_revisions implies include_minor_revisions.)
  391. * <dt> include_all_revisions
  392. * <dd> (boolean) Return all matching revisions for each page.
  393. * Normally only the most recent matching revision is returned
  394. * for each page.
  395. * </dl>
  396. *
  397. * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
  398. * matching revisions.
  399. */
  400. function mostRecent($params = false) {
  401. $result = $this->_backend->most_recent($params);
  402. return new WikiDB_PageRevisionIterator($this, $result);
  403. }
  404. /**
  405. * @access public
  406. *
  407. * @return Iterator A generic iterator containing rows of (duplicate) pagename, wantedfrom.
  408. */
  409. function wantedPages($exclude_from='', $exclude='', $sortby=false, $limit=false) {
  410. return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
  411. //return new WikiDB_PageIterator($this, $result);
  412. }
  413. /**
  414. * Call the appropriate backend method.
  415. *
  416. * @access public
  417. * @param string $from Page to rename
  418. * @param string $to New name
  419. * @param boolean $updateWikiLinks If the text in all pages should be replaced.
  420. * @return boolean true or false
  421. */
  422. function renamePage($from, $to, $updateWikiLinks = false) {
  423. assert(is_string($from) && $from != '');
  424. assert(is_string($to) && $to != '');
  425. $result = false;
  426. if (method_exists($this->_backend, 'rename_page')) {
  427. $oldpage = $this->getPage($from);
  428. $newpage = $this->getPage($to);
  429. //update all WikiLinks in existing pages
  430. //non-atomic! i.e. if rename fails the links are not undone
  431. if ($updateWikiLinks) {
  432. require_once('lib/plugin/WikiAdminSearchReplace.php');
  433. $links = $oldpage->getBackLinks();
  434. while ($linked_page = $links->next()) {
  435. WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,
  436. $linked_page->getName(),
  437. $from, $to);
  438. }
  439. // ape: Disabled to avoid recursive modification when renaming
  440. // a page like 'PageApe' to 'PageApeTwo'.
  441. //
  442. // $links = $newpage->getBackLinks();
  443. // while ($linked_page = $links->next()) {
  444. // WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,
  445. // $linked_page->getName(),
  446. // $from, $to);
  447. // }
  448. }
  449. if ($oldpage->exists() and ! $newpage->exists()) {
  450. if ($result = $this->_backend->rename_page($from, $to)) {
  451. //create a RecentChanges entry with explaining summary
  452. $page = $this->getPage($to);
  453. $current = $page->getCurrentRevision();
  454. $meta = $current->_data;
  455. $version = $current->getVersion();
  456. $meta['summary'] = sprintf(_("renamed from %s"), $from);
  457. $page->save($current->getPackedContent(), $version + 1, $meta);
  458. }
  459. } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
  460. // if a version 0 exists try it also.
  461. $result = $this->_backend->rename_page($from, $to);
  462. }
  463. } else {
  464. trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
  465. E_USER_WARNING);
  466. }
  467. /* Generate notification emails? */
  468. if ($result and !isa($GLOBALS['request'], 'MockRequest')) {
  469. $notify = $this->get('notify');
  470. if (!empty($notify) and is_array($notify)) {
  471. list($emails, $userids) = $oldpage->getPageChangeEmails($notify);
  472. if (!empty($emails)) {
  473. $oldpage->sendPageRenameNotification($to, $meta, $emails, $userids);
  474. }
  475. }
  476. }
  477. return $result;
  478. }
  479. /** Get timestamp when database was last modified.
  480. *
  481. * @return string A string consisting of two integers,
  482. * separated by a space. The first is the time in
  483. * unix timestamp format, the second is a modification
  484. * count for the database.
  485. *
  486. * The idea is that you can cast the return value to an
  487. * int to get a timestamp, or you can use the string value
  488. * as a good hash for the entire database.
  489. */
  490. function getTimestamp() {
  491. $ts = $this->get('_timestamp');
  492. return sprintf("%d %d", $ts[0], $ts[1]);
  493. }
  494. /**
  495. * Update the database timestamp.
  496. *
  497. */
  498. function touch() {
  499. $ts = $this->get('_timestamp');
  500. $this->set('_timestamp', array(time(), $ts[1] + 1));
  501. }
  502. /**
  503. * Access WikiDB global meta-data.
  504. *
  505. * NOTE: this is currently implemented in a hackish and
  506. * not very efficient manner.
  507. *
  508. * @access public
  509. *
  510. * @param string $key Which meta data to get.
  511. * Some reserved meta-data keys are:
  512. * <dl>
  513. * <dt>'_timestamp' <dd> Data used by getTimestamp().
  514. * </dl>
  515. *
  516. * @return scalar The requested value, or false if the requested data
  517. * is not set.
  518. */
  519. function get($key) {
  520. if (!$key || $key[0] == '%')
  521. return false;
  522. /*
  523. * Hack Alert: We can use any page (existing or not) to store
  524. * this data (as long as we always use the same one.)
  525. */
  526. $gd = $this->getPage('global_data');
  527. $data = $gd->get('__global');
  528. if ($data && isset($data[$key]))
  529. return $data[$key];
  530. else
  531. return false;
  532. }
  533. /**
  534. * Set global meta-data.
  535. *
  536. * NOTE: this is currently implemented in a hackish and
  537. * not very efficient manner.
  538. *
  539. * @see get
  540. * @access public
  541. *
  542. * @param string $key Meta-data key to set.
  543. * @param string $newval New value.
  544. */
  545. function set($key, $newval) {
  546. if (!$key || $key[0] == '%')
  547. return;
  548. $gd = $this->getPage('global_data');
  549. $data = $gd->get('__global');
  550. if ($data === false)
  551. $data = array();
  552. if (empty($newval))
  553. unset($data[$key]);
  554. else
  555. $data[$key] = $newval;
  556. $gd->set('__global', $data);
  557. }
  558. /* TODO: these are really backend methods */
  559. // SQL result: for simple select or create/update queries
  560. // returns the database specific resource type
  561. function genericSqlQuery($sql, $args=false) {
  562. if (function_exists('debug_backtrace')) { // >= 4.3.0
  563. echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
  564. }
  565. trigger_error("no SQL database", E_USER_ERROR);
  566. return false;
  567. }
  568. // SQL iter: for simple select or create/update queries
  569. // returns the generic iterator object (count,next)
  570. function genericSqlIter($sql, $field_list = NULL) {
  571. if (function_exists('debug_backtrace')) { // >= 4.3.0
  572. echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
  573. }
  574. trigger_error("no SQL database", E_USER_ERROR);
  575. return false;
  576. }
  577. // see backend upstream methods
  578. // ADODB adds surrounding quotes, SQL not yet!
  579. function quote ($s) {
  580. return $s;
  581. }
  582. function isOpen () {
  583. global $request;
  584. if (!$request->_dbi) return false;
  585. else return false; /* so far only needed for sql so false it.
  586. later we have to check dba also */
  587. }
  588. function getParam($param) {
  589. global $DBParams;
  590. if (isset($DBParams[$param])) return $DBParams[$param];
  591. elseif ($param == 'prefix') return '';
  592. else return false;
  593. }
  594. function getAuthParam($param) {
  595. global $DBAuthParams;
  596. if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
  597. elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER'];
  598. elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY'];
  599. else return false;
  600. }
  601. };
  602. /**
  603. * An abstract base class which representing a wiki-page within a
  604. * WikiDB.
  605. *
  606. * A WikiDB_Page contains a number (at least one) of
  607. * WikiDB_PageRevisions.
  608. */
  609. class WikiDB_Page
  610. {
  611. function WikiDB_Page(&$wikidb, $pagename) {
  612. $this->_wikidb = &$wikidb;
  613. $this->_pagename = $pagename;
  614. if (DEBUG) {
  615. if (!(is_string($pagename) and $pagename != '')) {
  616. if (function_exists("xdebug_get_function_stack")) {
  617. echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
  618. } elseif (function_exists("debug_backtrace")) { // >= 4.3.0
  619. printSimpleTrace(debug_backtrace());
  620. }
  621. trigger_error("empty pagename", E_USER_WARNING);
  622. return false;
  623. }
  624. } else {
  625. assert(is_string($pagename) and $pagename != '');
  626. }
  627. }
  628. /**
  629. * Get the name of the wiki page.
  630. *
  631. * @access public
  632. *
  633. * @return string The page name.
  634. */
  635. function getName() {
  636. return $this->_pagename;
  637. }
  638. // To reduce the memory footprint for larger sets of pagelists,
  639. // we don't cache the content (only true or false) and
  640. // we purge the pagedata (_cached_html) also
  641. function exists() {
  642. if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
  643. $current = $this->getCurrentRevision(false);
  644. if (!$current) return false;
  645. return ! $current->hasDefaultContents();
  646. }
  647. /**
  648. * Delete an old revision of a WikiDB_Page.
  649. *
  650. * Deletes the specified revision of the page.
  651. * It is a fatal error to attempt to delete the current revision.
  652. *
  653. * @access public
  654. *
  655. * @param integer $version Which revision to delete. (You can also
  656. * use a WikiDB_PageRevision object here.)
  657. */
  658. function deleteRevision($version) {
  659. $backend = &$this->_wikidb->_backend;
  660. $cache = &$this->_wikidb->_cache;
  661. $pagename = &$this->_pagename;
  662. $version = $this->_coerce_to_version($version);
  663. if ($version == 0)
  664. return;
  665. $backend->lock(array('page','version'));
  666. $latestversion = $cache->get_latest_version($pagename);
  667. if ($latestversion && ($version == $latestversion)) {
  668. $backend->unlock(array('page','version'));
  669. trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
  670. $pagename), E_USER_ERROR);
  671. return;
  672. }
  673. $cache->delete_versiondata($pagename, $version);
  674. $backend->unlock(array('page','version'));
  675. }
  676. /*
  677. * Delete a revision, or possibly merge it with a previous
  678. * revision.
  679. *
  680. * The idea is this:
  681. * Suppose an author make a (major) edit to a page. Shortly
  682. * after that the same author makes a minor edit (e.g. to fix
  683. * spelling mistakes he just made.)
  684. *
  685. * Now some time later, where cleaning out old saved revisions,
  686. * and would like to delete his minor revision (since there's
  687. * really no point in keeping minor revisions around for a long
  688. * time.)
  689. *
  690. * Note that the text after the minor revision probably represents
  691. * what the author intended to write better than the text after
  692. * the preceding major edit.
  693. *
  694. * So what we really want to do is merge the minor edit with the
  695. * preceding edit.
  696. *
  697. * We will only do this when:
  698. * <ul>
  699. * <li>The revision being deleted is a minor one, and
  700. * <li>It has the same author as the immediately preceding revision.
  701. * </ul>
  702. */
  703. function mergeRevision($version) {
  704. $backend = &$this->_wikidb->_backend;
  705. $cache = &$this->_wikidb->_cache;
  706. $pagename = &$this->_pagename;
  707. $version = $this->_coerce_to_version($version);
  708. if ($version == 0)
  709. return;
  710. $backend->lock(array('version'));
  711. $latestversion = $cache->get_latest_version($pagename);
  712. if ($latestversion && $version == $latestversion) {
  713. $backend->unlock(array('version'));
  714. trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
  715. $pagename), E_USER_ERROR);
  716. return;
  717. }
  718. $versiondata = $cache->get_versiondata($pagename, $version, true);
  719. if (!$versiondata) {
  720. // Not there? ... we're done!
  721. $backend->unlock(array('version'));
  722. return;
  723. }
  724. if ($versiondata['is_minor_edit']) {
  725. $previous = $backend->get_previous_version($pagename, $version);
  726. if ($previous) {
  727. $prevdata = $cache->get_versiondata($pagename, $previous);
  728. if ($prevdata['author_id'] == $versiondata['author_id']) {
  729. // This is a minor revision, previous version is
  730. // by the same author. We will merge the
  731. // revisions.
  732. $cache->update_versiondata($pagename, $previous,
  733. array('%content' => $versiondata['%content'],
  734. '_supplanted' => $versiondata['_supplanted']));
  735. }
  736. }
  737. }
  738. $cache->delete_versiondata($pagename, $version);
  739. $backend->unlock(array('version'));
  740. }
  741. /**
  742. * Create a new revision of a {@link WikiDB_Page}.
  743. *
  744. * @access public
  745. *
  746. * @param int $version Version number for new revision.
  747. * To ensure proper serialization of edits, $version must be
  748. * exactly one higher than the current latest version.
  749. * (You can defeat this check by setting $version to
  750. * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
  751. *
  752. * @param string $content Contents of new revision.
  753. *
  754. * @param hash $metadata Metadata for new revision.
  755. * All values in the hash should be scalars (strings or integers).
  756. *
  757. * @param array $links List of pagenames which this page links to.
  758. *
  759. * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
  760. * $version was incorrect, returns false
  761. */
  762. function createRevision($version, &$content, $metadata, $links) {
  763. $backend = &$this->_wikidb->_backend;
  764. $cache = &$this->_wikidb->_cache;
  765. $pagename = &$this->_pagename;
  766. $cache->invalidate_cache($pagename);
  767. $backend->lock(array('version','page','recent','link','nonempty'));
  768. $latestversion = $backend->get_latest_version($pagename);
  769. $newversion = ($latestversion ? $latestversion : 0) + 1;
  770. assert($newversion >= 1);
  771. if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
  772. $backend->unlock(array('version','page','recent','link','nonempty'));
  773. return false;
  774. }
  775. $data = $metadata;
  776. foreach ($data as $key => $val) {
  777. if (empty($val) || $key[0] == '_' || $key[0] == '%')
  778. unset($data[$key]);
  779. }
  780. assert(!empty($data['author']));
  781. if (empty($data['author_id']))
  782. @$data['author_id'] = $data['author'];
  783. if (empty($data['mtime']))
  784. $data['mtime'] = time();
  785. if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
  786. // Ensure mtimes are monotonic.
  787. $pdata = $cache->get_versiondata($pagename, $latestversion);
  788. if ($data['mtime'] < $pdata['mtime']) {
  789. trigger_error(sprintf(_("%s: Date of new revision is %s"),
  790. $pagename,"'non-monotonic'"),
  791. E_USER_NOTICE);
  792. $data['orig_mtime'] = $data['mtime'];
  793. $data['mtime'] = $pdata['mtime'];
  794. }
  795. // FIXME: use (possibly user specified) 'mtime' time or
  796. // time()?
  797. $cache->update_versiondata($pagename, $latestversion,
  798. array('_supplanted' => $data['mtime']));
  799. }
  800. $data['%content'] = &$content;
  801. $cache->set_versiondata($pagename, $newversion, $data);
  802. //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
  803. //':deleted' => empty($content)));
  804. $backend->set_links($pagename, $links);
  805. $backend->unlock(array('version','page','recent','link','nonempty'));
  806. return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
  807. $data);
  808. }
  809. /** A higher-level interface to createRevision.
  810. *
  811. * This takes care of computing the links, and storing
  812. * a cached version of the transformed wiki-text.
  813. *
  814. * @param string $wikitext The page content.
  815. *
  816. * @param int $version Version number for new revision.
  817. * To ensure proper serialization of edits, $version must be
  818. * exactly one higher than the current latest version.
  819. * (You can defeat this check by setting $version to
  820. * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
  821. *
  822. * @param hash $meta Meta-data for new revision.
  823. */
  824. function save($wikitext, $version, $meta) {
  825. $formatted = new TransformedText($this, $wikitext, $meta);
  826. $type = $formatted->getType();
  827. $meta['pagetype'] = $type->getName();
  828. $links = $formatted->getWikiPageLinks();
  829. $backend = &$this->_wikidb->_backend;
  830. $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
  831. if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
  832. $this->set('_cached_html', $formatted->pack());
  833. // FIXME: probably should have some global state information
  834. // in the backend to control when to optimize.
  835. //
  836. // We're doing this here rather than in createRevision because
  837. // postgresql can't optimize while locked.
  838. if ((DEBUG & _DEBUG_SQL)
  839. or (DATABASE_OPTIMISE_FREQUENCY > 0 and
  840. (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) {
  841. if ($backend->optimize()) {
  842. if (DEBUG)
  843. trigger_error(_("Optimizing database"), E_USER_NOTICE);
  844. }
  845. }
  846. /* Generate notification emails? */
  847. if (isa($newrevision, 'WikiDB_PageRevision')) {
  848. // Save didn't fail because of concurrent updates.
  849. $notify = $this->_wikidb->get('notify');
  850. if (!empty($notify) and is_array($notify) and !isa($GLOBALS['request'],'MockRequest')) {
  851. list($emails, $userids) = $this->getPageChangeEmails($notify);
  852. if (!empty($emails)) {
  853. $this->sendPageChangeNotification($wikitext, $version, $meta, $emails, $userids);
  854. }
  855. }
  856. $newrevision->_transformedContent = $formatted;
  857. }
  858. return $newrevision;
  859. }
  860. function getPageChangeEmails($notify) {
  861. $emails = array(); $userids = array();
  862. foreach ($notify as $page => $users) {
  863. if (glob_match($page, $this->_pagename)) {
  864. foreach ($users as $userid => $user) {
  865. if (!$user) { // handle the case for ModeratePage: no prefs, just userid's.
  866. global $request;
  867. $u = $request->getUser();
  868. if ($u->UserName() == $userid) {
  869. $prefs = $u->getPreferences();
  870. } else {
  871. // not current user
  872. if (ENABLE_USER_NEW) {
  873. $u = WikiUser($userid);
  874. $u->getPreferences();
  875. $prefs = &$u->_prefs;
  876. } else {
  877. $u = new WikiUser($GLOBALS['request'], $userid);
  878. $prefs = $u->getPreferences();
  879. }
  880. }
  881. $emails[] = $prefs->get('email');
  882. $userids[] = $userid;
  883. } else {
  884. if (!empty($user['verified']) and !empty($user['email'])) {
  885. $emails[] = $user['email'];
  886. $userids[] = $userid;
  887. } elseif (!empty($user['email'])) {
  888. global $request;
  889. // do a dynamic emailVerified check update
  890. $u = $request->getUser();
  891. if ($u->UserName() == $userid) {
  892. if ($request->_prefs->get('emailVerified')) {
  893. $emails[] = $user['email'];
  894. $userids[] = $userid;
  895. $notify[$page][$userid]['verified'] = 1;
  896. $request->_dbi->set('notify', $notify);
  897. }
  898. } else {
  899. // not current user
  900. if (ENABLE_USER_NEW) {
  901. $u = WikiUser($userid);
  902. $u->getPreferences();
  903. $prefs = &$u->_prefs;
  904. } else {
  905. $u = new WikiUser($GLOBALS['request'], $userid);
  906. $prefs = $u->getPreferences();
  907. }
  908. if ($prefs->get('emailVerified')) {
  909. $emails[] = $user['email'];
  910. $userids[] = $userid;
  911. $notify[$page][$userid]['verified'] = 1;
  912. $request->_dbi->set('notify', $notify);
  913. }
  914. }
  915. // ignore verification
  916. /*
  917. if (DEBUG) {
  918. if (!in_array($user['email'],$emails))
  919. $emails[] = $user['email'];
  920. }
  921. */
  922. }
  923. }
  924. }
  925. }
  926. }
  927. $emails = array_unique($emails);
  928. $userids = array_unique($userids);
  929. return array($emails, $userids);
  930. }
  931. /**
  932. * Send udiff for a changed page to multiple users.
  933. * See rename and remove methods also
  934. */
  935. function sendPageChangeNotification(&$wikitext, $version, $meta, $emails, $userids) {
  936. global $request;
  937. if (@is_array($request->_deferredPageChangeNotification)) {
  938. // collapse multiple changes (loaddir) into one email
  939. $request->_deferredPageChangeNotification[]
  940. = array($this->_pagename, $emails, $userids);
  941. return;
  942. }
  943. $backend = &$this->_wikidb->_backend;
  944. //$backend = &$request->_dbi->_backend;
  945. $subject = _("Page change").' '.urlencode($this->_pagename);
  946. $previous = $backend->get_previous_version($this->_pagename, $version);
  947. if (!isset($meta['mtime'])) $meta['mtime'] = time();
  948. if ($previous) {
  949. $difflink = WikiURL($this->_pagename, array('action'=>'diff'), true);
  950. $cache = &$this->_wikidb->_cache;
  951. //$cache = &$request->_dbi->_cache;
  952. $this_content = explode("\n", $wikitext);
  953. $prevdata = $cache->get_versiondata($this->_pagename, $previous, true);
  954. if (empty($prevdata['%content']))
  955. $prevdata = $backend->get_versiondata($this->_pagename, $previous, true);
  956. $other_content = explode("\n", $prevdata['%content']);
  957. include_once("lib/difflib.php");
  958. $diff2 = new Diff($other_content, $this_content);
  959. //$context_lines = max(4, count($other_content) + 1,
  960. // count($this_content) + 1);
  961. $fmt = new UnifiedDiffFormatter(/*$context_lines*/);
  962. $content = $this->_pagename . " " . $previous . " " .
  963. Iso8601DateTime($prevdata['mtime']) . "\n";
  964. $content .= $this->_pagename . " " . $version . " " .
  965. Iso8601DateTime($meta['mtime']) . "\n";
  966. $content .= $fmt->format($diff2);
  967. } else {
  968. $difflink = WikiURL($this->_pagename,array(),true);
  969. $content = $this->_pagename . " " . $version . " " .
  970. Iso8601DateTime($meta['mtime']) . "\n";
  971. $content .= _("New page");
  972. }
  973. $from = $request->_user->getId();
  974. $editedby = sprintf(_("Edited by: %s"), $from);
  975. $emails = join(',',$emails);
  976. $headers = "From: $from <nobody>\r\n" .
  977. "Bcc: $emails\r\n" .
  978. "MIME-Version: 1.0\r\n" .
  979. "Content-Type: text/plain; charset=".CHARSET."; format=flowed\r\n" .
  980. "Content-Transfer-Encoding: 8bit";
  981. if (mail("<undisclosed-recipients>",
  982. "[".WIKI_NAME."] ".$subject,
  983. $subject."\n". $editedby."\n". $difflink."\n\n". $content,
  984. $headers))
  985. trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
  986. $this->_pagename, join(',',$userids)), E_USER_NOTICE);
  987. else
  988. trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
  989. $this->_pagename, join(',',$userids)), E_USER_WARNING);
  990. }
  991. /** support mass rename / remove (not yet tested)
  992. */
  993. function sendPageRenameNotification($to, &$meta, $emails, $userids) {
  994. global $request;
  995. if (@is_array($request->_deferredPageRenameNotification)) {
  996. $request->_deferredPageRenameNotification[] = array($this->_pagename,
  997. $to, $meta, $emails, $userids);
  998. } else {
  999. $oldname = $this->_pagename;
  1000. $from = $request->_user->getId();
  1001. $editedby = sprintf(_("Edited by: %s"), $from);
  1002. $emails = join(',',$emails);
  1003. $subject = sprintf(_("Page rename %s to %s"), urlencode($oldname), urlencode($to));
  1004. $link = WikiURL($to, true);
  1005. $headers = "From: $from <nobody>\r\n" .
  1006. "Bcc: $emails\r\n" .
  1007. "MIME-Version: 1.0\r\n" .
  1008. "Content-Type: text/plain; charset=".CHARSET."; format=flowed\r\n" .
  1009. "Content-Transfer-Encoding: 8bit";
  1010. if (mail("<undisclosed-recipients>",
  1011. "[".WIKI_NAME."] ".$subject,
  1012. $subject."\n".$editedby."\n".$link."\n\n"."Renamed $from to $to",
  1013. $headers))
  1014. trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
  1015. $oldname, join(',',$userids)), E_USER_NOTICE);
  1016. else
  1017. trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
  1018. $oldname, join(',',$userids)), E_USER_WARNING);
  1019. }
  1020. }
  1021. /**
  1022. * Get the most recent revision of a page.
  1023. *
  1024. * @access public
  1025. *
  1026. * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
  1027. */
  1028. function getCurrentRevision ($need_content = true) {
  1029. $backend = &$this->_wikidb->_backend;
  1030. $cache = &$this->_wikidb->_cache;
  1031. $pagename = &$this->_pagename;
  1032. // Prevent deadlock in case of memory exhausted errors
  1033. // Pure selection doesn't really need locking here.
  1034. // sf.net bug#927395
  1035. // I know it would be better to lock, but with lots of pages this deadlock is more
  1036. // severe than occasionally get not the latest revision.
  1037. // In spirit to wikiwiki: read fast, edit slower.
  1038. //$backend->lock();
  1039. $version = $cache->get_latest_version($pagename);
  1040. // getRevision gets the content also!
  1041. $revision = $this->getRevision($version, $need_content);
  1042. //$backend->unlock();
  1043. assert($revision);
  1044. return $revision;
  1045. }
  1046. /**
  1047. * Get a specific revision of a WikiDB_Page.
  1048. *
  1049. * @access public
  1050. *
  1051. * @param integer $version Which revision to get.
  1052. *
  1053. * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
  1054. * false if the requested revision does not exist in the {@link WikiDB}.
  1055. * Note that version zero of any page always exists.
  1056. */
  1057. function getRevision ($version, $need_content=true) {
  1058. $cache = &$this->_wikidb->_cache;
  1059. $pagename = &$this->_pagename;
  1060. if (! $version or $version == -1) // 0 or false
  1061. return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
  1062. assert($version > 0);
  1063. $vdata = $cache->get_versiondata($pagename, $version, $need_content);
  1064. if (!$vdata) {
  1065. return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
  1066. }
  1067. return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
  1068. $vdata);
  1069. }
  1070. /**
  1071. * Get previous page revision.
  1072. *
  1073. * This method find the most recent revision before a specified
  1074. * version.
  1075. *
  1076. * @access public
  1077. *
  1078. * @param integer $version Find most recent revision before this version.
  1079. * You can also use a WikiDB_PageRevision object to specify the $version.
  1080. *
  1081. * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
  1082. * requested revision does not exist in the {@link WikiDB}. Note that
  1083. * unless $version is greater than zero, a revision (perhaps version zero,
  1084. * the default revision) will always be found.
  1085. */
  1086. function getRevisionBefore ($version=false, $need_content=true) {
  1087. $backend = &$this->_wikidb->_backend;
  1088. $pagename = &$this->_pagename;
  1089. if ($version === false)
  1090. $version = $this->_wikidb->_cache->get_latest_version($pagename);
  1091. else
  1092. $version = $this->_coerce_to_version($version);
  1093. if ($version == 0)
  1094. return false;
  1095. //$backend->lock();
  1096. $previous = $backend->get_previous_version($pagename, $version);
  1097. $revision = $this->getRevision($previous, $need_content);
  1098. //$backend->unlock();
  1099. assert($revision);
  1100. return $revision;
  1101. }
  1102. /**
  1103. * Get all revisions of the WikiDB_Page.
  1104. *
  1105. * This does not include the version zero (default) revision in the
  1106. * returned revision set.
  1107. *
  1108. * @return WikiDB_PageRevisionIterator A
  1109. * WikiDB_PageRevisionIterator containing all revisions of this
  1110. * WikiDB_Page in reverse order by version number.
  1111. */
  1112. function getAllRevisions() {
  1113. $backend = &$this->_wikidb->_backend;
  1114. $revs = $backend->get_all_revisions($this->_pagename);
  1115. return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
  1116. }
  1117. /**
  1118. * Find pages which link to or are linked from a page.
  1119. *
  1120. * @access public
  1121. *
  1122. * @param boolean $reversed Which links to find: true for backlinks (default).
  1123. *
  1124. * @return WikiDB_PageIterator A WikiDB_PageIterator containing
  1125. * all matching pages.
  1126. */
  1127. function getLinks ($reversed = true, $include_empty=false, $sortby=false,
  1128. $limit=false, $exclude=false) {
  1129. $backend = &$this->_wikidb->_backend;
  1130. $result = $backend->get_links($this->_pagename, $reversed,
  1131. $include_empty, $sortby, $limit, $exclude);
  1132. return new WikiDB_PageIterator($this->_wikidb, $result,
  1133. array('include_empty' => $include_empty,
  1134. 'sortby' => $sortby,
  1135. 'limit' => $limit,
  1136. 'exclude' => $exclude));
  1137. }
  1138. /**
  1139. * All Links from other pages to this page.
  1140. */
  1141. function getBackLinks($include_empty=false, $sortby=false, $limit=false, $exclude=false) {
  1142. return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
  1143. }
  1144. /**
  1145. * Forward Links: All Links from this page to other pages.
  1146. */
  1147. function getPageLinks($include_empty=false, $sortby=false, $limit=false, $exclude=false) {
  1148. return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
  1149. }
  1150. /**
  1151. * possibly faster link existance check. not yet accelerated.
  1152. */
  1153. function existLink($link, $reversed=false) {
  1154. $backend = &$this->_wikidb->_backend;
  1155. if (method_exists($backend,'exists_link'))
  1156. return $backend->exists_link($this->_pagename, $link, $reversed);
  1157. //$cache = &$this->_wikidb->_cache;
  1158. // TODO: check cache if it is possible
  1159. $iter = $this->getLinks($reversed, false);
  1160. while ($page = $iter->next()) {
  1161. if ($page->getName() == $link)
  1162. return $page;
  1163. }
  1164. $iter->free();
  1165. return false;
  1166. }
  1167. /**
  1168. * Access WikiDB_Page non version-specific meta-data.
  1169. *
  1170. * @access public
  1171. *
  1172. * @param string $key Which meta data to get.
  1173. * Some reserved meta-data keys are:
  1174. * <dl>
  1175. * <dt>'date' <dd> Created as unixtime
  1176. * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
  1177. * <dt>'hits' <dd> Page hit counter.
  1178. * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
  1179. * In SQL stored now in an extra column.
  1180. * Optional data:
  1181. * <dt>'pref' <dd> Users preferences, stored only in homepages.
  1182. * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
  1183. * E.g. "owner.users"
  1184. * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
  1185. * page-headers and content.
  1186. + <dt>'moderation'<dd> ModeratedPage data
  1187. * <dt>'score' <dd> Page score (not yet implement, do we need?)
  1188. * </dl>
  1189. *
  1190. * @return scalar The requested value, or false if the requested data
  1191. * is not set.
  1192. */
  1193. function get($key) {
  1194. $cache = &$this->_wikidb->_cache;
  1195. $backend = &$this->_wikidb->_backend;
  1196. if (!$key || $key[0] == '%')
  1197. return false;
  1198. // several new SQL backends optimize this.
  1199. if (!WIKIDB_NOCACHE_MARKUP
  1200. and $key == '_cached_html'
  1201. and method_exists($backend, 'get_cached_html'))
  1202. {
  1203. return $backend->get_cached_html($this->_pagename);
  1204. }
  1205. $data = $cache->get_pagedata($this->_pagename);

Large files files are truncated, but you can click here to view the full file