]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/cvs.php
sprintf fine-tuning for gettext
[SourceForge/phpwiki.git] / lib / WikiDB / backend / cvs.php
1 <?php
2 rcs_id('$Id: cvs.php,v 1.6 2001-12-19 12:07:43 carstenklapp Exp $');
3 /**
4  * Backend for handling CVS repository. 
5  *
6  * ASSUMES: that the shell commands 'cvs', 'grep', 'rm', are all located 
7  * ASSUMES: in the path of the server calling this script.
8  *
9  * Author: Gerrit Riessen, gerrit.riessen@open-source-consultants.de
10  */
11
12 require_once('lib/WikiDB/backend.php');
13 require_once('lib/ErrorManager.php');
14
15 /** 
16  * Constants used by the CVS backend 
17  **/
18 // these are the parameters defined in db_params
19 define( 'CVS_DOC_DIR',              'doc_dir' );
20 define( 'CVS_REPOSITORY',           'repository' );
21 define( 'CVS_CHECK_FOR_REPOSITORY', 'check_for_repository' );
22 define( 'CVS_DEBUG_FILE',           'debug_file' );
23 define( 'CVS_PAGE_SOURCE',          'pgsrc' );
24 define( 'CVS_MODULE_NAME',          'module_name' );
25
26 // these are the things that are defined in the page hash
27 // CMD == Cvs Meta Data
28 define( 'CMD_LAST_MODIFIED', 'lastmodified' );
29 define( 'CMD_CONTENT',       '%content');
30 define( 'CMD_CREATED',       'created');
31 define( 'CMD_VERSION',       'version');
32 define( 'CMD_AUTHOR',        'author');
33 define( 'CMD_LINK_ATT',      '_links_' );
34
35 // file names used to store specific information
36 define( 'CVS_MP_FILE',              '.most_popular' );
37 define( 'CVS_MR_FILE',              '.most_recent' );
38
39 class WikiDB_backend_cvs
40 extends WikiDB_backend
41 {
42     var $_docDir;
43     var $_repository;
44     var $_module_name;
45     var $_debug_file;
46
47     /**
48      * In the following parameters should be defined in dbparam:
49      *   . wiki ==> directory where the pages should be stored
50      *              this is not the CVS repository location
51      *   . repository ==> local directory where the repository should be 
52      *                    created. This can also be a :pserver: but then
53      *                    set check_for_repository to false and checkout
54      *                    the documents beforehand. (This is basically CVSROOT)
55      *   . check_for_repository ==> boolean flag to indicate whether the 
56      *                              repository should be created, this only
57      *                              applies to local directories, for pserver
58      *                              set this to false and check out the 
59      *                              document base beforehand
60      *   . debug_file ==> file name where debug information should be sent.
61      *                    If file doesn't exist then it's created, if this
62      *                    is empty, then debugging is turned off.
63      *   . pgsrc ==> directory name where the default wiki pages are stored.
64      *               This is only required if the backend is to create a
65      *               new CVS repository.
66      *
67      * The class also adds a parameter 'module_name' to indicate the name
68      * of the cvs module that is being used to version the documents. The
69      * module_name is assumed to be the base name of directory given in
70      * wiki, e.g. if wiki == '/some/path/to/documents' then module_name 
71      * becomes 'documents' and this module will be created in the CVS 
72      * repository or assumed to exist. If on the other hand the parameter
73      * already exists, then it is not overwritten.
74      */
75     function WikiDB_backend_cvs( $dbparam ) 
76     {
77         // setup all the instance values.
78         $this->_docDir = $dbparam{CVS_DOC_DIR};
79         $this->_repository = $dbparam{CVS_REPOSITORY};
80         if ( ! $dbparam{CVS_MODULE_NAME} ) {
81             $this->_module_name = basename( $this->_docDir );
82             $dbparam{CVS_MODULE_NAME} = $this->_module_name;
83         } else {
84             $this->_module_name = $dbparam{CVS_MODULE_NAME};
85         }
86         $this->_debug_file = $dbparam{CVS_DEBUG_FILE};
87
88         if ( !($dbparam{CVS_CHECK_FOR_REPOSITORY}
89                 && is_dir( $this->_repository )
90                 && is_dir( $this->_repository . "/CVSROOT" )
91                 && is_dir( $this->_repository . "/" . $this->_module_name ))) {
92
93             $this->_cvsDebug( sprintf(_("Creating new repository [%s]"),$this->_repository) );
94
95             // doesn't exist, need to create it and the replace the wiki 
96             // document directory.
97             $this->_mkdir( $this->_repository, 0775 );
98     
99             // assume that the repository is a local directory, prefix :local:
100             if ( !ereg( "^:local:", $this->_repository ) ) {
101                 $this->_repository = ":local:" . $this->_repository;
102             }
103             
104             $cmdLine = sprintf( "cvs -d \"%s\" init", $this->_repository);
105             $this->_execCommand( $cmdLine, $cmdOutput, true );
106
107             $this->_mkdir( $this->_docDir, 0775 );
108             $cmdLine = sprintf("cd %s; cvs -d \"%s\" import -m no_message "
109                                ."%s V R", $this->_docDir, $this->_repository,
110                                $this->_module_name );
111             $this->_execCommand( $cmdLine, $cmdOutput, true );
112             
113             // remove the wiki directory and check it out from the 
114             // CVS repository
115             $cmdLine = sprintf( "rm -fr %s; cd %s; cvs -d \"%s\" co %s",
116                                 $this->_docDir, dirname($this->_docDir), 
117                                 $this->_repository, $this->_module_name);
118             $this->_execCommand( $cmdLine, $cmdOutput, true );
119             
120             // add the default pages using the update_pagedata
121             $metaData = array();
122             $metaData[$AUTHOR] = "PhpWiki -- CVS Backend";
123
124             if ( is_dir( $dbparam[CVS_PAGE_SOURCE] ) ) {
125                 $d = opendir( $dbparam[CVS_PAGE_SOURCE] );
126                 while ( $entry = readdir( $d ) ) {
127                     $filename = $dbparam[CVS_PAGE_SOURCE] . "/" . $entry;
128                     $this->_cvsDebug( sprintf(_("Found [%s] in [%s]"),$entry,$dbparam[CVS_PAGE_SOURCE]) );
129                     
130                     if ( is_file( $filename ) ) {
131                         $metaData[CMD_CONTENT] = join('',file($filename));
132                         $this->update_pagedata( $entry, $metaData );
133                     }
134                 }
135                 closedir( $d );
136             }
137             
138             // ensure that the results of the is_dir are cleared
139             clearstatcache();
140         }
141     }
142
143     /**
144      * Return: metadata about page
145      */
146     function get_pagedata($pagename) 
147     {
148         // the metadata information about a page is stored in the 
149         // CVS directory of the document root in serialized form. The
150         // file always has the name, i.e. '_$pagename'.
151         $metaFile = $this->_docDir . "/CVS/_" . $pagename;
152
153         if ( file_exists( $metaFile ) ) {
154             
155             $megaHash = 
156                  unserialize(join( '',$this->_readFileWithPath($metaFile)));
157
158             $filename = $this->_docDir . "/" . $pagename;
159             if ( file_exists( $filename ) ) {
160                 $megaHash[CMD_CONTENT] = $this->_readFileWithPath( $filename );
161             } else {
162                 $megaHash[CMD_CONTENT] = "";
163             }
164
165             $this->_updateMostRecent( $pagename );
166             $this->_updateMostPopular( $pagename );
167
168             return $megaHash;
169         } else {
170             return false;
171         }
172     }
173
174     /**
175      * This will create a new page if page being requested does not
176      * exist.
177      */
178     function update_pagedata($pagename, $newdata = array() ) 
179     {
180         // check argument
181         if ( ! is_array( $newdata ) ) {
182             trigger_error("update_pagedata: " . sprintf(_("Argument %s was not array"),"'newdata'"), 
183                           E_USER_WARNING);
184         }
185
186         // retrieve the meta data
187         $metaData = $this->get_pagedata( $pagename );
188
189         if ( ! $metaData ) {
190             $this->_cvsDebug( "update_pagedata: " . _("no meta data found") );
191             // this means that the page does not exist, we need to create
192             // it.
193             $metaData = array();
194
195             $metaData[CMD_CREATED] = time();
196             $metaData[CMD_VERSION] = "1";
197
198             if ( ! isset($newdata[CMD_CONTENT])) {
199                 $metaData[CMD_CONTENT] = "";
200             } else {
201                 $metaData[CMD_CONTENT] = $newdata[CMD_CONTENT];
202             }
203
204             // create an empty page ...
205             $this->_writePage( $pagename, $metaData[CMD_CONTENT] );
206             $this->_addPage( $pagename );
207
208             // make sure that the page is written and committed a second time
209             unset( $newdata[CMD_CONTENT] );
210             unset( $metaData[CMD_CONTENT] );
211         }
212
213         // change any meta data information
214         foreach ( $newdata as $key => $value ) {
215             if ( $value == false || empty( $value ) ) {
216                 unset( $metaData[$key] );
217             } else {
218                 $metaData[$key] = $value;
219             }
220         }
221
222         // update the page data, if required. Use newdata because it could
223         // be empty and thus unset($metaData[CMD_CONTENT]).
224         if ( isset( $newdata[CMD_CONTENT] ) ) {
225             $this->_writePage( $pagename, $newdata[CMD_CONTENT] );
226         }
227
228         // remove any content from the meta data before storing it
229         unset( $metaData[CMD_CONTENT] );
230         $metaData[CMD_LAST_MODIFIED] = time();
231
232         $metaData[CMD_VERSION] = $this->_commitPage( $pagename, $metaData );
233         $this->_writeMetaInfo( $pagename, $metaData );
234     }
235
236     function get_latest_version($pagename) 
237     {
238         $metaData = $this->get_pagedata( $pagename );
239         if ( $metaData ) {
240             // the version number is everything after the '1.'
241             return $metaData[CMD_VERSION];
242         } else {
243             $this->_cvsDebug( "get_latest_versioned " . sprintf(_("FAILED for [%s]"),$pagename) );
244             return 0;
245         }
246     }
247
248     function get_previous_version($pagename, $version) 
249     {
250         // cvs increments the version numbers, so this is real easy ;-)
251         return ($version > 0 ? $version - 1 : 0);
252     }
253
254     /**
255      * the version parameter is assumed to be everything after the '1.'
256      * in the CVS versioning system.
257      */
258     function get_versiondata($pagename, $version, $want_content = false) 
259     {
260         $this->_cvsDebug( "get_versiondata: [$pagename] [$version] [$want_content]" );
261       
262         $filedata = "";
263         if ( $want_content ) {
264             // retrieve the version from the repository
265             $cmdLine = sprintf("cvs -d \"%s\" co -p -r 1.%d %s/%s 2>&1", 
266                                $this->_repository, $version, 
267                                $this->_module_name, $pagename );
268             $this->_execCommand( $cmdLine, $filedata, true );
269         
270             // TODO: DEBUG: 5 is a magic number here, depending on the
271             // TODO: DEBUG: version of cvs used here, 5 might have to
272             // TODO: DEBUG: change. Basically find a more reliable way of
273             // TODO: DEBUG: doing this.
274             // the first 5 lines contain various bits of 
275             // administrative information that can be ignored.
276             for ( $i = 0; $i < 5; $i++ ) {
277                 array_shift( $filedata );
278             }
279         }
280
281         /**
282          * Now obtain the rest of the pagehash information, this is contained
283          * in the log message for the revision in serialized form.
284          */
285         $cmdLine = sprintf("cd %s; cvs log -r1.%d %s", $this->_docDir,
286                            $version, $pagename );
287         $this->_execCommand( $cmdLine, $logdata, true );
288
289         // shift log data until we get to the 'revision X.X' line
290         // FIXME: ensure that we don't enter an endless loop here
291         while ( !ereg( "^revision 1.([0-9]+)$", $logdata[0], $revInfo ) ) {
292             array_shift( $logdata );
293         }
294
295         // serialized hash information now stored in position 2
296         $rVal = unserialize( _unescape( $logdata[2] ) );
297
298         // version information is incorrect
299         $rVal[CMD_VERSION] = $revInfo[1];
300         $rVal[CMD_CONTENT] = $filedata;
301
302         foreach ( $rVal as $key => $value ) {
303             $this->_cvsDebug( "$key == [$value]" );
304         }
305       
306         return $rVal;
307     }
308
309     /**
310      * This returns false if page was not deleted or could not be deleted
311      * else return true.
312      */
313     function delete_page($pagename) 
314     {
315         $this->_cvsDebug( "delete_page [$pagename]") ;
316         $filename = $this->_docDir . "/" . $pagename;
317         $metaFile = $this->_docDir . "/CVS/_" . $pagename;
318         
319         // obtain a write block before deleting the file
320         if ( $this->_deleteFile( $filename ) == false ) {
321             return false;
322         }
323         
324         $this->_deleteFile( $metaFile );
325         
326         $this->_removePage( $pagename );
327
328         return true;
329     }
330
331     function delete_versiondata($pagename, $version) 
332     {
333         // TODO: Not Implemented.
334         // TODO: This is, for CVS, difficult because it implies removing a
335         // TODO: revision somewhere in the middle of a revision tree, and
336         // TODO: this is basically not possible!
337         trigger_error( "delete_versiondata: " . _("Not Implemented"), E_USER_WARNING);
338     }
339
340     function set_versiondata($pagename, $version, $data) 
341     {
342         // TODO: Not Implemented.
343         // TODO: requires changing the log(commit) message for a particular
344         // TODO: version and this can't be done??? (You can edit the repository
345         // TODO: file directly but i don't know of a way of doing it via
346         // TODO: the cvs tools).
347         trigger_error( "set_versiondata: " . _("Not Implemented"), E_USER_WARNING);
348     }
349
350     function update_versiondata($pagename, $version, $newdata) 
351     {
352         // TODO: same problem as set_versiondata
353         trigger_error( "set_versiondata: " . _("Not Implemented"), E_USER_WARNING);
354     }
355
356     function set_links($pagename, $links) 
357     {
358         // TODO: needs to be tested ....
359         $megaHash = get_pagedata( $pagename );
360         $megaHash[CMD_LINK_ATT] = $links;
361         $this->_writeMetaInfo( $pagename, $megaHash );
362     }
363
364     function get_links($pagename, $reversed) 
365     {
366         // TODO: ignores the $reversed argument and returns
367         // TODO: the value of _links_ attribute of the meta information
368         // TODO: to implement a reversed version, i guess, we going to
369         // TODO: need to do a grep on all files for the pagename in 
370         // TODO: in question and return all those page names that contained
371         // TODO: the required pagename!
372         $megaHash = get_pagedata( $pagename );
373         return $megaHash[CMD_LINK_ATT];
374     }
375
376     function get_all_revisions($pagename) 
377     {
378         // TODO: should replace this with something more efficient
379         include_once('lib/WikiDB/backend/dumb/AllRevisionsIter.php');
380         return new WikiDB_backend_dumb_AllRevisionsIter($this, $pagename);
381     }
382
383     function get_all_pages($include_defaulted) 
384     {
385         // FIXME: this ignores the include_defaulted parameter.
386         return new Cvs_Backend_Array_Iterator( 
387                               $this->_getAllFileNamesInDir( $this->_docDir ));
388     }
389
390     function text_search($search = '', $fullsearch = false) 
391     {
392         if ( $fullsearch ) {
393             return new Cvs_Backend_Full_Search_Iterator(
394                                $this->_getAllFileNamesInDir( $this->_docDir ), 
395                                $search, 
396                                $this->_docDir );
397         } else {
398             return new Cvs_Backend_Title_Search_Iterator(
399                                $this->_getAllFileNamesInDir( $this->_docDir ),
400                                $search);
401         }
402     }
403
404     function most_popular($limit) 
405     {
406         // TODO: needs to be tested ...
407         $mp = $this->_getMostPopular();
408         arsort( $mp, SORT_NUMERIC );
409         $returnVal = array();
410
411         while ( (list($key, $val) = each($a)) && $limit > 0 ) {
412             $returnVal[] = $key;
413             $limit--;
414         }
415         return $returnVal;
416     }
417
418     /**
419      * This only accepts the 'since' and 'limit' attributes, everything
420      * else is ignored.
421      */
422     function most_recent($params) 
423     {
424         // TODO: needs to be tested ...
425         // most recent are those pages with the highest time value ...
426         $mr = $this->_getMostRecent();
427         arsort( $mp, SORT_NUMERIC );
428         $returnVal = array();
429
430         if ( isset( $params['limit'] ) ) {
431             $limit = $params['limit'];
432             while ( (list($key, $val) = each($a)) && $limit > 0 ) {
433                 $returnVal[] = $key;
434                 $limit--;
435             }
436         } else if ( isset( $params['since'] ) ) {
437             while ( (list($key, $val) = each($a)) ) {
438                 if ( $val > $params['since'] ) {
439                     $returnVal[] = $key;
440                 }
441             }
442         }
443
444         return new Cvs_Backend_Array_Iterator( $returnVal );
445     }
446
447     function lock($write_lock = true) 
448     {
449         // TODO: to be implemented
450         trigger_error( "lock: " . _("Not Implemented"), E_USER_WARNING);
451     }
452
453     function unlock($force = false) 
454     {
455         // TODO: to be implemented
456         trigger_error( "unlock: " . _("Not Implemented"), E_USER_WARNING);
457     }
458
459     function close () 
460     {
461     }
462
463     function sync() 
464     {
465     }
466
467     function optimize() 
468     {
469     }
470
471     /**
472      * What we do here is take a listing of the documents directory and
473      * check that each page has metadata file. If not, then a metadata
474      * file is created for the page.
475      *
476      * This can happen if rebuild() was called and someone has added
477      * files to the CVS repository not via PhpWiki. These files are 
478      * added to the document directory but without any metadata files.
479      */
480     function check() 
481     {
482         // TODO:
483         // TODO: test this .... i.e. add test to unit test file.
484         // TODO:
485         $page_names = $this->_getAllFileNamesInDir($this->_docDir);
486         $meta_names = $this->_getAllFileNamesInDir($this->_docDir . "/CVS");
487
488         array_walk( $meta_names, '_strip_leading_underscore' );
489         reset( $meta_names );
490         $no_meta_files = array_diff( $page_names, $meta_names );
491
492         array_walk( $no_meta_files, '_create_meta_file', $this );
493
494         return true;
495     }
496
497     /**
498      * Do an update of the CVS repository 
499      */
500     function rebuild() 
501     {
502         // TODO:
503         // TODO: test this .... i.e. add test to unit test file.
504         // TODO:
505         $cmdLine = sprintf( "cd %s; cvs update -d 2>&1", $this->_docDir );
506         $this->_execCommand( $cmdLine, $cmdOutput, true );
507         return true;
508     }
509     
510     // 
511     // ..-.-..-.-..-.-.. .--..-......-.--. --.-....----.....
512     // The rest are all internal methods, not to be used 
513     // directly.
514     // ..-.-..-.-..-.-.. .--..-......-.--. --.-....----.....
515     //
516     function _create_meta_file( $page_name, $key, &$backend )
517     {
518         // this is used as part of an array walk and therefore takes
519         // the backend argument
520         $backend->_cvsDebug( sprintf(_("Creating meta file for [%s]"),$page_name) );
521         $backend->update_pagedata( $page_name, array() );
522     }
523
524     function _strip_leading_underscore( &$item ) 
525     {
526         $item = ereg_replace( "^_", "", $item );
527     }
528
529     /**
530      * update the most popular information by incrementing the count
531      * for the following page. If the page was not defined, it is entered
532      * with a value of 1.
533      */
534     function _updateMostPopular( $pagename )
535     {
536         $mp = $this->_getMostPopular();
537         if ( isset( $mp[$pagename] ) ) {
538             $mp[$pagename]++;
539         } else {
540             $mp[$pagename] = 1;
541         }
542         $this->_writeFileWithPath( $this->_docDir . "/CVS/" . CVS_MP_FILE, 
543                                    serialize( $mp ) );
544     }
545
546
547     /**
548      * Returns an array containing the most popular information. This
549      * creates the most popular file if it does not exist.
550      */
551     function _getMostPopular()
552     {
553         $mostPopular = $this->_docDir . "/CVS/" . CVS_MP_FILE;
554         if ( !file_exists( $mostPopular ) ) {
555             $this->_writeFileWithPath( $mostPopular, serialize( array() ) );
556         }
557         return unserialize(join( '',$this->_readFileWithPath($mostPopular)));
558     }
559
560     function _getMostRecent()
561     {
562         $mostRecent = $this->_docDir . "/CVS/" . CVS_MR_FILE;
563         if ( !file_exists( $mostRecent ) ) {
564             $this->_writeFileWithPath( $mostRecent, serialize( array() ) );
565         }
566         return unserialize(join( '',$this->_readFileWithPath($mostRecent)));
567     }
568
569     function _updateMostRecent( $pagename )
570     {
571         $mr = $this->_getMostRecent();
572         $mr[$pagename] = time();
573         $this->_writeFileWithPath( $this->_docDir . "/CVS/" . CVS_MR_FILE, 
574                                    serialize( $mr ) );
575     }
576
577     function _writeMetaInfo( $pagename, $hashInfo )
578     {
579         $this->_writeFileWithPath( $this->_docDir . "/CVS/_" . $pagename, 
580                                    serialize( $hashInfo ) );
581     }
582     function _writePage( $pagename, $content )
583     {
584         $this->_writeFileWithPath( $this->_docDir . "/". $pagename, $content );
585     }
586     function _removePage( $pagename )
587     {
588         $cmdLine = sprintf("cd %s; cvs remove %s 2>&1; cvs commit -m '%s' "
589                            ."%s 2>&1", $this->_docDir, $pagename, 
590                            "remove page", $pagename );
591         
592         $this->_execCommand( $cmdLine, $cmdRemoveOutput, true );
593     }
594
595     /**
596      * this returns the new version number of the file.
597      */
598     function _commitPage( $pagename, &$meta_data )
599     {
600         $cmdLine = sprintf( "cd %s; cvs commit -m \"%s\" %s 2>&1", 
601                             $this->_docDir, 
602                             escapeshellcmd( serialize( $meta_data ) ),
603                             $pagename );
604         $this->_execCommand( $cmdLine, $cmdOutput, true );
605
606         $cmdOutput = implode( "\n", $cmdOutput );
607         $revInfo = array();
608         ereg( "\nnew revision: 1[.]([0-9]+); previous revision: ", $cmdOutput,
609               $revInfo );
610
611         $this->_cvsDebug( "CP: revInfo 0: $revInfo[0]" );
612         $this->_cvsDebug( "CP: $cmdOutput" );
613         if ( isset( $revInfo[1] ) ) {
614             $this->_cvsDebug( "CP: " . _("got revision information") );
615             return $revInfo[1];
616         } else {
617             ereg( "\ninitial revision: 1[.]([0-9]+)", $cmdOutput, $revInfo );
618             if ( isset( $revInfo[1] ) ) {
619                 $this->_cvsDebug( "CP: " . _("is initial release") );
620                 return 1;
621             }
622             $this->_cvsDebug( "CP: " . _("returning old version") );
623             return $meta_data[CMD_VERSION];
624         }
625     }
626     function _addPage( $pagename )
627     {
628         // TODO: need to add a check for the mimetype so that binary
629         // TODO: files are added as binary files
630         $cmdLine = sprintf("cd %s; cvs add %s 2>&1", $this->_docDir, 
631                            $pagename );
632         $this->_execCommand( $cmdLine, $cmdAddOutput, true );
633     }
634
635     /**
636      * Returns an array containing all the names of files contained
637      * in a particular directory. The list is sorted according the 
638      * string representation of the filenames.
639      */
640     function _getAllFileNamesInDir( $dirName ) 
641     {
642         $namelist = array();
643         $d = opendir( $dirName );
644         while ( $entry = readdir( $d ) ) {
645             $namelist[] = $entry;
646         }
647         closedir( $d );
648         sort( $namelist, SORT_STRING );
649         return $namelist;
650     }
651
652     /**
653      * Recursively create all directories.
654      */
655     function _mkdir( $path, $mode ) 
656     {
657         $directoryName = dirname( $path );
658         if ( $directoryName != "/" && $directoryName != "\\"  
659              && !is_dir( $directoryName ) && $directoryName != "" ) {
660             $rVal = $this->_mkdir( $directoryName, $mode );
661         }
662         else {
663             $rVal = true;
664         }
665       
666         return ($rVal && @mkdir( $path, $mode ) );
667     }
668
669     /**
670      * Recursively create all directories and then the file.
671      */
672     function _createFile( $path, $mode ) 
673     {
674         $this->_mkdir( dirname( $path ), $mode );
675         touch( $path );
676         chmod( $path, $mode );
677     }
678
679     /**
680      * The lord giveth, and the lord taketh.
681      */
682     function _deleteFile( $filename )
683     {
684         if( $fd = fopen($filename, 'a') ) { 
685             
686             $locked = flock($fd,2);  // Exclusive blocking lock 
687
688             if (!$locked) { 
689                 $this->_cvsError(_("Unable to delete file, lock was not obtained."),
690                                  __LINE__, $filename, EM_NOTICE_ERRORS );
691             } 
692
693             if ( ($rVal = unlink( $filename )) != 0 ) {
694                 $this->_cvsDebug( "[$filename] --> Unlink returned [$rVal]" );
695             }
696
697             return $rVal;
698         } else {
699             $this->_cvsError( "deleteFile: " . _("Unable to open file"),
700                       __LINE__, $filename, EM_NOTICE_ERRORS );
701             return false;
702         }
703     }
704
705     /**
706      * Called when something happened that causes the CVS backend to 
707      * fail.
708      */
709     function _cvsError( $msg     = _("no message"), 
710                         $errline = 0, 
711                         $errfile = "lib/WikiDB/backend/cvs.php",
712                         $errno   = EM_FATAL_ERRORS)
713     {
714         $err = new PhpError( $errno, "[CVS(be)]: " . $msg, $errfile, $errline);
715         // send error to the debug routine
716         $this->_cvsDebug( $err->getDetail() );
717         // send the error to the error manager
718         $GLOBALS['ErrorManager']->handleError( $err );
719     }
720
721     /**
722      * Debug function specifically for the CVS database functions.
723      * Can be deactived by setting the WikiDB['debug_file'] to ""
724      */
725     function _cvsDebug( $msg )  
726     {
727         if ( $this->_debug_file == "" ) {
728             return;
729         }
730         
731         if ( !file_exists( $this->_debug_file  ) ) {
732             $this->_createFile( $this->_debug_file, 0755 );
733         }
734
735         if ( $fdlock = @fopen( $this->_debug_file, 'a' ) ) {
736             $locked = flock( $fdlock, 2 );
737             if ( !$locked ) {
738                 fclose( $fdlock );
739                 return;
740             }
741             
742             $fdappend = @fopen( $this->_debug_file, 'a' );
743             fwrite( $fdappend, ($msg . "\n") );
744             fclose( $fdappend );
745             fclose( $fdlock );
746         }
747         else {
748             // TODO: this should be replaced ...
749             printf( _("unable to locate/open [%s], turning debug off"),$filename)."\n";
750             $this->_debug_file = "";
751         }
752     }
753
754     /**
755      * Execute a command and potentially exit if the flag exitOnNonZero is 
756      * set to true and the return value was nonZero
757      */
758     function _execCommand( $cmdLine, &$cmdOutput, $exitOnNonZero )
759     {
760         $this->_cvsDebug( sprintf(_("Preparing to execute [%s]"),$cmdLine) );
761         exec( $cmdLine, $cmdOutput, $cmdReturnVal );
762         if ( $exitOnNonZero && ($cmdReturnVal != 0) ) {
763             $this->_cvsDebug( sprintf(_("Command failed [%s], Output:"),$cmdLine) ." [". 
764                               join("\n",$cmdOutput) . "]" );
765             $this->_cvsError( sprintf(_("Command failed [%s], Return value: %s"),$cmdLine,$cmdReturnVal),
766                             __LINE__ );
767         }
768         $this->_cvsDebug( _("Done execution")." [" . join("\n", $cmdOutput ) . "]" );
769
770         return $cmdReturnVal;
771     }
772
773     /**
774      * Read locks a file, reads it, and returns it contents
775      */
776     function _readFileWithPath( $filename ) 
777     {
778         if ( $fd = @fopen( $filename, "r" ) )  {
779             $locked = flock( $fd, 1 ); // read lock
780             if ( !$locked ) {
781                 fclose( $fd );
782                 $this->_cvsError( _("Unable to obtain read lock."),__LINE__);
783             }
784
785             $content = file( $filename );
786             fclose( $fd );
787             return $content;
788         } else {
789             $this->_cvsError( sprintf(_("Unable to open file '%s' for reading"),$filename),
790                               __LINE__ );
791             return false;
792         }
793     }
794
795     /**
796      * Either replace the contents of an existing file or create a 
797      * new file in the particular store using the page name as the
798      * file name.
799      * 
800      * Nothing is returned, might be useful to return something ;-)
801      */
802     function _writeFileWithPath( $filename, $contents )
803     { 
804         // TODO: $contents should probably be a reference parameter ...
805         if( $fd = fopen($filename, 'a') ) { 
806             $locked = flock($fd,2);  // Exclusive blocking lock 
807             if (!$locked) { 
808                 $this->_cvsError( _("Timeout while obtaining lock."),__LINE__);
809             } 
810
811             // Second filehandle -- we use this to write the contents
812             $fdsafe = fopen($filename, 'w'); 
813             fwrite($fdsafe, $contents); 
814             fclose($fdsafe); 
815             fclose($fd);
816         } else {
817             $this->_cvsError( sprintf(_("Could not open file '%s' for writing"),$filename), 
818                               __LINE__ );
819         }
820     }
821
822    /**
823     * Copy the contents of the source directory to the destination directory.
824     */
825     function _copyFilesFromDirectory( $src, $dest )
826     {
827         $this->_cvsDebug( sprintf(_("Copying from [%s] to [%s]"),$src,$dest) );
828
829         if ( is_dir( $src ) && is_dir( $dest ) ) {
830             $this->_cvsDebug( _("Copying") ." " );
831             $d = opendir( $src );
832             while ( $entry = readdir( $d ) ) {
833                 if ( is_file( $src . "/" . $entry )
834                      && copy( $src . "/" . $entry, $dest . "/" . $entry ) ) {
835                     $this->_cvsDebug( sprintf(_("Copied to [%s]"),"$dest/$entry") );
836                 } else {
837                     $this->_cvsDebug( sprintf(_("Failed to copy [%s]"),"$src/$entry") );
838                 }
839             }
840             closedir( $d );
841             return true;
842         } else {
843             $this->_cvsDebug( _("Not copying") );
844             return false;
845         }
846     }
847
848     /**
849      * Unescape a string value. Normally this comes from doing an 
850      * escapeshellcmd. This converts the following:
851      *    \{ --> {
852      *    \} --> }
853      *    \; --> ;
854      *    \" --> "
855      */
856     function _unescape( $val )
857     {
858         $val = str_replace( "\\{", "{", $val );
859         $val = str_replace( "\\}", "}", $val );
860         $val = str_replace( "\\;", ";", $val );
861         $val = str_replace( "\\\"", "\"", $val );
862         
863         return $val;
864     }
865
866     /**
867      * Function for removing the newlines from the ends of the
868      * file data returned from file(..). This is used in retrievePage
869      */
870     function _strip_newlines( &$item, $key )
871     {
872         $item = ereg_replace( "\n$", "", $item );
873     }
874
875 } /* End of WikiDB_backend_cvs class */
876
877 /**
878  * Generic iterator for stepping through an array of values.
879  */
880 class Cvs_Backend_Array_Iterator
881 extends WikiDB_backend_iterator
882 {
883     var $_array;
884
885     function Cvs_Backend_Iterator( $arrayValue = Array() )
886     {
887         $this->_array = $arrayValue;
888     }
889
890     function next() 
891     {
892         while ( ($rVal = array_pop( $this->_array )) != NULL ) {
893             return $rVal;
894         }
895         return false;
896     }
897
898     function free()
899     {
900         unset( $this->_array );
901     }
902 }
903
904 class Cvs_Backend_Full_Search_Iterator
905 extends Cvs_Backend_Array_Iterator
906 {
907     var $_searchString = '';
908     var $_docDir = "";
909
910     function Cvs_Backend_Title_Search_Iterator( $arrayValue = Array(),
911                                                 $searchString  = "",
912                                                 $documentDir = ".")
913     {
914         $this->Cvs_Backend_Array_Iterator( $arrayValue );
915         $_searchString = $searchString;
916         $_docDir = $documentDir;
917     }
918
919     function next()
920     {
921         do {
922             $pageName = Cvs_Backend_Array_Iterator::next();
923         } while ( !$this->_searchFile( $_searchString, 
924                                        $_docDir . "/" . $pageName ));
925
926         return $pageName;
927     }
928
929     /**
930      * Does nothing more than a grep and search the entire contents
931      * of the given file. Returns TRUE of the searchstring was found, 
932      * false if the search string wasn't find or the file was a directory
933      * or could not be read.
934      */
935     function _searchFile( $searchString, $fileName )
936     {
937         // TODO: using grep here, it might make more sense to use
938         // TODO: some sort of inbuilt/language specific method for
939         // TODO: searching files.
940         $cmdLine = sprintf( "grep -E -i '%s' %s > /dev/null 2>&1", 
941                             $searchString, $fileName );
942         
943         return ( WikiDB_backend_cvs::_execCommand( $cmdLine, $cmdOutput, 
944                                                    false ) == 0 );
945     }
946 }
947
948 /**
949  * Iterator used for doing a title search.
950  */
951 class Cvs_Backend_Title_Search_Iterator
952 extends Cvs_Backend_Array_Iterator
953 {
954     var $_searchString = '';
955
956     function Cvs_Backend_Title_Search_Iterator( $arrayValue = Array(),
957                                                 $searchString  = "")
958     {
959         $this->Cvs_Backend_Array_Iterator( $arrayValue );
960         $_searchString = $searchString;
961     }
962
963     function next()
964     {
965         do {
966             $pageName = Cvs_Backend_Array_Iterator::next();
967         } while ( !eregi( $this->_searchString, $pageName ) );
968
969         return $pageName;
970     }
971 }
972
973
974
975 ?>