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

/lib/util/opToolkit.class.php

https://github.com/bb-dev/OpenPNE3
PHP | 594 lines | 420 code | 94 blank | 80 comment | 70 complexity | 5971f76259473bafcfe21f7bf6a3444d MD5 | raw file
  1. <?php
  2. /**
  3. * This file is part of the OpenPNE package.
  4. * (c) OpenPNE Project (http://www.openpne.jp/)
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file and the NOTICE file that were distributed with this source code.
  8. */
  9. /**
  10. * opToolkit provides basic utility methods for OpenPNE.
  11. *
  12. * @package OpenPNE
  13. * @subpackage util
  14. * @author Kousuke Ebihara <ebihara@tejimaya.com>
  15. */
  16. class opToolkit
  17. {
  18. /**
  19. * Returns the list of mobile e-mail address domains.
  20. *
  21. * @return array
  22. */
  23. public static function getMobileMailAddressDomains()
  24. {
  25. return (array)include(sfContext::getInstance()->getConfigCache()->checkConfig('config/mobile_mail_domain.yml'));
  26. }
  27. /**
  28. * Checks if a string is a mobile e-mail address.
  29. *
  30. * @param string
  31. *
  32. * @return bool true if $string is valid mobile e-mail address and false otherwise.
  33. */
  34. public static function isMobileEmailAddress($string)
  35. {
  36. $pieces = explode('@', $string, 2);
  37. $domain = array_pop($pieces);
  38. return in_array($domain, self::getMobileMailAddressDomains());
  39. }
  40. /**
  41. * Takes a text that matched pattern and replaces it to a marker.
  42. *
  43. * Replaces text that matched $pattern to a marker.
  44. * This method returns replaced text and a correspondence table of marker and pre-convert text
  45. *
  46. * @param string $subject
  47. * @param array $patterns
  48. *
  49. * @return array
  50. */
  51. public static function replacePatternsToMarker($subject, $patterns = array())
  52. {
  53. $i = 0;
  54. $list = array();
  55. if (empty($patterns))
  56. {
  57. $patterns = array(
  58. '/<input[^>]+>/is',
  59. '/<textarea.*?<\/textarea>/is',
  60. '/<option.*?<\/option>/is',
  61. '/<img[^>]+>/is',
  62. '/<head.*?<\/head>/is',
  63. );
  64. }
  65. foreach ($patterns as $pattern)
  66. {
  67. if (preg_match_all($pattern, $subject, $matches))
  68. {
  69. foreach ($matches[0] as $match)
  70. {
  71. $replacement = '<<<MARKER:'.$i.'>>>';
  72. $list[$replacement] = $match;
  73. $i++;
  74. }
  75. }
  76. }
  77. $subject = str_replace(array_values($list), array_keys($list), $subject);
  78. return array($list, $subject);
  79. }
  80. public static function isEnabledRegistration($mode = '')
  81. {
  82. $registration = opConfig::get('enable_registration');
  83. if ($registration == 3)
  84. {
  85. return true;
  86. }
  87. if (!$mode && $registration)
  88. {
  89. return true;
  90. }
  91. if ($mode == 'mobile' && $registration == 1)
  92. {
  93. return true;
  94. }
  95. if ($mode == 'pc' && $registration == 2)
  96. {
  97. return true;
  98. }
  99. return false;
  100. }
  101. /**
  102. * Unifys EOL characters in the string.
  103. *
  104. * @param string $string
  105. * @param string $eol
  106. *
  107. * @return string
  108. */
  109. public static function unifyEOLCharacter($string, $eol = "\n")
  110. {
  111. $eols = array("\r\n", "\r", "\n");
  112. if (!in_array($eol, $eols))
  113. {
  114. return $string;
  115. }
  116. // first, unifys to LF
  117. $string = str_replace("\r\n", "\n", $string);
  118. $string = str_replace("\r", "\n", $string);
  119. // second, unifys to specify EOL character
  120. if ($eol !== "\n")
  121. {
  122. $string = str_replace("\n", $eol, $string);
  123. }
  124. return $string;
  125. }
  126. public static function extractEnclosedStrings($string, $enclosure = '"')
  127. {
  128. $result = array('base' => $string, 'enclosed' => array());
  129. $enclosureCount = substr_count($string, $enclosure);
  130. for ($i = 0; $i < $enclosureCount; $i++)
  131. {
  132. $begin = strpos($string, $enclosure);
  133. $finish = strpos($string, $enclosure, $begin + 1);
  134. if ($begin !== false && $finish !== false)
  135. {
  136. $head = substr($string, 0, $begin - 1);
  137. $body = substr($string, $begin + 1, $finish - $begin - 1);
  138. $foot = substr($string, $finish + 1);
  139. $string = $head.$foot;
  140. $result['enclosed'][] = $body;
  141. $i++;
  142. }
  143. }
  144. $result['base'] = $string;
  145. return $result;
  146. }
  147. public static function generatePasswordString($length = 12, $is_use_mark = true)
  148. {
  149. $result = '';
  150. $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  151. if ($is_use_mark)
  152. {
  153. $str .= '#$-=?@[]_';
  154. }
  155. $range = strlen($str) - 1;
  156. while ($length > strlen($result))
  157. {
  158. $result .= $str[rand(0, $range)];
  159. }
  160. return $result;
  161. }
  162. public static function stripNullByteDeep($value)
  163. {
  164. return is_array($value) ?
  165. array_map(array('opToolkit', 'stripNullByteDeep'), $value) :
  166. (is_string($value) ? preg_replace("/[\x{0}-\x{08}\x{0b}-\x{1f}\x{7f}-\x{9f}\x{ad}]/u", '', $value) : $value);
  167. }
  168. public static function appendMobileInputModeAttributesForFormWidget(sfWidget $widget, $mode = 'alphabet')
  169. {
  170. $modes = array(
  171. 'hiragana' => 1,
  172. 'hankakukana' => 2,
  173. 'alphabet' => 3,
  174. 'numeric' => 4,
  175. );
  176. if (empty($modes[$mode]))
  177. {
  178. return false;
  179. }
  180. $widget->setAttribute('istyle', $modes[$mode]);
  181. $widget->setAttribute('mode', $mode);
  182. }
  183. /**
  184. * This method calculates how many days to go until specified day.
  185. *
  186. * @param string $targetDay
  187. * @return int between from target days.
  188. */
  189. public static function extractTargetDay($targetDay)
  190. {
  191. If (!$targetDay)
  192. {
  193. return -1;
  194. }
  195. list(, $m, $d) = explode('-', $targetDay);
  196. $m = (int)$m;
  197. $d = (int)$d;
  198. if ($m == 0 || $d == 0) {
  199. return -1;
  200. }
  201. $y = date('Y');
  202. $today = mktime(0, 0, 0);
  203. $theday_thisyear = mktime(0, 0, 0, $m, $d, $y);
  204. $theday_nextyear = mktime(0, 0, 0, $m, $d, $y + 1);
  205. if ($theday_thisyear < $today) {
  206. $theday_next = $theday_nextyear;
  207. } else {
  208. $theday_next = $theday_thisyear;
  209. }
  210. return ($theday_next - $today) / 86400;
  211. }
  212. public static function retrieveAPIList($isWithI18n = true)
  213. {
  214. $result = array();
  215. $context = sfContext::getInstance();
  216. $config = new sfRoutingConfigHandler();
  217. $currentApp = sfConfig::get('sf_app');
  218. $i18n = $context->getI18n();
  219. sfConfig::set('sf_app', 'api');
  220. $routing = new sfPatternRouting($context->getEventDispatcher());
  221. $routing->setRoutes($config->evaluate($context->getConfiguration()->getConfigPaths('config/routing.yml')));
  222. sfConfig::set('sf_app', $currentApp);
  223. $context->getEventDispatcher()->notify(new sfEvent($routing, 'routing.load_configuration'));
  224. $routes = $routing->getRoutes();
  225. foreach ($routes as $route)
  226. {
  227. if ($route instanceof opAPIRouteInterface)
  228. {
  229. $caption = $route->getAPICaption();
  230. if ($isWithI18n)
  231. {
  232. $caption = $i18n->__($caption, null, 'api');
  233. }
  234. $result[$route->getAPIName()] = $caption;
  235. }
  236. }
  237. return $result;
  238. }
  239. static public function getCultureChoices($cultures)
  240. {
  241. $choices = array();
  242. foreach ($cultures as $culture)
  243. {
  244. $c = explode('_', $culture);
  245. try
  246. {
  247. $cultureInfo = sfCultureInfo::getInstance($culture);
  248. $choices[$culture] = $cultureInfo->getLanguage($c[0]);
  249. if (isset($c[1]))
  250. {
  251. $choices[$culture] .= ' ('.$cultureInfo->getCountry($c[1]).')';
  252. }
  253. }
  254. catch (sfException $e)
  255. {
  256. $choices[$culture] = $culture;
  257. }
  258. }
  259. return $choices;
  260. }
  261. static public function getPresetProfileList()
  262. {
  263. $configPath = 'config/preset_profile.yml';
  264. sfContext::getInstance()->getConfigCache()->registerConfigHandler($configPath, 'sfSimpleYamlConfigHandler', array());
  265. $list = include(sfContext::getInstance()->getConfigCache()->checkConfig($configPath));
  266. return $list;
  267. }
  268. public static function arrayMapRecursive($callback, $array)
  269. {
  270. $result = array();
  271. foreach ($array as $key => $value)
  272. {
  273. $result[$key] = is_array($value) ? call_user_func(array('opToolkit', 'arrayMapRecursive'), $callback, $value) : call_user_func($callback, $value);
  274. }
  275. return $result;
  276. }
  277. /**
  278. * This method file download.
  279. *
  280. * @param string $original_filename
  281. * @param bin $bin
  282. * @return none binaryFile
  283. */
  284. static public function fileDownload($original_filename, $bin)
  285. {
  286. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) {
  287. $original_filename = mb_convert_encoding($original_filename, 'SJIS', 'UTF-8');
  288. }
  289. $original_filename = str_replace(array("\r", "\n"), '', $original_filename);
  290. header('Content-Disposition: attachment; filename="'.$original_filename.'"');
  291. header('Content-Length: '.strlen($bin));
  292. header('Content-Type: application/octet-stream');
  293. echo $bin;
  294. exit;
  295. }
  296. public static function isSecurePage()
  297. {
  298. $context = sfContext::getInstance();
  299. $action = $context->getActionStack()->getLastEntry()->getActionInstance();
  300. $credential = $action->getCredential();
  301. if (sfConfig::get('sf_login_module') === $context->getModuleName()
  302. && sfConfig::get('sf_login_action') === $context->getActionName())
  303. {
  304. return false;
  305. }
  306. if (sfConfig::get('sf_secure_module') == $context->getModuleName()
  307. && sfConfig::get('sf_secure_action') == $context->getActionName())
  308. {
  309. return false;
  310. }
  311. if (!$action->isSecure())
  312. {
  313. return false;
  314. }
  315. if ((is_array($credential) && !in_array('SNSMember', $credential))
  316. || (is_string($credential) && 'SNSMember' !== $credential))
  317. {
  318. return false;
  319. }
  320. return true;
  321. }
  322. public static function setIsSecure($action)
  323. {
  324. $security = $action->getSecurityConfiguration();
  325. $security[$action->getActionName()]['is_secure'] = true;
  326. $action->setSecurityConfiguration($security);
  327. }
  328. public static function clearCache()
  329. {
  330. $filesystem = new sfFilesystem();
  331. $filesystem->remove(sfFinder::type('file')->discard('.sf')->in(sfConfig::get('sf_cache_dir')));
  332. @$filesystem->remove(sfFinder::type('file')->in(sfConfig::get('sf_web_dir').'/cache/'));
  333. }
  334. /**
  335. * calculateAge
  336. */
  337. public static function calculateAge($birthdayString)
  338. {
  339. $birthdayTime = strtotime($birthdayString);
  340. if (false === $birthdayTime)
  341. {
  342. return false;
  343. }
  344. $thisYear = intval(date('Y'));
  345. $today = intval(date('nd'));
  346. $age = $thisYear - date('Y', $birthdayTime);
  347. if ($today < date('n', $birthdayTime) * 100 + date('d', $birthdayTime)) $age--;
  348. return $age;
  349. }
  350. public static function createStringDsnFromArray($arrayDsn)
  351. {
  352. $result = array();
  353. $table = array(
  354. 'host' => 'hostspec',
  355. 'port' => 'port',
  356. 'dbname' => 'database',
  357. 'unix_socket' => 'unix_socket',
  358. );
  359. if (!empty($arrayDsn['hostspec']))
  360. {
  361. $pieces = explode(':', $arrayDsn['hostspec']);
  362. $arrayDsn['hostspec'] = $pieces[0];
  363. if (isset($pieces[1]))
  364. {
  365. $arrayDsn['port'] = $pieces[1];
  366. }
  367. }
  368. if (!empty($arrayDsn['protocol']) && !empty($arrayDsn['proto_opts']))
  369. {
  370. if ('unix' === $arrayDsn['protocol'])
  371. {
  372. $arrayDsn['unix_socket'] = $arrayDsn['proto_opts'];
  373. }
  374. }
  375. foreach ($table as $k => $v)
  376. {
  377. if (isset($arrayDsn[$v]))
  378. {
  379. $result[] = $k.'='.$arrayDsn[$v];
  380. }
  381. }
  382. return $arrayDsn['phptype'].':'.implode(';', $result);
  383. }
  384. public static function calculateUsableMemorySize()
  385. {
  386. $limit = trim(ini_get('memory_limit'));
  387. if ('-1' === $limit)
  388. {
  389. return null;
  390. }
  391. $unit = strtolower($limit[strlen($limit)-1]);
  392. $units = array(
  393. 'k' => 1,
  394. 'm' => 2,
  395. 'g' => 3,
  396. );
  397. if (isset($units[$unit]))
  398. {
  399. $limit *= pow(1024, $units[$unit]);
  400. }
  401. $usage = memory_get_usage();
  402. return ($limit - $usage);
  403. }
  404. /**
  405. * Generates a randomized hash (from Ethna 2.5.0)
  406. *
  407. * Licensed under The BSD License. Original is the Ethna_Util::getRandom() method.
  408. *
  409. * Copyright (c) 2004-2006, Masaki Fujimoto
  410. * All rights reserved.
  411. *
  412. * @author Masaki Fujimoto <fujimoto@php.net>
  413. * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
  414. *
  415. * @param int $length Length of a hash
  416. * @return string
  417. */
  418. public function getRandom($length = 64)
  419. {
  420. static $srand = false;
  421. if ($srand == false)
  422. {
  423. list($usec, $sec) = explode(' ', microtime());
  424. mt_srand((float) $sec + ((float) $usec * 100000) + getmypid());
  425. $srand = true;
  426. }
  427. // Is the "open_basedir" is on, and accessing to /proc is allowed?
  428. // If the "open_basedir" is empty, this method consider that accessing to it is allowed.
  429. $devfile = '/proc/net/dev';
  430. $open_basedir_conf = ini_get('open_basedir');
  431. $devfile_enabled = (empty($open_basedir_conf)
  432. || (preg_match('#:/proc#', $open_basedir_conf) > 0
  433. || preg_match('#^/proc#', $open_basedir_conf) > 0));
  434. $value = '';
  435. for ($i = 0; $i < 2; $i++)
  436. {
  437. // for Linux
  438. if ($devfile_enabled && file_exists($devfile))
  439. {
  440. $rx = $tx = 0;
  441. $fp = fopen($devfile, 'r');
  442. if ($fp != null)
  443. {
  444. $header = true;
  445. while (feof($fp) === false)
  446. {
  447. $s = fgets($fp, 4096);
  448. if ($header)
  449. {
  450. $header = false;
  451. continue;
  452. }
  453. $v = preg_split('/[:\s]+/', $s);
  454. if (is_array($v) && count($v) > 10)
  455. {
  456. $rx += $v[2];
  457. $tx += $v[10];
  458. }
  459. }
  460. }
  461. $platform_value = $rx.$tx.mt_rand().getmypid();
  462. }
  463. else
  464. {
  465. $platform_value = mt_rand().getmypid();
  466. }
  467. $now = strftime('%Y%m%d %T');
  468. $time = gettimeofday();
  469. $v = $now.$time['usec'].$platform_value.mt_rand(0, time());
  470. $value .= md5($v);
  471. }
  472. if ($length < 64)
  473. {
  474. $value = substr($value, 0, $length);
  475. }
  476. return $value;
  477. }
  478. static public function writeCacheFile($pathToCacheFile, $content)
  479. {
  480. $filesystem = new sfFilesystem();
  481. $currentUmask = umask();
  482. umask(0000);
  483. $tmpFile = tempnam(dirname($pathToCacheFile), basename($pathToCacheFile));
  484. if (!$fp = @fopen($tmpFile, 'wb'))
  485. {
  486. throw new sfCacheException('Failed to write cache file.');
  487. }
  488. @fwrite($fp, $content);
  489. @fclose($fp);
  490. if (!@rename($tmpFile, $pathToCacheFile))
  491. {
  492. if ($filesystem->copy($tmpFile, $pathToCacheFile, array('override' => true)))
  493. {
  494. $filesystem->remove($tmpFile);
  495. }
  496. }
  497. $filesystem->chmod($pathToCacheFile, 0666);
  498. umask($currentUmask);
  499. }
  500. }