PageRenderTime 25ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Utility/CakeText.php

https://gitlab.com/nghiep5890/bakery
PHP | 710 lines | 601 code | 31 blank | 78 comment | 59 complexity | b5c587ec130a839f145be21c74d67e56 MD5 | raw file
  1. <?php
  2. /**
  3. * String handling methods.
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Utility
  15. * @since CakePHP(tm) v 1.2.0.5551
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. /**
  19. * String handling methods.
  20. *
  21. * @package Cake.Utility
  22. */
  23. class CakeText {
  24. /**
  25. * Generate a random UUID
  26. *
  27. * @see http://www.ietf.org/rfc/rfc4122.txt
  28. * @return string RFC 4122 UUID
  29. */
  30. public static function uuid() {
  31. $node = env('SERVER_ADDR');
  32. if (strpos($node, ':') !== false) {
  33. if (substr_count($node, '::')) {
  34. $node = str_replace(
  35. '::', str_repeat(':0000', 8 - substr_count($node, ':')) . ':', $node
  36. );
  37. }
  38. $node = explode(':', $node);
  39. $ipSix = '';
  40. foreach ($node as $id) {
  41. $ipSix .= str_pad(base_convert($id, 16, 2), 16, 0, STR_PAD_LEFT);
  42. }
  43. $node = base_convert($ipSix, 2, 10);
  44. if (strlen($node) < 38) {
  45. $node = null;
  46. } else {
  47. $node = crc32($node);
  48. }
  49. } elseif (empty($node)) {
  50. $host = env('HOSTNAME');
  51. if (empty($host)) {
  52. $host = env('HOST');
  53. }
  54. if (!empty($host)) {
  55. $ip = gethostbyname($host);
  56. if ($ip === $host) {
  57. $node = crc32($host);
  58. } else {
  59. $node = ip2long($ip);
  60. }
  61. }
  62. } elseif ($node !== '127.0.0.1') {
  63. $node = ip2long($node);
  64. } else {
  65. $node = null;
  66. }
  67. if (empty($node)) {
  68. $node = crc32(Configure::read('Security.salt'));
  69. }
  70. if (function_exists('hphp_get_thread_id')) {
  71. $pid = hphp_get_thread_id();
  72. } elseif (function_exists('zend_thread_id')) {
  73. $pid = zend_thread_id();
  74. } else {
  75. $pid = getmypid();
  76. }
  77. if (!$pid || $pid > 65535) {
  78. $pid = mt_rand(0, 0xfff) | 0x4000;
  79. }
  80. list($timeMid, $timeLow) = explode(' ', microtime());
  81. return sprintf(
  82. "%08x-%04x-%04x-%02x%02x-%04x%08x", (int)$timeLow, (int)substr($timeMid, 2) & 0xffff,
  83. mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node
  84. );
  85. }
  86. /**
  87. * Tokenizes a string using $separator, ignoring any instance of $separator that appears between
  88. * $leftBound and $rightBound.
  89. *
  90. * @param string $data The data to tokenize.
  91. * @param string $separator The token to split the data on.
  92. * @param string $leftBound The left boundary to ignore separators in.
  93. * @param string $rightBound The right boundary to ignore separators in.
  94. * @return mixed Array of tokens in $data or original input if empty.
  95. */
  96. public static function tokenize($data, $separator = ',', $leftBound = '(', $rightBound = ')') {
  97. if (empty($data)) {
  98. return array();
  99. }
  100. $depth = 0;
  101. $offset = 0;
  102. $buffer = '';
  103. $results = array();
  104. $length = mb_strlen($data);
  105. $open = false;
  106. while ($offset <= $length) {
  107. $tmpOffset = -1;
  108. $offsets = array(
  109. mb_strpos($data, $separator, $offset),
  110. mb_strpos($data, $leftBound, $offset),
  111. mb_strpos($data, $rightBound, $offset)
  112. );
  113. for ($i = 0; $i < 3; $i++) {
  114. if ($offsets[$i] !== false && ($offsets[$i] < $tmpOffset || $tmpOffset == -1)) {
  115. $tmpOffset = $offsets[$i];
  116. }
  117. }
  118. if ($tmpOffset !== -1) {
  119. $buffer .= mb_substr($data, $offset, ($tmpOffset - $offset));
  120. $char = mb_substr($data, $tmpOffset, 1);
  121. if (!$depth && $char === $separator) {
  122. $results[] = $buffer;
  123. $buffer = '';
  124. } else {
  125. $buffer .= $char;
  126. }
  127. if ($leftBound !== $rightBound) {
  128. if ($char === $leftBound) {
  129. $depth++;
  130. }
  131. if ($char === $rightBound) {
  132. $depth--;
  133. }
  134. } else {
  135. if ($char === $leftBound) {
  136. if (!$open) {
  137. $depth++;
  138. $open = true;
  139. } else {
  140. $depth--;
  141. }
  142. }
  143. }
  144. $offset = ++$tmpOffset;
  145. } else {
  146. $results[] = $buffer . mb_substr($data, $offset);
  147. $offset = $length + 1;
  148. }
  149. }
  150. if (empty($results) && !empty($buffer)) {
  151. $results[] = $buffer;
  152. }
  153. if (!empty($results)) {
  154. return array_map('trim', $results);
  155. }
  156. return array();
  157. }
  158. /**
  159. * Replaces variable placeholders inside a $str with any given $data. Each key in the $data array
  160. * corresponds to a variable placeholder name in $str.
  161. * Example: `CakeText::insert(':name is :age years old.', array('name' => 'Bob', '65'));`
  162. * Returns: Bob is 65 years old.
  163. *
  164. * Available $options are:
  165. *
  166. * - before: The character or string in front of the name of the variable placeholder (Defaults to `:`)
  167. * - after: The character or string after the name of the variable placeholder (Defaults to null)
  168. * - escape: The character or string used to escape the before character / string (Defaults to `\`)
  169. * - format: A regex to use for matching variable placeholders. Default is: `/(?<!\\)\:%s/`
  170. * (Overwrites before, after, breaks escape / clean)
  171. * - clean: A boolean or array with instructions for CakeText::cleanInsert
  172. *
  173. * @param string $str A string containing variable placeholders
  174. * @param array $data A key => val array where each key stands for a placeholder variable name
  175. * to be replaced with val
  176. * @param array $options An array of options, see description above
  177. * @return string
  178. */
  179. public static function insert($str, $data, $options = array()) {
  180. $defaults = array(
  181. 'before' => ':', 'after' => null, 'escape' => '\\', 'format' => null, 'clean' => false
  182. );
  183. $options += $defaults;
  184. $format = $options['format'];
  185. $data = (array)$data;
  186. if (empty($data)) {
  187. return ($options['clean']) ? CakeText::cleanInsert($str, $options) : $str;
  188. }
  189. if (!isset($format)) {
  190. $format = sprintf(
  191. '/(?<!%s)%s%%s%s/',
  192. preg_quote($options['escape'], '/'),
  193. str_replace('%', '%%', preg_quote($options['before'], '/')),
  194. str_replace('%', '%%', preg_quote($options['after'], '/'))
  195. );
  196. }
  197. if (strpos($str, '?') !== false && is_numeric(key($data))) {
  198. $offset = 0;
  199. while (($pos = strpos($str, '?', $offset)) !== false) {
  200. $val = array_shift($data);
  201. $offset = $pos + strlen($val);
  202. $str = substr_replace($str, $val, $pos, 1);
  203. }
  204. return ($options['clean']) ? CakeText::cleanInsert($str, $options) : $str;
  205. }
  206. asort($data);
  207. $dataKeys = array_keys($data);
  208. $hashKeys = array_map('crc32', $dataKeys);
  209. $tempData = array_combine($dataKeys, $hashKeys);
  210. krsort($tempData);
  211. foreach ($tempData as $key => $hashVal) {
  212. $key = sprintf($format, preg_quote($key, '/'));
  213. $str = preg_replace($key, $hashVal, $str);
  214. }
  215. $dataReplacements = array_combine($hashKeys, array_values($data));
  216. foreach ($dataReplacements as $tmpHash => $tmpValue) {
  217. $tmpValue = (is_array($tmpValue)) ? '' : $tmpValue;
  218. $str = str_replace($tmpHash, $tmpValue, $str);
  219. }
  220. if (!isset($options['format']) && isset($options['before'])) {
  221. $str = str_replace($options['escape'] . $options['before'], $options['before'], $str);
  222. }
  223. return ($options['clean']) ? CakeText::cleanInsert($str, $options) : $str;
  224. }
  225. /**
  226. * Cleans up a CakeText::insert() formatted string with given $options depending on the 'clean' key in
  227. * $options. The default method used is text but html is also available. The goal of this function
  228. * is to replace all whitespace and unneeded markup around placeholders that did not get replaced
  229. * by CakeText::insert().
  230. *
  231. * @param string $str CakeText to clean.
  232. * @param array $options Options list.
  233. * @return string
  234. * @see CakeText::insert()
  235. */
  236. public static function cleanInsert($str, $options) {
  237. $clean = $options['clean'];
  238. if (!$clean) {
  239. return $str;
  240. }
  241. if ($clean === true) {
  242. $clean = array('method' => 'text');
  243. }
  244. if (!is_array($clean)) {
  245. $clean = array('method' => $options['clean']);
  246. }
  247. switch ($clean['method']) {
  248. case 'html':
  249. $clean = array_merge(array(
  250. 'word' => '[\w,.]+',
  251. 'andText' => true,
  252. 'replacement' => '',
  253. ), $clean);
  254. $kleenex = sprintf(
  255. '/[\s]*[a-z]+=(")(%s%s%s[\s]*)+\\1/i',
  256. preg_quote($options['before'], '/'),
  257. $clean['word'],
  258. preg_quote($options['after'], '/')
  259. );
  260. $str = preg_replace($kleenex, $clean['replacement'], $str);
  261. if ($clean['andText']) {
  262. $options['clean'] = array('method' => 'text');
  263. $str = CakeText::cleanInsert($str, $options);
  264. }
  265. break;
  266. case 'text':
  267. $clean = array_merge(array(
  268. 'word' => '[\w,.]+',
  269. 'gap' => '[\s]*(?:(?:and|or)[\s]*)?',
  270. 'replacement' => '',
  271. ), $clean);
  272. $kleenex = sprintf(
  273. '/(%s%s%s%s|%s%s%s%s)/',
  274. preg_quote($options['before'], '/'),
  275. $clean['word'],
  276. preg_quote($options['after'], '/'),
  277. $clean['gap'],
  278. $clean['gap'],
  279. preg_quote($options['before'], '/'),
  280. $clean['word'],
  281. preg_quote($options['after'], '/')
  282. );
  283. $str = preg_replace($kleenex, $clean['replacement'], $str);
  284. break;
  285. }
  286. return $str;
  287. }
  288. /**
  289. * Wraps text to a specific width, can optionally wrap at word breaks.
  290. *
  291. * ### Options
  292. *
  293. * - `width` The width to wrap to. Defaults to 72.
  294. * - `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
  295. * - `indent` CakeText to indent with. Defaults to null.
  296. * - `indentAt` 0 based index to start indenting at. Defaults to 0.
  297. *
  298. * @param string $text The text to format.
  299. * @param array|int $options Array of options to use, or an integer to wrap the text to.
  300. * @return string Formatted text.
  301. */
  302. public static function wrap($text, $options = array()) {
  303. if (is_numeric($options)) {
  304. $options = array('width' => $options);
  305. }
  306. $options += array('width' => 72, 'wordWrap' => true, 'indent' => null, 'indentAt' => 0);
  307. if ($options['wordWrap']) {
  308. $wrapped = static::wordWrap($text, $options['width'], "\n");
  309. } else {
  310. $wrapped = trim(chunk_split($text, $options['width'] - 1, "\n"));
  311. }
  312. if (!empty($options['indent'])) {
  313. $chunks = explode("\n", $wrapped);
  314. for ($i = $options['indentAt'], $len = count($chunks); $i < $len; $i++) {
  315. $chunks[$i] = $options['indent'] . $chunks[$i];
  316. }
  317. $wrapped = implode("\n", $chunks);
  318. }
  319. return $wrapped;
  320. }
  321. /**
  322. * Unicode aware version of wordwrap.
  323. *
  324. * @param string $text The text to format.
  325. * @param int $width The width to wrap to. Defaults to 72.
  326. * @param string $break The line is broken using the optional break parameter. Defaults to '\n'.
  327. * @param bool $cut If the cut is set to true, the string is always wrapped at the specified width.
  328. * @return string Formatted text.
  329. */
  330. public static function wordWrap($text, $width = 72, $break = "\n", $cut = false) {
  331. $paragraphs = explode($break, $text);
  332. foreach ($paragraphs as &$paragraph) {
  333. $paragraph = static::_wordWrap($paragraph, $width, $break, $cut);
  334. }
  335. return implode($break, $paragraphs);
  336. }
  337. /**
  338. * Helper method for wordWrap().
  339. *
  340. * @param string $text The text to format.
  341. * @param int $width The width to wrap to. Defaults to 72.
  342. * @param string $break The line is broken using the optional break parameter. Defaults to '\n'.
  343. * @param bool $cut If the cut is set to true, the string is always wrapped at the specified width.
  344. * @return string Formatted text.
  345. */
  346. protected static function _wordWrap($text, $width = 72, $break = "\n", $cut = false) {
  347. if ($cut) {
  348. $parts = array();
  349. while (mb_strlen($text) > 0) {
  350. $part = mb_substr($text, 0, $width);
  351. $parts[] = trim($part);
  352. $text = trim(mb_substr($text, mb_strlen($part)));
  353. }
  354. return implode($break, $parts);
  355. }
  356. $parts = array();
  357. while (mb_strlen($text) > 0) {
  358. if ($width >= mb_strlen($text)) {
  359. $parts[] = trim($text);
  360. break;
  361. }
  362. $part = mb_substr($text, 0, $width);
  363. $nextChar = mb_substr($text, $width, 1);
  364. if ($nextChar !== ' ') {
  365. $breakAt = mb_strrpos($part, ' ');
  366. if ($breakAt === false) {
  367. $breakAt = mb_strpos($text, ' ', $width);
  368. }
  369. if ($breakAt === false) {
  370. $parts[] = trim($text);
  371. break;
  372. }
  373. $part = mb_substr($text, 0, $breakAt);
  374. }
  375. $part = trim($part);
  376. $parts[] = $part;
  377. $text = trim(mb_substr($text, mb_strlen($part)));
  378. }
  379. return implode($break, $parts);
  380. }
  381. /**
  382. * Highlights a given phrase in a text. You can specify any expression in highlighter that
  383. * may include the \1 expression to include the $phrase found.
  384. *
  385. * ### Options:
  386. *
  387. * - `format` The piece of html with that the phrase will be highlighted
  388. * - `html` If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
  389. * - `regex` a custom regex rule that is used to match words, default is '|$tag|iu'
  390. *
  391. * @param string $text Text to search the phrase in.
  392. * @param string|array $phrase The phrase or phrases that will be searched.
  393. * @param array $options An array of html attributes and options.
  394. * @return string The highlighted text
  395. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::highlight
  396. */
  397. public static function highlight($text, $phrase, $options = array()) {
  398. if (empty($phrase)) {
  399. return $text;
  400. }
  401. $defaults = array(
  402. 'format' => '<span class="highlight">\1</span>',
  403. 'html' => false,
  404. 'regex' => "|%s|iu"
  405. );
  406. $options += $defaults;
  407. extract($options);
  408. if (is_array($phrase)) {
  409. $replace = array();
  410. $with = array();
  411. foreach ($phrase as $key => $segment) {
  412. $segment = '(' . preg_quote($segment, '|') . ')';
  413. if ($html) {
  414. $segment = "(?![^<]+>)$segment(?![^<]+>)";
  415. }
  416. $with[] = (is_array($format)) ? $format[$key] : $format;
  417. $replace[] = sprintf($options['regex'], $segment);
  418. }
  419. return preg_replace($replace, $with, $text);
  420. }
  421. $phrase = '(' . preg_quote($phrase, '|') . ')';
  422. if ($html) {
  423. $phrase = "(?![^<]+>)$phrase(?![^<]+>)";
  424. }
  425. return preg_replace(sprintf($options['regex'], $phrase), $format, $text);
  426. }
  427. /**
  428. * Strips given text of all links (<a href=....).
  429. *
  430. * @param string $text Text
  431. * @return string The text without links
  432. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::stripLinks
  433. */
  434. public static function stripLinks($text) {
  435. return preg_replace('|<a\s+[^>]+>|im', '', preg_replace('|<\/a>|im', '', $text));
  436. }
  437. /**
  438. * Truncates text starting from the end.
  439. *
  440. * Cuts a string to the length of $length and replaces the first characters
  441. * with the ellipsis if the text is longer than length.
  442. *
  443. * ### Options:
  444. *
  445. * - `ellipsis` Will be used as Beginning and prepended to the trimmed string
  446. * - `exact` If false, $text will not be cut mid-word
  447. *
  448. * @param string $text CakeText to truncate.
  449. * @param int $length Length of returned string, including ellipsis.
  450. * @param array $options An array of options.
  451. * @return string Trimmed string.
  452. */
  453. public static function tail($text, $length = 100, $options = array()) {
  454. $defaults = array(
  455. 'ellipsis' => '...', 'exact' => true
  456. );
  457. $options += $defaults;
  458. extract($options);
  459. if (!function_exists('mb_strlen')) {
  460. class_exists('Multibyte');
  461. }
  462. if (mb_strlen($text) <= $length) {
  463. return $text;
  464. }
  465. $truncate = mb_substr($text, mb_strlen($text) - $length + mb_strlen($ellipsis));
  466. if (!$exact) {
  467. $spacepos = mb_strpos($truncate, ' ');
  468. $truncate = $spacepos === false ? '' : trim(mb_substr($truncate, $spacepos));
  469. }
  470. return $ellipsis . $truncate;
  471. }
  472. /**
  473. * Truncates text.
  474. *
  475. * Cuts a string to the length of $length and replaces the last characters
  476. * with the ellipsis if the text is longer than length.
  477. *
  478. * ### Options:
  479. *
  480. * - `ellipsis` Will be used as Ending and appended to the trimmed string (`ending` is deprecated)
  481. * - `exact` If false, $text will not be cut mid-word
  482. * - `html` If true, HTML tags would be handled correctly
  483. *
  484. * @param string $text CakeText to truncate.
  485. * @param int $length Length of returned string, including ellipsis.
  486. * @param array $options An array of html attributes and options.
  487. * @return string Trimmed string.
  488. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::truncate
  489. */
  490. public static function truncate($text, $length = 100, $options = array()) {
  491. $defaults = array(
  492. 'ellipsis' => '...', 'exact' => true, 'html' => false
  493. );
  494. if (isset($options['ending'])) {
  495. $defaults['ellipsis'] = $options['ending'];
  496. } elseif (!empty($options['html']) && Configure::read('App.encoding') === 'UTF-8') {
  497. $defaults['ellipsis'] = "\xe2\x80\xa6";
  498. }
  499. $options += $defaults;
  500. extract($options);
  501. if (!function_exists('mb_strlen')) {
  502. class_exists('Multibyte');
  503. }
  504. if ($html) {
  505. if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
  506. return $text;
  507. }
  508. $totalLength = mb_strlen(strip_tags($ellipsis));
  509. $openTags = array();
  510. $truncate = '';
  511. preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
  512. foreach ($tags as $tag) {
  513. if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) {
  514. if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) {
  515. array_unshift($openTags, $tag[2]);
  516. } elseif (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) {
  517. $pos = array_search($closeTag[1], $openTags);
  518. if ($pos !== false) {
  519. array_splice($openTags, $pos, 1);
  520. }
  521. }
  522. }
  523. $truncate .= $tag[1];
  524. $contentLength = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]));
  525. if ($contentLength + $totalLength > $length) {
  526. $left = $length - $totalLength;
  527. $entitiesLength = 0;
  528. if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE)) {
  529. foreach ($entities[0] as $entity) {
  530. if ($entity[1] + 1 - $entitiesLength <= $left) {
  531. $left--;
  532. $entitiesLength += mb_strlen($entity[0]);
  533. } else {
  534. break;
  535. }
  536. }
  537. }
  538. $truncate .= mb_substr($tag[3], 0, $left + $entitiesLength);
  539. break;
  540. } else {
  541. $truncate .= $tag[3];
  542. $totalLength += $contentLength;
  543. }
  544. if ($totalLength >= $length) {
  545. break;
  546. }
  547. }
  548. } else {
  549. if (mb_strlen($text) <= $length) {
  550. return $text;
  551. }
  552. $truncate = mb_substr($text, 0, $length - mb_strlen($ellipsis));
  553. }
  554. if (!$exact) {
  555. $spacepos = mb_strrpos($truncate, ' ');
  556. if ($html) {
  557. $truncateCheck = mb_substr($truncate, 0, $spacepos);
  558. $lastOpenTag = mb_strrpos($truncateCheck, '<');
  559. $lastCloseTag = mb_strrpos($truncateCheck, '>');
  560. if ($lastOpenTag > $lastCloseTag) {
  561. preg_match_all('/<[\w]+[^>]*>/s', $truncate, $lastTagMatches);
  562. $lastTag = array_pop($lastTagMatches[0]);
  563. $spacepos = mb_strrpos($truncate, $lastTag) + mb_strlen($lastTag);
  564. }
  565. $bits = mb_substr($truncate, $spacepos);
  566. preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER);
  567. if (!empty($droppedTags)) {
  568. if (!empty($openTags)) {
  569. foreach ($droppedTags as $closingTag) {
  570. if (!in_array($closingTag[1], $openTags)) {
  571. array_unshift($openTags, $closingTag[1]);
  572. }
  573. }
  574. } else {
  575. foreach ($droppedTags as $closingTag) {
  576. $openTags[] = $closingTag[1];
  577. }
  578. }
  579. }
  580. }
  581. $truncate = mb_substr($truncate, 0, $spacepos);
  582. }
  583. $truncate .= $ellipsis;
  584. if ($html) {
  585. foreach ($openTags as $tag) {
  586. $truncate .= '</' . $tag . '>';
  587. }
  588. }
  589. return $truncate;
  590. }
  591. /**
  592. * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side
  593. * determined by radius.
  594. *
  595. * @param string $text CakeText to search the phrase in
  596. * @param string $phrase Phrase that will be searched for
  597. * @param int $radius The amount of characters that will be returned on each side of the founded phrase
  598. * @param string $ellipsis Ending that will be appended
  599. * @return string Modified string
  600. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::excerpt
  601. */
  602. public static function excerpt($text, $phrase, $radius = 100, $ellipsis = '...') {
  603. if (empty($text) || empty($phrase)) {
  604. return static::truncate($text, $radius * 2, array('ellipsis' => $ellipsis));
  605. }
  606. $append = $prepend = $ellipsis;
  607. $phraseLen = mb_strlen($phrase);
  608. $textLen = mb_strlen($text);
  609. $pos = mb_strpos(mb_strtolower($text), mb_strtolower($phrase));
  610. if ($pos === false) {
  611. return mb_substr($text, 0, $radius) . $ellipsis;
  612. }
  613. $startPos = $pos - $radius;
  614. if ($startPos <= 0) {
  615. $startPos = 0;
  616. $prepend = '';
  617. }
  618. $endPos = $pos + $phraseLen + $radius;
  619. if ($endPos >= $textLen) {
  620. $endPos = $textLen;
  621. $append = '';
  622. }
  623. $excerpt = mb_substr($text, $startPos, $endPos - $startPos);
  624. $excerpt = $prepend . $excerpt . $append;
  625. return $excerpt;
  626. }
  627. /**
  628. * Creates a comma separated list where the last two items are joined with 'and', forming natural language.
  629. *
  630. * @param array $list The list to be joined.
  631. * @param string $and The word used to join the last and second last items together with. Defaults to 'and'.
  632. * @param string $separator The separator used to join all the other items together. Defaults to ', '.
  633. * @return string The glued together string.
  634. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::toList
  635. */
  636. public static function toList($list, $and = null, $separator = ', ') {
  637. if ($and === null) {
  638. $and = __d('cake', 'and');
  639. }
  640. if (count($list) > 1) {
  641. return implode($separator, array_slice($list, null, -1)) . ' ' . $and . ' ' . array_pop($list);
  642. }
  643. return array_pop($list);
  644. }
  645. }