text.lib.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. <?php // $Id: text.lib.php 20087 2009-04-24 20:44:55Z juliomontoya $
  2. /*
  3. ==============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2004-2009 Dokeos S.A.
  6. Copyright (c) 2003 Ghent University (UGent)
  7. Copyright (c) 2001 Universite catholique de Louvain (UCL)
  8. Copyright (c) various contributors
  9. For a full list of contributors, see "credits.txt".
  10. The full license can be read in "license.txt".
  11. This program is free software; you can redistribute it and/or
  12. modify it under the terms of the GNU General Public License
  13. as published by the Free Software Foundation; either version 2
  14. of the License, or (at your option) any later version.
  15. See the GNU General Public License for more details.
  16. Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
  17. ==============================================================================
  18. */
  19. /**
  20. ==============================================================================
  21. * This is the text library for Dokeos.
  22. * Include/require it in your code to use its functionality.
  23. *
  24. * @package dokeos.library
  25. ==============================================================================
  26. */
  27. /*
  28. ==============================================================================
  29. FUNCTIONS
  30. ==============================================================================
  31. */
  32. /**
  33. * function make_clickable($string)
  34. *
  35. * @desc completes url contained in the text with "<a href ...".
  36. * However the function simply returns the submitted text without any
  37. * transformation if it already contains some "<a href:" or "<img src=".
  38. * @param string $text text to be converted
  39. * @return text after conversion
  40. * @author Rewritten by Nathan Codding - Feb 6, 2001.
  41. * completed by Hugues Peeters - July 22, 2002
  42. *
  43. * Actually this function is taken from the PHP BB 1.4 script
  44. * - Goes through the given string, and replaces xxxx://yyyy with an HTML <a> tag linking
  45. * to that URL
  46. * - Goes through the given string, and replaces www.xxxx.yyyy[zzzz] with an HTML <a> tag linking
  47. * to http://www.xxxx.yyyy[/zzzz]
  48. * - Goes through the given string, and replaces xxxx@yyyy with an HTML mailto: tag linking
  49. * to that email address
  50. * - Only matches these 2 patterns either after a space, or at the beginning of a line
  51. *
  52. * Notes: the email one might get annoying - it's easy to make it more restrictive, though.. maybe
  53. * have it require something like xxxx@yyyy.zzzz or such. We'll see.
  54. */
  55. function make_clickable($string)
  56. {
  57. if(!stristr($string,' src=') && !stristr($string,' href='))
  58. {
  59. $string=eregi_replace("(https?|ftp)://([a-z0-9#?/&=._+:~%-]+)","<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>",$string);
  60. $string=eregi_replace("([a-z0-9_.-]+@[a-z0-9.-]+)","<a href=\"mailto:\\1\">\\1</a>",$string);
  61. }
  62. return $string;
  63. }
  64. /**
  65. * formats the date according to the locale settings
  66. *
  67. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  68. * @author Christophe Gesch� <gesche@ipm.ucl.ac.be>
  69. * originally inspired from from PhpMyAdmin
  70. * @param string $date_format date pattern
  71. * @param integer $time_stamp, default is NOW.
  72. * @return the formatted date
  73. */
  74. function format_locale_date($date_format, $time_stamp = -1)
  75. {
  76. static $initialized = false;
  77. static $days_short, $days_long, $months_short, $months_long;
  78. if (!$initialized)
  79. {
  80. // Defining the shorts for the days
  81. $days_short = array (get_lang("SundayShort"), get_lang("MondayShort"), get_lang("TuesdayShort"), get_lang("WednesdayShort"), get_lang("ThursdayShort"), get_lang("FridayShort"), get_lang("SaturdayShort"));
  82. // Defining the days of the week to allow translation of the days
  83. $days_long = array (get_lang("SundayLong"), get_lang("MondayLong"), get_lang("TuesdayLong"), get_lang("WednesdayLong"), get_lang("ThursdayLong"), get_lang("FridayLong"), get_lang("SaturdayLong"));
  84. // Defining the shorts for the months
  85. $months_short = array (get_lang("JanuaryShort"), get_lang("FebruaryShort"), get_lang("MarchShort"), get_lang("AprilShort"), get_lang("MayShort"), get_lang("JuneShort"), get_lang("JulyShort"), get_lang("AugustShort"), get_lang("SeptemberShort"), get_lang("OctoberShort"), get_lang("NovemberShort"), get_lang("DecemberShort"));
  86. // Defining the months of the year to allow translation of the months
  87. $months_long = array (get_lang("JanuaryLong"), get_lang("FebruaryLong"), get_lang("MarchLong"), get_lang("AprilLong"), get_lang("MayLong"), get_lang("JuneLong"), get_lang("JulyLong"), get_lang("AugustLong"), get_lang("SeptemberLong"), get_lang("OctoberLong"), get_lang("NovemberLong"), get_lang("DecemberLong"));
  88. $initialized = true;
  89. }
  90. if ($time_stamp == -1) $time_stamp = time();
  91. // with the ereg we replace %aAbB of date format
  92. //(they can be done by the system when locale date aren't aivailable
  93. $date = ereg_replace('%[A]', $days_long[(int)strftime('%w', $time_stamp)], $date_format);
  94. $date = ereg_replace('%[a]', $days_short[(int)strftime('%w', $time_stamp)], $date);
  95. $date = ereg_replace('%[B]', $months_long[(int)strftime('%m', $time_stamp)-1], $date);
  96. $date = ereg_replace('%[b]', $months_short[(int)strftime('%m', $time_stamp)-1], $date);
  97. return strftime($date, $time_stamp);
  98. } // end function format_locale_date
  99. /**
  100. * @desc this function does some parsing on the text that gets inputted. This parsing can be of any kind
  101. * LaTeX notation, Word Censoring, Glossary Terminology (extension will available soon), Musical Notations, ...
  102. * The inspiration for this filter function came from Moodle an phpBB who both use a similar approach
  103. * @param $input string. some text
  104. * @return $output string. some text that contains the parsed elements.
  105. * @example [tex]\sqrt(2)[/tex]
  106. * @author Patrick Cool <patrick.cool@UGent.be>
  107. * @version March 2OO6
  108. */
  109. function text_filter($input, $filter=true)
  110. {
  111. //$input=stripslashes($input);
  112. if ($filter==true)
  113. {
  114. // *** parse [tex]...[/tex] tags *** //
  115. // which will return techexplorer or image html depending on the capabilities of the
  116. // browser of the user (using some javascript that checks if the browser has the TechExplorer plugin installed or not)
  117. $input=_text_parse_tex($input);
  118. // *** parse [teximage]...[/teximage] tags *** //
  119. // these force the gif rendering of LaTeX using the mimetex gif renderer
  120. //$input=_text_parse_tex_image($input);
  121. // *** parse [texexplorer]...[/texexplorer] tags *** //
  122. // these force the texeplorer LaTeX notation
  123. $input=_text_parse_texexplorer($input);
  124. // *** Censor Words *** //
  125. // censor words. This function removes certain words by [censored]
  126. // this can be usefull when the campus is open to the world.
  127. // $input=text_censor_words($input);
  128. // *** parse [?]...[/?] tags *** //
  129. // for the glossary tool (see http://www.dokeos.com/extensions)
  130. $input=_text_parse_glossary($input);
  131. // parse [wiki]...[/wiki] tags
  132. // this is for the coolwiki plugin.
  133. // $input=text_parse_wiki($input);
  134. // parse [tool]...[/tool] tags
  135. // this parse function adds a link to a certain tool
  136. // $input=text_parse_tool($input);
  137. // parse [user]...[/user] tags
  138. // parse [email]...[/email] tags
  139. // parse [code]...[/code] tags
  140. }
  141. return $input;
  142. }
  143. /**
  144. * Apply parsing to content to parse tex commandos that are seperated by [tex]
  145. * [/tex] to make it readable for techexplorer plugin.
  146. * This function should not be accessed directly but should be accesse through the text_filter function
  147. * @param string $text The text to parse
  148. * @return string The text after parsing.
  149. * @author Patrick Cool <patrick.cool@UGent.be>
  150. * @version June 2004
  151. */
  152. function _text_parse_tex($textext)
  153. {
  154. //$textext = str_replace(array ("[tex]", "[/tex]"), array ('[*****]', '[/*****]'), $textext);
  155. //$textext=stripslashes($texttext);
  156. $input_array=preg_split("/(\[tex]|\[\/tex])/",$textext,-1, PREG_SPLIT_DELIM_CAPTURE);
  157. foreach ($input_array as $key=>$value)
  158. {
  159. if ($key>0 && $input_array[$key-1]=='[tex]' AND $input_array[$key+1]=='[/tex]')
  160. {
  161. $input_array[$key]=latex_gif_renderer($value);
  162. unset($input_array[$key-1]);
  163. unset($input_array[$key+1]);
  164. //echo 'LaTeX: <embed type="application/x-techexplorer" texdata="'.stripslashes($value).'" autosize="true" pluginspage="http://www.integretechpub.com/techexplorer/"><br />';
  165. }
  166. }
  167. $output=implode('',$input_array);
  168. return $output;
  169. }
  170. /**
  171. * Apply parsing to content to parse tex commandos that are seperated by [tex]
  172. * [/tex] to make it readable for techexplorer plugin.
  173. * This function should not be accessed directly but should be accesse through the text_filter function
  174. * @param string $text The text to parse
  175. * @return string The text after parsing.
  176. * @author Patrick Cool <patrick.cool@UGent.be>
  177. * @version June 2004
  178. */
  179. function _text_parse_texexplorer($textext)
  180. {
  181. if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
  182. {
  183. $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);
  184. }
  185. else
  186. {
  187. $textext = str_replace(array ("[texexplorer]", "[/texexplorer]"), array ("<embed type=\"application/x-techexplorer\" texdata=\"", "\" autosize=\"true\" pluginspage=\"http://www.integretechpub.com/techexplorer/\">"), $textext);
  188. }
  189. return $textext;
  190. }
  191. /**
  192. * This function should not be accessed directly but should be accesse through the text_filter function
  193. * @author Patrick Cool <patrick.cool@UGent.be>
  194. */
  195. function _text_parse_glossary($input)
  196. {
  197. return $input;
  198. }
  199. /**
  200. * @desc this function makes a valid link to a different tool
  201. * This function should not be accessed directly but should be accesse through the text_filter function
  202. * @author Patrick Cool <patrick.cool@UGent.be>
  203. */
  204. function _text_parse_tool($input)
  205. {
  206. // an array with all the valid tools
  207. $tools[]=array(TOOL_ANNOUNCEMENT, 'announcements/announcements.php');
  208. $tools[]=array(TOOL_CALENDAR_EVENT, 'calendar/agenda.php');
  209. // check if the name between the [tool] [/tool] tags is a valid one
  210. }
  211. /**
  212. * render LaTeX code into a gif or retrieve a cached version of the gif
  213. * @author Patrick Cool <patrick.cool@UGent.be> Ghent University
  214. */
  215. function latex_gif_renderer($latex_code)
  216. {
  217. global $_course;
  218. // setting the paths and filenames
  219. $mimetex_path=api_get_path(LIBRARY_PATH).'mimetex/';
  220. $temp_path=api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp/';
  221. $latex_filename=md5($latex_code).'.gif';
  222. if(!file_exists($temp_path.$latex_filename) OR isset($_GET['render']))
  223. {
  224. if ((PHP_OS == "WINNT") || (PHP_OS == "WIN32") || (PHP_OS == "Windows"))
  225. {
  226. $mimetex_command=$mimetex_path.'mimetex.exe -e "'.$temp_path.md5($latex_code).'.gif" '.escapeshellarg($latex_code).'';
  227. }
  228. else
  229. {
  230. $mimetex_command=$mimetex_path.'mimetex.linux -e "'.$temp_path.md5($latex_code).'.gif" '.escapeshellarg($latex_code);
  231. }
  232. exec($mimetex_command);
  233. //echo 'volgende shell commando werd uitgevoerd:<br /><pre>'.$mimetex_command.'</pre><hr>';
  234. }
  235. $return = "<a href=\"\" onclick=\"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');\">";
  236. $return .= '<img src="'.api_get_path(WEB_COURSE_PATH).$_course['path'].'/temp/'.$latex_filename.'" alt="'.$latex_code.'" border="0" /></a>';
  237. return $return;
  238. }
  239. /**
  240. * Returns the difference between the current date (date(now)) with the parameter $date in a string format like "2 days, 1 hour"
  241. * Example: $date="2008-03-07 15:44:08";
  242. * date_to_str($date) it will return 3 days, 20 hours
  243. *
  244. * @param string The string has to be the result of a date function in this format -> date("Y-m-d H:i:s",time());
  245. * @return string The difference between the current date and the parameter in a literal way "3 days, 2 hour" *
  246. * @author Julio Montoya
  247. */
  248. function date_to_str_ago($date)
  249. {
  250. static $initialized = false;
  251. static $today, $yesterday;
  252. static $min_decade, $min_year, $min_month, $min_week, $min_day, $min_hour, $min_minute;
  253. static $min_decades, $min_years, $min_months, $min_weeks, $min_days, $min_hours, $min_minutes;
  254. static $sec_time_time, $sec_time_sing, $sec_time_plu;
  255. if (!$initialized) {
  256. $today = ucfirst(get_lang('Today'));
  257. $yesterday = ucfirst(get_lang('Yesterday'));
  258. $min_decade=get_lang('MinDecade');
  259. $min_year=get_lang('MinYear');
  260. $min_month=get_lang('MinMonth');
  261. $min_week=get_lang('MinWeek');
  262. $min_day=get_lang('MinDay');
  263. $min_hour=get_lang('MinHour');
  264. $min_minute=get_lang('MinMinute');
  265. $min_decades=get_lang('MinDecades');
  266. $min_years=get_lang('MinYears');
  267. $min_months=get_lang('MinMonths');
  268. $min_weeks=get_lang('MinWeeks');
  269. $min_days=get_lang('MinDays');
  270. $min_hours=get_lang('MinHours');
  271. $min_minutes=get_lang('MinMinutes');
  272. // original 1
  273. //$sec_time=array("century"=>3.1556926*pow(10,9),"decade"=>315569260,"year"=>31556926,"month"=>2629743.83,"week"=>604800,"day"=>86400,"hour"=>3600,"minute"=>60,"second"=>1);
  274. //$sec_time=array(get_lang('MinDecade')=>315569260,get_lang('MinYear')=>31556926,get_lang('MinMonth')=>2629743.83,get_lang('MinWeek')=>604800,get_lang('MinDay')=>86400,get_lang('MinHour')=>3600,get_lang('MinMinute')=>60);
  275. $sec_time_time=array(315569260,31556926,2629743.83,604800,86400,3600,60);
  276. $sec_time_sing=array($min_decade,$min_year,$min_month,$min_week,$min_day,$min_hour,$min_minute);
  277. $sec_time_plu =array($min_decades,$min_years,$min_months,$min_weeks,$min_days,$min_hours,$min_minutes);
  278. $initialized = true;
  279. }
  280. $dst_date=strtotime($date);
  281. //for not call date several times
  282. $date_array=date("s/i/G/j/n/Y",$dst_date);
  283. $date_split=explode("/",$date_array);
  284. $dst_s=$date_split[0];
  285. $dst_m=$date_split[1];
  286. $dst_h=$date_split[2];
  287. $dst_day=$date_split[3];
  288. $dst_mth=$date_split[4];
  289. $dst_yr=$date_split[5];
  290. $dst_date = mktime($dst_h,$dst_m,$dst_s,$dst_mth,$dst_day,$dst_yr);
  291. $time=$offset = time()-$dst_date; //seconds between current days and today
  292. //------------ Here start the functions sec_to_str
  293. $act_day=date('d');
  294. $act_mth=date('n');
  295. $act_yr = date('Y');
  296. if ($dst_day==$act_day && $dst_mth==$act_mth && $dst_yr == $act_yr ) {
  297. return $today;
  298. }
  299. if ($dst_day==$act_day-1 && $dst_mth==$act_mth && $dst_yr == $act_yr ) {
  300. return $yesterday;
  301. }
  302. $str_result=array();
  303. $time_result=array();
  304. $key_result=array();
  305. $str='';
  306. $i=0;
  307. for ($i=0;$i<count($sec_time_time);$i++) {
  308. $seconds=$sec_time_time[$i];
  309. if($seconds > $time) {
  310. continue;
  311. }
  312. $current_value=intval($time/$seconds);
  313. if ($current_value != 1) {
  314. $date_str= $sec_time_plu[$i];
  315. } else {
  316. $date_str= $sec_time_sing[$i];
  317. }
  318. $key_result[]=$sec_time_sing[$i];
  319. $str_result[]=$current_value.' '.$date_str;
  320. $time_result[]= $current_value;
  321. $str.=$current_value.$date_str;
  322. $time%=$seconds;
  323. }
  324. if ($key_result[0]== $min_day && $key_result[1]== $min_minute) {
  325. $key_result[1]=' 0 '.$min_hours;
  326. $str_result[0]=$time_result[0].' '.$key_result[0];
  327. $str_result[1]=$key_result[1];
  328. }
  329. if ($key_result[0]== $min_year && ($key_result[1]== $min_day || $key_result[1]== $min_week)) {
  330. $key_result[1]=' 0 '.$min_months;
  331. $str_result[0]=$time_result[0].' '.$key_result[0];
  332. $str_result[1]=$key_result[1];
  333. }
  334. if (!empty($str_result[1])) {
  335. $str=$str_result[0].', '.$str_result[1];
  336. } else {
  337. $str=$str_result[0];
  338. }
  339. return $str;
  340. }
  341. /**
  342. * This functions cuts a paragraph
  343. * i.e cut('Merry Xmas from Lima',13) = "Merry Xmas fr..."
  344. * @param string the text to "cut"
  345. * @param int count of chars
  346. * @return string
  347. * */
  348. function cut($text,$maxchar)
  349. {
  350. if (strlen($text) > $maxchar) {
  351. return substr($text, 0, $maxchar).'...' ;
  352. } else {
  353. return $text;
  354. }
  355. }
  356. /**
  357. * Show a number as only integers if no decimals, but will show 2 decimals if exist.
  358. *
  359. * @param mixed number to convert
  360. * @param int decimal points 0=never, 1=if needed, 2=always
  361. * @return mixed an integer or a float depends on the parameter
  362. */
  363. function float_format($number, $flag = 1)
  364. {
  365. if (is_numeric($number)) { // a number
  366. if (!$number) { // zero
  367. $result = ($flag == 2 ? '0.00' : '0'); // output zero
  368. } else { // value
  369. if (floor($number) == $number) { // whole number
  370. $result = number_format($number, ($flag == 2 ? 2 : 0)); // format
  371. } else { // cents
  372. $result = number_format(round($number, 2), ($flag == 0 ? 0 : 2)); // format
  373. } // integer or decimal
  374. } // value
  375. return $result;
  376. }
  377. }
  378. ?>