]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/FileFinder.php
Assume function_exists("_")
[SourceForge/phpwiki.git] / lib / FileFinder.php
1 <?php
2
3 require_once(dirname(__FILE__) . '/stdlib.php');
4
5 /**
6  * A class for finding files.
7  *
8  * This should really provided by pear. We don't want really to mess around
9  * with all the lousy systems. (WindowsNT, Win95, Mac, ...)
10  * But pear has only System and File, which do nothing.
11  * Anyway, in good PHP style we ignore the rest of the world and try to behave
12  * as on unix only. That means we use / as pathsep in all our constants.
13  */
14 class FileFinder
15 {
16     public $_pathsep, $_path;
17
18     /**
19      * Constructor.
20      *
21      * @param $path array A list of directories in which to search for files.
22      */
23     function FileFinder($path = false)
24     {
25         $this->_pathsep = $this->_get_syspath_separator();
26         if (!isset($this->_path) and $path === false)
27             $path = $this->_get_include_path();
28         $this->_path = $path;
29     }
30
31     /**
32      * Find file.
33      *
34      * @param $file string File to search for.
35      * @return string The filename (including path), if found, otherwise false.
36      */
37     function findFile($file, $missing_okay = false)
38     {
39         if ($this->_is_abs($file)) {
40             if (file_exists($file))
41                 return $file;
42         } elseif (($dir = $this->_search_path($file))) {
43             return $dir . $this->_use_path_separator($dir) . $file;
44         }
45         return $missing_okay ? false : $this->_not_found($file);
46     }
47
48     /**
49      * Unify used pathsep character.
50      * Accepts array of paths also.
51      * This might not work on Windows95 or FAT volumes. (not tested)
52      */
53     function slashifyPath($path)
54     {
55         return $this->forcePathSlashes($path, $this->_pathsep);
56     }
57
58     /**
59      * Force using '/' as path seperator.
60      */
61     function forcePathSlashes($path, $sep = '/')
62     {
63         if (is_array($path)) {
64             $result = array();
65             foreach ($path as $dir) {
66                 $result[] = $this->forcePathSlashes($dir, $sep);
67             }
68             return $result;
69         } else {
70             if (isWindows() or $this->_isOtherPathsep()) {
71                 if (isWindows()) $from = "\\";
72                 else $from = "\\";
73                 // PHP is stupid enough to use \\ instead of \
74                 if (isWindows()) {
75                     if (substr($path, 0, 2) != '\\\\')
76                         $path = str_replace('\\\\', '\\', $path);
77                     else // UNC paths
78                         $path = '\\\\' . str_replace('\\\\', '\\', substr($path, 2));
79                 }
80                 return strtr($path, $from, $sep);
81             } else
82                 return $path;
83         }
84     }
85
86     /**
87      * Try to include file.
88      *
89      * If file is found in the path, then the files directory is added
90      * to PHP's include_path (if it's not already there.) Then the
91      * file is include_once()'d.
92      *
93      * @param $file string File to include.
94      * @return bool True if file was successfully included.
95      */
96     function includeOnce($file)
97     {
98         if (($ret = @include_once($file)))
99             return $ret;
100
101         if (!$this->_is_abs($file)) {
102             if (($dir = $this->_search_path($file)) && is_file($dir . $this->_pathsep . $file)) {
103                 $this->_append_to_include_path($dir);
104                 return include_once($file);
105             }
106         }
107         return $this->_not_found($file);
108     }
109
110     function _isOtherPathsep()
111     {
112         return $this->_pathsep != '/';
113     }
114
115     /**
116      * The system-dependent path-separator character.
117      * UNIX,WindowsNT,MacOSX: /
118      * Windows95: \
119      * Mac:       :
120      *
121      * @access private
122      * @return string path_separator.
123      */
124     function _get_syspath_separator()
125     {
126         if (!empty($this->_pathsep)) return $this->_pathsep;
127         elseif (isWindowsNT()) return "/"; // we can safely use '/'
128         elseif (isWindows()) return "\\"; // FAT might use '\'
129         // VMS or LispM is really weird, we ignore it.
130         else return '/';
131     }
132
133     /**
134      * The path-separator character of the given path.
135      * Windows accepts "/" also, but gets confused with mixed path_separators,
136      * e.g "C:\Apache\phpwiki/locale/button"
137      * > dir "C:\Apache\phpwiki/locale/button" =>
138      *       Parameterformat nicht korrekt - "locale"
139      * So if there's any '\' in the path, either fix them to '/' (not in Win95 or FAT?)
140      * or use '\' for ours.
141      *
142      * @access private
143      * @return string path_separator.
144      */
145     function _use_path_separator($path)
146     {
147         if (isWindows95()) {
148             if (empty($path)) return "\\";
149             else return (strchr($path, "\\")) ? "\\" : '/';
150         } else {
151             return $this->_get_syspath_separator();
152         }
153     }
154
155     /**
156      * Determine if path is absolute.
157      *
158      * @access private
159      * @param $path string Path.
160      * @return bool True if path is absolute.
161      */
162     function _is_abs($path)
163     {
164         if (substr($path, 0, 1) == '/') {
165             return true;
166         } elseif (isWindows() and preg_match("/^[a-z]:/i", $path)
167             and (substr($path, 2, 1) == "/" or substr($path, 2, 1) == "\\")
168         ) {
169             return true;
170         } else {
171             return false;
172         }
173     }
174
175     /**
176      * Strip ending '/' or '\' from path.
177      *
178      * @access private
179      * @param $path string Path.
180      * @return bool New path (destructive)
181      */
182     function _strip_last_pathchar(&$path)
183     {
184         if (substr($path, -1) == '/' or substr($path, -1) == "\\")
185             $path = substr($path, 0, -1);
186         return $path;
187     }
188
189     /**
190      * Report a "file not found" error.
191      *
192      * @access private
193      * @param $file string Name of missing file.
194      * @return bool false.
195      */
196     function _not_found($file)
197     {
198         trigger_error(sprintf(_("%s: file not found"), $file), E_USER_ERROR);
199         return false;
200     }
201
202     /**
203      * Search our path for a file.
204      *
205      * @access private
206      * @param $file string File to find.
207      * @return string Directory which contains $file, or false.
208      * [5x,44ms]
209      */
210     function _search_path($file)
211     {
212         foreach ($this->_path as $dir) {
213             // ensure we use the same pathsep
214             if ($this->_isOtherPathsep()) {
215                 $dir = $this->slashifyPath($dir);
216                 $file = $this->slashifyPath($file);
217                 if (file_exists($dir . $this->_pathsep . $file))
218                     return $dir;
219             } elseif (@file_exists($dir . $this->_pathsep . $file))
220                 return $dir;
221         }
222         return false;
223     }
224
225     /**
226      * The system-dependent path-separator character. On UNIX systems,
227      * this character is ':'; on Win32 systems it is ';'.
228      * Fixme:
229      * On Mac it cannot be : because this is the seperator there!
230      *
231      * @access private
232      * @return string path_separator.
233      */
234     function _get_ini_separator()
235     {
236         return isWindows() ? ';' : ':';
237         // return preg_match('/^Windows/', php_uname())
238     }
239
240     /**
241      * Get the value of PHP's include_path.
242      *
243      * @access private
244      * @return array Include path.
245      */
246     function _get_include_path()
247     {
248         if (defined("INCLUDE_PATH"))
249             $path = INCLUDE_PATH;
250         else {
251             $path = @get_cfg_var('include_path'); // FIXME: report warning
252             if (empty($path)) $path = @ini_get('include_path');
253         }
254         if (empty($path))
255             $path = '.';
256         return explode($this->_get_ini_separator(), $this->slashifyPath($path));
257     }
258
259     /**
260      * Add a directory to the end of PHP's include_path.
261      *
262      * The directory is appended only if it is not already listed in
263      * the include_path.
264      *
265      * @access private
266      * @param $dir string Directory to add.
267      */
268     function _append_to_include_path($dir)
269     {
270         $dir = $this->slashifyPath($dir);
271         if (!in_array($dir, $this->_path)) {
272             $this->_path[] = $dir;
273         }
274         /*
275          * Some (buggy) PHP's (notable SourceForge's PHP 4.0.6)
276          * sometimes don't seem to heed their include_path.
277          * I.e. sometimes a file is not found even though it seems to
278          * be in the current include_path. A simple
279          * ini_set('include_path', ini_get('include_path')) seems to
280          * be enough to fix the problem
281          *
282          * This following line should be in the above if-block, but we
283          * put it here, as it seems to work-around the bug.
284          */
285         $GLOBALS['INCLUDE_PATH'] = implode($this->_get_ini_separator(), $this->_path);
286         @ini_set('include_path', $GLOBALS['INCLUDE_PATH']);
287     }
288
289     /**
290      * Add a directory to the front of PHP's include_path.
291      *
292      * The directory is prepended, and removed from the tail if already existing.
293      *
294      * @access private
295      * @param $dir string Directory to add.
296      */
297     function _prepend_to_include_path($dir)
298     {
299         $dir = $this->slashifyPath($dir);
300         // remove duplicates
301         if ($i = array_search($dir, $this->_path) !== false) {
302             array_splice($this->_path, $i, 1);
303         }
304         array_unshift($this->_path, $dir);
305         $GLOBALS['INCLUDE_PATH'] = implode($this->_path, $this->_get_ini_separator());
306         @ini_set('include_path', $GLOBALS['INCLUDE_PATH']);
307     }
308
309     // Return all the possible shortened locale specifiers for the given locale.
310     // Most specific first.
311     // de_DE.iso8859-1@euro => de_DE.iso8859-1, de_DE, de
312     // This code might needed somewhere else also.
313     function locale_versions($lang)
314     {
315         // Try less specific versions of the locale
316         $langs[] = $lang;
317         foreach (array('@', '.', '_') as $sep) {
318             if (($tail = strchr($lang, $sep)))
319                 $langs[] = substr($lang, 0, -strlen($tail));
320         }
321         return $langs;
322     }
323
324     /**
325      * Try to figure out the appropriate value for $LANG.
326      *
327      * @access private
328      * @return string The value of $LANG.
329      */
330     function _get_lang()
331     {
332         if (!empty($GLOBALS['LANG']))
333             return $GLOBALS['LANG'];
334
335         foreach (array('LC_ALL', 'LC_MESSAGES', 'LC_RESPONSES') as $var) {
336             $lang = setlocale(constant($var), 0);
337             if (!empty($lang))
338                 return $lang;
339         }
340
341         foreach (array('LC_ALL', 'LC_MESSAGES', 'LC_RESPONSES', 'LANG') as $var) {
342             $lang = getenv($var);
343             if (!empty($lang))
344                 return $lang;
345         }
346
347         return "C";
348     }
349 }
350
351 /**
352  * A class for finding PEAR code.
353  *
354  * This is a subclass of FileFinder which searches a standard list of
355  * directories where PEAR code is likely to be installed.
356  *
357  * Example usage:
358  *
359  * <pre>
360  *   $pearFinder = new PearFileFinder;
361  *   $pearFinder->includeOnce('DB.php');
362  * </pre>
363  *
364  * The above code will look for 'DB.php', if found, the directory in
365  * which it was found will be added to PHP's include_path, and the
366  * file will be included. (If the file is not found, and E_USER_ERROR
367  * will be thrown.)
368  */
369 class PearFileFinder
370     extends FileFinder
371 {
372     /**
373      * Constructor.
374      *
375      * @param $path array Where to look for PEAR library code.
376      * A good set of defaults is provided, so you can probably leave
377      * this parameter blank.
378      */
379     function PearFileFinder($path = array())
380     {
381         $this->FileFinder(array_merge(
382             $path,
383             array('/usr/share/php',
384                 '/usr/lib/php',
385                 '/usr/local/share/php',
386                 '/usr/local/lib/php',
387                 '/System/Library/PHP',
388                 '/Apache/pear' // Windows
389             )));
390     }
391 }
392
393 /**
394  * Find PhpWiki localized files.
395  *
396  * This is a subclass of FileFinder which searches PHP's include_path
397  * for files. It looks first for "locale/$LANG/$file", then for
398  * "$file".
399  *
400  * If $LANG is something like "de_DE.iso8859-1@euro", this class will
401  * also search under various less specific variations like
402  * "de_DE.iso8859-1", "de_DE" and "de".
403  */
404 class LocalizedFileFinder
405     extends FileFinder
406 {
407     /**
408      * Constructor.
409      */
410     function LocalizedFileFinder()
411     {
412         $this->_pathsep = $this->_get_syspath_separator();
413         $include_path = $this->_get_include_path();
414         $path = array();
415
416         $lang = $this->_get_lang();
417         assert(!empty($lang));
418
419         if ($locales = $this->locale_versions($lang)) {
420             foreach ($locales as $lang) {
421                 if ($lang == 'C') $lang = 'en';
422                 foreach ($include_path as $dir) {
423                     $path[] = $this->slashifyPath($dir . "/locale/$lang");
424                 }
425             }
426         }
427         $this->FileFinder(array_merge($path, $include_path));
428     }
429 }
430
431 /**
432  * Find PhpWiki localized theme buttons.
433  *
434  * This is a subclass of FileFinder which searches PHP's include_path
435  * for files. It looks first for "buttons/$LANG/$file", then for
436  * "$file".
437  *
438  * If $LANG is something like "de_DE.iso8859-1@euro", this class will
439  * also search under various less specific variations like
440  * "de_DE.iso8859-1", "de_DE" and "de".
441  */
442 class LocalizedButtonFinder
443     extends FileFinder
444 {
445     /**
446      * Constructor.
447      */
448     function LocalizedButtonFinder()
449     {
450         global $WikiTheme;
451         $this->_pathsep = $this->_get_syspath_separator();
452         $include_path = $this->_get_include_path();
453         $path = array();
454
455         $lang = $this->_get_lang();
456         assert(!empty($lang));
457         assert(!empty($WikiTheme));
458
459         if (is_object($WikiTheme)) {
460             $langs = $this->locale_versions($lang);
461             foreach ($langs as $lang) {
462                 if ($lang == 'C') $lang = 'en';
463                 foreach ($include_path as $dir) {
464                     $path[] = $this->slashifyPath($WikiTheme->file("buttons/$lang"));
465                 }
466             }
467         }
468
469         $this->FileFinder(array_merge($path, $include_path));
470     }
471 }
472
473 // Search PHP's include_path to find file or directory.
474 function FindFile($file, $missing_okay = false, $slashify = false)
475 {
476     static $finder;
477     if (!isset($finder)) {
478         $finder = new FileFinder;
479         // remove "/lib" from dirname(__FILE__)
480         $wikidir = preg_replace('/.lib$/', '', dirname(__FILE__));
481         // let the system favor its local pear?
482         $finder->_append_to_include_path(dirname(__FILE__) . "/pear");
483         $finder->_prepend_to_include_path($wikidir);
484         // Don't override existing INCLUDE_PATH config.
485         if (!defined("INCLUDE_PATH"))
486             define("INCLUDE_PATH", implode($finder->_get_ini_separator(), $finder->_path));
487     }
488     $s = $finder->findFile($file, $missing_okay);
489     if ($slashify)
490         $s = $finder->slashifyPath($s);
491     return $s;
492 }
493
494 // Search PHP's include_path to find file or directory.
495 // Searches for "locale/$LANG/$file", then for "$file".
496 function FindLocalizedFile($file, $missing_okay = false, $re_init = false)
497 {
498     static $finder;
499     if ($re_init or !isset($finder))
500         $finder = new LocalizedFileFinder;
501     return $finder->findFile($file, $missing_okay);
502 }
503
504 function FindLocalizedButtonFile($file, $missing_okay = false, $re_init = false)
505 {
506     static $buttonfinder;
507     if ($re_init or !isset($buttonfinder))
508         $buttonfinder = new LocalizedButtonFinder;
509     return $buttonfinder->findFile($file, $missing_okay);
510 }
511
512 /**
513  * Prefixes with PHPWIKI_DIR and slashify.
514  * For example to unify with
515  *   require_once dirname(__FILE__).'/lib/file.php'
516  *   require_once 'lib/file.php' loading style.
517  * Doesn't expand "~" or symlinks yet. truename would be perfect.
518  *
519  * NormalizeLocalFileName("lib/config.php") => /home/user/phpwiki/lib/config.php
520  */
521 function NormalizeLocalFileName($file)
522 {
523     static $finder;
524     if (!isset($finder)) {
525         $finder = new FileFinder;
526     }
527     // remove "/lib" from dirname(__FILE__)
528     if ($finder->_is_abs($file))
529         return $finder->slashifyPath($file);
530     else {
531         if (defined("PHPWIKI_DIR")) $wikidir = PHPWIKI_DIR;
532         else $wikidir = preg_replace('/.lib$/', '', dirname(__FILE__));
533         $wikidir = $finder->_strip_last_pathchar($wikidir);
534         $pathsep = $finder->_use_path_separator($wikidir);
535         return $finder->slashifyPath($wikidir . $pathsep . $file);
536         // return PHPWIKI_DIR . "/" . $file;
537     }
538 }
539
540 /**
541  * Prefixes with DATA_PATH and slashify
542  */
543 function NormalizeWebFileName($file)
544 {
545     static $finder;
546     if (!isset($finder)) {
547         $finder = new FileFinder;
548     }
549     if (defined("DATA_PATH")) {
550         $wikipath = DATA_PATH;
551         $wikipath = $finder->_strip_last_pathchar($wikipath);
552         if (!$file)
553             return $finder->forcePathSlashes($wikipath);
554         else
555             return $finder->forcePathSlashes($wikipath . '/' . $file);
556     } else {
557         return $finder->forcePathSlashes($file);
558     }
559 }
560
561 function isWindows()
562 {
563     static $win;
564     if (isset($win)) return $win;
565     //return preg_match('/^Windows/', php_uname());
566     $win = (substr(PHP_OS, 0, 3) == 'WIN');
567     return $win;
568 }
569
570 function isWindows95()
571 {
572     static $win95;
573     if (isset($win95)) return $win95;
574     $win95 = isWindows() and !isWindowsNT();
575     return $win95;
576 }
577
578 function isWindowsNT()
579 {
580     static $winnt;
581     if (isset($winnt)) return $winnt;
582     // FIXME: Do this using PHP_OS instead of php_uname().
583     // $winnt = (PHP_OS == "WINNT"); // example from http://www.php.net/manual/en/ref.readline.php
584     if (function_usable('php_uname'))
585         $winnt = preg_match('/^Windows NT/', php_uname());
586     else
587         $winnt = false; // FIXME: punt.
588     return $winnt;
589 }
590
591 // Local Variables:
592 // mode: php
593 // tab-width: 8
594 // c-basic-offset: 4
595 // c-hanging-comment-ender-p: nil
596 // indent-tabs-mode: nil
597 // End: