/package/app/app/symfony/util/sfToolkit.class.php

https://bitbucket.org/pandaos/kaltura · PHP · 517 lines · 339 code · 50 blank · 128 comment · 67 complexity · c4fb25e57392222068ae69d58f23fec8 MD5 · raw file

  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
  5. * (c) 2004-2006 Sean Kerr.
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * sfToolkit provides basic utility methods.
  12. *
  13. * @package symfony
  14. * @subpackage util
  15. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  16. * @author Sean Kerr <skerr@mojavi.org>
  17. * @version SVN: $Id: sfToolkit.class.php 3251 2007-01-12 20:49:29Z fabien $
  18. */
  19. class sfToolkit
  20. {
  21. /**
  22. * Extract the class or interface name from filename.
  23. *
  24. * @param string A filename.
  25. *
  26. * @return string A class or interface name, if one can be extracted, otherwise null.
  27. */
  28. public static function extractClassName($filename)
  29. {
  30. $retval = null;
  31. if (self::isPathAbsolute($filename))
  32. {
  33. $filename = basename($filename);
  34. }
  35. $pattern = '/(.*?)\.(class|interface)\.php/i';
  36. if (preg_match($pattern, $filename, $match))
  37. {
  38. $retval = $match[1];
  39. }
  40. return $retval;
  41. }
  42. /**
  43. * Clear all files in a given directory.
  44. *
  45. * @param string An absolute filesystem path to a directory.
  46. *
  47. * @return void
  48. */
  49. public static function clearDirectory($directory)
  50. {
  51. if (!is_dir($directory))
  52. {
  53. return;
  54. }
  55. // open a file point to the cache dir
  56. $fp = opendir($directory);
  57. // ignore names
  58. $ignore = array('.', '..', 'CVS', '.svn');
  59. while (($file = readdir($fp)) !== false)
  60. {
  61. if (!in_array($file, $ignore))
  62. {
  63. if (is_link($directory.'/'.$file))
  64. {
  65. // delete symlink
  66. unlink($directory.'/'.$file);
  67. }
  68. else if (is_dir($directory.'/'.$file))
  69. {
  70. // recurse through directory
  71. self::clearDirectory($directory.'/'.$file);
  72. // delete the directory
  73. rmdir($directory.'/'.$file);
  74. }
  75. else
  76. {
  77. // delete the file
  78. unlink($directory.'/'.$file);
  79. }
  80. }
  81. }
  82. // close file pointer
  83. fclose($fp);
  84. }
  85. /**
  86. * Clear all files and directories corresponding to a glob pattern.
  87. *
  88. * @param string An absolute filesystem pattern.
  89. *
  90. * @return void
  91. */
  92. public static function clearGlob($pattern)
  93. {
  94. $files = glob($pattern);
  95. // order is important when removing directories
  96. sort($files);
  97. foreach ($files as $file)
  98. {
  99. if (is_dir($file))
  100. {
  101. // delete directory
  102. self::clearDirectory($file);
  103. }
  104. else
  105. {
  106. // delete file
  107. unlink($file);
  108. }
  109. }
  110. }
  111. /**
  112. * Determine if a filesystem path is absolute.
  113. *
  114. * @param path A filesystem path.
  115. *
  116. * @return bool true, if the path is absolute, otherwise false.
  117. */
  118. public static function isPathAbsolute($path)
  119. {
  120. if ($path[0] == '/' || $path[0] == '\\' ||
  121. (strlen($path) > 3 && ctype_alpha($path[0]) &&
  122. $path[1] == ':' &&
  123. ($path[2] == '\\' || $path[2] == '/')
  124. )
  125. )
  126. {
  127. return true;
  128. }
  129. return false;
  130. }
  131. /**
  132. * Determine if a lock file is present.
  133. *
  134. * @param integer A max amount of life time for the lock file.
  135. *
  136. * @return bool true, if the lock file is present, otherwise false.
  137. */
  138. public static function hasLockFile($lockFile, $maxLockFileLifeTime = 0)
  139. {
  140. $isLocked = false;
  141. if (is_readable($lockFile) && ($last_access = fileatime($lockFile)))
  142. {
  143. $now = time();
  144. $timeDiff = $now - $last_access;
  145. if (!$maxLockFileLifeTime || $timeDiff < $maxLockFileLifeTime)
  146. {
  147. $isLocked = true;
  148. }
  149. else
  150. {
  151. unlink($lockFile);
  152. }
  153. }
  154. return $isLocked;
  155. }
  156. public static function stripComments($source)
  157. {
  158. if (!sfConfig::get('sf_strip_comments', true))
  159. {
  160. return $source;
  161. }
  162. // tokenizer available?
  163. if (!function_exists('token_get_all'))
  164. {
  165. $source = sfToolkit::pregtr($source, array('#/\*((?!\*/)[\d\D\s])*\*/#' => '', // remove /* ... */
  166. '#^\s*//.*$#m' => '')); // remove // ...
  167. return $source;
  168. }
  169. $output = '';
  170. $tokens = token_get_all($source);
  171. foreach ($tokens as $token)
  172. {
  173. if (is_string($token))
  174. {
  175. // simple 1-character token
  176. $output .= $token;
  177. }
  178. else
  179. {
  180. // token array
  181. list($id, $text) = $token;
  182. switch ($id)
  183. {
  184. case T_COMMENT:
  185. case T_DOC_COMMENT:
  186. // no action on comments
  187. break;
  188. default:
  189. // anything else -> output "as is"
  190. $output .= $text;
  191. break;
  192. }
  193. }
  194. }
  195. return $output;
  196. }
  197. public static function stripslashesDeep($value)
  198. {
  199. return is_array($value) ? array_map(array('sfToolkit', 'stripslashesDeep'), $value) : stripslashes($value);
  200. }
  201. // code from php at moechofe dot com (array_merge comment on php.net)
  202. /*
  203. * array arrayDeepMerge ( array array1 [, array array2 [, array ...]] )
  204. *
  205. * Like array_merge
  206. *
  207. * arrayDeepMerge() merges the elements of one or more arrays together so
  208. * that the values of one are appended to the end of the previous one. It
  209. * returns the resulting array.
  210. * If the input arrays have the same string keys, then the later value for
  211. * that key will overwrite the previous one. If, however, the arrays contain
  212. * numeric keys, the later value will not overwrite the original value, but
  213. * will be appended.
  214. * If only one array is given and the array is numerically indexed, the keys
  215. * get reindexed in a continuous way.
  216. *
  217. * Different from array_merge
  218. * If string keys have arrays for values, these arrays will merge recursively.
  219. */
  220. public static function arrayDeepMerge()
  221. {
  222. switch (func_num_args())
  223. {
  224. case 0:
  225. return false;
  226. case 1:
  227. return func_get_arg(0);
  228. case 2:
  229. $args = func_get_args();
  230. $args[2] = array();
  231. if (is_array($args[0]) && is_array($args[1]))
  232. {
  233. foreach (array_unique(array_merge(array_keys($args[0]),array_keys($args[1]))) as $key)
  234. {
  235. $isKey0 = array_key_exists($key, $args[0]);
  236. $isKey1 = array_key_exists($key, $args[1]);
  237. if ($isKey0 && $isKey1 && is_array($args[0][$key]) && is_array($args[1][$key]))
  238. {
  239. $args[2][$key] = self::arrayDeepMerge($args[0][$key], $args[1][$key]);
  240. }
  241. else if ($isKey0 && $isKey1)
  242. {
  243. $args[2][$key] = $args[1][$key];
  244. }
  245. else if (!$isKey1)
  246. {
  247. $args[2][$key] = $args[0][$key];
  248. }
  249. else if (!$isKey0)
  250. {
  251. $args[2][$key] = $args[1][$key];
  252. }
  253. }
  254. return $args[2];
  255. }
  256. else
  257. {
  258. return $args[1];
  259. }
  260. default :
  261. $args = func_get_args();
  262. $args[1] = sfToolkit::arrayDeepMerge($args[0], $args[1]);
  263. array_shift($args);
  264. return call_user_func_array(array('sfToolkit', 'arrayDeepMerge'), $args);
  265. break;
  266. }
  267. }
  268. public static function stringToArray($string)
  269. {
  270. preg_match_all('/
  271. \s*(\w+) # key \\1
  272. \s*=\s* # =
  273. (\'|")? # values may be included in \' or " \\2
  274. (.*?) # value \\3
  275. (?(2) \\2) # matching \' or " if needed \\4
  276. \s*(?:
  277. (?=\w+\s*=) | \s*$ # followed by another key= or the end of the string
  278. )
  279. /x', $string, $matches, PREG_SET_ORDER);
  280. $attributes = array();
  281. foreach ($matches as $val)
  282. {
  283. $attributes[$val[1]] = self::literalize($val[3]);
  284. }
  285. return $attributes;
  286. }
  287. /**
  288. * Finds the type of the passed value, returns the value as the new type.
  289. *
  290. * @param string
  291. * @return mixed
  292. */
  293. public static function literalize($value, $quoted = false)
  294. {
  295. // lowercase our value for comparison
  296. $value = trim($value);
  297. $lvalue = strtolower($value);
  298. if (in_array($lvalue, array('null', '~', '')))
  299. {
  300. $value = null;
  301. }
  302. else if (in_array($lvalue, array('true', 'on', '+', 'yes')))
  303. {
  304. $value = true;
  305. }
  306. else if (in_array($lvalue, array('false', 'off', '-', 'no')))
  307. {
  308. $value = false;
  309. }
  310. else if (ctype_digit($value))
  311. {
  312. $value = (int) $value;
  313. }
  314. else if (is_numeric($value))
  315. {
  316. $value = (float) $value;
  317. }
  318. else
  319. {
  320. $value = self::replaceConstants($value);
  321. if ($quoted)
  322. {
  323. $value = '\''.str_replace('\'', '\\\'', $value).'\'';
  324. }
  325. }
  326. return $value;
  327. }
  328. /**
  329. * Replaces constant identifiers in a scalar value.
  330. *
  331. * @param string the value to perform the replacement on
  332. * @return string the value with substitutions made
  333. */
  334. public static function replaceConstants($value)
  335. {
  336. return is_string($value) ? preg_replace('/%(.+?)%/e', 'sfConfig::has(strtolower("\\1")) ? sfConfig::get(strtolower("\\1")) : "%\\1%"', $value) : $value;
  337. }
  338. /**
  339. * Returns subject replaced with regular expression matchs
  340. *
  341. * @param mixed subject to search
  342. * @param array array of search => replace pairs
  343. */
  344. public static function pregtr($search, $replacePairs)
  345. {
  346. return preg_replace(array_keys($replacePairs), array_values($replacePairs), $search);
  347. }
  348. public static function isArrayValuesEmpty($array)
  349. {
  350. static $isEmpty = true;
  351. foreach ($array as $value)
  352. {
  353. $isEmpty = (is_array($value)) ? self::isArrayValuesEmpty($value) : (strlen($value) == 0);
  354. if (!$isEmpty)
  355. {
  356. break;
  357. }
  358. }
  359. return $isEmpty;
  360. }
  361. /**
  362. * Check if a string is an utf8 using a W3C regular expression
  363. * http://fr3.php.net/manual/en/function.mb-detect-encoding.php#50087
  364. *
  365. * @param string
  366. *
  367. * @return bool true if $string is valid UTF-8 and false otherwise.
  368. */
  369. public static function isUTF8($string)
  370. {
  371. // from http://w3.org/International/questions/qa-forms-utf-8.html
  372. return preg_match('%^(?:
  373. [\x09\x0A\x0D\x20-\x7E] # ASCII
  374. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  375. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  376. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  377. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  378. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  379. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  380. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  381. )*$%xs', $string);
  382. }
  383. public static function getArrayValueForPath($values, $name, $default = null)
  384. {
  385. if (false !== ($offset = strpos($name, '[')))
  386. {
  387. if (isset($values[substr($name, 0, $offset)]))
  388. {
  389. $array = $values[substr($name, 0, $offset)];
  390. while ($pos = strpos($name, '[', $offset))
  391. {
  392. $end = strpos($name, ']', $pos);
  393. if ($end == $pos + 1)
  394. {
  395. // reached a []
  396. break;
  397. }
  398. else if (!isset($array[substr($name, $pos + 1, $end - $pos - 1)]))
  399. {
  400. return $default;
  401. }
  402. $array = $array[substr($name, $pos + 1, $end - $pos - 1)];
  403. $offset = $end;
  404. }
  405. return $array;
  406. }
  407. }
  408. return $default;
  409. }
  410. public static function getPhpCli()
  411. {
  412. $path = getenv('PATH') ? getenv('PATH') : getenv('Path');
  413. $suffixes = DIRECTORY_SEPARATOR == '\\' ? (getenv('PATHEXT') ? explode(PATH_SEPARATOR, getenv('PATHEXT')) : array('.exe', '.bat', '.cmd', '.com')) : array('');
  414. foreach (array('php5', 'php') as $phpCli)
  415. {
  416. foreach ($suffixes as $suffix)
  417. {
  418. foreach (explode(PATH_SEPARATOR, $path) as $dir)
  419. {
  420. $file = $dir.DIRECTORY_SEPARATOR.$phpCli.$suffix;
  421. if (is_executable($file))
  422. {
  423. return $file;
  424. }
  425. }
  426. }
  427. }
  428. throw new sfException('Unable to find PHP executable');
  429. }
  430. /**
  431. * From PEAR System.php
  432. *
  433. * LICENSE: This source file is subject to version 3.0 of the PHP license
  434. * that is available through the world-wide-web at the following URI:
  435. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  436. * the PHP License and are unable to obtain it through the web, please
  437. * send a note to license@php.net so we can mail you a copy immediately.
  438. *
  439. * @author Tomas V.V.Cox <cox@idecnet.com>
  440. * @copyright 1997-2006 The PHP Group
  441. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  442. */
  443. public static function getTmpDir()
  444. {
  445. if (DIRECTORY_SEPARATOR == '\\')
  446. {
  447. if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP'))
  448. {
  449. return $var;
  450. }
  451. if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP'))
  452. {
  453. return $var;
  454. }
  455. if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir'))
  456. {
  457. return $var;
  458. }
  459. return getenv('SystemRoot').'\temp';
  460. }
  461. if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR'))
  462. {
  463. return $var;
  464. }
  465. return '/tmp';
  466. }
  467. }