finder.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. <?php
  2. /**
  3. * Part of the Fuel framework.
  4. *
  5. * @package Fuel
  6. * @version 1.5
  7. * @author Fuel Development Team
  8. * @license MIT License
  9. * @copyright 2010 - 2013 Fuel Development Team
  10. * @link http://fuelphp.com
  11. */
  12. namespace Fuel\Core;
  13. /**
  14. * The Finder class allows for searching through a search path for a given
  15. * file, as well as loading a given file.
  16. *
  17. * @package Fuel
  18. * @subpackage Core
  19. */
  20. class Finder
  21. {
  22. /**
  23. * @var Finder $instance Singleton master instance
  24. */
  25. protected static $instance = null;
  26. /**
  27. * An alias for Finder::instance()->locate();
  28. *
  29. * @param string $dir Directory to look in
  30. * @param string $file File to find
  31. * @param string $ext File extension
  32. * @param bool $multiple Whether to find multiple files
  33. * @param bool $cache Whether to cache this path or not
  34. * @return mixed Path, or paths, or false
  35. */
  36. public static function search($dir, $file, $ext = '.php', $multiple = false, $cache = true)
  37. {
  38. return static::instance()->locate($dir, $file, $ext, $multiple, $cache);
  39. }
  40. /**
  41. * Gets a singleton instance of Finder
  42. *
  43. * @return Finder
  44. */
  45. public static function instance()
  46. {
  47. if ( ! static::$instance)
  48. {
  49. static::$instance = static::forge(array(APPPATH, COREPATH));
  50. }
  51. return static::$instance;
  52. }
  53. /**
  54. * Forges new Finders.
  55. *
  56. * @param array $paths The paths to initialize with
  57. * @return Finder
  58. */
  59. public static function forge($paths = array())
  60. {
  61. return new static($paths);
  62. }
  63. /**
  64. * @var array $paths Holds all of the search paths
  65. */
  66. protected $paths = array();
  67. /**
  68. * @var array $flash_paths Search paths that only last for one lookup
  69. */
  70. protected $flash_paths = array();
  71. /**
  72. * @var int $cache_lifetime the amount of time to cache in seconds
  73. */
  74. protected $cache_lifetime = null;
  75. /**
  76. * @var string $cache_dir path to the cache file location
  77. */
  78. protected $cache_dir = null;
  79. /**
  80. * @var array $cached_paths Cached lookup paths
  81. */
  82. protected $cached_paths = array();
  83. /**
  84. * @var bool $cache_valid Whether the path cache is valid or not
  85. */
  86. protected $cache_valid = true;
  87. /**
  88. * Takes in an array of paths, preps them and gets the party started.
  89. *
  90. * @param array $paths The paths to initialize with
  91. */
  92. public function __construct($paths = array())
  93. {
  94. $this->add_path($paths);
  95. }
  96. /**
  97. * Adds a path (or paths) to the search path at a given position.
  98. *
  99. * Possible positions:
  100. * (null): Append to the end of the search path
  101. * (-1): Prepend to the start of the search path
  102. * (index): The path will get inserted AFTER the given index
  103. *
  104. * @param string|array $path The path to add
  105. * @param int $pos The position to add the path
  106. * @return $this
  107. * @throws OutOfBoundsException
  108. */
  109. public function add_path($paths, $pos = null)
  110. {
  111. if ( ! is_array($paths))
  112. {
  113. $paths = array($paths);
  114. }
  115. foreach ($paths as $path)
  116. {
  117. if ($pos === null)
  118. {
  119. array_push($this->paths, $this->prep_path($path));
  120. }
  121. elseif ($pos === -1)
  122. {
  123. array_unshift($this->paths, $this->prep_path($path));
  124. }
  125. else
  126. {
  127. if ($pos > count($this->paths))
  128. {
  129. throw new \OutOfBoundsException(sprintf('Position "%s" is out of range.', $pos));
  130. }
  131. array_splice($this->paths, $pos, 0, $this->prep_path($path));
  132. }
  133. }
  134. return $this;
  135. }
  136. /**
  137. * Removes a path from the search path.
  138. *
  139. * @param string $path Path to remove
  140. * @return $this
  141. */
  142. public function remove_path($path)
  143. {
  144. foreach ($this->paths as $i => $p)
  145. {
  146. if ($p === $path)
  147. {
  148. unset($this->paths[$i]);
  149. break;
  150. }
  151. }
  152. return $this;
  153. }
  154. /**
  155. * Adds multiple flash paths.
  156. *
  157. * @param array $paths The paths to add
  158. * @return $this
  159. */
  160. public function flash($paths)
  161. {
  162. if ( ! is_array($paths))
  163. {
  164. $paths = array($paths);
  165. }
  166. foreach ($paths as $path)
  167. {
  168. array_push($this->flash_paths, $this->prep_path($path));
  169. }
  170. return $this;
  171. }
  172. /**
  173. * Clears the flash paths.
  174. *
  175. * @return $this
  176. */
  177. public function clear_flash()
  178. {
  179. $this->flash_paths = array();
  180. return $this;
  181. }
  182. /**
  183. * Returns the current search paths...including flash paths.
  184. *
  185. * @return array Search paths
  186. */
  187. public function paths()
  188. {
  189. return array_merge($this->flash_paths, $this->paths);
  190. }
  191. /**
  192. * Prepares a path for usage. It ensures that the path has a trailing
  193. * Directory Separator.
  194. *
  195. * @param string $path The path to prepare
  196. * @return string
  197. */
  198. public function prep_path($path)
  199. {
  200. $path = str_replace(array('/', '\\'), DS, $path);
  201. return rtrim($path, DS).DS;
  202. }
  203. /**
  204. * Prepares an array of paths.
  205. *
  206. * @param array $paths The paths to prepare
  207. * @return array
  208. */
  209. public function prep_paths(array $paths)
  210. {
  211. foreach ($paths as &$path)
  212. {
  213. $path = $this->prep_path($path);
  214. }
  215. return $paths;
  216. }
  217. /**
  218. * Gets a list of all the files in a given directory inside all of the
  219. * loaded search paths (e.g. the cascading file system). This is useful
  220. * for things like finding all the config files in all the search paths.
  221. *
  222. * @param string The directory to look in
  223. * @param string The file filter
  224. * @return array the array of files
  225. */
  226. public function list_files($directory = null, $filter = '*.php')
  227. {
  228. $paths = $this->paths;
  229. // get extra information of the active request
  230. if (class_exists('Request', false) and ($uri = \Uri::string()) !== null)
  231. {
  232. $paths = array_merge(\Request::active()->get_paths(), $paths);
  233. }
  234. // Merge in the flash paths then reset the flash paths
  235. $paths = array_merge($this->flash_paths, $paths);
  236. $this->clear_flash();
  237. $found = array();
  238. foreach ($paths as $path)
  239. {
  240. if (($f = glob($path.$directory.DS.$filter)) !== false)
  241. {
  242. $found = array_merge($f, $found);
  243. }
  244. }
  245. return $found;
  246. }
  247. /**
  248. * Locates a given file in the search paths.
  249. *
  250. * @param string $dir Directory to look in
  251. * @param string $file File to find
  252. * @param string $ext File extension
  253. * @param bool $multiple Whether to find multiple files
  254. * @param bool $cache Whether to cache this path or not
  255. * @return mixed Path, or paths, or false
  256. */
  257. public function locate($dir, $file, $ext = '.php', $multiple = false, $cache = true)
  258. {
  259. $found = $multiple ? array() : false;
  260. // absolute path requested?
  261. if ($file[0] === '/' or (isset($file[1]) and $file[1] === ':'))
  262. {
  263. if ( ! is_file($file))
  264. {
  265. // at this point, found would be either empty array or false
  266. return $found;
  267. }
  268. return $multiple ? array($file) : $file;
  269. }
  270. $cache_id = $multiple ? 'M.' : 'S.';
  271. $paths = array();
  272. // If a filename contains a :: then it is trying to be found in a namespace.
  273. // This is sometimes used to load a view from a non-loaded module.
  274. if ($pos = strripos($file, '::'))
  275. {
  276. // get the namespace path
  277. if ($path = \Autoloader::namespace_path('\\'.ucfirst(substr($file, 0, $pos))))
  278. {
  279. $cache_id .= substr($file, 0, $pos);
  280. // and strip the classes directory as we need the module root
  281. $paths = array(substr($path, 0, -8));
  282. // strip the namespace from the filename
  283. $file = substr($file, $pos + 2);
  284. }
  285. }
  286. else
  287. {
  288. $paths = $this->paths;
  289. // get extra information of the active request
  290. if (class_exists('Request', false) and ($uri = \Uri::string()) !== null)
  291. {
  292. $cache_id .= $uri;
  293. $paths = array_merge(\Request::active()->get_paths(), $paths);
  294. }
  295. }
  296. // Merge in the flash paths then reset the flash paths
  297. $paths = array_merge($this->flash_paths, $paths);
  298. $this->clear_flash();
  299. $file = $this->prep_path($dir).$file.$ext;
  300. $cache_id .= $file;
  301. if ($cache and $cached_path = $this->from_cache($cache_id))
  302. {
  303. return $cached_path;
  304. }
  305. foreach ($paths as $dir)
  306. {
  307. $file_path = $dir.$file;
  308. if (is_file($file_path))
  309. {
  310. if ( ! $multiple)
  311. {
  312. $found = $file_path;
  313. break;
  314. }
  315. $found[] = $file_path;
  316. }
  317. }
  318. if ( ! empty($found) and $cache)
  319. {
  320. $this->add_to_cache($cache_id, $found);
  321. }
  322. return $found;
  323. }
  324. /**
  325. * Reads in the cached paths with the given cache id.
  326. *
  327. * @param string $cache_id Cache id to read
  328. * @return void
  329. */
  330. public function read_cache($cache_id)
  331. {
  332. // make sure we have all config data
  333. empty($this->cache_dir) and $this->cache_dir = \Config::get('cache_dir', APPPATH.'cache/');
  334. empty($this->cache_lifetime) and $this->cache_lifetime = \Config::get('cache_lifetime', 3600);
  335. if ($cached = $this->cache($cache_id))
  336. {
  337. $this->cached_paths = $cached;
  338. }
  339. }
  340. /**
  341. * Writes out the cached paths if they need to be.
  342. *
  343. * @param string $cache_id Cache id to read
  344. * @return void
  345. */
  346. public function write_cache($cache_id)
  347. {
  348. $this->cache_valid or $this->cache($cache_id, $this->cached_paths);
  349. }
  350. /**
  351. * Loads in the given cache_id from the cache if it exists.
  352. *
  353. * @param string $cache_id Cache id to load
  354. * @return string|bool Path or false if not found
  355. */
  356. protected function from_cache($cache_id)
  357. {
  358. $cache_id = md5($cache_id);
  359. if (array_key_exists($cache_id, $this->cached_paths))
  360. {
  361. return $this->cached_paths[$cache_id];
  362. }
  363. return false;
  364. }
  365. /**
  366. * Loads in the given cache_id from the cache if it exists.
  367. *
  368. * @param string $cache_id Cache id to load
  369. * @return string|bool Path or false if not found
  370. */
  371. protected function add_to_cache($cache_id, $path)
  372. {
  373. $cache_id = md5($cache_id);
  374. $this->cached_paths[$cache_id] = $path;
  375. $this->cache_valid = false;
  376. }
  377. /**
  378. * This method does basic filesystem caching. It is used for things like path caching.
  379. *
  380. * This method is from KohanaPHP's Kohana class.
  381. *
  382. * @param string the cache name
  383. * @param array the data to cache (if non given it returns)
  384. * @param int the number of seconds for the cache too live
  385. */
  386. protected function cache($name, $data = null, $lifetime = null)
  387. {
  388. // Cache file is a hash of the name
  389. $file = $name.'.pathcache';
  390. // Cache directories are split by keys to prevent filesystem overload
  391. $dir = rtrim($this->cache_dir, DS).DS;
  392. if ($lifetime === NULL)
  393. {
  394. // Use the default lifetime
  395. $lifetime = $this->cache_lifetime;
  396. }
  397. if ($data === null)
  398. {
  399. if (is_file($dir.$file))
  400. {
  401. if ((time() - filemtime($dir.$file)) < $lifetime)
  402. {
  403. // Return the cache
  404. return unserialize(file_get_contents($dir.$file));
  405. }
  406. else
  407. {
  408. try
  409. {
  410. // Cache has expired
  411. unlink($dir.$file);
  412. }
  413. catch (Exception $e)
  414. {
  415. // Cache has mostly likely already been deleted,
  416. // let return happen normally.
  417. }
  418. }
  419. }
  420. // Cache not found
  421. return NULL;
  422. }
  423. if ( ! is_dir($dir))
  424. {
  425. // Create the cache directory
  426. mkdir($dir, octdec(\Config::get('file.chmod.folders', 0777)), true);
  427. // Set permissions (must be manually set to fix umask issues)
  428. chmod($dir, octdec(\Config::get('file.chmod.folders', 0777)));
  429. }
  430. // Force the data to be a string
  431. $data = serialize($data);
  432. try
  433. {
  434. // Write the cache
  435. return (bool) file_put_contents($dir.$file, $data, LOCK_EX);
  436. }
  437. catch (Exception $e)
  438. {
  439. // Failed to write cache
  440. return false;
  441. }
  442. }
  443. }