text.lib.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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) {
  190. $delimiter = $delimiter[1];
  191. }
  192. $enclosure = (string) $enclosure;
  193. if (api_byte_count($enclosure) > 1) {
  194. $enclosure = $enclosure[1];
  195. }
  196. $escape = (string) $escape;
  197. if (api_byte_count($escape) > 1) {
  198. $escape = $escape[1];
  199. }
  200. $str = (string) $string;
  201. $len = api_byte_count($str);
  202. $enclosed = false;
  203. $escaped = false;
  204. $value = '';
  205. $result = array();
  206. for ($i = 0; $i < $len; $i++) {
  207. $char = $str[$i];
  208. if ($char == $escape) {
  209. if (!$escaped) {
  210. $escaped = true;
  211. continue;
  212. }
  213. }
  214. $escaped = false;
  215. switch ($char) {
  216. case $enclosure:
  217. if ($enclosed && $str[$i + 1] == $enclosure) {
  218. $value .= $char;
  219. $i++;
  220. } else {
  221. $enclosed = !$enclosed;
  222. }
  223. break;
  224. case $delimiter:
  225. if (!$enclosed) {
  226. $result[] = $value;
  227. $value = '';
  228. } else {
  229. $value .= $char;
  230. }
  231. break;
  232. default:
  233. $value .= $char;
  234. break;
  235. }
  236. }
  237. if (!empty($value)) {
  238. $result[] = $value;
  239. }
  240. return $result;
  241. }
  242. /**
  243. * Reads a line from a file pointer and parses it for CSV fields. This function is not affected by the OS-locale settings.
  244. * @param resource $handle The file pointer, it must be valid and must point to a file successfully opened by fopen().
  245. * @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).
  246. * If no length is specified, it will keep reading from the stream until it reaches the end of the line.
  247. * @param string $delimiter (optional) The field delimiter, one character only. The default delimiter character is comma {,).
  248. * @param string $enclosure (optional) The field enclosure, one character only. The default enclosure character is quote (").
  249. * @param string $escape (optional) The escape character, one character only. The default escape character is backslash (\).
  250. * @return array Returns an array containing the fields read.
  251. * Note: In order this function to work correctly with UTF-8, limitation for the parameters $delimiter, $enclosure and $escape
  252. * should be kept. These parameters should be single ASCII characters only.
  253. * @link http://php.net/manual/en/function.fgetcsv.php
  254. */
  255. function api_fgetcsv($handle, $length = null, $delimiter = ',', $enclosure = '"', $escape = '\\') {
  256. if (($line = is_null($length) ? fgets($handle) : fgets($handle, $length)) !== false) {
  257. $line = rtrim($line, "\r\n");
  258. return api_str_getcsv($line, $delimiter, $enclosure, $escape);
  259. }
  260. return false;
  261. }
  262. /* Functions for supporting ASCIIMathML mathematical formulas and ASCIIsvg maathematical graphics */
  263. /**
  264. * Dectects ASCIIMathML formula presence within a given html text.
  265. * @param string $html The input html text.
  266. * @return bool Returns TRUE when there is a formula found or FALSE otherwise.
  267. */
  268. function api_contains_asciimathml($html) {
  269. if (!preg_match_all('/<span[^>]*class\s*=\s*[\'"](.*?)[\'"][^>]*>/mi', $html, $matches)) {
  270. return false;
  271. }
  272. foreach ($matches[1] as $string) {
  273. $string = ' ' . str_replace(',', ' ', $string) . ' ';
  274. if (preg_match('/\sAM\s/m', $string)) {
  275. return true;
  276. }
  277. }
  278. return false;
  279. }
  280. /**
  281. * Dectects ASCIIsvg graphics presence within a given html text.
  282. * @param string $html The input html text.
  283. * @return bool Returns TRUE when there is a graph found or FALSE otherwise.
  284. */
  285. function api_contains_asciisvg($html) {
  286. if (!preg_match_all('/<embed([^>]*?)>/mi', $html, $matches)) {
  287. return false;
  288. }
  289. foreach ($matches[1] as $string) {
  290. $string = ' ' . str_replace(',', ' ', $string) . ' ';
  291. if (preg_match('/sscr\s*=\s*[\'"](.*?)[\'"]/m', $string)) {
  292. return true;
  293. }
  294. }
  295. return false;
  296. }
  297. /* Miscellaneous text processing functions */
  298. /**
  299. * Convers a string from camel case into underscore.
  300. * Works correctly with ASCII strings only, implementation for human-language strings is not necessary.
  301. * @param string $string The input string (ASCII)
  302. * @return string The converted result string
  303. */
  304. function api_camel_case_to_underscore($string) {
  305. return strtolower(preg_replace('/([a-z])([A-Z])/', "$1_$2", $string));
  306. }
  307. /**
  308. * Converts a string with underscores into camel case.
  309. * Works correctly with ASCII strings only, implementation for human-language strings is not necessary.
  310. * @param string $string The input string (ASCII)
  311. * @param bool $capitalise_first_char (optional) If true (default), the function capitalises the first char in the result string.
  312. * @return string The converted result string
  313. */
  314. function api_underscore_to_camel_case($string, $capitalise_first_char = true) {
  315. if ($capitalise_first_char) {
  316. $string = ucfirst($string);
  317. }
  318. return preg_replace_callback('/_([a-z])/', '_api_camelize', $string);
  319. }
  320. // A function for internal use, only for this library.
  321. function _api_camelize($match) {
  322. return strtoupper($match[1]);
  323. }
  324. /**
  325. * Truncates a string.
  326. *
  327. * @author Brouckaert Olivier
  328. * @param string $text The text to truncate.
  329. * @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.
  330. * @param string $suffix A suffix to be added as a replacement.
  331. * @param string $encoding (optional) The encoding to be used. If it is omitted, the platform character set will be used by default.
  332. * @param boolean $middle If this parameter is true, truncation is done in the middle of the string.
  333. * @return string Truncated string, decorated with the given suffix (replacement).
  334. */
  335. function api_trunc_str($text, $length = 30, $suffix = '...', $middle = false, $encoding = null) {
  336. if (empty($encoding)) {
  337. $encoding = api_get_system_encoding();
  338. }
  339. $text_length = api_strlen($text, $encoding);
  340. if ($text_length <= $length) {
  341. return $text;
  342. }
  343. if ($middle) {
  344. return rtrim(api_substr($text, 0, round($length / 2), $encoding)) . $suffix . ltrim(api_substr($text, - round($length / 2), $text_length, $encoding));
  345. }
  346. return rtrim(api_substr($text, 0, $length, $encoding)) . $suffix;
  347. }
  348. /**
  349. * Handling simple and double apostrofe in order that strings be stored properly in database
  350. *
  351. * @author Denes Nagy
  352. * @param string variable - the variable to be revised
  353. */
  354. function domesticate($input) {
  355. $input = stripslashes($input);
  356. $input = str_replace("'", "''", $input);
  357. $input = str_replace('"', "''", $input);
  358. return ($input);
  359. }
  360. /**
  361. * function make_clickable($string)
  362. *
  363. * @desc Completes url contained in the text with "<a href ...".
  364. * However the function simply returns the submitted text without any
  365. * transformation if it already contains some "<a href:" or "<img src=".
  366. * @param string $text text to be converted
  367. * @return text after conversion
  368. * See http://php.net/manual/fr/function.eregi-replace.php
  369. *
  370. * - Goes through the given string, and replaces xxxx://yyyy with an HTML <a> tag linking
  371. * to that URL
  372. * - Goes through the given string, and replaces www.xxxx.yyyy[zzzz] with an HTML <a> tag linking
  373. * to http://www.xxxx.yyyy[/zzzz]
  374. * - Goes through the given string, and replaces xxxx@yyyy with an HTML mailto: tag linking
  375. * to that email address
  376. * - Only matches these 2 patterns either after a space, or at the beginning of a line
  377. *
  378. */
  379. function make_clickable($text) {
  380. $regex = '/(\S+@\S+\.\S+)/i';
  381. $replace = "<a href='mailto:$1'>$1</a>";
  382. $result = preg_replace($regex, $replace, $text);
  383. return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $result);
  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. return $input;
  397. }
  398. /**
  399. * Applies parsing for tex commands that are separated by [tex]
  400. * [/tex] to make it readable for techexplorer plugin.
  401. * This function should not be accessed directly but should be accesse through the text_filter function
  402. * @param string $text The text to parse
  403. * @return string The text after parsing.
  404. * @author Patrick Cool <patrick.cool@UGent.be>
  405. * @version June 2004
  406. */
  407. function _text_parse_tex($textext) {
  408. $input_array = preg_split("/(\[tex]|\[\/tex])/", $textext, -1, PREG_SPLIT_DELIM_CAPTURE);
  409. foreach ($input_array as $key => $value) {
  410. if ($key > 0 && $input_array[$key - 1] == '[tex]' AND $input_array[$key + 1] == '[/tex]') {
  411. $input_array[$key] = latex_gif_renderer($value);
  412. unset($input_array[$key - 1]);
  413. unset($input_array[$key + 1]);
  414. }
  415. }
  416. $output = implode('', $input_array);
  417. return $output;
  418. }
  419. /**
  420. * This function should not be accessed directly but should be accesse through the text_filter function
  421. * @author Patrick Cool <patrick.cool@UGent.be>
  422. */
  423. function _text_parse_glossary($input) {
  424. return $input;
  425. }
  426. /**
  427. * @desc This function makes a valid link to a different tool.
  428. * This function should not be accessed directly but should be accesse through the text_filter function
  429. * @author Patrick Cool <patrick.cool@UGent.be>
  430. */
  431. function _text_parse_tool($input) {
  432. // An array with all the valid tools
  433. $tools[] = array(TOOL_ANNOUNCEMENT, 'announcements/announcements.php');
  434. $tools[] = array(TOOL_CALENDAR_EVENT, 'calendar/agenda.php');
  435. // Check if the name between the [tool] [/tool] tags is a valid one
  436. }
  437. /**
  438. * Renders LaTeX code into a gif or retrieve a cached version of the gif.
  439. * @author Patrick Cool <patrick.cool@UGent.be> Ghent University
  440. */
  441. function latex_gif_renderer($latex_code) {
  442. global $_course;
  443. // Setting the paths and filenames
  444. $mimetex_path = api_get_path(LIBRARY_PATH) . 'mimetex/';
  445. $temp_path = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/temp/';
  446. $latex_filename = md5($latex_code) . '.gif';
  447. if (!file_exists($temp_path . $latex_filename) OR isset($_GET['render'])) {
  448. if (IS_WINDOWS_OS) {
  449. $mimetex_command = $mimetex_path . 'mimetex.exe -e "' . $temp_path . md5($latex_code) . '.gif" ' . escapeshellarg($latex_code) . '';
  450. } else {
  451. $mimetex_command = $mimetex_path . 'mimetex.cgi -e "' . $temp_path . md5($latex_code) . '.gif" ' . escapeshellarg($latex_code);
  452. }
  453. exec($mimetex_command);
  454. //echo 'volgende shell commando werd uitgevoerd:<br /><pre>'.$mimetex_command.'</pre><hr>';
  455. }
  456. $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');\">";
  457. $return .= '<img src="' . api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/temp/' . $latex_filename . '" alt="' . $latex_code . '" border="0" /></a>';
  458. return $return;
  459. }
  460. /**
  461. * This functions cuts a paragraph
  462. * i.e cut('Merry Xmas from Lima',13) = "Merry Xmas fr..."
  463. * @param string The text to "cut"
  464. * @param int Count of chars
  465. * @param bool Whether to embed in a <span title="...">...</span>
  466. * @return string
  467. * */
  468. function cut($text, $maxchar, $embed = false) {
  469. if (api_strlen($text) > $maxchar) {
  470. if ($embed) {
  471. return '<span title="' . $text . '">' . api_substr($text, 0, $maxchar) . '...</span>';
  472. }
  473. return api_substr($text, 0, $maxchar) . ' ...';
  474. }
  475. return $text;
  476. }
  477. /**
  478. * Show a number as only integers if no decimals, but will show 2 decimals if exist.
  479. *
  480. * @param mixed Number to convert
  481. * @param int Decimal points 0=never, 1=if needed, 2=always
  482. * @return mixed An integer or a float depends on the parameter
  483. */
  484. function float_format($number, $flag = 1) {
  485. if (is_numeric($number)) {
  486. if (!$number) {
  487. $result = ($flag == 2 ? '0.' . str_repeat('0', EXERCISE_NUMBER_OF_DECIMALS) : '0');
  488. } else {
  489. if (floor($number) == $number) {
  490. $result = number_format($number, ($flag == 2 ? EXERCISE_NUMBER_OF_DECIMALS : 0));
  491. } else {
  492. $result = number_format(round($number, 2), ($flag == 0 ? 0 : EXERCISE_NUMBER_OF_DECIMALS));
  493. }
  494. }
  495. return $result;
  496. }
  497. }
  498. // TODO: To be checked for correct timezone management.
  499. /**
  500. * Function to obtain last week timestamps
  501. * @return array Times for every day inside week
  502. */
  503. function get_last_week() {
  504. $week = date('W');
  505. $year = date('Y');
  506. $lastweek = $week - 1;
  507. if ($lastweek == 0) {
  508. $week = 52;
  509. $year--;
  510. }
  511. $lastweek = sprintf("%02d", $lastweek);
  512. $arrdays = array();
  513. for ($i = 1; $i <= 7; $i++) {
  514. $arrdays[] = strtotime("$year" . "W$lastweek" . "$i");
  515. }
  516. return $arrdays;
  517. }
  518. /**
  519. * Gets the week from a day
  520. * @param string Date in UTC (2010-01-01 12:12:12)
  521. * @return int Returns an integer with the week number of the year
  522. */
  523. function get_week_from_day($date) {
  524. if (!empty($date)) {
  525. $time = api_strtotime($date, 'UTC');
  526. return date('W', $time);
  527. } else {
  528. return date('W');
  529. }
  530. }
  531. /**
  532. * Deprecated functions
  533. */
  534. /**
  535. * Applies parsing the content for tex commands that are separated by [tex]
  536. * [/tex] to make it readable for techexplorer plugin.
  537. * @param string $text The text to parse
  538. * @return string The text after parsing.
  539. * @author Patrick Cool <patrick.cool@UGent.be>
  540. * @version June 2004
  541. */
  542. function api_parse_tex($textext) {
  543. /*
  544. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) {
  545. 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);
  546. }
  547. return str_replace(array('[tex]', '[/tex]'), array("<embed type=\"application/x-techexplorer\" texdata=\"", "\" autosize=\"true\" pluginspage=\"http://www.integretechpub.com/techexplorer/\">"), $textext);
  548. */
  549. return $textext;
  550. }
  551. /**
  552. * Applies parsing for tex commandos that are seperated by [tex]
  553. * [/tex] to make it readable for techexplorer plugin.
  554. * This function should not be accessed directly but should be accesse through the text_filter function
  555. * @param string $text The text to parse
  556. * @return string The text after parsing.
  557. * @author Patrick Cool <patrick.cool@UGent.be>
  558. * @version June 2004
  559. */
  560. function _text_parse_texexplorer($textext) {
  561. /*
  562. if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
  563. $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);
  564. } else {
  565. $textext = str_replace(array("[texexplorer]", "[/texexplorer]"), array("<embed type=\"application/x-techexplorer\" texdata=\"", "\" autosize=\"true\" pluginspage=\"http://www.integretechpub.com/techexplorer/\">"), $textext);
  566. }
  567. return $textext;
  568. */
  569. return $textext;
  570. }
  571. /**
  572. * This function splits the string into words and then joins them back together again one by one.
  573. * Example: "Test example of a long string"
  574. * substrwords(5) = Test ... *
  575. * @param string
  576. * @param int the max number of character
  577. * @param string how the string will be end
  578. * @return a reduce string
  579. */
  580. function substrwords($text, $maxchar, $end = '...') {
  581. if (strlen($text) > $maxchar) {
  582. $words = explode(" ", $text);
  583. $output = '';
  584. $i = 0;
  585. while (1) {
  586. $length = (strlen($output) + strlen($words[$i]));
  587. if ($length > $maxchar) {
  588. break;
  589. } else {
  590. $output = $output . " " . $words[$i];
  591. $i++;
  592. };
  593. };
  594. } else {
  595. $output = $text;
  596. return $output;
  597. }
  598. return $output . $end;
  599. }
  600. function implode_with_key($glue, $array) {
  601. if (!empty($array)) {
  602. $string = '';
  603. foreach ($array as $key => $value) {
  604. if (empty($value)) {
  605. $value = 'null';
  606. }
  607. $string .= $key . " : " . $value . " $glue ";
  608. }
  609. return $string;
  610. }
  611. return '';
  612. }
  613. function lang2db($string) {
  614. $string = str_replace("\\'", "'", $string);
  615. $string = Database::escape_string($string);
  616. return $string;
  617. }
  618. /**
  619. * function string2binary converts the string "true" or "false" to the boolean true false (0 or 1)
  620. * This is used for the Chamilo Config Settings as these store true or false as string
  621. * and the api_get_setting('course_create_active_tools') should be 0 or 1 (used for
  622. * the visibility of the tool)
  623. * @param string $variable
  624. * @author Patrick Cool, patrick.cool@ugent.be
  625. */
  626. function string2binary($variable) {
  627. if ($variable == 'true') {
  628. return true;
  629. }
  630. if ($variable == 'false') {
  631. return false;
  632. }
  633. }
  634. /**
  635. * Transform the file size in a human readable format.
  636. *
  637. * @param int Size of the file in bytes
  638. * @return string A human readable representation of the file size
  639. */
  640. function format_file_size($file_size) {
  641. $file_size = intval($file_size);
  642. if($file_size >= 1073741824) {
  643. $file_size = round($file_size / 1073741824 * 100) / 100 . 'G';
  644. } elseif($file_size >= 1048576) {
  645. $file_size = round($file_size / 1048576 * 100) / 100 . 'M';
  646. } elseif($file_size >= 1024) {
  647. $file_size = round($file_size / 1024 * 100) / 100 . 'k';
  648. } else {
  649. $file_size = $file_size . 'B';
  650. }
  651. return $file_size;
  652. }
  653. function return_datetime_from_array($array) {
  654. $year = '0000';
  655. $month = $day = $hours = $minutes = $seconds = '00';
  656. if (isset($array['Y']) && (isset($array['F']) || isset($array['M'])) && isset($array['d']) && isset($array['H']) && isset($array['i'])) {
  657. $year = $array['Y'];
  658. $month = isset($array['F'])?$array['F']:$array['M'];
  659. if (intval($month) < 10 ) $month = '0'.$month;
  660. $day = $array['d'];
  661. if (intval($day) < 10 ) $day = '0'.$day;
  662. $hours = $array['H'];
  663. if (intval($hours) < 10 ) $hours = '0'.$hours;
  664. $minutes = $array['i'];
  665. if (intval($minutes) < 10 ) $minutes = '0'.$minutes;
  666. }
  667. if (checkdate($month,$day,$year)) {
  668. $datetime = $year.'-'.$month.'-'.$day.' '.$hours.':'.$minutes.':'.$seconds;
  669. }
  670. return $datetime;
  671. }