text.lib.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  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(array("\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 = array('%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], array('/', '#', '?')) &&
  385. !preg_match('/^[a-z0-9-]+?\.php/i', $url))
  386. $url = 'http://'.$url;
  387. return Security::remove_XSS($url);
  388. /*// Replace ampersands and single quotes only when displaying.
  389. if ( 'display' == $_context ) {
  390. $url = wp_kses_normalize_entities( $url );
  391. $url = str_replace( '&amp;', '&#038;', $url );
  392. $url = str_replace( "'", '&#039;', $url );
  393. }
  394. if ( '/' === $url[0] ) {
  395. $good_protocol_url = $url;
  396. } else {
  397. if ( ! is_array( $protocols ) )
  398. $protocols = wp_allowed_protocols();
  399. $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
  400. if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
  401. return '';
  402. }
  403. /**
  404. * Filter a string cleaned and escaped for output as a URL.
  405. *
  406. * @since 2.3.0
  407. *
  408. * @param string $good_protocol_url The cleaned URL to be returned.
  409. * @param string $original_url The URL prior to cleaning.
  410. * @param string $_context If 'display', replace ampersands and single quotes only.
  411. */
  412. //return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );98
  413. }
  414. /**
  415. * Perform a deep string replace operation to ensure the values in $search are no longer present
  416. *
  417. * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
  418. * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
  419. * str_replace would return
  420. *
  421. * @since wordpress 2.8.1
  422. * @access private
  423. *
  424. * @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
  425. * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
  426. * @return string The string with the replaced svalues.
  427. */
  428. function _deep_replace($search, $subject)
  429. {
  430. $subject = (string) $subject;
  431. $count = 1;
  432. while ($count) {
  433. $subject = str_replace($search, '', $subject, $count);
  434. }
  435. return $subject;
  436. }
  437. /**
  438. * Callback to convert URL match to HTML A element.
  439. *
  440. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  441. * make_clickable()}.
  442. *
  443. * @since wordpress 2.3.2
  444. * @access private
  445. *
  446. * @param array $matches Single Regex Match.
  447. * @return string HTML A element with URL address.
  448. */
  449. function _make_web_ftp_clickable_cb($matches)
  450. {
  451. $ret = '';
  452. $dest = $matches[2];
  453. $dest = 'http://'.$dest;
  454. $dest = esc_url($dest);
  455. if (empty($dest)) {
  456. return $matches[0];
  457. }
  458. // removed trailing [.,;:)] from URL
  459. if (in_array(substr($dest, -1), array('.', ',', ';', ':', ')')) === true) {
  460. $ret = substr($dest, -1);
  461. $dest = substr($dest, 0, strlen($dest) - 1);
  462. }
  463. return $matches[1]."<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
  464. }
  465. /**
  466. * Callback to convert email address match to HTML A element.
  467. *
  468. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  469. * make_clickable()}.
  470. *
  471. * @since wordpress 2.3.2
  472. * @access private
  473. *
  474. * @param array $matches Single Regex Match.
  475. * @return string HTML A element with email address.
  476. */
  477. function _make_email_clickable_cb($matches)
  478. {
  479. $email = $matches[2].'@'.$matches[3];
  480. return $matches[1]."<a href=\"mailto:$email\">$email</a>";
  481. }
  482. /**
  483. * Convert plaintext URI to HTML links.
  484. *
  485. * Converts URI, www and ftp, and email addresses. Finishes by fixing links
  486. * within links.
  487. *
  488. * @since wordpress 0.71
  489. *
  490. * @param string $text Content to convert URIs.
  491. * @return string Content with converted URIs.
  492. */
  493. function make_clickable($text)
  494. {
  495. $r = '';
  496. $textarr = preg_split('/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE); // split out HTML tags
  497. $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
  498. foreach ($textarr as $piece) {
  499. if (preg_match('|^<code[\s>]|i', $piece) || preg_match('|^<pre[\s>]|i', $piece)) {
  500. $nested_code_pre++;
  501. } elseif (('</code>' === strtolower($piece) || '</pre>' === strtolower($piece)) && $nested_code_pre) {
  502. $nested_code_pre--;
  503. }
  504. if ($nested_code_pre || empty($piece) || ($piece[0] === '<' && !preg_match('|^<\s*[\w]{1,20}+://|', $piece))) {
  505. $r .= $piece;
  506. continue;
  507. }
  508. // Long strings might contain expensive edge cases ...
  509. if (10000 < strlen($piece)) {
  510. // ... break it up
  511. foreach (_split_str_by_whitespace($piece, 2100) as $chunk) { // 2100: Extra room for scheme and leading and trailing paretheses
  512. if (2101 < strlen($chunk)) {
  513. $r .= $chunk; // Too big, no whitespace: bail.
  514. } else {
  515. $r .= make_clickable($chunk);
  516. }
  517. }
  518. } else {
  519. $ret = " $piece "; // Pad with whitespace to simplify the regexes
  520. $url_clickable = '~
  521. ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
  522. ( # 2: URL
  523. [\\w]{1,20}+:// # Scheme and hier-part prefix
  524. (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
  525. [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
  526. (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
  527. [\'.,;:!?)] # Punctuation URL character
  528. [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
  529. )*
  530. )
  531. (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
  532. ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
  533. // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
  534. $ret = preg_replace_callback($url_clickable, '_make_url_clickable_cb', $ret);
  535. $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret);
  536. $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
  537. $ret = substr($ret, 1, -1); // Remove our whitespace padding.
  538. $r .= $ret;
  539. }
  540. }
  541. // Cleanup of accidental links within links
  542. $r = preg_replace('#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r);
  543. return $r;
  544. }
  545. /**
  546. * Breaks a string into chunks by splitting at whitespace characters.
  547. * The length of each returned chunk is as close to the specified length goal as possible,
  548. * with the caveat that each chunk includes its trailing delimiter.
  549. * Chunks longer than the goal are guaranteed to not have any inner whitespace.
  550. *
  551. * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
  552. *
  553. * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
  554. *
  555. * <code>
  556. * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
  557. * array (
  558. * 0 => '1234 67890 ', // 11 characters: Perfect split
  559. * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
  560. * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
  561. * 3 => '1234 890 ', // 11 characters: Perfect split
  562. * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
  563. * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
  564. * 6 => ' 45678 ', // 11 characters: Perfect split
  565. * 7 => '1 3 5 7 9', // 9 characters: End of $string
  566. * );
  567. * </code>
  568. *
  569. * @since wordpress 3.4.0
  570. * @access private
  571. *
  572. * @param string $string The string to split.
  573. * @param int $goal The desired chunk length.
  574. * @return array Numeric array of chunks.
  575. */
  576. function _split_str_by_whitespace($string, $goal)
  577. {
  578. $chunks = array();
  579. $string_nullspace = strtr($string, "\r\n\t\v\f ", "\000\000\000\000\000\000");
  580. while ($goal < strlen($string_nullspace)) {
  581. $pos = strrpos(substr($string_nullspace, 0, $goal + 1), "\000");
  582. if (false === $pos) {
  583. $pos = strpos($string_nullspace, "\000", $goal + 1);
  584. if (false === $pos) {
  585. break;
  586. }
  587. }
  588. $chunks[] = substr($string, 0, $pos + 1);
  589. $string = substr($string, $pos + 1);
  590. $string_nullspace = substr($string_nullspace, $pos + 1);
  591. }
  592. if ($string) {
  593. $chunks[] = $string;
  594. }
  595. return $chunks;
  596. }
  597. /**
  598. * This functions cuts a paragraph
  599. * i.e cut('Merry Xmas from Lima',13) = "Merry Xmas fr..."
  600. * @param string The text to "cut"
  601. * @param int Count of chars
  602. * @param bool Whether to embed in a <span title="...">...</span>
  603. * @return string
  604. * */
  605. function cut($text, $maxchar, $embed = false)
  606. {
  607. if (api_strlen($text) > $maxchar) {
  608. if ($embed) {
  609. return '<p title="'.$text.'">'.api_substr($text, 0, $maxchar).'...</p>';
  610. }
  611. return api_substr($text, 0, $maxchar).' ...';
  612. }
  613. return $text;
  614. }
  615. /**
  616. * Show a number as only integers if no decimals, but will show 2 decimals if exist.
  617. *
  618. * @param mixed Number to convert
  619. * @param int Decimal points 0=never, 1=if needed, 2=always
  620. * @return mixed An integer or a float depends on the parameter
  621. */
  622. function float_format($number, $flag = 1)
  623. {
  624. if (is_numeric($number)) {
  625. if (!$number) {
  626. $result = ($flag == 2 ? '0.'.str_repeat('0', EXERCISE_NUMBER_OF_DECIMALS) : '0');
  627. } else {
  628. if (floor($number) == $number) {
  629. $result = number_format($number, ($flag == 2 ? EXERCISE_NUMBER_OF_DECIMALS : 0));
  630. } else {
  631. $result = number_format(round($number, 2), ($flag == 0 ? 0 : EXERCISE_NUMBER_OF_DECIMALS));
  632. }
  633. }
  634. return $result;
  635. }
  636. }
  637. // TODO: To be checked for correct timezone management.
  638. /**
  639. * Function to obtain last week timestamps
  640. * @return array Times for every day inside week
  641. */
  642. function get_last_week()
  643. {
  644. $week = date('W');
  645. $year = date('Y');
  646. $lastweek = $week - 1;
  647. if ($lastweek == 0) {
  648. $week = 52;
  649. $year--;
  650. }
  651. $lastweek = sprintf("%02d", $lastweek);
  652. $arrdays = array();
  653. for ($i = 1; $i <= 7; $i++) {
  654. $arrdays[] = strtotime("$year"."W$lastweek"."$i");
  655. }
  656. return $arrdays;
  657. }
  658. /**
  659. * Gets the week from a day
  660. * @param string Date in UTC (2010-01-01 12:12:12)
  661. * @return int Returns an integer with the week number of the year
  662. */
  663. function get_week_from_day($date)
  664. {
  665. if (!empty($date)) {
  666. $time = api_strtotime($date, 'UTC');
  667. return date('W', $time);
  668. } else {
  669. return date('W');
  670. }
  671. }
  672. /**
  673. * This function splits the string into words and then joins them back together again one by one.
  674. * Example: "Test example of a long string"
  675. * substrwords(5) = Test ... *
  676. * @param string
  677. * @param int the max number of character
  678. * @param string how the string will be end
  679. * @return a reduce string
  680. */
  681. function substrwords($text, $maxchar, $end = '...')
  682. {
  683. if (strlen($text) > $maxchar) {
  684. $words = explode(" ", $text);
  685. $output = '';
  686. $i = 0;
  687. while (1) {
  688. $length = (strlen($output) + strlen($words[$i]));
  689. if ($length > $maxchar) {
  690. break;
  691. } else {
  692. $output = $output." ".$words[$i];
  693. $i++;
  694. }
  695. }
  696. } else {
  697. $output = $text;
  698. return $output;
  699. }
  700. return $output.$end;
  701. }
  702. function implode_with_key($glue, $array)
  703. {
  704. if (!empty($array)) {
  705. $string = '';
  706. foreach ($array as $key => $value) {
  707. if (empty($value)) {
  708. $value = 'null';
  709. }
  710. $string .= $key." : ".$value." $glue ";
  711. }
  712. return $string;
  713. }
  714. return '';
  715. }
  716. /**
  717. * Transform the file size in a human readable format.
  718. *
  719. * @param int $file_size Size of the file in bytes
  720. * @return string A human readable representation of the file size
  721. */
  722. function format_file_size($file_size)
  723. {
  724. $file_size = intval($file_size);
  725. if ($file_size >= 1073741824) {
  726. $file_size = (round($file_size / 1073741824 * 100) / 100).'G';
  727. } elseif ($file_size >= 1048576) {
  728. $file_size = (round($file_size / 1048576 * 100) / 100).'M';
  729. } elseif ($file_size >= 1024) {
  730. $file_size = (round($file_size / 1024 * 100) / 100).'k';
  731. } else {
  732. $file_size = $file_size.'B';
  733. }
  734. return $file_size;
  735. }
  736. function return_datetime_from_array($array)
  737. {
  738. $year = '0000';
  739. $month = $day = $hours = $minutes = $seconds = '00';
  740. if (isset($array['Y']) && (isset($array['F']) || isset($array['M'])) && isset($array['d']) && isset($array['H']) && isset($array['i'])) {
  741. $year = $array['Y'];
  742. $month = isset($array['F']) ? $array['F'] : $array['M'];
  743. if (intval($month) < 10) $month = '0'.$month;
  744. $day = $array['d'];
  745. if (intval($day) < 10) $day = '0'.$day;
  746. $hours = $array['H'];
  747. if (intval($hours) < 10) $hours = '0'.$hours;
  748. $minutes = $array['i'];
  749. if (intval($minutes) < 10) $minutes = '0'.$minutes;
  750. }
  751. if (checkdate($month, $day, $year)) {
  752. $datetime = $year.'-'.$month.'-'.$day.' '.$hours.':'.$minutes.':'.$seconds;
  753. }
  754. return $datetime;
  755. }
  756. /**
  757. * Converts an string CLEANYO[admin][amann,acostea]
  758. * into an array:
  759. *
  760. * array(
  761. * CLEANYO
  762. * admin
  763. * amann,acostea
  764. * )
  765. *
  766. * @param $array
  767. * @return array
  768. */
  769. function bracketsToArray($array)
  770. {
  771. return preg_split('/[\[\]]+/', $array, -1, PREG_SPLIT_NO_EMPTY);
  772. }
  773. /**
  774. * @param string $string
  775. * @param bool $capitalizeFirstCharacter
  776. * @return mixed
  777. */
  778. function underScoreToCamelCase($string, $capitalizeFirstCharacter = true)
  779. {
  780. $str = str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
  781. if (!$capitalizeFirstCharacter) {
  782. $str[0] = strtolower($str[0]);
  783. }
  784. return $str;
  785. }
  786. /**
  787. * @param string $value
  788. */
  789. function trim_value(& $value)
  790. {
  791. $value = trim($value);
  792. }