2 rcs_id('$Id: file.php,v 1.6 2004-01-26 09:17:51 rurban Exp $');
5 Copyright 1999, 2000, 2001, 2002, 2003 $ThePhpWikiProgrammingTeam
7 This file is part of PhpWiki.
9 PhpWiki is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 PhpWiki is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with PhpWiki; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 * Backend for handling file storage.
29 * Author: Jochen Kalmbach, Jochen@kalmbachnet.de
34 * - Implement "optimize" / "sync" / "check" / "rebuild"
35 * - Optimize "get_previous_version"
36 * - Optimize "get_links" (reversed = true)
37 * - Optimize "get_all_revisions"
38 * - Optimize "most_popular" (separate file for "hitcount",
39 * which contains all pages)
40 * - Optimize "most_recent"
41 * - What should be done in "lock"/"unlock"/"close" ?
42 * - "WikiDB_backend_file_iter": Do I need to return 'version' and 'versiondata' ?
46 require_once('lib/WikiDB/backend.php');
47 require_once('lib/ErrorManager.php');
51 class WikiDB_backend_file
52 extends WikiDB_backend
57 var $_page_data; // temporarily stores the pagedata (via _loadPageData)
58 var $_page_version_data; // temporarily stores the versiondata (via _loadVersionData)
59 var $_latest_versions; // temporarily stores the latest version-numbers (for every pagename) (via _loadLatestVersions)
62 function WikiDB_backend_file( $dbparam )
64 $this->data_dir = $dbparam['directory'];
65 if (is_dir($this->data_dir) == false) {
66 mkdir($this->data_dir, 0755);
70 = array('ver_data' => $this->data_dir.'/'.'ver_data',
71 'page_data' => $this->data_dir.'/'.'page_data',
72 'latest_ver' => $this->data_dir.'/'.'latest_ver',
73 'links' => $this->data_dir.'/'.'links' );
75 foreach ($this->_dir_names as $key => $val) {
76 if (is_dir($val) == false)
80 $this->_page_data = NULL;
81 $this->_page_version_data = NULL;
82 $this->_latest_versions = NULL;
87 // *********************************************************************
88 // common file load / save functions:
89 function _pagename2filename($type, $pagename, $version) {
91 return $this->_dir_names[$type].'/'.urlencode($pagename);
93 return $this->_dir_names[$type].'/'.urlencode($pagename).'--'.$version;
96 function _loadPage($type, $pagename, $version, $set_pagename = true) {
97 $filename = $this->_pagename2filename($type, $pagename, $version);
98 if ($fd = @fopen($filename, "rb")) {
99 $locked = flock($fd, 1); # Read lock
101 ExitWiki("Timeout while obtaining lock. Please try again");
103 if ($data = fread($fd, filesize($filename))) {
104 $pd = unserialize($data);
105 if ($set_pagename == true)
106 $pd['pagename'] = $pagename;
108 $pd['version'] = $version;
110 ExitWiki(sprintf(gettext("'%s': corrupt file"),
111 htmlspecialchars($filename)));
120 function _savePage($type, $pagename, $version, $data) {
121 $filename = $this->_pagename2filename($type, $pagename, $version);
122 if($fd = fopen($filename, 'a+b')) {
123 $locked = flock($fd,2); #Exclusive blocking lock
125 ExitWiki("Timeout while obtaining lock. Please try again");
131 $pagedata = serialize($data);
132 fwrite($fd, $pagedata);
135 ExitWiki("Error while writing page '$pagename'");
139 function _removePage($type, $pagename, $version) {
140 $filename = $this->_pagename2filename($type, $pagename, $version);
141 $f = @unlink($filename);
143 trigger_error("delete file failed: ".$filename." ver: ".$version, E_USER_WARNING);
146 // *********************************************************************
149 // *********************************************************************
150 // Load/Save Version-Data
151 function _loadVersionData($pagename, $version) {
152 if ($this->_page_version_data != NULL) {
153 if ( ($this->_page_version_data['pagename'] == $pagename) &&
154 ($this->_page_version_data['version'] == $version) ) {
155 return $this->_page_version_data;
158 $vd = $this->_loadPage('ver_data', $pagename, $version);
160 $this->_page_version_data = $vd;
161 if ( ($this->_page_version_data['pagename'] == $pagename) &&
162 ($this->_page_version_data['version'] == $version) ) {
163 return $this->_page_version_data;
169 function _saveVersionData($pagename, $version, $data) {
170 $this->_savePage('ver_data', $pagename, $version, $data);
172 // check if this is a newer version:
173 if ($this->_getLatestVersion($pagename) < $version) {
174 // write new latest-version-info
175 $this->_setLatestVersion($pagename, $version);
180 // *********************************************************************
181 // Load/Save Page-Data
182 function _loadPageData($pagename) {
183 if ($this->_page_data != NULL) {
184 if ($this->_page_data['pagename'] == $pagename) {
185 return $this->_page_data;
188 $pd = $this->_loadPage('page_data', $pagename, 0);
190 $this->_page_data = $pd;
191 if ($this->_page_data != NULL) {
192 if ($this->_page_data['pagename'] == $pagename) {
193 return $this->_page_data;
196 return array(); // no values found
199 function _savePageData($pagename, $data) {
200 $this->_savePage('page_data', $pagename, 0, $data);
203 // *********************************************************************
204 // Load/Save Latest-Version
205 function _saveLatestVersions() {
206 $data = $this->_latest_versions;
209 $this->_savePage('latest_ver', 'latest_versions', 0, $data);
212 function _setLatestVersion($pagename, $version) {
213 // make sure the page version list is loaded:
214 $this->_getLatestVersion($pagename);
216 $this->_getLatestVersion($pagename);
217 $this->_latest_versions[$pagename] = $version;
220 // Remove this page from the Latest-Version-List:
221 unset($this->_latest_versions[$pagename]);
223 $this->_saveLatestVersions();
226 function _loadLatestVersions() {
227 if ($this->_latest_versions != NULL)
230 $pd = $this->_loadPage('latest_ver', 'latest_versions', 0, false);
232 $this->_latest_versions = $pd;
234 $this->_latest_versions = array(); // empty array
237 function _getLatestVersion($pagename) {
238 $this->_loadLatestVersions();
239 if (array_key_exists($pagename, $this->_latest_versions) == false)
240 return 0; // do version exists
241 return $this->_latest_versions[$pagename];
245 // *********************************************************************
246 // Load/Save Page-Links
247 function _loadPageLinks($pagename) {
248 $pd = $this->_loadPage('links', $pagename, 0, false);
251 return array(); // no values found
254 function _savePageLinks($pagename, $links) {
255 $this->_savePage('links', $pagename, 0, $links);
261 * Get page meta-data from database.
263 * @param $pagename string Page name.
265 * Returns a hash containing the page meta-data.
266 * Returns an empty array if there is no meta-data for the requested page.
267 * Keys which might be present in the hash are:
269 * <dt> locked <dd> If the page is locked.
270 * <dt> hits <dd> The page hit count.
271 * <dt> created <dd> Unix time of page creation. (FIXME: Deprecated: I
272 * don't think we need this...)
275 function get_pagedata($pagename) {
276 return $this->_loadPageData($pagename);
280 * Update the page meta-data.
282 * Set page meta-data.
284 * Only meta-data whose keys are preset in $newdata is affected.
288 * $backend->update_pagedata($pagename, array('locked' => 1));
290 * will set the value of 'locked' to 1 for the specified page, but it
291 * will not affect the value of 'hits' (or whatever other meta-data
292 * may have been stored for the page.)
294 * To delete a particular piece of meta-data, set it's value to false.
296 * $backend->update_pagedata($pagename, array('locked' => false));
299 * @param $pagename string Page name.
300 * @param $newdata hash New meta-data.
303 * This will create a new page if page being requested does not
306 function update_pagedata($pagename, $newdata) {
307 $data = $this->get_pagedata($pagename);
308 if (count($data) == 0) {
309 $this->_savePageData($pagename, $newdata); // create a new pagedata-file
313 foreach ($newdata as $key => $val) {
319 $this->_savePageData($pagename, $data); // write new pagedata-file
324 * Get the current version number for a page.
326 * @param $pagename string Page name.
327 * @return int The latest version number for the page. Returns zero if
328 * no versions of a page exist.
330 function get_latest_version($pagename) {
331 return $this->_getLatestVersion($pagename);
335 * Get preceding version number.
337 * @param $pagename string Page name.
338 * @param $version int Find version before this one.
339 * @return int The version number of the version in the database which
340 * immediately preceeds $version.
342 function get_previous_version($pagename, $version) {
343 return ($version > 0 ? $version - 1 : 0);
347 * Get revision meta-data and content.
349 * @param $pagename string Page name.
350 * @param $version integer Which version to get.
351 * @param $want_content boolean
352 * Indicates the caller really wants the page content. If this
353 * flag is not set, the backend is free to skip fetching of the
354 * page content (as that may be expensive). If the backend omits
355 * the content, the backend might still want to set the value of
356 * '%content' to the empty string if it knows there's no content.
358 * @return hash The version data, or false if specified version does not
361 * Some keys which might be present in the $versiondata hash are:
364 * <dd> This is a pseudo-meta-data element (since it's actually
365 * the page data, get it?) containing the page content.
366 * If the content was not fetched, this key may not be present.
368 * For description of other version meta-data see WikiDB_PageRevision::get().
369 * @see WikiDB_PageRevision::get
371 function get_versiondata($pagename, $version, $want_content = false) {
372 $vd = $this->_loadVersionData($pagename, $version);
379 * Delete page from the database.
381 * Delete page (and all it's revisions) from the database.
383 * @param $pagename string Page name.
385 function delete_page($pagename) {
386 $ver = $this->get_latest_version($pagename);
388 $this->_removePage('ver_data', $pagename, $ver);
389 $ver = $this->get_previous_version($pagename, $ver);
391 $this->_removePage('page_data', $pagename, 0);
392 $this->_removePage('links', $pagename, 0);
393 // remove page from latest_version...
394 $this->_setLatestVersion($pagename, 0);
398 * Delete an old revision of a page.
400 * Note that one is never allowed to delete the most recent version,
401 * but that this requirement is enforced by WikiDB not by the backend.
403 * In fact, to be safe, backends should probably allow the deletion of
404 * the most recent version.
406 * @param $pagename string Page name.
407 * @param $version integer Version to delete.
409 function delete_versiondata($pagename, $version) {
410 if ($this->get_latest_version($pagename) == $version) {
411 // try to delete the latest version!
412 // so check if an older version exist:
413 if ($this->get_versiondata($pagename, $this->get_previous_version($pagename, $version), false) == false) {
414 // there is no older version....
415 // so the completely page will be removed:
416 $this->delete_page($pagename);
420 $this->_removePage('ver_data', $pagename, $version);
424 * Create a new page revision.
426 * If the given ($pagename,$version) is already in the database,
427 * this method completely overwrites any stored data for that version.
429 * @param $pagename string Page name.
430 * @param $version int New revisions content.
431 * @param $data hash New revision metadata.
433 * @see get_versiondata
435 function set_versiondata($pagename, $version, $data) {
436 $this->_saveVersionData($pagename, $version, $data);
440 * Update page version meta-data.
442 * If the given ($pagename,$version) is already in the database,
443 * this method only changes those meta-data values whose keys are
444 * explicity listed in $newdata.
446 * @param $pagename string Page name.
447 * @param $version int New revisions content.
448 * @param $newdata hash New revision metadata.
449 * @see set_versiondata, get_versiondata
451 function update_versiondata($pagename, $version, $newdata) {
452 $data = $this->get_versiondata($pagename, $version, true);
457 foreach ($newdata as $key => $val) {
463 $this->set_versiondata($pagename, $version, $data);
467 * Set links for page.
469 * @param $pagename string Page name.
471 * @param $links array List of page(names) which page links to.
473 function set_links($pagename, $links) {
474 $this->_savePageLinks($pagename, $links);
478 * Find pages which link to or are linked from a page.
480 * @param $pagename string Page name.
481 * @param $reversed boolean True to get backlinks.
483 * FIXME: array or iterator?
484 * @return object A WikiDB_backend_iterator.
486 function get_links($pagename, $reversed) {
487 if ($reversed == false)
488 return new WikiDB_backend_file_iter($this, $this->_loadPageLinks($pagename));
490 $this->_loadLatestVersions();
491 $pagenames = $this->_latest_versions; // now we have an array with the key is the pagename of all pages
493 $out = array(); // create empty out array
495 foreach ($pagenames as $key => $val) {
496 $links = $this->_loadPageLinks($key);
497 foreach ($links as $key2 => $val2) {
498 if ($val2 == $pagename)
499 array_push($out, $key);
502 return new WikiDB_backend_file_iter($this, $out);
506 * Get all revisions of a page.
508 * @param $pagename string The page name.
509 * @return object A WikiDB_backend_iterator.
511 function get_all_revisions($pagename) {
512 include_once('lib/WikiDB/backend/dumb/AllRevisionsIter.php');
513 return new WikiDB_backend_dumb_AllRevisionsIter($this, $pagename);
517 * Get all pages in the database.
519 * Pages should be returned in alphabetical order if that is
524 * @param $include_defaulted boolean
525 * If set, even pages with no content will be returned
526 * --- but still only if they have at least one revision (not
527 * counting the default revision 0) entered in the database.
529 * Normally pages whose current revision has empty content
530 * are not returned as these pages are considered to be
533 * @return object A WikiDB_backend_iterator.
535 function get_all_pages($include_deleted=false, $orderby='pagename') {
536 $this->_loadLatestVersions();
537 $a = array_keys($this->_latest_versions);
539 return new WikiDB_backend_file_iter($this, $a);
543 * Title or full text search.
545 * Pages should be returned in alphabetical order if that is
550 * @param $search object A TextSearchQuery object describing what pages
551 * are to be searched for.
553 * @param $fullsearch boolean If true, a full text search is performed,
554 * otherwise a title search is performed.
556 * @return object A WikiDB_backend_iterator.
558 * @see WikiDB::titleSearch
560 function text_search($search = '', $fullsearch = false) {
561 // This is method implements a simple linear search
562 // through all the pages in the database.
564 // It is expected that most backends will overload
565 // method with something more efficient.
566 include_once('lib/WikiDB/backend/dumb/TextSearchIter.php');
567 $pages = $this->get_all_pages(false);
568 return new WikiDB_backend_dumb_TextSearchIter($this, $pages, $search, $fullsearch);
572 * Find pages with highest hit counts.
574 * Find the pages with the highest hit counts. The pages should
575 * be returned in reverse order by hit count.
578 * @param $limit integer No more than this many pages
579 * @return object A WikiDB_backend_iterator.
581 function most_popular($limit) {
582 // This is method fetches all pages, then
583 // sorts them by hit count.
584 // (Not very efficient.)
586 // It is expected that most backends will overload
587 // method with something more efficient.
588 include_once('lib/WikiDB/backend/dumb/MostPopularIter.php');
589 $pages = $this->get_all_pages(false,'hits DESC');
591 return new WikiDB_backend_dumb_MostPopularIter($this, $pages, $limit);
595 * Find recent changes.
598 * @param $params hash See WikiDB::mostRecent for a description
599 * of parameters which can be included in this hash.
600 * @return object A WikiDB_backend_iterator.
601 * @see WikiDB::mostRecent
603 function most_recent($params) {
604 // This method is very inefficient and searches through
605 // all pages for the most recent changes.
607 // It is expected that most backends will overload
608 // method with something more efficient.
609 include_once('lib/WikiDB/backend/dumb/MostRecentIter.php');
610 $pages = $this->get_all_pages(true,'mtime DESC');
611 return new WikiDB_backend_dumb_MostRecentIter($this, $pages, $params);
615 * Lock backend database.
617 * Calls may be nested.
619 * @param $write_lock boolean Unless this is set to false, a write lock
620 * is acquired, otherwise a read lock. If the backend doesn't support
621 * read locking, then it should make a write lock no matter which type
622 * of lock was requested.
624 * All backends <em>should</em> support write locking.
626 function lock($write_lock = true) {
627 //trigger_error("lock: Not Implemented", E_USER_WARNING);
631 * Unlock backend database.
633 * @param $force boolean Normally, the database is not unlocked until
634 * unlock() is called as many times as lock() has been. If $force is
635 * set to true, the the database is unconditionally unlocked.
637 function unlock($force = false) {
638 //trigger_error("unlock: Not Implemented", E_USER_WARNING);
646 //trigger_error("close: Not Implemented", E_USER_WARNING);
650 * Synchronize with filesystem.
652 * This should flush all unwritten data to the filesystem.
655 //trigger_error("sync: Not Implemented", E_USER_WARNING);
659 * Optimize the database.
661 function optimize() {
662 //trigger_error("optimize: Not Implemented", E_USER_WARNING);
666 * Check database integrity.
668 * This should check the validity of the internal structure of the database.
669 * Errors should be reported via:
671 * trigger_error("Message goes here.", E_USER_WARNING);
674 * @return boolean True iff database is in a consistent state.
677 //trigger_error("check: Not Implemented", E_USER_WARNING);
681 * Put the database into a consistent state.
683 * This should put the database into a consistent state.
684 * (I.e. rebuild indexes, etc...)
686 * @return boolean True iff successful.
689 //trigger_error("rebuild: Not Implemented", E_USER_WARNING);
692 function _parse_searchwords($search) {
693 $search = strtolower(trim($search));
695 return array(array(),array());
697 $words = preg_split('/\s+/', $search);
699 foreach ($words as $key => $word) {
700 if ($word[0] == '-' && $word != '-') {
701 $word = substr($word, 1);
702 $exclude[] = preg_quote($word);
706 return array($words, $exclude);
711 class WikiDB_backend_file_iter extends WikiDB_backend_iterator
713 function WikiDB_backend_file_iter(&$backend, &$query_result) {
714 $this->_backend = &$backend;
715 $this->_result = $query_result;
717 if (count($this->_result) > 0)
718 reset($this->_result);
722 $backend = &$this->_backend;
727 if (count($this->_result) <= 0)
730 $e = each($this->_result);
736 $pagedata = $backend->get_pagedata($pn);
737 $rec = array('pagename' => $pn,
738 'pagedata' => $pagedata);
740 //$rec['version'] = $backend->get_latest_version($pn);
741 //$rec['versiondata'] = $backend->get_versiondata($pn, $rec['version'], true);
750 // $Log: not supported by cvs2svn $
751 // Revision 1.5 2004/01/25 08:17:29 rurban
752 // ORDER BY support for all other backends,
753 // all non-SQL simply ignoring it, using plain old dumb_iter instead
755 // Revision 1.4 2003/02/24 01:53:28 dairiki
756 // Bug fix. Don't need to urldecode pagenames in WikiDB_backend_file_iter.
758 // Revision 1.3 2003/01/04 03:41:51 wainstead
759 // Added copyleft flowerboxes
761 // Revision 1.2 2003/01/04 03:30:34 wainstead
762 // added log tag, converted file to unix format
770 // c-hanging-comment-ender-p: nil
771 // indent-tabs-mode: nil