text.lib.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is the text library for Chamilo.
  5. * It is loaded during the global initialization,
  6. * so the functions below are available everywhere.
  7. *
  8. * @package chamilo.library
  9. */
  10. define('EXERCISE_NUMBER_OF_DECIMALS', 2);
  11. /* XML processing functions */
  12. // A regular expression for accessing declared encoding within xml-formatted text.
  13. // Published by Steve Minutillo,
  14. // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss/
  15. define('_PCRE_XML_ENCODING', '/<\?xml.*encoding=[\'"](.*?)[\'"].*\?>/m');
  16. /**
  17. * This function strips all html-tags found in the input string and outputs a pure text.
  18. * Mostly, the function is to be used before language or encoding detection of the input string.
  19. *
  20. * @param string $string the input string with html-tags to be converted to plain text
  21. *
  22. * @return string the returned plain text as a result
  23. */
  24. function api_html_to_text($string)
  25. {
  26. // These purifications have been found experimentally, for nice looking output.
  27. $string = preg_replace('/<br[^>]*>/i', "\n", $string);
  28. $string = preg_replace('/<\/?(div|p|h[1-6]|table|ol|ul|blockquote)[^>]*>/i', "\n", $string);
  29. $string = preg_replace('/<\/(tr|li)[^>]*>/i', "\n", $string);
  30. $string = preg_replace('/<\/(td|th)[^>]*>/i', "\t", $string);
  31. $string = strip_tags($string);
  32. // Line endings unification and cleaning.
  33. $string = str_replace(["\r\n", "\n\r", "\r"], "\n", $string);
  34. $string = preg_replace('/\s*\n/', "\n", $string);
  35. $string = preg_replace('/\n+/', "\n", $string);
  36. return trim($string);
  37. }
  38. /**
  39. * Detects encoding of html-formatted text.
  40. *
  41. * @param string $string the input html-formatted text
  42. *
  43. * @return string returns the detected encoding
  44. */
  45. function api_detect_encoding_html($string)
  46. {
  47. if (@preg_match('/<head.*(<meta[^>]*content=[^>]*>).*<\/head>/si', $string, $matches)) {
  48. if (@preg_match('/<meta[^>]*charset=(.*)["\';][^>]*>/si', $matches[1], $matches)) {
  49. return api_refine_encoding_id(trim($matches[1]));
  50. }
  51. }
  52. return api_detect_encoding(api_html_to_text($string));
  53. }
  54. /**
  55. * Converts the text of a html-document to a given encoding, the meta-tag is changed accordingly.
  56. *
  57. * @param string $string the input full-html document
  58. * @param string the new encoding value to be set
  59. */
  60. function api_set_encoding_html(&$string, $encoding)
  61. {
  62. $old_encoding = api_detect_encoding_html($string);
  63. if (@preg_match('/(.*<head.*)(<meta[^>]*content=[^>]*>)(.*<\/head>.*)/si', $string, $matches)) {
  64. $meta = $matches[2];
  65. if (@preg_match("/(<meta[^>]*charset=)(.*)([\"';][^>]*>)/si", $meta, $matches1)) {
  66. $meta = $matches1[1].$encoding.$matches1[3];
  67. $string = $matches[1].$meta.$matches[3];
  68. } else {
  69. $string = $matches[1].'<meta http-equiv="Content-Type" content="text/html; charset='.$encoding.'"/>'.$matches[3];
  70. }
  71. } else {
  72. $count = 1;
  73. if (strpos('</head>', strtolower($string)) !== false) {
  74. $string = str_ireplace(
  75. '</head>',
  76. '<meta http-equiv="Content-Type" content="text/html; charset='.$encoding.'"/></head>',
  77. $string,
  78. $count
  79. );
  80. } else {
  81. $string = str_ireplace(
  82. '<body>',
  83. '<head><meta http-equiv="Content-Type" content="text/html; charset='.$encoding.'"/></head><body>',
  84. $string,
  85. $count
  86. );
  87. }
  88. }
  89. $string = api_convert_encoding($string, $encoding, $old_encoding);
  90. }
  91. /**
  92. * Returns the title of a html document.
  93. *
  94. * @param string $string the contents of the input document
  95. * @param string $output_encoding The encoding of the retrieved title.
  96. * If the value is not set, the system encoding is assumed.
  97. * @param string $input_encoding The encoding of the input document. If the value is not set, it is detected.
  98. *
  99. * @return string the retrieved title, html-entities and extra-whitespace between the words are cleaned
  100. */
  101. function api_get_title_html(&$string, $output_encoding = null, $input_encoding = null)
  102. {
  103. if (@preg_match('/<head.+<title[^>]*>(.*)<\/title>/msi', $string, $matches)) {
  104. if (empty($output_encoding)) {
  105. $output_encoding = api_get_system_encoding();
  106. }
  107. if (empty($input_encoding)) {
  108. $input_encoding = api_detect_encoding_html($string);
  109. }
  110. return trim(
  111. @preg_replace(
  112. '/\s+/',
  113. ' ',
  114. api_html_entity_decode(
  115. api_convert_encoding($matches[1], $output_encoding, $input_encoding),
  116. ENT_QUOTES,
  117. $output_encoding
  118. )
  119. )
  120. );
  121. }
  122. return '';
  123. }
  124. /**
  125. * Detects encoding of xml-formatted text.
  126. *
  127. * @param string $string the input xml-formatted text
  128. * @param string $default_encoding This is the default encoding to be returned
  129. * if there is no way the xml-text's encoding to be detected.
  130. * If it not spesified, the system encoding is assumed then.
  131. *
  132. * @return string returns the detected encoding
  133. *
  134. * @todo The second parameter is to be eliminated. See api_detect_encoding_html().
  135. */
  136. function api_detect_encoding_xml($string, $default_encoding = null)
  137. {
  138. if (preg_match(_PCRE_XML_ENCODING, $string, $matches)) {
  139. return api_refine_encoding_id($matches[1]);
  140. }
  141. if (api_is_valid_utf8($string)) {
  142. return 'UTF-8';
  143. }
  144. if (empty($default_encoding)) {
  145. $default_encoding = _api_mb_internal_encoding();
  146. }
  147. return api_refine_encoding_id($default_encoding);
  148. }
  149. /**
  150. * Converts character encoding of a xml-formatted text.
  151. * If inside the text the encoding is declared, it is modified accordingly.
  152. *
  153. * @param string $string the text being converted
  154. * @param string $to_encoding the encoding that text is being converted to
  155. * @param string $from_encoding (optional) The encoding that text is being converted from.
  156. * If it is omited, it is tried to be detected then.
  157. *
  158. * @return string returns the converted xml-text
  159. */
  160. function api_convert_encoding_xml($string, $to_encoding, $from_encoding = null)
  161. {
  162. return _api_convert_encoding_xml($string, $to_encoding, $from_encoding);
  163. }
  164. /**
  165. * Converts character encoding of a xml-formatted text into UTF-8.
  166. * If inside the text the encoding is declared, it is set to UTF-8.
  167. *
  168. * @param string $string the text being converted
  169. * @param string $from_encoding (optional) The encoding that text is being converted from.
  170. * If it is omited, it is tried to be detected then.
  171. *
  172. * @return string returns the converted xml-text
  173. */
  174. function api_utf8_encode_xml($string, $from_encoding = null)
  175. {
  176. return _api_convert_encoding_xml($string, 'UTF-8', $from_encoding);
  177. }
  178. /**
  179. * Converts character encoding of a xml-formatted text from UTF-8 into a specified encoding.
  180. * If inside the text the encoding is declared, it is modified accordingly.
  181. *
  182. * @param string $string the text being converted
  183. * @param string $to_encoding (optional) The encoding that text is being converted to.
  184. * If it is omitted, the platform character set is assumed.
  185. *
  186. * @return string returns the converted xml-text
  187. */
  188. function api_utf8_decode_xml($string, $to_encoding = 'UTF-8')
  189. {
  190. return _api_convert_encoding_xml($string, $to_encoding, 'UTF-8');
  191. }
  192. /**
  193. * Converts character encoding of a xml-formatted text.
  194. * If inside the text the encoding is declared, it is modified accordingly.
  195. *
  196. * @param string $string the text being converted
  197. * @param string $to_encoding the encoding that text is being converted to
  198. * @param string $from_encoding (optional) The encoding that text is being converted from.
  199. * If the value is empty, it is tried to be detected then.
  200. *
  201. * @return string returns the converted xml-text
  202. */
  203. function _api_convert_encoding_xml(&$string, $to_encoding, $from_encoding)
  204. {
  205. if (empty($from_encoding)) {
  206. $from_encoding = api_detect_encoding_xml($string);
  207. }
  208. $to_encoding = api_refine_encoding_id($to_encoding);
  209. if (!preg_match('/<\?xml.*\?>/m', $string, $matches)) {
  210. return api_convert_encoding(
  211. '<?xml version="1.0" encoding="'.$to_encoding.'"?>'."\n".$string,
  212. $to_encoding,
  213. $from_encoding
  214. );
  215. }
  216. if (!preg_match(_PCRE_XML_ENCODING, $string)) {
  217. if (strpos($matches[0], 'standalone') !== false) {
  218. // The encoding option should precede the standalone option,
  219. // othewise DOMDocument fails to load the document.
  220. $replace = str_replace('standalone', ' encoding="'.$to_encoding.'" standalone', $matches[0]);
  221. } else {
  222. $replace = str_replace('?>', ' encoding="'.$to_encoding.'"?>', $matches[0]);
  223. }
  224. return api_convert_encoding(str_replace($matches[0], $replace, $string), $to_encoding, $from_encoding);
  225. }
  226. global $_api_encoding;
  227. $_api_encoding = api_refine_encoding_id($to_encoding);
  228. return api_convert_encoding(
  229. preg_replace_callback(
  230. _PCRE_XML_ENCODING,
  231. '_api_convert_encoding_xml_callback',
  232. $string
  233. ),
  234. $to_encoding,
  235. $from_encoding
  236. );
  237. }
  238. /**
  239. * A callback for serving the function _api_convert_encoding_xml().
  240. *
  241. * @param array $matches input array of matches corresponding to the xml-declaration
  242. *
  243. * @return string returns the xml-declaration with modified encoding
  244. */
  245. function _api_convert_encoding_xml_callback($matches)
  246. {
  247. global $_api_encoding;
  248. return str_replace($matches[1], $_api_encoding, $matches[0]);
  249. }
  250. /* Functions for supporting ASCIIMathML mathematical formulas and ASCIIsvg maathematical graphics */
  251. /**
  252. * Dectects ASCIIMathML formula presence within a given html text.
  253. *
  254. * @param string $html the input html text
  255. *
  256. * @return bool returns TRUE when there is a formula found or FALSE otherwise
  257. */
  258. function api_contains_asciimathml($html)
  259. {
  260. if (!preg_match_all('/<span[^>]*class\s*=\s*[\'"](.*?)[\'"][^>]*>/mi', $html, $matches)) {
  261. return false;
  262. }
  263. foreach ($matches[1] as $string) {
  264. $string = ' '.str_replace(',', ' ', $string).' ';
  265. if (preg_match('/\sAM\s/m', $string)) {
  266. return true;
  267. }
  268. }
  269. return false;
  270. }
  271. /**
  272. * Dectects ASCIIsvg graphics presence within a given html text.
  273. *
  274. * @param string $html the input html text
  275. *
  276. * @return bool returns TRUE when there is a graph found or FALSE otherwise
  277. */
  278. function api_contains_asciisvg($html)
  279. {
  280. if (!preg_match_all('/<embed([^>]*?)>/mi', $html, $matches)) {
  281. return false;
  282. }
  283. foreach ($matches[1] as $string) {
  284. $string = ' '.str_replace(',', ' ', $string).' ';
  285. if (preg_match('/sscr\s*=\s*[\'"](.*?)[\'"]/m', $string)) {
  286. return true;
  287. }
  288. }
  289. return false;
  290. }
  291. /**
  292. * Convers a string from camel case into underscore.
  293. * Works correctly with ASCII strings only, implementation for human-language strings is not necessary.
  294. *
  295. * @param string $string The input string (ASCII)
  296. *
  297. * @return string The converted result string
  298. */
  299. function api_camel_case_to_underscore($string)
  300. {
  301. return strtolower(preg_replace('/([a-z])([A-Z])/', "$1_$2", $string));
  302. }
  303. /**
  304. * Converts a string with underscores into camel case.
  305. * Works correctly with ASCII strings only, implementation for human-language strings is not necessary.
  306. *
  307. * @param string $string The input string (ASCII)
  308. * @param bool $capitalise_first_char (optional)
  309. * If true (default), the function capitalises the first char in the result string
  310. *
  311. * @return string The converted result string
  312. */
  313. function api_underscore_to_camel_case($string, $capitalise_first_char = true)
  314. {
  315. if ($capitalise_first_char) {
  316. $string = ucfirst($string);
  317. }
  318. return preg_replace_callback('/_([a-z])/', '_api_camelize', $string);
  319. }
  320. // A function for internal use, only for this library.
  321. function _api_camelize($match)
  322. {
  323. return strtoupper($match[1]);
  324. }
  325. /**
  326. * Truncates a string.
  327. *
  328. * @author Brouckaert Olivier
  329. *
  330. * @param string $text the text to truncate
  331. * @param int $length The approximate desired length. The length of the suffix below is to be added to
  332. * have the total length of the result string.
  333. * @param string $suffix a suffix to be added as a replacement
  334. * @param string $encoding (optional) The encoding to be used. If it is omitted,
  335. * the platform character set will be used by default.
  336. * @param bool $middle if this parameter is true, truncation is done in the middle of the string
  337. *
  338. * @return string truncated string, decorated with the given suffix (replacement)
  339. */
  340. function api_trunc_str($text, $length = 30, $suffix = '...', $middle = false, $encoding = null)
  341. {
  342. if (empty($encoding)) {
  343. $encoding = api_get_system_encoding();
  344. }
  345. $text_length = api_strlen($text, $encoding);
  346. if ($text_length <= $length) {
  347. return $text;
  348. }
  349. if ($middle) {
  350. return rtrim(
  351. api_substr(
  352. $text,
  353. 0,
  354. round($length / 2),
  355. $encoding
  356. )
  357. ).
  358. $suffix.
  359. ltrim(
  360. api_substr(
  361. $text,
  362. -round($length / 2),
  363. $text_length,
  364. $encoding
  365. )
  366. );
  367. }
  368. return rtrim(api_substr($text, 0, $length, $encoding)).$suffix;
  369. }
  370. /**
  371. * Handling simple and double apostrofe in order that strings be stored properly in database.
  372. *
  373. * @author Denes Nagy
  374. *
  375. * @param string variable - the variable to be revised
  376. *
  377. * @return string
  378. */
  379. function domesticate($input)
  380. {
  381. $input = str_replace(["'", '"'], "''", stripslashes($input));
  382. return $input;
  383. }
  384. /**
  385. * function make_clickable($string).
  386. *
  387. * @desc Completes url contained in the text with "<a href ...".
  388. * However the function simply returns the submitted text without any
  389. * transformation if it already contains some "<a href:" or "<img src=".
  390. *
  391. * @param string $text text to be converted
  392. *
  393. * @return text after conversion
  394. *
  395. * @author Rewritten by Nathan Codding - Feb 6, 2001.
  396. * completed by Hugues Peeters - July 22, 2002
  397. *
  398. * Actually this function is taken from the PHP BB 1.4 script
  399. * - Goes through the given string, and replaces xxxx://yyyy with an HTML <a> tag linking
  400. * to that URL
  401. * - Goes through the given string, and replaces www.xxxx.yyyy[zzzz] with an HTML <a> tag linking
  402. * to http://www.xxxx.yyyy[/zzzz]
  403. * - Goes through the given string, and replaces xxxx@yyyy with an HTML mailto: tag linking
  404. * to that email address
  405. * - Only matches these 2 patterns either after a space, or at the beginning of a line
  406. *
  407. * Notes: the email one might get annoying - it's easy to make it more restrictive, though.. maybe
  408. * have it require something like xxxx@yyyy.zzzz or such. We'll see.
  409. */
  410. /**
  411. * Callback to convert URI match to HTML A element.
  412. *
  413. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link * make_clickable()}.
  414. *
  415. * @since Wordpress 2.3.2
  416. *
  417. * @param array $matches single Regex Match
  418. *
  419. * @return string HTML A element with URI address
  420. */
  421. function _make_url_clickable_cb($matches)
  422. {
  423. $url = $matches[2];
  424. if (')' == $matches[3] && strpos($url, '(')) {
  425. // If the trailing character is a closing parethesis, and the URL has an opening
  426. // parenthesis in it, add the closing parenthesis to the URL.
  427. // Then we can let the parenthesis balancer do its thing below.
  428. $url .= $matches[3];
  429. $suffix = '';
  430. } else {
  431. $suffix = $matches[3];
  432. }
  433. // Include parentheses in the URL only if paired
  434. while (substr_count($url, '(') < substr_count($url, ')')) {
  435. $suffix = strrchr($url, ')').$suffix;
  436. $url = substr($url, 0, strrpos($url, ')'));
  437. }
  438. $url = esc_url($url);
  439. if (empty($url)) {
  440. return $matches[0];
  441. }
  442. return $matches[1]."<a href=\"$url\" rel=\"nofollow\">$url</a>".$suffix;
  443. }
  444. /**
  445. * Checks and cleans a URL.
  446. *
  447. * A number of characters are removed from the URL. If the URL is for displaying
  448. * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
  449. * is applied to the returned cleaned URL.
  450. *
  451. * @since wordpress 2.8.0
  452. *
  453. * @uses \wp_kses_bad_protocol() To only permit protocols in the URL set
  454. * via $protocols or the common ones set in the function.
  455. *
  456. * @param string $url the URL to be cleaned
  457. * @param array $protocols Optional. An array of acceptable protocols.
  458. * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher',
  459. * 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
  460. * @param string $_context Private. Use esc_url_raw() for database usage.
  461. *
  462. * @return string the cleaned $url after the 'clean_url' filter is applied
  463. */
  464. function esc_url($url, $protocols = null, $_context = 'display')
  465. {
  466. //$original_url = $url;
  467. if ('' == $url) {
  468. return $url;
  469. }
  470. $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
  471. $strip = ['%0d', '%0a', '%0D', '%0A'];
  472. $url = _deep_replace($strip, $url);
  473. $url = str_replace(';//', '://', $url);
  474. /* If the URL doesn't appear to contain a scheme, we
  475. * presume it needs http:// appended (unless a relative
  476. * link starting with /, # or ? or a php file).
  477. */
  478. if (strpos($url, ':') === false && !in_array($url[0], ['/', '#', '?']) &&
  479. !preg_match('/^[a-z0-9-]+?\.php/i', $url)) {
  480. $url = 'http://'.$url;
  481. }
  482. return Security::remove_XSS($url);
  483. }
  484. /**
  485. * Perform a deep string replace operation to ensure the values in $search are no longer present.
  486. *
  487. * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
  488. * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
  489. * str_replace would return
  490. *
  491. * @since wordpress 2.8.1
  492. *
  493. * @param string|array $search The value being searched for, otherwise known as the needle.
  494. * An array may be used to designate multiple needles.
  495. * @param string $subject the string being searched and replaced on, otherwise known as the haystack
  496. *
  497. * @return string the string with the replaced svalues
  498. */
  499. function _deep_replace($search, $subject)
  500. {
  501. $subject = (string) $subject;
  502. $count = 1;
  503. while ($count) {
  504. $subject = str_replace($search, '', $subject, $count);
  505. }
  506. return $subject;
  507. }
  508. /**
  509. * Callback to convert URL match to HTML A element.
  510. *
  511. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link * make_clickable()}.
  512. *
  513. * @since wordpress 2.3.2
  514. *
  515. * @param array $matches single Regex Match
  516. *
  517. * @return string HTML A element with URL address
  518. */
  519. function _make_web_ftp_clickable_cb($matches)
  520. {
  521. $ret = '';
  522. $dest = $matches[2];
  523. $dest = 'http://'.$dest;
  524. $dest = esc_url($dest);
  525. if (empty($dest)) {
  526. return $matches[0];
  527. }
  528. // removed trailing [.,;:)] from URL
  529. if (in_array(substr($dest, -1), ['.', ',', ';', ':', ')']) === true) {
  530. $ret = substr($dest, -1);
  531. $dest = substr($dest, 0, strlen($dest) - 1);
  532. }
  533. return $matches[1]."<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
  534. }
  535. /**
  536. * Callback to convert email address match to HTML A element.
  537. *
  538. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link * make_clickable()}.
  539. *
  540. * @since wordpress 2.3.2
  541. *
  542. * @param array $matches single Regex Match
  543. *
  544. * @return string HTML A element with email address
  545. */
  546. function _make_email_clickable_cb($matches)
  547. {
  548. $email = $matches[2].'@'.$matches[3];
  549. return $matches[1]."<a href=\"mailto:$email\">$email</a>";
  550. }
  551. /**
  552. * Convert plaintext URI to HTML links.
  553. *
  554. * Converts URI, www and ftp, and email addresses. Finishes by fixing links
  555. * within links.
  556. *
  557. * @since wordpress 0.71
  558. *
  559. * @param string $text content to convert URIs
  560. *
  561. * @return string content with converted URIs
  562. */
  563. function make_clickable($text)
  564. {
  565. $r = '';
  566. // split out HTML tags
  567. $textarr = preg_split('/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  568. $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
  569. foreach ($textarr as $piece) {
  570. if (preg_match('|^<code[\s>]|i', $piece) || preg_match('|^<pre[\s>]|i', $piece)) {
  571. $nested_code_pre++;
  572. } elseif (('</code>' === strtolower($piece) || '</pre>' === strtolower($piece)) && $nested_code_pre) {
  573. $nested_code_pre--;
  574. }
  575. if ($nested_code_pre ||
  576. empty($piece) ||
  577. ($piece[0] === '<' && !preg_match('|^<\s*[\w]{1,20}+://|', $piece))
  578. ) {
  579. $r .= $piece;
  580. continue;
  581. }
  582. // Long strings might contain expensive edge cases ...
  583. if (10000 < strlen($piece)) {
  584. // ... break it up
  585. foreach (_split_str_by_whitespace($piece, 2100) as $chunk) {
  586. // 2100: Extra room for scheme and leading and trailing paretheses
  587. if (2101 < strlen($chunk)) {
  588. $r .= $chunk; // Too big, no whitespace: bail.
  589. } else {
  590. $r .= make_clickable($chunk);
  591. }
  592. }
  593. } else {
  594. $ret = " $piece "; // Pad with whitespace to simplify the regexes
  595. $url_clickable = '~
  596. ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
  597. ( # 2: URL
  598. [\\w]{1,20}+:// # Scheme and hier-part prefix
  599. (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
  600. [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
  601. (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
  602. [\'.,;:!?)] # Punctuation URL character
  603. [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
  604. )*
  605. )
  606. (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
  607. ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
  608. // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
  609. $ret = preg_replace_callback($url_clickable, '_make_url_clickable_cb', $ret);
  610. $ret = preg_replace_callback(
  611. '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is',
  612. '_make_web_ftp_clickable_cb',
  613. $ret
  614. );
  615. $ret = preg_replace_callback(
  616. '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i',
  617. '_make_email_clickable_cb',
  618. $ret
  619. );
  620. $ret = substr($ret, 1, -1); // Remove our whitespace padding.
  621. $r .= $ret;
  622. }
  623. }
  624. // Cleanup of accidental links within links
  625. $r = preg_replace('#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r);
  626. return $r;
  627. }
  628. /**
  629. * Breaks a string into chunks by splitting at whitespace characters.
  630. * The length of each returned chunk is as close to the specified length goal as possible,
  631. * with the caveat that each chunk includes its trailing delimiter.
  632. * Chunks longer than the goal are guaranteed to not have any inner whitespace.
  633. *
  634. * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
  635. *
  636. * Input string must have no null characters (or eventual transformations on output chunks
  637. * must not care about null characters)
  638. *
  639. * <code>
  640. * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
  641. * array (
  642. * 0 => '1234 67890 ', // 11 characters: Perfect split
  643. * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
  644. * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
  645. * 3 => '1234 890 ', // 11 characters: Perfect split
  646. * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
  647. * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
  648. * 6 => ' 45678 ', // 11 characters: Perfect split
  649. * 7 => '1 3 5 7 9', // 9 characters: End of $string
  650. * );
  651. * </code>
  652. *
  653. * @since wordpress 3.4.0
  654. *
  655. * @param string $string the string to split
  656. * @param int $goal the desired chunk length
  657. *
  658. * @return array numeric array of chunks
  659. */
  660. function _split_str_by_whitespace($string, $goal)
  661. {
  662. $chunks = [];
  663. $string_nullspace = strtr($string, "\r\n\t\v\f ", "\000\000\000\000\000\000");
  664. while ($goal < strlen($string_nullspace)) {
  665. $pos = strrpos(substr($string_nullspace, 0, $goal + 1), "\000");
  666. if (false === $pos) {
  667. $pos = strpos($string_nullspace, "\000", $goal + 1);
  668. if (false === $pos) {
  669. break;
  670. }
  671. }
  672. $chunks[] = substr($string, 0, $pos + 1);
  673. $string = substr($string, $pos + 1);
  674. $string_nullspace = substr($string_nullspace, $pos + 1);
  675. }
  676. if ($string) {
  677. $chunks[] = $string;
  678. }
  679. return $chunks;
  680. }
  681. /**
  682. * This functions cuts a paragraph
  683. * i.e cut('Merry Xmas from Lima',13) = "Merry Xmas fr...".
  684. *
  685. * @param string The text to "cut"
  686. * @param int Count of chars
  687. * @param bool Whether to embed in a <span title="...">...</span>
  688. *
  689. * @return string
  690. * */
  691. function cut($text, $maxchar, $embed = false)
  692. {
  693. if (api_strlen($text) > $maxchar) {
  694. if ($embed) {
  695. return '<p title="'.$text.'">'.api_substr($text, 0, $maxchar).'...</p>';
  696. }
  697. return api_substr($text, 0, $maxchar).' ...';
  698. }
  699. return $text;
  700. }
  701. /**
  702. * Show a number as only integers if no decimals, but will show 2 decimals if exist.
  703. *
  704. * @param mixed Number to convert
  705. * @param int Decimal points 0=never, 1=if needed, 2=always
  706. * @param string $decimalPoint
  707. * @param string $thousandsSeparator
  708. *
  709. * @return mixed An integer or a float depends on the parameter
  710. */
  711. function float_format($number, $flag = 1, $decimalPoint = '.', $thousandsSeparator = ',')
  712. {
  713. if (is_numeric($number)) {
  714. if (!$number) {
  715. $result = ($flag == 2 ? '0.'.str_repeat('0', EXERCISE_NUMBER_OF_DECIMALS) : '0');
  716. } else {
  717. if (floor($number) == $number) {
  718. $result = number_format(
  719. $number,
  720. ($flag == 2 ? EXERCISE_NUMBER_OF_DECIMALS : 0),
  721. $decimalPoint,
  722. $thousandsSeparator
  723. );
  724. } else {
  725. $result = number_format(
  726. round($number, 2),
  727. ($flag == 0 ? 0 : EXERCISE_NUMBER_OF_DECIMALS),
  728. $decimalPoint,
  729. $thousandsSeparator
  730. );
  731. }
  732. }
  733. return $result;
  734. }
  735. }
  736. // TODO: To be checked for correct timezone management.
  737. /**
  738. * Function to obtain last week timestamps.
  739. *
  740. * @return array Times for every day inside week
  741. */
  742. function get_last_week()
  743. {
  744. $week = date('W');
  745. $year = date('Y');
  746. $lastweek = $week - 1;
  747. if ($lastweek == 0) {
  748. $week = 52;
  749. $year--;
  750. }
  751. $lastweek = sprintf("%02d", $lastweek);
  752. $arrdays = [];
  753. for ($i = 1; $i <= 7; $i++) {
  754. $arrdays[] = strtotime("$year"."W$lastweek"."$i");
  755. }
  756. return $arrdays;
  757. }
  758. /**
  759. * Gets the week from a day.
  760. *
  761. * @param string Date in UTC (2010-01-01 12:12:12)
  762. *
  763. * @return int Returns an integer with the week number of the year
  764. */
  765. function get_week_from_day($date)
  766. {
  767. if (!empty($date)) {
  768. $time = api_strtotime($date, 'UTC');
  769. return date('W', $time);
  770. }
  771. return date('W');
  772. }
  773. /**
  774. * This function splits the string into words and then joins them back together again one by one.
  775. * Example: "Test example of a long string"
  776. * substrwords(5) = Test ... *.
  777. *
  778. * @param string
  779. * @param int the max number of character
  780. * @param string how the string will be end
  781. *
  782. * @return a reduce string
  783. */
  784. function substrwords($text, $maxchar, $end = '...')
  785. {
  786. if (strlen($text) > $maxchar) {
  787. $words = explode(" ", $text);
  788. $output = '';
  789. $i = 0;
  790. while (1) {
  791. $length = (strlen($output) + strlen($words[$i]));
  792. if ($length > $maxchar) {
  793. break;
  794. } else {
  795. $output = $output." ".$words[$i];
  796. $i++;
  797. }
  798. }
  799. } else {
  800. $output = $text;
  801. return $output;
  802. }
  803. return $output.$end;
  804. }
  805. function implode_with_key($glue, $array)
  806. {
  807. if (!empty($array)) {
  808. $string = '';
  809. foreach ($array as $key => $value) {
  810. if (empty($value)) {
  811. $value = 'null';
  812. }
  813. $string .= $key." : ".$value." $glue ";
  814. }
  815. return $string;
  816. }
  817. return '';
  818. }
  819. /**
  820. * Transform the file size in a human readable format.
  821. *
  822. * @param int $file_size Size of the file in bytes
  823. *
  824. * @return string A human readable representation of the file size
  825. */
  826. function format_file_size($file_size)
  827. {
  828. $file_size = (int) $file_size;
  829. if ($file_size >= 1073741824) {
  830. $file_size = (round($file_size / 1073741824 * 100) / 100).'G';
  831. } elseif ($file_size >= 1048576) {
  832. $file_size = (round($file_size / 1048576 * 100) / 100).'M';
  833. } elseif ($file_size >= 1024) {
  834. $file_size = (round($file_size / 1024 * 100) / 100).'k';
  835. } else {
  836. $file_size = $file_size.'B';
  837. }
  838. return $file_size;
  839. }
  840. /**
  841. * Converts an string CLEANYO[admin][amann,acostea]
  842. * into an array:.
  843. *
  844. * array(
  845. * CLEANYO
  846. * admin
  847. * amann,acostea
  848. * )
  849. *
  850. * @param $array
  851. *
  852. * @return array
  853. */
  854. function bracketsToArray($array)
  855. {
  856. return preg_split('/[\[\]]+/', $array, -1, PREG_SPLIT_NO_EMPTY);
  857. }
  858. /**
  859. * @param string $string
  860. * @param bool $capitalizeFirstCharacter
  861. *
  862. * @return mixed
  863. */
  864. function underScoreToCamelCase($string, $capitalizeFirstCharacter = true)
  865. {
  866. $str = str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
  867. if (!$capitalizeFirstCharacter) {
  868. $str[0] = strtolower($str[0]);
  869. }
  870. return $str;
  871. }
  872. /**
  873. * @param string $value
  874. */
  875. function trim_value(&$value)
  876. {
  877. $value = trim($value);
  878. }
  879. /**
  880. * Strips only the given tags in the given HTML string.
  881. *
  882. * @param string $html
  883. * @param array $tags
  884. *
  885. * @return string
  886. */
  887. function strip_tags_blacklist($html, $tags)
  888. {
  889. foreach ($tags as $tag) {
  890. $regex = '#<\s*'.$tag.'[^>]*>.*?<\s*/\s*'.$tag.'>#msi';
  891. $html = preg_replace($regex, '', $html);
  892. }
  893. return $html;
  894. }