PageRenderTime 52ms CodeModel.GetById 14ms RepoModel.GetById 11ms app.codeStats 0ms

/src/system/application/helpers/utility_helper.php

https://bitbucket.org/seezoo/seezoo/
PHP | 439 lines | 341 code | 44 blank | 54 comment | 58 complexity | 88abebaed99b9c223d1ceb74a1a53232 MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * ====================================================================
  4. *
  5. * Seezoo utility helper functions
  6. *
  7. * @package Seezoo Core
  8. * @author Yoshiaki Sugimoto <neo.yoshiaki.sugimoto@gmail.com>
  9. *
  10. * ====================================================================
  11. */
  12. // ------------- Date-Time managing utirities --------------
  13. // db_datetime : DB登録用のDATETIME生成
  14. if ( ! function_exists('db_datetime'))
  15. {
  16. function db_datetime()
  17. {
  18. return date('Y-m-d H:i:s', time());
  19. }
  20. }
  21. // set_public_datetime : DATETIME形式からフォーマットで出力
  22. if ( ! function_exists('set_public_datetime'))
  23. {
  24. function set_public_datetime($format, $datetime)
  25. {
  26. // PHP5.1.0以前はstrtotimeは-1を返却するのでここで吸収
  27. if ((int)strtotime($datetime) < 1)
  28. {
  29. return '';
  30. }
  31. return date($format, strtotime($datetime));
  32. }
  33. }
  34. // parse_date : dateの値を整形
  35. if ( ! function_exists('parse_date'))
  36. {
  37. function parse_date($dt)
  38. {
  39. list($y, $m, $d) = explode('-', $dt);
  40. return $y . '年' . $m . '月' . $d . '日';
  41. };
  42. }
  43. // perse_datetime : datetimeの値を整形
  44. if ( ! function_exists('parse_datetime'))
  45. {
  46. function parse_datetime($dt, $format = 'ymd')
  47. {
  48. $data = explode(' ', $dt);
  49. if ($format === 'ymd')
  50. {
  51. list($y, $m, $d) = explode('-', $data[0]);
  52. return $y . '年' . $m . '月' . $d . '日';
  53. }
  54. else if ($format === 'his')
  55. {
  56. list($h, $i, $s) = explode(':', $data[1]);
  57. return $h . '時' . $i . '分' . $s . '秒';
  58. }
  59. else if ($format == 'hi')
  60. {
  61. list($h, $i, $s) = explode(':', $data[1]);
  62. return $h . '時' . $i . '分';
  63. }
  64. }
  65. }
  66. // hour_list : 時間の配列を生成
  67. if ( ! function_exists('hour_list'))
  68. {
  69. function hour_list()
  70. {
  71. for ($i = 0; $i < 24; $i++)
  72. {
  73. $key = ($i < 10) ? '0' . $i : (string)$i;
  74. $list[$key] = $key;
  75. }
  76. return $list;
  77. }
  78. }
  79. // minute_list : 分の配列を生成
  80. if ( ! function_exists('minute_list'))
  81. {
  82. function minute_list()
  83. {
  84. for ($i = 0; $i < 60; $i++)
  85. {
  86. $key = ($i < 10) ? '0' . $i : (string)$i;
  87. $list[$key] = $key;
  88. }
  89. return $list;
  90. }
  91. }
  92. // ----------------- String utirities -----------------
  93. // uri_encode_path : "/"を除いてURIエンコードをかける
  94. if ( ! function_exists('uri_encode_path'))
  95. {
  96. function uri_encode_path($path)
  97. {
  98. $p = rawurlencode($path);
  99. return str_replace('%2F', '/', $p);
  100. }
  101. }
  102. // multi_uri_decode : 文字列に「%」が含まれていればデコード
  103. if ( ! function_exists('multi_uri_decode'))
  104. {
  105. function multi_uri_decode($str)
  106. {
  107. if (strpos($str, '%') !== FALSE)
  108. {
  109. $str = rawurldecode($str);
  110. }
  111. return $str;
  112. }
  113. }
  114. // multi_uri_encode : 文字列をURIエンコード
  115. if ( ! function_exists('multi_uri_encode'))
  116. {
  117. function multi_uri_encode($str)
  118. {
  119. return rawurlencode($str);
  120. }
  121. }
  122. // prep_str : htmlspecialcharsのショートカット
  123. if ( ! function_exists('prep_str'))
  124. {
  125. function prep_str($str)
  126. {
  127. return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
  128. }
  129. }
  130. // unprep_str : htmlspecialchars_decodeのショートカット
  131. if ( ! function_exists('unprep_str'))
  132. {
  133. function unprep_str($str)
  134. {
  135. if ( function_exists('htmlspecialchars_decode') )
  136. {
  137. return htmlspecialchars_decode($str, ENT_QUOTES);
  138. }
  139. else
  140. {
  141. return html_entity_decode($str, ENT_QUOTES);
  142. }
  143. }
  144. }
  145. // link_format : URL形式のストリングを<a>タグで囲む
  146. if ( ! function_exists(('link_format')))
  147. {
  148. function link_format($str, $target_blank = TRUE)
  149. {
  150. return preg_replace(
  151. '/(https?:\/\/[\w\.\/]+)([\/|\?]?[\-_.!~\*a-zA-Z0-9\/\?:;@&=+$,%#]+)?/',
  152. '<a href="$1$2" ' . (($target_blank === TRUE) ? 'target="blank"' : '') . '>$1$2</a>',
  153. $str
  154. );
  155. }
  156. }
  157. // truncate : 文字列を指定文字列でsplitする
  158. if ( ! function_exists('truncate'))
  159. {
  160. function truncate($str, $length = 50, $suffix = '...')
  161. {
  162. $len = ( function_exists('mb_strlen') )
  163. ? mb_strlen($str)
  164. : strlen($str);
  165. if ($len <= $length)
  166. {
  167. return $str;
  168. }
  169. else
  170. {
  171. $str = ( function_exists('mb_substr') )
  172. ? mb_substr($str, 0, $length)
  173. : substr($str, 0, $length);
  174. return $str . $suffix;
  175. }
  176. }
  177. }
  178. // ----------------- request utility function --------------------------
  179. /**
  180. * common http request
  181. */
  182. if ( ! function_exists('http_request') )
  183. {
  184. function http_request(
  185. $uri, // request uri
  186. $method = 'GET', // request method
  187. $header = array(), // request headers array
  188. $postbody = "") // post body(encoded)
  189. {
  190. if ( is_array($postbody) )
  191. {
  192. $stack = array();
  193. foreach ($postbody as $key => $val)
  194. {
  195. if ( is_array($val) )
  196. {
  197. foreach ($val as $v)
  198. {
  199. $stack[] = rawurlencode($key) . '[]=' . rawurlencode($v);
  200. }
  201. }
  202. else
  203. {
  204. $stack[] = rawurlencode($key) . '=' . rawurlencode($val);
  205. }
  206. }
  207. $post = implode('&', $stack);
  208. }
  209. else
  210. {
  211. $post = $postbody;
  212. }
  213. // CURLモジュールが有効な場合はcurlでリクエスト
  214. if ( extension_loaded('curl') )
  215. {
  216. return _http_request_curl(
  217. $uri,
  218. strtoupper($method),
  219. $header,
  220. $post
  221. );
  222. }
  223. // それ以外はソケット接続でリクエスト
  224. else
  225. {
  226. return _http_request_socket(
  227. $uri,
  228. strtoupper($method),
  229. $header,
  230. $post
  231. );
  232. }
  233. }
  234. }
  235. /**
  236. * curlでリクエスト
  237. */
  238. if ( ! function_exists('_http_request_curl') )
  239. {
  240. function _http_request_curl($uri, $method, $header, $post)
  241. {
  242. $handle = curl_init();
  243. if (isset($_SERVER['HTTP_USER_AGENT']))
  244. {
  245. curl_setopt($handle, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  246. }
  247. if (count($header) > 0)
  248. {
  249. curl_setopt($handle, CURLOPT_HTTPHEADER, $header);
  250. }
  251. curl_setopt_array($handle, array(
  252. CURLOPT_RETURNTRANSFER => TRUE,
  253. CURLOPT_HEADER => FALSE
  254. ));
  255. if ($method === 'POST')
  256. {
  257. curl_setopt($handle, CURLOPT_POST, TRUE);
  258. if ($post != '')
  259. {
  260. curl_setopt($handle, CURLOPT_POSTFIELDS, $post);
  261. }
  262. }
  263. curl_setopt($handle, CURLOPT_URL, $uri);
  264. $resp = curl_exec($handle);
  265. if ( ! $resp )
  266. {
  267. $resp = FALSE;
  268. }
  269. curl_close($handle);
  270. return $resp;
  271. }
  272. }
  273. if ( ! function_exists('_http_request_socket') )
  274. {
  275. function _http_request_socket($uri, $method, $header, $post)
  276. {
  277. // parse URLs
  278. $URL = parse_url($uri);
  279. $scheme = $URL['scheme'];
  280. $path = $URL['path'];
  281. $host = $URL['host'];
  282. $query = (isset($URL['query'])) ? '?' . $URL['query'] : '';
  283. $port = (isset($URL['port']))
  284. ? $URL['port'] : ($scheme == 'https' || $_SERVER['HTTPS'] === 'on')
  285. ? 443 : 80;
  286. // build request-line-header
  287. $request = $method . ' ' . $path . $query . ' HTTP/1.1' . "\r\n"
  288. . 'Host: ' . $host . "\r\n";
  289. if ( isset($_SERVER['HTTP_USER_AGENT']))
  290. {
  291. $request .= 'User-Agent: ' . $_SERVER['HTTP_USER_AGENT'] . "\r\n";
  292. }
  293. if (count($header) > 0)
  294. {
  295. foreach ($header as $head)
  296. {
  297. $request .= $head . "\r\n";
  298. }
  299. }
  300. if ($method === 'POST')
  301. {
  302. $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
  303. if ( ! empty($post) )
  304. {
  305. $request .= 'Content-Length: ' . strlen($post) . "\r\n";
  306. $request .= "\r\n";
  307. $request .= $post;
  308. }
  309. }
  310. else
  311. {
  312. $request .= "\r\n";
  313. }
  314. $fp = @fsockopen($host, $port);
  315. if ( ! $fp )
  316. {
  317. return FALSE;
  318. }
  319. // send request
  320. fputs($fp, $request);
  321. // get response
  322. $resp = '';
  323. while ( ! feof($fp) )
  324. {
  325. $resp .= fgets($fp, 4096);
  326. }
  327. fclose($fp);
  328. // split header
  329. $exp = explode("\r\n\r\n", $resp);
  330. if (count($exp) < 2)
  331. {
  332. return FALSE;
  333. }
  334. // returns response body only.
  335. return implode("\r\n\r\n", array_slice($exp, 1));
  336. }
  337. }
  338. /**
  339. * fgetcsv_reg : CSVの読み込みとパース
  340. * @see http://yossy.iimp.jp/wp/?p=56 (original)
  341. * @param $handle file resource or filepath
  342. * @param $length
  343. * @param $delimiter
  344. * @param $enc
  345. * @return mixed bool or array
  346. */
  347. if ( ! function_exists('fgetcsv_reg') )
  348. {
  349. function fgetcsv_reg($handle, $length = null, $delimiter = ',', $enc = '"')
  350. {
  351. // pre process : Is first argument resource?
  352. if ( ! is_resource($handle) )
  353. {
  354. if ( ! preg_match('/.+\.csv$/', $handle) || ! file_exists($handle) )
  355. {
  356. return FALSE;
  357. }
  358. else
  359. {
  360. // open file and call recursive
  361. return fgetcsv_reg(fopen($handle, 'rb'), $length, $delimiter, $enc);
  362. }
  363. }
  364. // main process
  365. $delimiter = preg_quote($delimiter);
  366. $enc = preg_quote($enc);
  367. $_line = "";
  368. $eof = FALSE;
  369. // pre:create regexes
  370. $regex = array(
  371. 'item' => '/' . $enc . '/',
  372. 'line' => '/(?:\\r\\n|[\\r\\n])?$/',
  373. 'pattern'=> '/(' . $enc . '[^'. $enc . ']*(?:' . $enc . $enc . '[^'. $enc . ']*)*' . $enc . '|[^' . $delimiter . ']*)' . $delimiter . '/',
  374. 'replace'=> '/^' . $enc . '(.*)' . $enc . '$/s'
  375. );
  376. while ( $eof !== TRUE && ! feof($handle) )
  377. {
  378. $_line .= ( empty($length ) ? fgets($handle) : fgets($handle, $length));
  379. $itemcnt = preg_match_all($regex['item'], $_line, $dummy);
  380. if ( $itemcnt % 2 === 0 )
  381. {
  382. $eof = TRUE;
  383. }
  384. }
  385. $_csv_line = preg_replace($regex['line'], $delimiter, trim($_line));
  386. preg_match_all($regex['pattern'], $_csv_line, $_csv_matches);
  387. $_csv_data = $_csv_matches[1];
  388. for ( $_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++ )
  389. {
  390. $_csv_data[$_csv_i] = preg_replace($regex['replace'], '$1', $_csv_data[$_csv_i]);
  391. $_csv_data[$_csv_i] = str_replace($enc . $enc, $enc, $_csv_data[$_csv_i]);
  392. }
  393. return empty($_line) ? FALSE : $_csv_data;
  394. }
  395. }