PageRenderTime 65ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/pandaos/kaltura
PHP | 551 lines | 379 code | 52 blank | 120 comment | 75 complexity | 3a708d8ad18bfb056ce0b61b8a9a575e MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, BSD-3-Clause, LGPL-2.1, GPL-2.0, LGPL-3.0, JSON, MPL-2.0-no-copyleft-exception, Apache-2.0
  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 4385 2007-06-25 16:40:04Z 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. $isLocked = @unlink($lockFile) ? false : true;
  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. * Checks if a string is an utf8.
  363. *
  364. * Yi Stone Li<yili@yahoo-inc.com>
  365. * Copyright (c) 2007 Yahoo! Inc. All rights reserved.
  366. * Licensed under the BSD open source license
  367. *
  368. * @param string
  369. *
  370. * @return bool true if $string is valid UTF-8 and false otherwise.
  371. */
  372. public static function isUTF8($string)
  373. {
  374. for ($idx = 0, $strlen = strlen($string); $idx < $strlen; $idx++)
  375. {
  376. $byte = ord($string[$idx]);
  377. if ($byte & 0x80)
  378. {
  379. if (($byte & 0xE0) == 0xC0)
  380. {
  381. // 2 byte char
  382. $bytes_remaining = 1;
  383. }
  384. else if (($byte & 0xF0) == 0xE0)
  385. {
  386. // 3 byte char
  387. $bytes_remaining = 2;
  388. }
  389. else if (($byte & 0xF8) == 0xF0)
  390. {
  391. // 4 byte char
  392. $bytes_remaining = 3;
  393. }
  394. else
  395. {
  396. return false;
  397. }
  398. if ($idx + $bytes_remaining >= $strlen)
  399. {
  400. return false;
  401. }
  402. while ($bytes_remaining--)
  403. {
  404. if ((ord($string[++$idx]) & 0xC0) != 0x80)
  405. {
  406. return false;
  407. }
  408. }
  409. }
  410. }
  411. return true;
  412. }
  413. public static function getArrayValueForPath($values, $name, $default = null)
  414. {
  415. if (false !== ($offset = strpos($name, '[')))
  416. {
  417. if (isset($values[substr($name, 0, $offset)]))
  418. {
  419. $array = $values[substr($name, 0, $offset)];
  420. while ($pos = strpos($name, '[', $offset))
  421. {
  422. $end = strpos($name, ']', $pos);
  423. if ($end == $pos + 1)
  424. {
  425. // reached a []
  426. break;
  427. }
  428. else if (!isset($array[substr($name, $pos + 1, $end - $pos - 1)]))
  429. {
  430. return $default;
  431. }
  432. $array = $array[substr($name, $pos + 1, $end - $pos - 1)];
  433. $offset = $end;
  434. }
  435. return $array;
  436. }
  437. }
  438. return $default;
  439. }
  440. public static function getPhpCli()
  441. {
  442. $path = getenv('PATH') ? getenv('PATH') : getenv('Path');
  443. $suffixes = DIRECTORY_SEPARATOR == '\\' ? (getenv('PATHEXT') ? explode(PATH_SEPARATOR, getenv('PATHEXT')) : array('.exe', '.bat', '.cmd', '.com')) : array('');
  444. foreach (array('php5', 'php') as $phpCli)
  445. {
  446. foreach ($suffixes as $suffix)
  447. {
  448. foreach (explode(PATH_SEPARATOR, $path) as $dir)
  449. {
  450. $file = $dir.DIRECTORY_SEPARATOR.$phpCli.$suffix;
  451. if (is_executable($file))
  452. {
  453. return $file;
  454. }
  455. }
  456. }
  457. }
  458. throw new sfException('Unable to find PHP executable');
  459. }
  460. /**
  461. * From PEAR System.php
  462. *
  463. * LICENSE: This source file is subject to version 3.0 of the PHP license
  464. * that is available through the world-wide-web at the following URI:
  465. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  466. * the PHP License and are unable to obtain it through the web, please
  467. * send a note to license@php.net so we can mail you a copy immediately.
  468. *
  469. * @author Tomas V.V.Cox <cox@idecnet.com>
  470. * @copyright 1997-2006 The PHP Group
  471. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  472. */
  473. public static function getTmpDir()
  474. {
  475. if (DIRECTORY_SEPARATOR == '\\')
  476. {
  477. if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP'))
  478. {
  479. return $var;
  480. }
  481. if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP'))
  482. {
  483. return $var;
  484. }
  485. if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir'))
  486. {
  487. return $var;
  488. }
  489. return getenv('SystemRoot').'\temp';
  490. }
  491. if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR'))
  492. {
  493. return $var;
  494. }
  495. return '/tmp';
  496. }
  497. }