text.lib.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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. // These purifications have been found experimentally, for nice looking output.
  19. $string = preg_replace('/<br[^>]*>/i', "\n", $string);
  20. $string = preg_replace('/<\/?(div|p|h[1-6]|table|ol|ul|blockquote)[^>]*>/i', "\n", $string);
  21. $string = preg_replace('/<\/(tr|li)[^>]*>/i', "\n", $string);
  22. $string = preg_replace('/<\/(td|th)[^>]*>/i', "\t", $string);
  23. $string = strip_tags($string);
  24. // Line endings unification and cleaning.
  25. $string = str_replace(array("\r\n", "\n\r", "\r"), "\n", $string);
  26. $string = preg_replace('/\s*\n/', "\n", $string);
  27. $string = preg_replace('/\n+/', "\n", $string);
  28. return trim($string);
  29. }
  30. /**
  31. * Detects encoding of html-formatted text.
  32. * @param string $string The input html-formatted text.
  33. * @return string Returns the detected encoding.
  34. */
  35. function api_detect_encoding_html($string) {
  36. if (@preg_match('/<head.*(<meta[^>]*content=[^>]*>).*<\/head>/si', $string, $matches)) {
  37. if (@preg_match('/<meta[^>]*charset=(.*)["\';][^>]*>/si', $matches[1], $matches)) {
  38. return api_refine_encoding_id(trim($matches[1]));
  39. }
  40. }
  41. return api_detect_encoding(api_html_to_text($string));
  42. }
  43. /**
  44. * Converts the text of a html-document to a given encoding, the meta-tag is changed accordingly.
  45. * @param string $string The input full-html document.
  46. * @param string The new encoding value to be set.
  47. */
  48. function api_set_encoding_html(&$string, $encoding) {
  49. $old_encoding = api_detect_encoding_html($string);
  50. if (@preg_match('/(.*<head.*)(<meta[^>]*content=[^>]*>)(.*<\/head>.*)/si', $string, $matches)) {
  51. $meta = $matches[2];
  52. if (@preg_match("/(<meta[^>]*charset=)(.*)([\"';][^>]*>)/si", $meta, $matches1)) {
  53. $meta = $matches1[1] . $encoding . $matches1[3];
  54. $string = $matches[1] . $meta . $matches[3];
  55. } else {
  56. $string = $matches[1] . '<meta http-equiv="Content-Type" content="text/html; charset='.$encoding.'"/>' . $matches[3];
  57. }
  58. } else {
  59. $count = 1;
  60. $string = str_ireplace('</head>', '<meta http-equiv="Content-Type" content="text/html; charset='.$encoding.'"/></head>', $string, $count);
  61. }
  62. $string = api_convert_encoding($string, $encoding, $old_encoding);
  63. }
  64. /**
  65. * Returns the title of a html document.
  66. * @param string $string The contents of the input document.
  67. * @param string $input_encoding The encoding of the input document. If the value is not set, it is detected.
  68. * @param string $$output_encoding The encoding of the retrieved title. If the value is not set, the system encoding is assumend.
  69. * @return string The retrieved title, html-entities and extra-whitespace between the words are cleaned.
  70. */
  71. function api_get_title_html(&$string, $output_encoding = null, $input_encoding = null) {
  72. if (@preg_match('/<head.+<title[^>]*>(.*)<\/title>/msi', $string, $matches)) {
  73. if (empty($output_encoding)) {
  74. $output_encoding = api_get_system_encoding();
  75. }
  76. if (empty($input_encoding)) {
  77. $input_encoding = api_detect_encoding_html($string);
  78. }
  79. return trim(@preg_replace('/\s+/', ' ', api_html_entity_decode(api_convert_encoding($matches[1], $output_encoding, $input_encoding), ENT_QUOTES, $output_encoding)));
  80. }
  81. return '';
  82. }
  83. /* XML processing functions */
  84. // A regular expression for accessing declared encoding within xml-formatted text.
  85. // Published by Steve Minutillo,
  86. // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss/
  87. define('_PCRE_XML_ENCODING', '/<\?xml.*encoding=[\'"](.*?)[\'"].*\?>/m');
  88. /**
  89. * Detects encoding of xml-formatted text.
  90. * @param string $string The input xml-formatted text.
  91. * @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.
  92. * @return string Returns the detected encoding.
  93. * @todo The second parameter is to be eliminated. See api_detect_encoding_html().
  94. */
  95. function api_detect_encoding_xml($string, $default_encoding = null) {
  96. if (preg_match(_PCRE_XML_ENCODING, $string, $matches)) {
  97. return api_refine_encoding_id($matches[1]);
  98. }
  99. if (api_is_valid_utf8($string)) {
  100. return 'UTF-8';
  101. }
  102. if (empty($default_encoding)) {
  103. $default_encoding = _api_mb_internal_encoding();
  104. }
  105. return api_refine_encoding_id($default_encoding);
  106. }
  107. /**
  108. * Converts character encoding of a xml-formatted text. If inside the text the encoding is declared, it is modified accordingly.
  109. * @param string $string The text being converted.
  110. * @param string $to_encoding The encoding that text is being converted to.
  111. * @param string $from_encoding (optional) The encoding that text is being converted from. If it is omited, it is tried to be detected then.
  112. * @return string Returns the converted xml-text.
  113. */
  114. function api_convert_encoding_xml($string, $to_encoding, $from_encoding = null) {
  115. return _api_convert_encoding_xml($string, $to_encoding, $from_encoding);
  116. }
  117. /**
  118. * 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.
  119. * @param string $string The text being converted.
  120. * @param string $from_encoding (optional) The encoding that text is being converted from. If it is omited, it is tried to be detected then.
  121. * @return string Returns the converted xml-text.
  122. */
  123. function api_utf8_encode_xml($string, $from_encoding = null) {
  124. return _api_convert_encoding_xml($string, 'UTF-8', $from_encoding);
  125. }
  126. /**
  127. * 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.
  128. * @param string $string The text being converted.
  129. * @param string $to_encoding (optional) The encoding that text is being converted to. If it is omited, the platform character set is assumed.
  130. * @return string Returns the converted xml-text.
  131. */
  132. function api_utf8_decode_xml($string, $to_encoding = null) {
  133. if (empty($to_encoding)) {
  134. $to_encoding = _api_mb_internal_encoding();
  135. }
  136. return _api_convert_encoding_xml($string, $to_encoding, 'UTF-8');
  137. }
  138. /**
  139. * Converts character encoding of a xml-formatted text. If inside the text the encoding is declared, it is modified accordingly.
  140. * @param string $string The text being converted.
  141. * @param string $to_encoding The encoding that text is being converted to.
  142. * @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.
  143. * @return string Returns the converted xml-text.
  144. */
  145. function _api_convert_encoding_xml(&$string, $to_encoding, $from_encoding) {
  146. if (empty($from_encoding)) {
  147. $from_encoding = api_detect_encoding_xml($string);
  148. }
  149. $to_encoding = api_refine_encoding_id($to_encoding);
  150. if (!preg_match('/<\?xml.*\?>/m', $string, $matches)) {
  151. return api_convert_encoding('<?xml version="1.0" encoding="'.$to_encoding.'"?>'."\n".$string, $to_encoding, $from_encoding);
  152. }
  153. if (!preg_match(_PCRE_XML_ENCODING, $string)) {
  154. if (strpos($matches[0], 'standalone') !== false) {
  155. // The encoding option should precede the standalone option, othewise DOMDocument fails to load the document.
  156. $replace = str_replace('standalone', ' encoding="'.$to_encoding.'" standalone' , $matches[0]);
  157. } else {
  158. $replace = str_replace('?>', ' encoding="'.$to_encoding.'"?>' , $matches[0]);
  159. }
  160. return api_convert_encoding(str_replace($matches[0], $replace, $string), $to_encoding, $from_encoding);
  161. }
  162. global $_api_encoding;
  163. $_api_encoding = api_refine_encoding_id($to_encoding);
  164. return api_convert_encoding(preg_replace_callback(_PCRE_XML_ENCODING, '_api_convert_encoding_xml_callback', $string), $to_encoding, $from_encoding);
  165. }
  166. /**
  167. * A callback for serving the function _api_convert_encoding_xml().
  168. * @param array $matches Input array of matches corresponding to the xml-declaration.
  169. * @return string Returns the xml-declaration with modified encoding.
  170. */
  171. function _api_convert_encoding_xml_callback($matches) {
  172. global $_api_encoding;
  173. return str_replace($matches[1], $_api_encoding, $matches[0]);
  174. }
  175. /* CSV processing functions */
  176. /**
  177. * Parses CSV data (one line) into an array. This function is not affected by the OS-locale settings.
  178. * @param string $string The input string.
  179. * @param string $delimiter (optional) The field delimiter, one character only. The default delimiter character is comma {,).
  180. * @param string $enclosure (optional) The field enclosure, one character only. The default enclosure character is quote (").
  181. * @param string $escape (optional) The escape character, one character only. The default escape character is backslash (\).
  182. * @return array Returns an array containing the fields read.
  183. * Note: In order this function to work correctly with UTF-8, limitation for the parameters $delimiter, $enclosure and $escape
  184. * should be kept. These parameters should be single ASCII characters only. Thus the implementation of this function is faster.
  185. * @link http://php.net/manual/en/function.str-getcsv.php (exists as of PHP 5 >= 5.3.0)
  186. */
  187. function & api_str_getcsv(& $string, $delimiter = ',', $enclosure = '"', $escape = '\\') {
  188. $delimiter = (string)$delimiter;
  189. if (api_byte_count($delimiter) > 1) { $delimiter = $delimiter[1]; }
  190. $enclosure = (string)$enclosure;
  191. if (api_byte_count($enclosure) > 1) { $enclosure = $enclosure[1]; }
  192. $escape = (string)$escape;
  193. if (api_byte_count($escape) > 1) { $escape = $escape[1]; }
  194. $str = (string)$string;
  195. $len = api_byte_count($str);
  196. $enclosed = false;
  197. $escaped = false;
  198. $value = '';
  199. $result = array();
  200. for ($i = 0; $i < $len; $i++) {
  201. $char = $str[$i];
  202. if ($char == $escape) {
  203. if (!$escaped) {
  204. $escaped = true;
  205. continue;
  206. }
  207. }
  208. $escaped = false;
  209. switch ($char) {
  210. case $enclosure:
  211. if ($enclosed && $str[$i + 1] == $enclosure) {
  212. $value .= $char;
  213. $i++;
  214. } else {
  215. $enclosed = !$enclosed;
  216. }
  217. break;
  218. case $delimiter:
  219. if (!$enclosed) {
  220. $result[] = $value;
  221. $value = '';
  222. } else {
  223. $value .= $char;
  224. }
  225. break;
  226. default:
  227. $value .= $char;
  228. break;
  229. }
  230. }
  231. if (!empty($value)) {
  232. $result[] = $value;
  233. }
  234. return $result;
  235. }
  236. /**
  237. * Reads a line from a file pointer and parses it for CSV fields. This function is not affected by the OS-locale settings.
  238. * @param resource $handle The file pointer, it must be valid and must point to a file successfully opened by fopen().
  239. * @param int $length (optional) Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first).
  240. * If no length is specified, it will keep reading from the stream until it reaches the end of the line.
  241. * @param string $delimiter (optional) The field delimiter, one character only. The default delimiter character is comma {,).
  242. * @param string $enclosure (optional) The field enclosure, one character only. The default enclosure character is quote (").
  243. * @param string $escape (optional) The escape character, one character only. The default escape character is backslash (\).
  244. * @return array Returns an array containing the fields read.
  245. * Note: In order this function to work correctly with UTF-8, limitation for the parameters $delimiter, $enclosure and $escape
  246. * should be kept. These parameters should be single ASCII characters only.
  247. * @link http://php.net/manual/en/function.fgetcsv.php
  248. */
  249. function api_fgetcsv($handle, $length = null, $delimiter = ',', $enclosure = '"', $escape = '\\') {
  250. if (($line = is_null($length) ? fgets($handle): fgets($handle, $length)) !== false) {
  251. $line = rtrim($line, "\r\n");
  252. return api_str_getcsv($line, $delimiter, $enclosure, $escape);
  253. }
  254. return false;
  255. }
  256. /* Functions for supporting ASCIIMathML mathematical formulas and ASCIIsvg maathematical graphics */
  257. /**
  258. * Dectects ASCIIMathML formula presence within a given html text.
  259. * @param string $html The input html text.
  260. * @return bool Returns TRUE when there is a formula found or FALSE otherwise.
  261. */
  262. function api_contains_asciimathml($html) {
  263. if (!preg_match_all('/<span[^>]*class\s*=\s*[\'"](.*?)[\'"][^>]*>/mi', $html, $matches)) {
  264. return false;
  265. }
  266. foreach ($matches[1] as $string) {
  267. $string = ' '.str_replace(',', ' ', $string).' ';
  268. if (preg_match('/\sAM\s/m', $string)) {
  269. return true;
  270. }
  271. }
  272. return false;
  273. }
  274. /**
  275. * Dectects ASCIIsvg graphics presence within a given html text.
  276. * @param string $html The input html text.
  277. * @return bool Returns TRUE when there is a graph found or FALSE otherwise.
  278. */
  279. function api_contains_asciisvg($html) {
  280. if (!preg_match_all('/<embed([^>]*?)>/mi', $html, $matches)) {
  281. return false;
  282. }
  283. foreach ($matches[1] as $string) {
  284. $string = ' '.str_replace(',', ' ', $string).' ';
  285. if (preg_match('/sscr\s*=\s*[\'"](.*?)[\'"]/m', $string)) {
  286. return true;
  287. }
  288. }
  289. return false;
  290. }
  291. /* Miscellaneous text processing functions */
  292. /**
  293. * Convers a string from camel case into underscore.
  294. * Works correctly with ASCII strings only, implementation for human-language strings is not necessary.
  295. * @param string $string The input string (ASCII)
  296. * @return string The converted result string
  297. */
  298. function api_camel_case_to_underscore($string) {
  299. return strtolower(preg_replace('/([a-z])([A-Z])/', "$1_$2", $string));
  300. }
  301. /**
  302. * Converts a string with underscores into camel case.
  303. * Works correctly with ASCII strings only, implementation for human-language strings is not necessary.
  304. * @param string $string The input string (ASCII)
  305. * @param bool $capitalise_first_char (optional) If true (default), the function capitalises the first char in the result string.
  306. * @return string The converted result string
  307. */
  308. function api_underscore_to_camel_case($string, $capitalise_first_char = true) {
  309. if ($capitalise_first_char) {
  310. $string = ucfirst($string);
  311. }
  312. return preg_replace_callback('/_([a-z])/', '_api_camelize', $string);
  313. }
  314. // A function for internal use, only for this library.
  315. function _api_camelize($match) {
  316. return strtoupper($match[1]);
  317. }
  318. /**
  319. * Truncates a string.
  320. *
  321. * @author Brouckaert Olivier
  322. * @param string $text The text to truncate.
  323. * @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.
  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, the platform character set will be used by default.
  326. * @param boolean $middle If this parameter is true, truncation is done in the middle of the string.
  327. * @return string Truncated string, decorated with the given suffix (replacement).
  328. */
  329. function api_trunc_str($text, $length = 30, $suffix = '...', $middle = false, $encoding = null) {
  330. if (empty($encoding)) {
  331. $encoding = api_get_system_encoding();
  332. }
  333. $text_length = api_strlen($text, $encoding);
  334. if ($text_length <= $length) {
  335. return $text;
  336. }
  337. if ($middle) {
  338. return rtrim(api_substr($text, 0, round($length / 2), $encoding)).$suffix.ltrim(api_substr($text, - round($length / 2), $text_length, $encoding));
  339. }
  340. return rtrim(api_substr($text, 0, $length, $encoding)).$suffix;
  341. }
  342. /**
  343. * Handling simple and double apostrofe in order that strings be stored properly in database
  344. *
  345. * @author Denes Nagy
  346. * @param string variable - the variable to be revised
  347. */
  348. function domesticate($input) {
  349. $input = stripslashes($input);
  350. $input = str_replace("'", "''", $input);
  351. $input = str_replace('"', "''", $input);
  352. return ($input);
  353. }
  354. /**
  355. * function make_clickable($string)
  356. *
  357. * @desc Completes url contained in the text with "<a href ...".
  358. * However the function simply returns the submitted text without any
  359. * transformation if it already contains some "<a href:" or "<img src=".
  360. * @param string $text text to be converted
  361. * @return text after conversion
  362. * @author Rewritten by Nathan Codding - Feb 6, 2001.
  363. * completed by Hugues Peeters - July 22, 2002
  364. *
  365. * Actually this function is taken from the PHP BB 1.4 script
  366. * - Goes through the given string, and replaces xxxx://yyyy with an HTML <a> tag linking
  367. * to that URL
  368. * - Goes through the given string, and replaces www.xxxx.yyyy[zzzz] with an HTML <a> tag linking
  369. * to http://www.xxxx.yyyy[/zzzz]
  370. * - Goes through the given string, and replaces xxxx@yyyy with an HTML mailto: tag linking
  371. * to that email address
  372. * - Only matches these 2 patterns either after a space, or at the beginning of a line
  373. *
  374. * Notes: the email one might get annoying - it's easy to make it more restrictive, though.. maybe
  375. * have it require something like xxxx@yyyy.zzzz or such. We'll see.
  376. */
  377. function make_clickable($string) {
  378. // TODO: eregi_replace() is deprecated as of PHP 5.3
  379. if (!stristr($string, ' src=') && !stristr($string, ' href=')) {
  380. $string = eregi_replace("(https?|ftp)://([a-z0-9#?/&=._+:~%-]+)", "<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>", $string);
  381. $string = eregi_replace("([a-z0-9_.-]+@[a-z0-9.-]+)", "<a href=\"mailto:\\1\">\\1</a>", $string);
  382. }
  383. return $string;
  384. }
  385. /**
  386. * @desc This function does some parsing on the text that gets inputted. This parsing can be of any kind
  387. * LaTeX notation, Word Censoring, Glossary Terminology (extension will available soon), Musical Notations, ...
  388. * The inspiration for this filter function came from Moodle an phpBB who both use a similar approach.
  389. * <code>[tex]\sqrt(2)[/tex]</code>
  390. * @param $input string. some text
  391. * @return $output string. some text that contains the parsed elements.
  392. * @author Patrick Cool <patrick.cool@UGent.be>
  393. * @version March 2OO6
  394. */
  395. function text_filter($input, $filter = true) {
  396. //$input = stripslashes($input);
  397. if ($filter) {
  398. // *** parse [tex]...[/tex] tags *** //
  399. // which will return techexplorer or image html depending on the capabilities of the
  400. // browser of the user (using some javascript that checks if the browser has the TechExplorer plugin installed or not)
  401. //$input = _text_parse_tex($input);
  402. // *** parse [teximage]...[/teximage] tags *** //
  403. // these force the gif rendering of LaTeX using the mimetex gif renderer
  404. //$input=_text_parse_tex_image($input);
  405. // *** parse [texexplorer]...[/texexplorer] tags *** //
  406. // these force the texeplorer LaTeX notation
  407. //$input = _text_parse_texexplorer($input);
  408. // *** Censor Words *** //
  409. // censor words. This function removes certain words by [censored]
  410. // this can be usefull when the campus is open to the world.
  411. // $input=text_censor_words($input);
  412. // *** parse [?]...[/?] tags *** //
  413. // for the glossary tool
  414. //$input = _text_parse_glossary($input);
  415. // parse [wiki]...[/wiki] tags
  416. // this is for the coolwiki plugin.
  417. // $input=text_parse_wiki($input);
  418. // parse [tool]...[/tool] tags
  419. // this parse function adds a link to a certain tool
  420. // $input=text_parse_tool($input);
  421. // parse [user]...[/user] tags
  422. // parse [email]...[/email] tags
  423. // parse [code]...[/code] tags
  424. }
  425. return $input;
  426. }
  427. /**
  428. * Applies parsing for tex commands that are separated by [tex]
  429. * [/tex] to make it readable for techexplorer plugin.
  430. * This function should not be accessed directly but should be accesse through the text_filter function
  431. * @param string $text The text to parse
  432. * @return string The text after parsing.
  433. * @author Patrick Cool <patrick.cool@UGent.be>
  434. * @version June 2004
  435. */
  436. function _text_parse_tex($textext) {
  437. //$textext = str_replace(array ("[tex]", "[/tex]"), array ('[*****]', '[/*****]'), $textext);
  438. //$textext = stripslashes($texttext);
  439. $input_array = preg_split("/(\[tex]|\[\/tex])/", $textext, -1, PREG_SPLIT_DELIM_CAPTURE);
  440. foreach ($input_array as $key => $value) {
  441. if ($key > 0 && $input_array[$key - 1] == '[tex]' AND $input_array[$key + 1] == '[/tex]') {
  442. $input_array[$key] = latex_gif_renderer($value);
  443. unset($input_array[$key - 1]);
  444. unset($input_array[$key + 1]);
  445. //echo 'LaTeX: <embed type="application/x-techexplorer" texdata="'.stripslashes($value).'" autosize="true" pluginspage="http://www.integretechpub.com/techexplorer/"><br />';
  446. }
  447. }
  448. $output = implode('',$input_array);
  449. return $output;
  450. }
  451. /**
  452. * This function should not be accessed directly but should be accesse through the text_filter function
  453. * @author Patrick Cool <patrick.cool@UGent.be>
  454. */
  455. function _text_parse_glossary($input) {
  456. return $input;
  457. }
  458. /**
  459. * @desc This function makes a valid link to a different tool.
  460. * This function should not be accessed directly but should be accesse through the text_filter function
  461. * @author Patrick Cool <patrick.cool@UGent.be>
  462. */
  463. function _text_parse_tool($input) {
  464. // An array with all the valid tools
  465. $tools[] = array(TOOL_ANNOUNCEMENT, 'announcements/announcements.php');
  466. $tools[] = array(TOOL_CALENDAR_EVENT, 'calendar/agenda.php');
  467. // Check if the name between the [tool] [/tool] tags is a valid one
  468. }
  469. /**
  470. * Renders LaTeX code into a gif or retrieve a cached version of the gif.
  471. * @author Patrick Cool <patrick.cool@UGent.be> Ghent University
  472. */
  473. function latex_gif_renderer($latex_code) {
  474. global $_course;
  475. // Setting the paths and filenames
  476. $mimetex_path = api_get_path(LIBRARY_PATH).'mimetex/';
  477. $temp_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp/';
  478. $latex_filename = md5($latex_code).'.gif';
  479. if (!file_exists($temp_path.$latex_filename) OR isset($_GET['render'])) {
  480. if (IS_WINDOWS_OS) {
  481. $mimetex_command = $mimetex_path.'mimetex.exe -e "'.$temp_path.md5($latex_code).'.gif" '.escapeshellarg($latex_code).'';
  482. } else {
  483. $mimetex_command = $mimetex_path.'mimetex.cgi -e "'.$temp_path.md5($latex_code).'.gif" '.escapeshellarg($latex_code);
  484. }
  485. exec($mimetex_command);
  486. //echo 'volgende shell commando werd uitgevoerd:<br /><pre>'.$mimetex_command.'</pre><hr>';
  487. }
  488. $return = "<a href=\"\" onclick=\"javascript: newWindow=window.open('".api_get_path(WEB_CODE_PATH)."inc/latex.php?code=".urlencode($latex_code)."&amp;filename=$latex_filename','latexCode','toolbar=no,location=no,scrollbars=yes,resizable=yes,status=yes,width=375,height=250,left=200,top=100');\">";
  489. $return .= '<img src="'.api_get_path(WEB_COURSE_PATH).$_course['path'].'/temp/'.$latex_filename.'" alt="'.$latex_code.'" border="0" /></a>';
  490. return $return;
  491. }
  492. /**
  493. * This functions cuts a paragraph
  494. * i.e cut('Merry Xmas from Lima',13) = "Merry Xmas fr..."
  495. * @param string The text to "cut"
  496. * @param int Count of chars
  497. * @param bool Whether to embed in a <span title="...">...</span>
  498. * @return string
  499. * */
  500. function cut($text, $maxchar, $embed = false) {
  501. if (api_strlen($text) > $maxchar) {
  502. if ($embed) {
  503. return '<span title="'.$text.'">'.api_substr($text, 0, $maxchar).'...</span>';
  504. }
  505. return api_substr($text, 0, $maxchar).' ...';
  506. }
  507. return $text;
  508. }
  509. /**
  510. * Show a number as only integers if no decimals, but will show 2 decimals if exist.
  511. *
  512. * @param mixed Number to convert
  513. * @param int Decimal points 0=never, 1=if needed, 2=always
  514. * @return mixed An integer or a float depends on the parameter
  515. */
  516. function float_format($number, $flag = 1) {
  517. if (is_numeric($number)) {
  518. if (!$number) {
  519. $result = ($flag == 2 ? '0.'.str_repeat('0', EXERCISE_NUMBER_OF_DECIMALS) : '0');
  520. } else {
  521. if (floor($number) == $number) {
  522. $result = number_format($number, ($flag == 2 ? EXERCISE_NUMBER_OF_DECIMALS : 0));
  523. } else {
  524. $result = number_format(round($number, 2), ($flag == 0 ? 0 : EXERCISE_NUMBER_OF_DECIMALS));
  525. }
  526. }
  527. return $result;
  528. }
  529. }
  530. // TODO: To be checked for correct timezone management.
  531. /**
  532. * Function to obtain last week timestamps
  533. * @return array Times for every day inside week
  534. */
  535. function get_last_week() {
  536. $week = date('W');
  537. $year = date('Y');
  538. $lastweek = $week - 1;
  539. if ($lastweek == 0) {
  540. $week = 52;
  541. $year--;
  542. }
  543. $lastweek = sprintf("%02d", $lastweek);
  544. $arrdays = array();
  545. for ($i = 1; $i <= 7; $i++) {
  546. $arrdays[] = strtotime("$year"."W$lastweek"."$i");
  547. }
  548. return $arrdays;
  549. }
  550. /**
  551. * Gets the week from a day
  552. * @param string Date in UTC (2010-01-01 12:12:12)
  553. * @return int Returns an integer with the week number of the year
  554. */
  555. function get_week_from_day($date) {
  556. if (!empty($date)) {
  557. $time = api_strtotime($date,'UTC');
  558. return date('W', $time);
  559. } else {
  560. return date('W');
  561. }
  562. }
  563. /**
  564. * Deprecated functions
  565. */
  566. /**
  567. * Applies parsing the content for tex commands that are separated by [tex]
  568. * [/tex] to make it readable for techexplorer plugin.
  569. * @param string $text The text to parse
  570. * @return string The text after parsing.
  571. * @author Patrick Cool <patrick.cool@UGent.be>
  572. * @version June 2004
  573. */
  574. function api_parse_tex($textext) {
  575. /*
  576. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) {
  577. return str_replace(array('[tex]', '[/tex]'), array("<object classid=\"clsid:5AFAB315-AD87-11D3-98BB-002035EFB1A4\"><param name=\"autosize\" value=\"true\" /><param name=\"DataType\" value=\"0\" /><param name=\"Data\" value=\"", "\" /></object>"), $textext);
  578. }
  579. return str_replace(array('[tex]', '[/tex]'), array("<embed type=\"application/x-techexplorer\" texdata=\"", "\" autosize=\"true\" pluginspage=\"http://www.integretechpub.com/techexplorer/\">"), $textext);
  580. */
  581. return $textext;
  582. }
  583. /**
  584. * Applies parsing for tex commandos that are seperated by [tex]
  585. * [/tex] to make it readable for techexplorer plugin.
  586. * This function should not be accessed directly but should be accesse through the text_filter function
  587. * @param string $text The text to parse
  588. * @return string The text after parsing.
  589. * @author Patrick Cool <patrick.cool@UGent.be>
  590. * @version June 2004
  591. */
  592. function _text_parse_texexplorer($textext) {
  593. /*
  594. if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
  595. $textext = str_replace(array("[texexplorer]", "[/texexplorer]"), array("<object classid=\"clsid:5AFAB315-AD87-11D3-98BB-002035EFB1A4\"><param name=\"autosize\" value=\"true\" /><param name=\"DataType\" value=\"0\" /><param name=\"Data\" value=\"", "\" /></object>"), $textext);
  596. } else {
  597. $textext = str_replace(array("[texexplorer]", "[/texexplorer]"), array("<embed type=\"application/x-techexplorer\" texdata=\"", "\" autosize=\"true\" pluginspage=\"http://www.integretechpub.com/techexplorer/\">"), $textext);
  598. }
  599. return $textext;
  600. */
  601. return $textext;
  602. }
  603. /**
  604. * This function splits the string into words and then joins them back together again one by one.
  605. * Example: "Test example of a long string"
  606. * substrwords(5) = Test ... *
  607. * @param string
  608. * @param int the max number of character
  609. * @param string how the string will be end
  610. * @return a reduce string
  611. */
  612. function substrwords($text,$maxchar,$end='...')
  613. {
  614. if(strlen($text)>$maxchar)
  615. {
  616. $words=explode(" ",$text);
  617. $output = '';
  618. $i=0;
  619. while(1)
  620. {
  621. $length = (strlen($output)+strlen($words[$i]));
  622. if($length>$maxchar)
  623. {
  624. break;
  625. }
  626. else
  627. {
  628. $output = $output." ".$words[$i];
  629. $i++;
  630. };
  631. };
  632. }
  633. else
  634. {
  635. $output = $text;
  636. return $output;
  637. }
  638. return $output.$end;
  639. }
  640. function implode_with_key($glue, $array) {
  641. if (!empty($array)) {
  642. $string = '';
  643. foreach($array as $key => $value) {
  644. if (empty($value)) {
  645. $value = 'null';
  646. }
  647. $string .= $key." : ".$value." $glue ";
  648. }
  649. return $string;
  650. }
  651. return '';
  652. }
  653. /**
  654. * Transform the file size in a human readable format.
  655. *
  656. * @param int Size of the file in bytes
  657. * @return string A human readable representation of the file size
  658. */
  659. function format_file_size($file_size) {
  660. $file_size = intval($file_size);
  661. if($file_size >= 1073741824) {
  662. $file_size = round($file_size / 1073741824 * 100) / 100 . 'G';
  663. } elseif($file_size >= 1048576) {
  664. $file_size = round($file_size / 1048576 * 100) / 100 . 'M';
  665. } elseif($file_size >= 1024) {
  666. $file_size = round($file_size / 1024 * 100) / 100 . 'k';
  667. } else {
  668. $file_size = $file_size . 'B';
  669. }
  670. return $file_size;
  671. }
  672. function return_datetime_from_array($array) {
  673. $year = '0000';
  674. $month = $day = $hours = $minutes = $seconds = '00';
  675. if (isset($array['Y']) && (isset($array['F']) || isset($array['M'])) && isset($array['d']) && isset($array['H']) && isset($array['i'])) {
  676. $year = $array['Y'];
  677. $month = isset($array['F'])?$array['F']:$array['M'];
  678. if (intval($month) < 10 ) $month = '0'.$month;
  679. $day = $array['d'];
  680. if (intval($day) < 10 ) $day = '0'.$day;
  681. $hours = $array['H'];
  682. if (intval($hours) < 10 ) $hours = '0'.$hours;
  683. $minutes = $array['i'];
  684. if (intval($minutes) < 10 ) $minutes = '0'.$minutes;
  685. }
  686. if (checkdate($month,$day,$year)) {
  687. $datetime = $year.'-'.$month.'-'.$day.' '.$hours.':'.$minutes.':'.$seconds;
  688. }
  689. return $datetime;
  690. }
  691. /**
  692. * Converts an string CLEANYO[admin][amann,acostea]
  693. * into an array:
  694. *
  695. * array(
  696. * CLEANYO
  697. * admin
  698. * amann,acostea
  699. * )
  700. *
  701. * @param $array
  702. * @return array
  703. */
  704. function bracketsToArray($array)
  705. {
  706. return preg_split('/[\[\]]+/', $array, -1, PREG_SPLIT_NO_EMPTY);
  707. }