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

/system/helpers/text_helper.php

https://gitlab.com/pollux1er/PerencoCanteenAdmin
PHP | 564 lines | 342 code | 59 blank | 163 comment | 40 complexity | 56f6be7dd5ec4fd7215095181d817c76 MD5 | raw file
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2016, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * CodeIgniter Text Helpers
  41. *
  42. * @package CodeIgniter
  43. * @subpackage Helpers
  44. * @category Helpers
  45. * @author EllisLab Dev Team
  46. * @link https://codeigniter.com/user_guide/helpers/text_helper.html
  47. */
  48. // ------------------------------------------------------------------------
  49. if ( ! function_exists('word_limiter'))
  50. {
  51. /**
  52. * Word Limiter
  53. *
  54. * Limits a string to X number of words.
  55. *
  56. * @param string
  57. * @param int
  58. * @param string the end character. Usually an ellipsis
  59. * @return string
  60. */
  61. function word_limiter($str, $limit = 100, $end_char = '&#8230;')
  62. {
  63. if (trim($str) === '')
  64. {
  65. return $str;
  66. }
  67. preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
  68. if (strlen($str) === strlen($matches[0]))
  69. {
  70. $end_char = '';
  71. }
  72. return rtrim($matches[0]).$end_char;
  73. }
  74. }
  75. // ------------------------------------------------------------------------
  76. if ( ! function_exists('character_limiter'))
  77. {
  78. /**
  79. * Character Limiter
  80. *
  81. * Limits the string based on the character count. Preserves complete words
  82. * so the character count may not be exactly as specified.
  83. *
  84. * @param string
  85. * @param int
  86. * @param string the end character. Usually an ellipsis
  87. * @return string
  88. */
  89. function character_limiter($str, $n = 500, $end_char = '&#8230;')
  90. {
  91. if (mb_strlen($str) < $n)
  92. {
  93. return $str;
  94. }
  95. // a bit complicated, but faster than preg_replace with \s+
  96. $str = preg_replace('/ {2,}/', ' ', str_replace(array("\r", "\n", "\t", "\x0B", "\x0C"), ' ', $str));
  97. if (mb_strlen($str) <= $n)
  98. {
  99. return $str;
  100. }
  101. $out = '';
  102. foreach (explode(' ', trim($str)) as $val)
  103. {
  104. $out .= $val.' ';
  105. if (mb_strlen($out) >= $n)
  106. {
  107. $out = trim($out);
  108. return (mb_strlen($out) === mb_strlen($str)) ? $out : $out.$end_char;
  109. }
  110. }
  111. }
  112. }
  113. // ------------------------------------------------------------------------
  114. if ( ! function_exists('ascii_to_entities'))
  115. {
  116. /**
  117. * High ASCII to Entities
  118. *
  119. * Converts high ASCII text and MS Word special characters to character entities
  120. *
  121. * @param string $str
  122. * @return string
  123. */
  124. function ascii_to_entities($str)
  125. {
  126. $out = '';
  127. for ($i = 0, $s = strlen($str) - 1, $count = 1, $temp = array(); $i <= $s; $i++)
  128. {
  129. $ordinal = ord($str[$i]);
  130. if ($ordinal < 128)
  131. {
  132. /*
  133. If the $temp array has a value but we have moved on, then it seems only
  134. fair that we output that entity and restart $temp before continuing. -Paul
  135. */
  136. if (count($temp) === 1)
  137. {
  138. $out .= '&#'.array_shift($temp).';';
  139. $count = 1;
  140. }
  141. $out .= $str[$i];
  142. }
  143. else
  144. {
  145. if (count($temp) === 0)
  146. {
  147. $count = ($ordinal < 224) ? 2 : 3;
  148. }
  149. $temp[] = $ordinal;
  150. if (count($temp) === $count)
  151. {
  152. $number = ($count === 3)
  153. ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64)
  154. : (($temp[0] % 32) * 64) + ($temp[1] % 64);
  155. $out .= '&#'.$number.';';
  156. $count = 1;
  157. $temp = array();
  158. }
  159. // If this is the last iteration, just output whatever we have
  160. elseif ($i === $s)
  161. {
  162. $out .= '&#'.implode(';', $temp).';';
  163. }
  164. }
  165. }
  166. return $out;
  167. }
  168. }
  169. // ------------------------------------------------------------------------
  170. if ( ! function_exists('entities_to_ascii'))
  171. {
  172. /**
  173. * Entities to ASCII
  174. *
  175. * Converts character entities back to ASCII
  176. *
  177. * @param string
  178. * @param bool
  179. * @return string
  180. */
  181. function entities_to_ascii($str, $all = TRUE)
  182. {
  183. if (preg_match_all('/\&#(\d+)\;/', $str, $matches))
  184. {
  185. for ($i = 0, $s = count($matches[0]); $i < $s; $i++)
  186. {
  187. $digits = $matches[1][$i];
  188. $out = '';
  189. if ($digits < 128)
  190. {
  191. $out .= chr($digits);
  192. }
  193. elseif ($digits < 2048)
  194. {
  195. $out .= chr(192 + (($digits - ($digits % 64)) / 64)).chr(128 + ($digits % 64));
  196. }
  197. else
  198. {
  199. $out .= chr(224 + (($digits - ($digits % 4096)) / 4096))
  200. .chr(128 + ((($digits % 4096) - ($digits % 64)) / 64))
  201. .chr(128 + ($digits % 64));
  202. }
  203. $str = str_replace($matches[0][$i], $out, $str);
  204. }
  205. }
  206. if ($all)
  207. {
  208. return str_replace(
  209. array('&amp;', '&lt;', '&gt;', '&quot;', '&apos;', '&#45;'),
  210. array('&', '<', '>', '"', "'", '-'),
  211. $str
  212. );
  213. }
  214. return $str;
  215. }
  216. }
  217. // ------------------------------------------------------------------------
  218. if ( ! function_exists('word_censor'))
  219. {
  220. /**
  221. * Word Censoring Function
  222. *
  223. * Supply a string and an array of disallowed words and any
  224. * matched words will be converted to #### or to the replacement
  225. * word you've submitted.
  226. *
  227. * @param string the text string
  228. * @param string the array of censored words
  229. * @param string the optional replacement value
  230. * @return string
  231. */
  232. function word_censor($str, $censored, $replacement = '')
  233. {
  234. if ( ! is_array($censored))
  235. {
  236. return $str;
  237. }
  238. $str = ' '.$str.' ';
  239. // \w, \b and a few others do not match on a unicode character
  240. // set for performance reasons. As a result words like über
  241. // will not match on a word boundary. Instead, we'll assume that
  242. // a bad word will be bookeneded by any of these characters.
  243. $delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';
  244. foreach ($censored as $badword)
  245. {
  246. $badword = str_replace('\*', '\w*?', preg_quote($badword, '/'));
  247. if ($replacement !== '')
  248. {
  249. $str = preg_replace(
  250. "/({$delim})(".$badword.")({$delim})/i",
  251. "\\1{$replacement}\\3",
  252. $str
  253. );
  254. }
  255. elseif (preg_match_all("/{$delim}(".$badword."){$delim}/i", $str, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE))
  256. {
  257. $matches = $matches[1];
  258. for ($i = count($matches) - 1; $i >= 0; $i--)
  259. {
  260. $length = strlen($matches[$i][0]);
  261. $str = substr_replace(
  262. $str,
  263. str_repeat('#', $length),
  264. $matches[$i][1],
  265. $length
  266. );
  267. }
  268. }
  269. }
  270. return trim($str);
  271. }
  272. }
  273. // ------------------------------------------------------------------------
  274. if ( ! function_exists('highlight_code'))
  275. {
  276. /**
  277. * Code Highlighter
  278. *
  279. * Colorizes code strings
  280. *
  281. * @param string the text string
  282. * @return string
  283. */
  284. function highlight_code($str)
  285. {
  286. /* The highlight string function encodes and highlights
  287. * brackets so we need them to start raw.
  288. *
  289. * Also replace any existing PHP tags to temporary markers
  290. * so they don't accidentally break the string out of PHP,
  291. * and thus, thwart the highlighting.
  292. */
  293. $str = str_replace(
  294. array('&lt;', '&gt;', '<?', '?>', '<%', '%>', '\\', '</script>'),
  295. array('<', '>', 'phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
  296. $str
  297. );
  298. // The highlight_string function requires that the text be surrounded
  299. // by PHP tags, which we will remove later
  300. $str = highlight_string('<?php '.$str.' ?>', TRUE);
  301. // Remove our artificially added PHP, and the syntax highlighting that came with it
  302. $str = preg_replace(
  303. array(
  304. '/<span style="color: #([A-Z0-9]+)">&lt;\?php(&nbsp;| )/i',
  305. '/(<span style="color: #[A-Z0-9]+">.*?)\?&gt;<\/span>\n<\/span>\n<\/code>/is',
  306. '/<span style="color: #[A-Z0-9]+"\><\/span>/i'
  307. ),
  308. array(
  309. '<span style="color: #$1">',
  310. "$1</span>\n</span>\n</code>",
  311. ''
  312. ),
  313. $str
  314. );
  315. // Replace our markers back to PHP tags.
  316. return str_replace(
  317. array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
  318. array('&lt;?', '?&gt;', '&lt;%', '%&gt;', '\\', '&lt;/script&gt;'),
  319. $str
  320. );
  321. }
  322. }
  323. // ------------------------------------------------------------------------
  324. if ( ! function_exists('highlight_phrase'))
  325. {
  326. /**
  327. * Phrase Highlighter
  328. *
  329. * Highlights a phrase within a text string
  330. *
  331. * @param string $str the text string
  332. * @param string $phrase the phrase you'd like to highlight
  333. * @param string $tag_open the openging tag to precede the phrase with
  334. * @param string $tag_close the closing tag to end the phrase with
  335. * @return string
  336. */
  337. function highlight_phrase($str, $phrase, $tag_open = '<mark>', $tag_close = '</mark>')
  338. {
  339. return ($str !== '' && $phrase !== '')
  340. ? preg_replace('/('.preg_quote($phrase, '/').')/i'.(UTF8_ENABLED ? 'u' : ''), $tag_open.'\\1'.$tag_close, $str)
  341. : $str;
  342. }
  343. }
  344. // ------------------------------------------------------------------------
  345. if ( ! function_exists('convert_accented_characters'))
  346. {
  347. /**
  348. * Convert Accented Foreign Characters to ASCII
  349. *
  350. * @param string $str Input string
  351. * @return string
  352. */
  353. function convert_accented_characters($str)
  354. {
  355. static $array_from, $array_to;
  356. if ( ! is_array($array_from))
  357. {
  358. if (file_exists(APPPATH.'config/foreign_chars.php'))
  359. {
  360. include(APPPATH.'config/foreign_chars.php');
  361. }
  362. if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php'))
  363. {
  364. include(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php');
  365. }
  366. if (empty($foreign_characters) OR ! is_array($foreign_characters))
  367. {
  368. $array_from = array();
  369. $array_to = array();
  370. return $str;
  371. }
  372. $array_from = array_keys($foreign_characters);
  373. $array_to = array_values($foreign_characters);
  374. }
  375. return preg_replace($array_from, $array_to, $str);
  376. }
  377. }
  378. // ------------------------------------------------------------------------
  379. if ( ! function_exists('word_wrap'))
  380. {
  381. /**
  382. * Word Wrap
  383. *
  384. * Wraps text at the specified character. Maintains the integrity of words.
  385. * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor
  386. * will URLs.
  387. *
  388. * @param string $str the text string
  389. * @param int $charlim = 76 the number of characters to wrap at
  390. * @return string
  391. */
  392. function word_wrap($str, $charlim = 76)
  393. {
  394. // Set the character limit
  395. is_numeric($charlim) OR $charlim = 76;
  396. // Reduce multiple spaces
  397. $str = preg_replace('| +|', ' ', $str);
  398. // Standardize newlines
  399. if (strpos($str, "\r") !== FALSE)
  400. {
  401. $str = str_replace(array("\r\n", "\r"), "\n", $str);
  402. }
  403. // If the current word is surrounded by {unwrap} tags we'll
  404. // strip the entire chunk and replace it with a marker.
  405. $unwrap = array();
  406. if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches))
  407. {
  408. for ($i = 0, $c = count($matches[0]); $i < $c; $i++)
  409. {
  410. $unwrap[] = $matches[1][$i];
  411. $str = str_replace($matches[0][$i], '{{unwrapped'.$i.'}}', $str);
  412. }
  413. }
  414. // Use PHP's native function to do the initial wordwrap.
  415. // We set the cut flag to FALSE so that any individual words that are
  416. // too long get left alone. In the next step we'll deal with them.
  417. $str = wordwrap($str, $charlim, "\n", FALSE);
  418. // Split the string into individual lines of text and cycle through them
  419. $output = '';
  420. foreach (explode("\n", $str) as $line)
  421. {
  422. // Is the line within the allowed character count?
  423. // If so we'll join it to the output and continue
  424. if (mb_strlen($line) <= $charlim)
  425. {
  426. $output .= $line."\n";
  427. continue;
  428. }
  429. $temp = '';
  430. while (mb_strlen($line) > $charlim)
  431. {
  432. // If the over-length word is a URL we won't wrap it
  433. if (preg_match('!\[url.+\]|://|www\.!', $line))
  434. {
  435. break;
  436. }
  437. // Trim the word down
  438. $temp .= mb_substr($line, 0, $charlim - 1);
  439. $line = mb_substr($line, $charlim - 1);
  440. }
  441. // If $temp contains data it means we had to split up an over-length
  442. // word into smaller chunks so we'll add it back to our current line
  443. if ($temp !== '')
  444. {
  445. $output .= $temp."\n".$line."\n";
  446. }
  447. else
  448. {
  449. $output .= $line."\n";
  450. }
  451. }
  452. // Put our markers back
  453. if (count($unwrap) > 0)
  454. {
  455. foreach ($unwrap as $key => $val)
  456. {
  457. $output = str_replace('{{unwrapped'.$key.'}}', $val, $output);
  458. }
  459. }
  460. return $output;
  461. }
  462. }
  463. // ------------------------------------------------------------------------
  464. if ( ! function_exists('ellipsize'))
  465. {
  466. /**
  467. * Ellipsize String
  468. *
  469. * This function will strip tags from a string, split it at its max_length and ellipsize
  470. *
  471. * @param string string to ellipsize
  472. * @param int max length of string
  473. * @param mixed int (1|0) or float, .5, .2, etc for position to split
  474. * @param string ellipsis ; Default '...'
  475. * @return string ellipsized string
  476. */
  477. function ellipsize($str, $max_length, $position = 1, $ellipsis = '&hellip;')
  478. {
  479. // Strip tags
  480. $str = trim(strip_tags($str));
  481. // Is the string long enough to ellipsize?
  482. if (mb_strlen($str) <= $max_length)
  483. {
  484. return $str;
  485. }
  486. $beg = mb_substr($str, 0, floor($max_length * $position));
  487. $position = ($position > 1) ? 1 : $position;
  488. if ($position === 1)
  489. {
  490. $end = mb_substr($str, 0, -($max_length - mb_strlen($beg)));
  491. }
  492. else
  493. {
  494. $end = mb_substr($str, -($max_length - mb_strlen($beg)));
  495. }
  496. return $beg.$ellipsis.$end;
  497. }
  498. }