text.lib.php 31 KB

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