text.lib.php 32 KB

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