21e8e4d63fe044ce608a1290fa1918d6c96c55ee
[acontent.git] / docs / home / classes / ContentUtility.class.php
1 <?php\r
2 /************************************************************************/\r
3 /* AContent                                                             */\r
4 /************************************************************************/\r
5 /* Copyright (c) 2010                                                   */\r
6 /* Inclusive Design Institute                                           */\r
7 /*                                                                      */\r
8 /* This program is free software. You can redistribute it and/or        */\r
9 /* modify it under the terms of the GNU General Public License          */\r
10 /* as published by the Free Software Foundation.                        */\r
11 /************************************************************************/\r
12 \r
13 /**\r
14 * Content Utility functions \r
15 * @access       public\r
16 * @author       Cindy Qi Li\r
17 */\r
18 \r
19 if (!defined('TR_INCLUDE_PATH')) exit;\r
20 \r
21 class ContentUtility {\r
22 \r
23         /**\r
24         * This function cuts out html body\r
25         * @access  public\r
26         * @param   $text  html text\r
27         * @author  Cindy Qi Li\r
28         */\r
29         public static function getHtmlBody($text) {\r
30                 /* strip everything before <body> */\r
31                 $start_pos      = strpos(strtolower($text), '<body');\r
32                 if ($start_pos !== false) {\r
33                         $start_pos      += strlen('<body');\r
34                         $end_pos        = strpos(strtolower($text), '>', $start_pos);\r
35                         $end_pos        += strlen('>');\r
36         \r
37                         $text = substr($text, $end_pos);\r
38                 }\r
39         \r
40                 /* strip everything after </body> */\r
41                 $end_pos        = strpos(strtolower($text), '</body>');\r
42                 if ($end_pos !== false) {\r
43                         $text = trim(substr($text, 0, $end_pos));\r
44                 }\r
45         \r
46                 return $text;\r
47         }\r
48 \r
49         /**\r
50         * This function cuts out requested tag information from html head\r
51         * @access  public\r
52         * @param   $text  html text\r
53         * @param   $tags  a string or an array of requested tags\r
54         * @author  Cindy Qi Li\r
55         */\r
56         public static function getHtmlHeadByTag($text, $tags)\r
57         {\r
58                 $head = ContentUtility::getHtmlHead($text);\r
59                 $rtn_text = "";\r
60                 \r
61                 if (!is_array($tags) && strlen(trim($tags)) > 0)\r
62                 {\r
63                         $tags = array(trim($tags));\r
64                 }\r
65                 foreach ($tags as $tag)\r
66                 {\r
67                         $tag = strtolower($tag);\r
68         \r
69                         /* strip everything before <{tag}> */\r
70                         $start_pos      = stripos($head, '<'.$tag);\r
71                         $temp_head = $head;\r
72                         \r
73                         while ($start_pos !== false) \r
74                         {\r
75                                 $temp_text = substr($temp_head, $start_pos);\r
76                 \r
77                                 /* strip everything after </{tag}> or />*/\r
78                                 $end_pos        = stripos($temp_text, '</' . $tag . '>');\r
79                 \r
80                                 if ($end_pos !== false) \r
81                                 {\r
82                                         $end_pos += strlen('</' . $tag . '>');\r
83                                         \r
84                                         // add an empty line after each tag information\r
85                                         $rtn_text .= trim(substr($temp_text, 0, $end_pos)) . '\r
86                 \r
87         ';\r
88                                 }\r
89                                 else  // match /> as ending tag if </tag> is not found\r
90                                 {\r
91                                         $end_pos        = stripos($temp_text, '/>');\r
92                                         \r
93                                         if($end_pos === false && stripos($temp_text, $tag.'>')===false){\r
94                                                 //if /> is not found, then this is not a valid XHTML\r
95                                                 //text iff it's not tag>\r
96                                                 $end_pos = stripos($temp_text, '>');\r
97                                                 $end_pos += strlen('>');\r
98                                         } else {\r
99                                                 $end_pos += strlen('/>');\r
100                                         }\r
101                                         // add an empty line after each tag information\r
102                                         $rtn_text .= trim(substr($temp_text, 0, $end_pos)) . '\r
103                 \r
104         ';\r
105                                 }\r
106                                 \r
107                                 // initialize vars for next round of matching\r
108                                 $temp_head = substr($temp_text, $end_pos);\r
109                                 $start_pos = stripos($temp_head, '<'.$tag);\r
110                         }\r
111                 }\r
112                 return $rtn_text;\r
113         }\r
114 \r
115         /**\r
116         * This function cuts out html head\r
117         * @access  private\r
118         * @param   $text  html text\r
119         * @author  Cindy Qi Li\r
120         */\r
121         private static function getHtmlHead ($text) {\r
122                 /* strip everything before <head> */\r
123                 $start_pos      = stripos($text, '<head');\r
124                 if ($start_pos !== false) {\r
125                         $start_pos      += strlen('<head');\r
126                         $end_pos        = stripos($text, '>', $start_pos);\r
127                         $end_pos        += strlen('>');\r
128         \r
129                         $text = substr($text, $end_pos);\r
130                 }\r
131         \r
132                 /* strip everything after </head> */\r
133                 $end_pos        = stripos($text, '</head');\r
134                 if ($end_pos !== false) {\r
135                         $text = trim(substr($text, 0, $end_pos));\r
136                 }\r
137                 return $text;\r
138         }\r
139 \r
140         private static function embedFLV($text) {\r
141                 global $content_base_href;\r
142                 \r
143                 // .flv - uses Flowplayer 3.0 from flowplayer.org (playing file via full URL)\r
144                 preg_match_all("#\[media[0-9a-z\|]*\]http://([\w\./-]+)\.flv\[/media\]#i",$text,$media_matches[0],PREG_SET_ORDER);\r
145                 $media_replace[0] ="<a class=\"flowplayerholder\"\r
146                 style=\"display:block;width:##WIDTH##px;height:##HEIGHT##px;\"\r
147                 href=\"http://##MEDIA1##.flv\">\r
148                 </a>";\r
149                 \r
150                 // .flv - uses Flowplayer 3.0 from flowplayer.org (playing file from AT_content_dir)\r
151                 preg_match_all("#\[media[0-9a-z\|]*\]([\w\./-]+)\.flv\[/media\]#i",$text,$media_matches[1],PREG_SET_ORDER);\r
152                 $media_replace[1] ="<a class=\"flowplayerholder\"\r
153                 style=\"display:block;width:##WIDTH##px;height:##HEIGHT##px;\"\r
154                 href=\"".TR_BASE_HREF."get.php/".$content_base_href."##MEDIA1##.flv\">\r
155                 </a>";\r
156                 \r
157                 $has_flv = false;\r
158                 // Executing the replace\r
159                 for ($i=0;$i<count($media_replace);$i++){\r
160                         foreach($media_matches[$i] as $media)\r
161                         {\r
162                                 if (is_array($media)) $has_flv = true;\r
163                                 \r
164                                 //find width and height for each matched media\r
165                                 if (preg_match("/\[media\|([0-9]*)\|([0-9]*)\]*/", $media[0], $matches)) \r
166                                 {\r
167                                         $width = $matches[1];\r
168                                         $height = $matches[2];\r
169                                 }\r
170                                 else\r
171                                 {\r
172                                         $width = 425;\r
173                                         $height = 350;\r
174                                 }\r
175                                 \r
176                                 //replace media tags with embedded media for each media tag\r
177                                 $media_input = $media_replace[$i];\r
178                                 $media_input = str_replace("##WIDTH##","$width",$media_input);\r
179                                 $media_input = str_replace("##HEIGHT##","$height",$media_input);\r
180                                 $media_input = str_replace("##MEDIA1##","$media[1]",$media_input);\r
181                                 $media_input = str_replace("##MEDIA2##","$media[2]",$media_input);\r
182                                 $text = str_replace($media[0],$media_input,$text);\r
183                         }\r
184                 }\r
185                 \r
186                 if ($has_flv)\r
187                 {\r
188                         $text .= '\r
189                         <script language="JavaScript">\r
190                                 $f("a.flowplayerholder", "'.TR_BASE_HREF.'include/jscripts/flowplayer/flowplayer-3.2.5.swf", { \r
191                                         clip: { autoPlay: false },              \r
192                                 plugins:  { \r
193                                         controls: { \r
194                                             all: false,  \r
195                                             play: true,  \r
196                                             scrubber: true \r
197                                         }         \r
198                                     }\r
199                                 });\r
200                         </script>\r
201                         ';\r
202                 }\r
203                 \r
204                 return $text;           \r
205         }\r
206         \r
207     /*\r
208      * This function converts the youtube playable url used in <object> tag (for instance: http://www.youtube.com/v/a0ryB0m0MiM)\r
209      * to youtube url that is used to browse (for instance: http://www.youtube.com/watch?v=a0ryB0m0MiM)\r
210      * @param: youtube playable URL. For instance, http://www.youtube.com/v/a0ryB0m0MiM\r
211      * @return: if the param is a youtube playable url, return the according youtube URL used to browse. \r
212      *          For instance: http://www.youtube.com/watch?v=a0ryB0m0MiM\r
213      *          Otherwise, return the original send-in parameter.\r
214      */\r
215     function convertYoutubePlayURLToWatchURL($youtube_playURL) {\r
216         return preg_replace("/(http:\/\/[a-z0-9\.]*)?youtube.com\/v\/(.*)/",\r
217                             "\\1youtube.com/watch?v=\\2", $youtube_playURL);\r
218     }\r
219 \r
220     /*\r
221      * This function converts the youtube url that is used to browse (for instance: http://www.youtube.com/watch?v=a0ryB0m0MiM)\r
222      * to youtube playable url used in <object> tag (for instance: http://www.youtube.com/v/a0ryB0m0MiM)\r
223      * @param: the youtube URL used to browse. \r
224      *         For instance: http://www.youtube.com/watch?v=a0ryB0m0MiM\r
225      * @return: if the param is a youtube url used to browse, return the according youtube playable URL. \r
226      *          For instance, http://www.youtube.com/v/a0ryB0m0MiM\r
227      *          Otherwise, return the original send-in parameter.\r
228      */\r
229     function convertYoutubeWatchURLToPlayURL($youtube_watchURL) {\r
230         return preg_replace("/(http:\/\/[a-z0-9\.]*)?youtube.com\/watch\?v=(.*)/",\r
231                             "\\1youtube.com/v/\\2", $youtube_watchURL);\r
232     }\r
233 \r
234         public static function embedMedia($text) {\r
235                 if (preg_match("/\[media(\|[0-9]+\|[0-9]+)?\]*/", $text)==0){\r
236                         return $text;\r
237                 }\r
238         \r
239                 // remove the spaces in [media] tag, otherwise, the next line converts URL inside [media] into <a> tag\r
240                 $text = preg_replace("/(\[media\])([\s]*)(.*)(\[\/media\])/", '$1$3$4', $text);\r
241                 $text = preg_replace("/(\[media\])(.*)([\s]*)(\[\/media\])/U", '$1$2$4', $text);\r
242                 \r
243                 $media_matches = Array();\r
244                 \r
245                 // First, we search though the text for all different kinds of media defined by media tags and store the results in $media_matches.\r
246         // Then the different replacements for the different media tags are stored in $media_replace.\r
247         // Lastly, we loop through all $media_matches / $media_replaces. (We choose $media_replace as index because $media_matches is multi-dimensioned.) It is important that for each $media_matches there is a $media_replace with the same index. For each media match we check the width/height, or we use the default value of 425x350. We then replace the height/width/media1/media2 parameter placeholders in $media_replace with the correct ones, before running a str_replace on $text, replacing the given media with its correct replacement.\r
248                 \r
249                 // youtube videos\r
250         preg_match_all("#\[media[0-9a-z\|]*\]http://([a-z0-9\.]*)?youtube.com/watch\?v=(.*)\[/media\]#iU",$text,$media_matches[1],PREG_SET_ORDER);\r
251         $media_replace[1] = '<object width="##WIDTH##" height="##HEIGHT##"><param name="movie" value="http://##MEDIA1##youtube.com/v/##MEDIA2##"></param><embed src="http://##MEDIA1##youtube.com/v/##MEDIA2##" type="application/x-shockwave-flash" width="##WIDTH##" height="##HEIGHT##"></embed></object>';\r
252                                 \r
253                 // .mpg\r
254                 preg_match_all("#\[media[0-9a-z\|]*\]([.\w\d]+[^\s\"]+).mpg\[/media\]#i",$text,$media_matches[2],PREG_SET_ORDER);\r
255                 $media_replace[2] = "<object data=\"##MEDIA1##.mpg\" type=\"video/mpeg\" width=\"##WIDTH##\" height=\"##HEIGHT##\"><param name=\"src\" value=\"##MEDIA1##.mpg\"><param name=\"autoplay\" value=\"false\"><param name=\"autoStart\" value=\"0\"><a href=\"##MEDIA1##.mpg\">##MEDIA1##.mpg</a></object>";\r
256                 \r
257                 // .avi\r
258                 preg_match_all("#\[media[0-9a-z\|]*\]([.\w\d]+[^\s\"]+).avi\[/media\]#i",$text,$media_matches[3],PREG_SET_ORDER);\r
259                 $media_replace[3] = "<object data=\"##MEDIA1##.avi\" type=\"video/x-msvideo\" width=\"##WIDTH##\" height=\"##HEIGHT##\"><param name=\"src\" value=\"##MEDIA1##.avi\"><param name=\"autoplay\" value=\"false\"><param name=\"autoStart\" value=\"0\"><a href=\"##MEDIA1##.avi\">##MEDIA1##.avi</a></object>";\r
260                 \r
261                 // .wmv\r
262                 preg_match_all("#\[media[0-9a-z\|]*\]([.\w\d]+[^\s\"]+).wmv\[/media\]#i",$text,$media_matches[4],PREG_SET_ORDER);\r
263                 $media_replace[4] = "<object data=\"##MEDIA1##.wmv\" type=\"video/x-ms-wmv\" width=\"##WIDTH##\" height=\"##HEIGHT##\"><param name=\"src\" value=\"##MEDIA1##.wmv\"><param name=\"autoplay\" value=\"false\"><param name=\"autoStart\" value=\"0\"><a href=\"##MEDIA1##.wmv\">##MEDIA1##.wmv</a></object>";\r
264                 \r
265                 // .swf\r
266                 preg_match_all("#\[media[0-9a-z\|]*\]([.\w\d]+[^\s\"]+).swf\[/media\]#i",$text,$media_matches[5],PREG_SET_ORDER);\r
267                 $media_replace[5] = "<object type=\"application/x-shockwave-flash\" data=\"##MEDIA1##.swf\" width=\"##WIDTH##\" height=\"##HEIGHT##\">  <param name=\"movie\" value=\"##MEDIA1##.swf\"><param name=\"loop\" value=\"false\"><a href=\"##MEDIA1##.swf\">##MEDIA1##.swf</a></object>";\r
268                 \r
269                 // .wav\r
270                 preg_match_all("#\[media[0-9a-z\|]*\](.+[^\s\"]+).wav\[/media\]#i",$text,$media_matches[6],PREG_SET_ORDER);\r
271                 $media_replace[6] ="<object type=\"audio/x-wav\" data=\"##MEDIA1##.wav\" width=\"##WIDTH##\" height=\"##HEIGHT##\"><param name=\"src\" value=\"##MEDIA1##.wav\"><param name=\"autoplay\" value=\"false\"><param name=\"autoStart\" value=\"0\"><a href=\"##MEDIA1##.wav\">##MEDIA1##.wav</a></object>";\r
272                 \r
273                 // .ogg\r
274                 preg_match_all("#\[media[0-9a-z\|]*\](.+[^\s\"]+).ogg\[/media\]#i",$text,$media_matches[7],PREG_SET_ORDER);\r
275                 $media_replace[7] ="<object type=\"application/ogg\" data=\"##MEDIA1##.ogg\" width=\"##WIDTH##\" height=\"##HEIGHT##\"><param name=\"src\" value=\"##MEDIA1##.ogg\"><a href=\"##MEDIA1##.ogg\">##MEDIA1##.ogg</a></object>";\r
276 \r
277         // .ogm\r
278         preg_match_all("#\[media[0-9a-z\|]*\](.+[^\s\"]+).ogm\[/media\]#i",$text,$media_matches[8],PREG_SET_ORDER);\r
279         $media_replace[8] ="<object type=\"application/ogm\" data=\"##MEDIA1##.ogm\" width=\"##WIDTH##\" height=\"##HEIGHT##\"><param name=\"src\" value=\"##MEDIA1##.ogm\"><a href=\"##MEDIA1##.ogg\">##MEDIA1##.ogm</a></object>";\r
280                 \r
281                 // .mid\r
282                 preg_match_all("#\[media[0-9a-z\|]*\](.+[^\s\"]+).mid\[/media\]#i",$text,$media_matches[9],PREG_SET_ORDER);\r
283                 $media_replace[9] ="<object type=\"application/x-midi\" data=\"##MEDIA1##.mid\" width=\"##WIDTH##\" height=\"##HEIGHT##\"><param name=\"src\" value=\"##MEDIA1##.mid\"><a href=\"##MEDIA1##.mid\">##MEDIA1##.mid</a></object>";\r
284                 \r
285                 $text = preg_replace("#\[media[0-9a-z\|]*\](.+[^\s\"]+).mid\[/media\]#i", "<object type=\"application/x-midi\" data=\"\\1.mid\" width=\"".$width."\" height=\"".$height."\"><param name=\"src\" value=\"\\1.mid\"><a href=\"\\1.mid\">\\1.mid</a></object>", $text);\r
286         \r
287                 // Executing the replace\r
288                 for ($i=1;$i<=count($media_replace);$i++){\r
289                         foreach($media_matches[$i] as $media)\r
290                         {\r
291                                 \r
292                                 //find width and height for each matched media\r
293                                 if (preg_match("/\[media\|([0-9]*)\|([0-9]*)\]*/", $media[0], $matches)) \r
294                                 {\r
295                                         $width = $matches[1];\r
296                                         $height = $matches[2];\r
297                                 }\r
298                                 else\r
299                                 {\r
300                                         $width = 425;\r
301                                         $height = 350;\r
302                                 }\r
303                                 \r
304                                 //replace media tags with embedded media for each media tag\r
305                                 $media_input = $media_replace[$i];\r
306                                 $media_input = str_replace("##WIDTH##","$width",$media_input);\r
307                                 $media_input = str_replace("##HEIGHT##","$height",$media_input);\r
308                                 $media_input = str_replace("##MEDIA1##","$media[1]",$media_input);\r
309                                 $media_input = str_replace("##MEDIA2##","$media[2]",$media_input);\r
310                                 $text = str_replace($media[0],$media_input,$text);\r
311                         }\r
312                 }\r
313                 \r
314                 return $text;\r
315         }\r
316 \r
317         public static function makeClickable($text) {\r
318                 $text = ContentUtility::embedMedia($text);\r
319         \r
320                 // convert plain text URL to clickable URL.\r
321                 // Limited conversion: It doesn't cover the case when the stuff in front of the URL is not a word. For example:\r
322                 // <p>http://google.ca</p>\r
323                 // "http://google.ca" \r
324                 $text = preg_replace('/(^|[\n ])([\w]*?)((?<!(\[media\]))http(s)?:\/\/[\w]+[^ \,\"\n\r\t\)<]*)/is', \r
325                                      '$1$2<a href="$3">$3</a>', $text);\r
326                 \r
327                 // convert email address to clickable URL that pops up "send email" interface with the address filled in\r
328                 $text = preg_replace('/(?|<a href="mailto[\s]*:[\s]*([_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]+)*'.'\@'\r
329                                     .'[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]+)*'.'(\.[a-zA-Z]{1,6})+)">(.*)<\/a>'\r
330                                     .'|((((([_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]+)*'.'\@'\r
331                                     .'[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]+)*'.'(\.[a-zA-Z]{1,6})+))))))/i',\r
332                                                         "<a href=\"mailto:\\1\">\\5</a>",\r
333                                                         $text);\r
334                 \r
335                 // flv conversion needs to come after url conversion (2 lines above) otherwise the url to flowplayer swf file\r
336                 // in the script for a.flowplayerholder is converted\r
337                 $text = ContentUtility::embedFLV($text);\r
338                 \r
339                 return $text;\r
340         }\r
341 \r
342         public static function myCodes($text, $html = false) {\r
343                 global $_base_path;\r
344                 global $HTTP_USER_AGENT;\r
345         \r
346                 if (substr($HTTP_USER_AGENT,0,11) == 'Mozilla/4.7') {\r
347                         $text = str_replace('[quote]','</p><p class="block">',$text);\r
348                         $text = str_replace('[/quote]','</p><p>',$text);\r
349         \r
350                         $text = str_replace('[reply]','</p><p class="block">',$text);\r
351                         $text = str_replace('[/reply]','</p><p>',$text);\r
352                 } else {\r
353                         $text = str_replace('[quote]','<blockquote>',$text);\r
354                         $text = str_replace('[/quote]','</blockquote><p>',$text);\r
355         \r
356                         $text = str_replace('[reply]','</p><blockquote class="block"><p>',$text);\r
357                         $text = str_replace('[/reply]','</p></blockquote><p>',$text);\r
358                 }\r
359         \r
360                 $text = str_replace('[b]','<strong>',$text);\r
361                 $text = str_replace('[/b]','</strong>',$text);\r
362         \r
363                 $text = str_replace('[i]','<em>',$text);\r
364                 $text = str_replace('[/i]','</em>',$text);\r
365         \r
366                 $text = str_replace('[u]','<u>',$text);\r
367                 $text = str_replace('[/u]','</u>',$text);\r
368         \r
369                 $text = str_replace('[center]','<center>',$text);\r
370                 $text = str_replace('[/center]','</center><p>',$text);\r
371         \r
372                 /* colours */\r
373                 $text = str_replace('[blue]','<span style="color: blue;">',$text);\r
374                 $text = str_replace('[/blue]','</span>',$text);\r
375         \r
376                 $text = str_replace('[orange]','<span style="color: orange;">',$text);\r
377                 $text = str_replace('[/orange]','</span>',$text);\r
378         \r
379                 $text = str_replace('[red]','<span style="color: red;">',$text);\r
380                 $text = str_replace('[/red]','</span>',$text);\r
381         \r
382                 $text = str_replace('[purple]','<span style="color: purple;">',$text);\r
383                 $text = str_replace('[/purple]','</span>',$text);\r
384         \r
385                 $text = str_replace('[green]','<span style="color: green;">',$text);\r
386                 $text = str_replace('[/green]','</span>',$text);\r
387         \r
388                 $text = str_replace('[gray]','<span style="color: gray;">',$text);\r
389                 $text = str_replace('[/gray]','</span>',$text);\r
390         \r
391                 $text = str_replace('[op]','<span class="bigspacer"></span> <a href="',$text);\r
392                 $text = str_replace('[/op]','">'._AT('view_entire_post').'</a>',$text);\r
393         \r
394                 $text = str_replace('[head1]','<h2>',$text);\r
395                 $text = str_replace('[/head1]','</h2>',$text);\r
396         \r
397                 $text = str_replace('[head2]','<h3>',$text);\r
398                 $text = str_replace('[/head2]','</h3>',$text);\r
399         \r
400                 $text = str_replace('[cid]',$_base_path.'content.php?_cid='.$_SESSION['s_cid'],$text);\r
401         \r
402                 global $sequence_links, $_course_id, $_content_id;\r
403                 if ($_course_id > 0 && !isset($sequence_links) && $_content_id > 0) {\r
404                         global $contentManager;\r
405                         $sequence_links = $contentManager->generateSequenceCrumbs($_content_id);\r
406                 }\r
407                 if (isset($sequence_links['previous']) && $sequence_links['previous']['url']) {\r
408                         $text = str_replace('[pid]', $sequence_links['previous']['url'], $text);\r
409                 }\r
410                 if (isset($sequence_links['next']) && $sequence_links['next']['url']) {\r
411                         $text = str_replace('[nid]', $sequence_links['next']['url'], $text);\r
412                 }\r
413                 if (isset($sequence_links['resume']) && $sequence_links['resume']['url']) {\r
414                         $text = str_replace('[nid]', $sequence_links['resume']['url'], $text);\r
415                 }\r
416                 if (isset($sequence_links['first']) && $sequence_links['first']['url']) {\r
417                         $text = str_replace('[fid]', $sequence_links['first']['url'], $text);\r
418                 }\r
419         \r
420                 /* contributed by Thomas M. Duffey <tduffey at homeboyz.com> */\r
421             $html = !$html ? 0 : 1;\r
422             \r
423                 // little hack added by greg to add syntax highlighting without using <?php \?\>\r
424                 \r
425                 $text = str_replace("[code]","[code]<?php",$text);\r
426                 $text = str_replace("[/code]","?>[/code]",$text);\r
427         \r
428                 $text = preg_replace("/\[code\]\s*(.*)\s*\[\\/code\]/Usei", "ContentUtility::highlightCode(ContentUtility::fixQuotes('\\1'), $html)", $text);\r
429                 // now remove the <?php added above and leave the syntax colour behind.\r
430                 $text = str_replace("&lt;?php", "", $text);\r
431                 $text = str_replace("?&gt;", "", $text);\r
432         \r
433                 return $text;\r
434         }\r
435 \r
436         /* contributed by Thomas M. Duffey <tduffey at homeboyz.com> */\r
437         private static function highlightCode($code, $html) {\r
438                 // XHTMLize PHP highlight_string output until it gets fixed in PHP\r
439                 static $search = array(\r
440                         '<br>',\r
441                         '<font',\r
442                         '</font>',\r
443                         'color="');\r
444         \r
445                 static $replace = array(\r
446                         '<br />',\r
447                         '<span',\r
448                         '</span>',\r
449                         'style="color:');\r
450                 if (!$html) {\r
451                         $code = str_replace('&lt;', '<', $code);\r
452                         $code = str_replace("\r", '', $code);\r
453                 }\r
454         \r
455                 return str_replace($search, $replace, highlight_string($code, true));\r
456         }\r
457         \r
458         /* contributed by Thomas M. Duffey <tduffey at homeboyz.com> */\r
459         private static function fixQuotes($text){\r
460                 return str_replace('\\"', '"', $text);\r
461         }\r
462 \r
463         public static function imageReplace($text) {\r
464                 /* image urls do not require http:// */\r
465                 \r
466         //      $text = eregi_replace("\[image(\|)?([[:alnum:][:space:]]*)\]" .\r
467         //                                               "[:space:]*" .\r
468         //                                               "([[:alnum:]#?/&=:\"'_.-]+)" .\r
469         //                                               "[:space:]*" .\r
470         //                                               "((\[/image\])|(.*\[/image\]))",\r
471         //                                "<img src=\"\\3\" alt=\"\\2\" />",\r
472         //                                $text);\r
473                  \r
474                 $text = preg_replace("/\[image(\|)?([a-zA-Z0-9\s]*)\]".\r
475                                      "[\s]*".\r
476                                      "([a-zA-Z0-9\#\?\/\&\=\:\\\"\'\_\.\-]+)[\s]*".\r
477                                      "((\[\/image\])|(.*\[\/image\]))/i",\r
478                                           "<img src=\"\\3\" alt=\"\\2\" />",\r
479                                           $text);\r
480                                           \r
481                 return $text;\r
482         }\r
483         \r
484         private static function formatFinalOutput($text, $nl2br = true) {\r
485                 global $_base_path;\r
486         \r
487                 $text = str_replace('CONTENT_DIR/', '', $text);\r
488                 if ($nl2br) {\r
489                         return nl2br(ContentUtility::imageReplace(ContentUtility::makeClickable(ContentUtility::myCodes(' '.$text, false))));\r
490                 }\r
491         \r
492                 return ContentUtility::imageReplace(ContentUtility::makeClickable(ContentUtility::myCodes(' '.$text, true)));\r
493         }\r
494 \r
495         /**\r
496         * This function converts the input string into AContent html content string \r
497         * @access  public\r
498         * @param   $input: input string\r
499         *          $html: whether the input is in html\r
500         * @return  converted AContent html content string\r
501         * @author  Cindy Qi Li\r
502         */\r
503         public static function formatContent($input, $html = 0) {\r
504                 global $_base_path, $_config;\r
505         \r
506                 if (!$html) {\r
507                         $input = str_replace('<', '&lt;', $input);\r
508                         $input = str_replace('&lt;?php', '<?php', $input); // for bug #2087\r
509                 } elseif ($html==2) {\r
510                         $output = '<iframe width="100%" frameborder="0" id="content_frame" marginheight="0" marginwidth="0" src="'.$input.'"></iframe>';\r
511                         $output .=      '<script type="text/javascript">\r
512                                                 function resizeIframe() {\r
513                                                         var height = document.documentElement.clientHeight;\r
514                                                         \r
515                                                         // not sure how to get this dynamically\r
516                                                         height -= 20; /* whatever you set your body bottom margin/padding to be */\r
517                                                         \r
518                                                         document.getElementById(\'content_frame\').style.height = height +"px";\r
519                                                         \r
520                                                 };\r
521                                                 document.getElementById(\'content_frame\').onload = resizeIframe;\r
522                                                 window.onresize = resizeIframe;\r
523                                                 </script>';\r
524                         return $output;\r
525                 }\r
526         \r
527                 /* Commented by Cindy Qi Li on Jan 12, 2010\r
528                  * AContent does not support glossary\r
529                 // do the glossary search and replace:\r
530                 if (is_array($glossary)) {\r
531                         foreach ($glossary as $k => $v) {\r
532                                 $k = urldecode($k);\r
533                                 $v = str_replace("\n", '<br />', $v);\r
534                                 $v = str_replace("\r", '', $v);\r
535         \r
536                                 // escape special characters\r
537                                 $k = preg_quote($k);\r
538         \r
539                                 $k = str_replace('&lt;', '<', $k);\r
540                                 $k = str_replace('/', '\/', $k);\r
541         \r
542                                 $original_term = $k;\r
543                                 $term = $original_term;\r
544         \r
545                                 $term = '(\s*'.$term.'\s*)';\r
546                                 $term = str_replace(' ','((<br \/>)*\s*)', $term); \r
547         \r
548                                 $def = htmlspecialchars($v, ENT_QUOTES, 'UTF-8');               \r
549                                 if ($simple) {\r
550                                         $input = preg_replace\r
551                                                         ("/(\[\?\])$term(\[\/\?\])/i",\r
552                                                         '<a href="'.$simple.'glossary.html#'.urlencode($original_term).'" target="body" class="at-term">\\2</a>',\r
553                                                         $input);\r
554                                 } else {\r
555                                         $input = preg_replace\r
556                                                 ("/(\[\?\])$term(\[\/\?\])/i",\r
557                                                 '\\2<sup><a class="tooltip" href="'.$_base_path.'mods/_core/glossary/index.php?g_cid='.$_SESSION['s_cid'].htmlentities(SEP).'w='.urlencode($original_term).'#term" title="'.addslashes($original_term).': '.$def.'">?</a></sup>',$input);\r
558                                 }\r
559                         }\r
560                 } else if (!$user_glossary) {\r
561                         $input = str_replace(array('[?]','[/?]'), '', $input);\r
562                 }\r
563                 */\r
564 \r
565                 \r
566                 $input = str_replace('CONTENT_DIR', '', $input);\r
567         \r
568                 if (isset($_config['latex_server']) && $_config['latex_server']) {\r
569                         // see: http://www.forkosh.com/mimetex.html\r
570                         $input = preg_replace('/\[tex\](.*?)\[\/tex\]/sie', "'<img src=\"'.\$_config['latex_server'].rawurlencode('$1').'\" align=\"middle\">'", $input);\r
571                 }\r
572         \r
573                 if ($html) {\r
574                         $x = ContentUtility::formatFinalOutput($input, false);\r
575                         return $x;\r
576                 }\r
577         \r
578                 $output = ContentUtility::formatFinalOutput($input);\r
579         \r
580                 $output = '<p>'.$input.'</p>';\r
581         \r
582                 return $output;\r
583         }\r
584         \r
585         /**\r
586          * This function returns html string of "table of content"\r
587          * @access: public\r
588          * @param: $content: a string\r
589          * @return: a html string of "table of content"\r
590          */\r
591         public static function getContentTable($content)\r
592         {\r
593                 preg_match_all("/<(h[\d]+)[^>]*>(.*)<\/(\s*)\\1(\s*)>/i", $content, $found_headers, PREG_SET_ORDER);\r
594                 \r
595                 if (count($found_headers) == 0) return array("", $content);\r
596                 else\r
597                 {\r
598                         $num_of_headers = 0;\r
599         \r
600                         for ($i = 0; $i < count($found_headers); $i++)\r
601                         {\r
602                                 $div_id = "_header_" . $num_of_headers++;\r
603                                 \r
604                                 if ($i == 0)\r
605                                 {\r
606                                         $content_table = "<div id=\"toc\">\n<fieldset id=\"toc\"><legend>". _AT("table_of_contents")."</legend>\n";\r
607                                 }\r
608         \r
609                                 $content = str_replace($found_headers[$i][0], '<div id="'.$div_id.'">'.$found_headers[$i][0].'</div>', $content);\r
610                                 $content_table .= '<a href="'.$_SERVER["REQUEST_URI"].'#'.$div_id.'" class="'.$found_headers[$i][1].'">'. $found_headers[$i][2]."</a>\n";\r
611         \r
612                                 if ($i == count($found_headers) - 1)\r
613                                 {\r
614                                         $content_table .= "</fieldset></div><br />";\r
615                                 }\r
616                         }\r
617                         return array($content_table, $content);\r
618                 }\r
619         }\r
620         \r
621         /**\r
622          * This function returns an array of content tools' shortcuts\r
623          * @access: public\r
624          * @param: $content_row: an array of the current content information\r
625          * @return: an array of all the tool short cuts that apply to the current content or content folder\r
626          */\r
627         public static function getToolShortcuts($content_row)\r
628         {\r
629                 global $_current_user, $_base_href, $contentManager, $_course_id;\r
630                 \r
631                 if (((!$content_row['content_parent_id'] && ($_SESSION['packaging'] == 'top'))\r
632                       || ($_SESSION['packaging'] == 'all'))\r
633                           || (isset($_current_user) && $_current_user->isAuthor($_course_id))) {\r
634                 \r
635                         $tool_shortcuts[] = array(\r
636                                   'title' => _AT('export_content_in_cp'), \r
637                                   'url' => $_base_href . 'home/ims/ims_export.php?_cid='.$content_row['content_id'],\r
638                                   'icon' => $_base_href . 'themes/'.$_SESSION['prefs']['PREF_THEME'].'/images/export.png');\r
639                         $tool_shortcuts[] = array(\r
640                                   'title' => _AT('export_content_in_cc'), \r
641                                   'url' => $_base_href . 'home/imscc/ims_export.php?_cid='.$content_row['content_id'].SEP.'to_a4a=1',\r
642                                   'icon' => $_base_href . 'themes/'.$_SESSION['prefs']['PREF_THEME'].'/images/export_cc.png');\r
643                 }\r
644                 \r
645                 if (isset($_current_user) && $_current_user->isAuthor($_course_id)) {\r
646                         if ($content_row['content_type'] == CONTENT_TYPE_CONTENT || $content_row['content_type'] == CONTENT_TYPE_WEBLINK) {\r
647                                 $tool_shortcuts[] = array(\r
648                                           'title' => _AT('edit_this_page'),   \r
649                                            'url' => $_base_href . 'home/editor/edit_content.php?_cid='.$content_row['content_id'],\r
650                                           'icon' => $_base_href . 'images/medit.gif');\r
651                         }\r
652                 \r
653                         $tool_shortcuts[] = array(\r
654                           'title' => _AT('add_sibling_folder'), \r
655                           'url' => $_base_href .\r
656                                 'home/editor/edit_content_folder.php?pid='.$contentManager->_menu_info[$content_row['content_id']]['content_parent_id'].SEP.'_course_id='.$_course_id,\r
657                            'icon' => $_base_href . 'images/add_sibling_folder.gif');\r
658 \r
659                         if ($content_row['content_type'] == CONTENT_TYPE_FOLDER || $content_row['content_type'] == CONTENT_TYPE_WEBLINK) {\r
660                                 $tool_shortcuts[] = array(\r
661                                   'title' => _AT('add_sub_folder'), \r
662                                   'url' => $_base_href .\r
663                                         'home/editor/edit_content_folder.php?_course_id='.$_course_id.SEP.'pid='.$content_row['content_id'],\r
664                                    'icon' => $_base_href . 'images/add_sub_folder.gif');\r
665                         }\r
666                         \r
667                         $tool_shortcuts[] = array(\r
668                           'title' => _AT('add_sibling_page'), \r
669                           'url' => $_base_href .\r
670                                 'home/editor/edit_content.php?pid='.$contentManager->_menu_info[$content_row['content_id']]['content_parent_id'].SEP.'_course_id='.$_course_id,\r
671                           'icon' => $_base_href . 'images/add_sibling_page.gif');\r
672                         \r
673                         if ($content_row['content_type'] == CONTENT_TYPE_CONTENT || $content_row['content_type'] == CONTENT_TYPE_WEBLINK) {\r
674                                 $tool_shortcuts[] = array(\r
675                                   'title' => _AT('delete_this_page'),   \r
676                                   'url' => $_base_href . 'home/editor/delete_content.php?_cid='.$content_row['content_id'],\r
677                                   'icon' => $_base_href . 'images/page_delete.gif');\r
678                         }\r
679                         else if ($content_row['content_type'] == CONTENT_TYPE_FOLDER) {\r
680                                 $tool_shortcuts[] = array(\r
681                                   'title' => _AT('add_sub_page'),       \r
682                                   'url' => $_base_href . 'home/editor/edit_content.php?_course_id='.$_course_id.SEP.'pid='.$content_row['content_id'],\r
683                                   'icon' => $_base_href . 'images/add_sub_page.gif');\r
684                                 \r
685                                 $tool_shortcuts[] = array(\r
686                                   'title' => _AT('delete_this_folder'),         \r
687                                   'url' => $_base_href . 'home/editor/delete_content.php?_cid='.$content_row['content_id'],\r
688                                   'icon' => $_base_href . 'images/page_delete.gif');\r
689                         }\r
690                 }\r
691                 return $tool_shortcuts;\r
692 \r
693 //      if (isset($_current_user) && $_current_user->isAuthor($_course_id)) {\r
694 //              $shortcuts[] = array('title' => _AT('add_sub_folder'),   'url' => $_base_href . 'home/editor/edit_content_folder.php?_course_id='.$_course_id.'pid='.$cid);\r
695 //              \r
696 ////            $shortcuts[] = array('title' => _AT('add_top_page'),     'url' => $_base_href . 'home/editor/edit_content.php?_course_id='.$_course_id, 'icon' => $_base_href . 'images/page_add.gif');\r
697 //              if ($contentManager->_menu_info[$cid]['content_parent_id']) {\r
698 //                      $shortcuts[] = array('title' => _AT('add_sibling_page'), 'url' => $_base_href .\r
699 //                              'home/editor/edit_content.php?_course_id='.$_course_id.SEP.'pid='.$contentManager->_menu_info[$cid]['content_parent_id'], 'icon' => $_base_href . 'images/page_add_sibling.gif');\r
700 //              }\r
701 //      \r
702 //              $shortcuts[] = array('title' => _AT('add_sub_page'),     'url' => $_base_href . 'home/editor/edit_content.php?_course_id='.$_course_id.SEP.'pid='.$cid);\r
703 //              $shortcuts[] = array('title' => _AT('delete_this_folder'), 'url' => $_base_href . 'home/editor/delete_content.php?_cid='.$cid, 'icon' => $_base_href . 'images/page_delete.gif');\r
704 //      }\r
705         }\r
706         \r
707         /**\r
708         * replace source object with alternatives according to user's preferences\r
709         * @access       public\r
710         * @param        $cid:                           content id.\r
711         * @param        $content:                       the original content page ($content_row['text'], from content.php).\r
712         * @param    $info_only:         when "true", return the array of info (has_text_alternative, has_audio_alternative, has_visual_alternative, has_sign_lang_alternative)\r
713         * @param    $only_on_secondary_type: \r
714         * @return       string                          $content: the content page with the appropriated resources.\r
715         * @see          $db                             from include/vitals.inc.php\r
716         * @author       Cindy Qi Li\r
717         */\r
718         public static function applyAlternatives($cid, $content, $info_only = false, $only_on_secondary_type = 0){\r
719                 global $db, $_course_id;\r
720                 \r
721                 include_once(TR_INCLUDE_PATH.'classes/DAO/DAO.class.php');\r
722                 $dao = new DAO();\r
723                 \r
724                 // All a4a resources have "&" converted to "&amp;". To match content with resources, \r
725         // need the same conversion on content. \r
726         $content = convertAmp($content);\r
727         \r
728         // keep &lt; (content saved in plain text format) as it is instead of &amp;lt;\r
729         $content = str_replace('&amp;lt;', '&lt;', $content);\r
730         \r
731         $video_exts = array("mpg", "avi", "wmv", "mov", "swf", "mp4", "flv");\r
732         \r
733         $audio_exts = array("mp3", "wav", "ogg", "mid");\r
734         $audio_width = 425;\r
735         $audio_height = 27;\r
736 \r
737                 $txt_exts = array("txt", "html", "htm");\r
738                 $image_exts = array("gif", "bmp", "png", "jpg", "jpeg", "png", "tif");\r
739                 $only_on_secondary_type = intval($only_on_secondary_type);\r
740                                 \r
741                 // intialize the 4 returned values when $info_only is on\r
742                 if ($info_only)\r
743                 {\r
744                         $has_text_alternative = false;\r
745                         $has_audio_alternative = false;\r
746                         $has_visual_alternative = false;\r
747                         $has_sign_lang_alternative = false;\r
748                 }\r
749 \r
750                 if (!$info_only && !$only_on_secondary_type && \r
751                     ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_TEXT']==0) && \r
752                     ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_AUDIO']==0) && \r
753                     ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_VISUAL']==0)) \r
754                 {\r
755                         //No user's preferences related to content format are declared\r
756                         if (!$info_only) {\r
757                                 return $content;\r
758                         } else {\r
759                                 return array($has_text_alternative, $has_audio_alternative, $has_visual_alternative, $has_sign_lang_alternative);\r
760                         }\r
761                 }\r
762                 // get all relations between primary resources and their alternatives\r
763         $sql = "SELECT DISTINCT c.content_path, pr.resource, ";\r
764         \r
765         // ignore primary resource type if the request is on particular secondary type.\r
766         // otherwise, if the primary resource is defined with multiple primary types, \r
767         // the primary resource would be replaced/appended multiple times.\r
768         if ($only_on_secondary_type == 0) {\r
769             $sql .= "prt.type_id primary_type, ";\r
770         }\r
771         $sql .= "sr.secondary_resource, srt.type_id secondary_type\r
772                           FROM ".TABLE_PREFIX."primary_resources pr, ".\r
773                                  TABLE_PREFIX."primary_resources_types prt,".\r
774                                  TABLE_PREFIX."secondary_resources sr,".\r
775                                  TABLE_PREFIX."secondary_resources_types srt,".\r
776                                  TABLE_PREFIX."content c\r
777                          WHERE pr.content_id=".$cid."\r
778                                AND pr.primary_resource_id = prt.primary_resource_id\r
779                                AND pr.primary_resource_id = sr.primary_resource_id\r
780                                AND sr.language_code='".$_SESSION['lang']."'\r
781                                AND sr.secondary_resource_id = srt.secondary_resource_id\r
782                            AND pr.content_id = c.content_id";\r
783                 if ($only_on_secondary_type > 0) {\r
784                         $sql .= " AND srt.type_id=".$only_on_secondary_type;\r
785                 }\r
786                 $sql .= " ORDER BY pr.primary_resource_id, prt.type_id";\r
787                 \r
788                 $rows = $dao->execute($sql);\r
789         \r
790                 if (!is_array($rows)) {\r
791                         if (!$info_only) {\r
792                                 return $content;\r
793                         } else {\r
794                                 return array($has_text_alternative, $has_audio_alternative, $has_visual_alternative, $has_sign_lang_alternative);\r
795                         }\r
796                 }\r
797                 \r
798                 foreach ($rows as $row) {\r
799             $alternative_rows[] = $row;\r
800             \r
801             $youtube_playURL = ContentUtility::convertYoutubeWatchURLToPlayURL($row['resource']);\r
802             \r
803             if ($row['resource'] <> $youtube_playURL) {\r
804                 $row['resource'] = $youtube_playURL;\r
805                 $alternative_rows[] = $row;\r
806             }\r
807         }\r
808 \r
809         foreach ($alternative_rows as $row) \r
810                 {\r
811                         if ($info_only || $only_on_secondary_type ||\r
812                             ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_TEXT']==1 && $row['primary_type']==3 &&\r
813                             ($_SESSION['prefs']['PREF_ALT_TO_TEXT']=="audio" && $row['secondary_type']==1 || \r
814                              $_SESSION['prefs']['PREF_ALT_TO_TEXT']=="visual" && $row['secondary_type']==4 || \r
815                              $_SESSION['prefs']['PREF_ALT_TO_TEXT']=="sign_lang" && $row['secondary_type']==2)) ||\r
816                              \r
817                              ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_AUDIO']==1 && $row['primary_type']==1 &&\r
818                              ($_SESSION['prefs']['PREF_ALT_TO_AUDIO']=="visual" && $row['secondary_type']==4 || \r
819                               $_SESSION['prefs']['PREF_ALT_TO_AUDIO']=="text" && $row['secondary_type']==3 || \r
820                               $_SESSION['prefs']['PREF_ALT_TO_AUDIO']=="sign_lang" && $row['secondary_type']==2)) ||\r
821                               \r
822                              ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_VISUAL']==1 && $row['primary_type']==4 &&\r
823                              ($_SESSION['prefs']['PREF_ALT_TO_VISUAL']=="audio" && $row['secondary_type']==1 || \r
824                               $_SESSION['prefs']['PREF_ALT_TO_VISUAL']=="text" && $row['secondary_type']==3 || \r
825                               $_SESSION['prefs']['PREF_ALT_TO_VISUAL']=="sign_lang" && $row['secondary_type']==2))\r
826                             )\r
827                         {\r
828                                 $ext = substr($row['secondary_resource'], strrpos($row['secondary_resource'], '.')+1);\r
829                                 \r
830                                 // alternative is video\r
831                                 if (in_array($ext, $video_exts)|| in_array($ext, $audio_exts) || \r
832                     preg_match("/http:\/\/.*youtube.com\/watch.*/", $row['secondary_resource'])) {\r
833                     if (in_array($ext, $audio_exts)) {\r
834                         // display audio medias in a smaller width/height (425 * 27)\r
835                         // A hack for now to handle audio media player size\r
836                         $target = '[media|'.$audio_width.'|'.$audio_height.']'.$row['secondary_resource'].'[/media]';\r
837                     } else {\r
838                         // use default media size for video medias\r
839                         $target = '[media]'.$row['secondary_resource'].'[/media]';\r
840                     }\r
841                     $target = ContentUtility::embedFLV(ContentUtility::embedMedia($target));\r
842                 }\r
843                                 // a text primary to be replaced by a visual alternative \r
844                                 else if (in_array($ext, $txt_exts))\r
845                                 {\r
846                                         if ($row['content_path'] <> '') \r
847                                                 $file_location = $row['content_path'].'/'.$row['secondary_resource'];\r
848                                         else \r
849                                                 $file_location = $row['secondary_resource'];\r
850                                         \r
851                                         $file = TR_CONTENT_DIR.$_SESSION['course_id'] . '/'.$file_location;\r
852                                         $target = '<br />'.file_get_contents($file);\r
853                                         \r
854                                         // check whether html file\r
855                                         if (preg_match('/.*\<html.*\<\/html\>.*/s', $target))\r
856                                         { // is a html file, use iframe to display\r
857                                                 // get real path to the text file\r
858                                                 if (defined('TR_FORCE_GET_FILE') && TR_FORCE_GET_FILE) {\r
859                                                         $course_base_href = 'get.php/';\r
860                                                 } else {\r
861                                                         $course_base_href = 'content/' . $_SESSION['course_id'] . '/';\r
862                                                 }\r
863                 \r
864                                                 $file = TR_BASE_HREF . $course_base_href.$file_location;\r
865                                                         \r
866                                                 $target = '<iframe width="100%" frameborder="0" class="autoHeight" scrolling="auto" src="'.$file.'"></iframe>';\r
867                                         }\r
868                                         else\r
869                                         { // is a text file, insert/replace into content\r
870                                                 $target = nl2br($target);\r
871                                         }\r
872                                 } \r
873                                 else if (in_array($ext, $image_exts))\r
874                                         $target = '<img border="0" alt="'._AT('alternate_text').'" src="'.$row['secondary_resource'].'"/>';\r
875                                 // otherwise\r
876                                 else\r
877                                         $target = '<p><a href="'.$row['secondary_resource'].'">'.$row['secondary_resource'].'</a></p>';\r
878         \r
879                                 // replace or append the target alternative to the source\r
880                                 if (($row['primary_type']==3 && $_SESSION['prefs']['PREF_ALT_TO_TEXT_APPEND_OR_REPLACE'] == 'replace') ||\r
881                                         ($row['primary_type']==1 && $_SESSION['prefs']['PREF_ALT_TO_AUDIO_APPEND_OR_REPLACE']=='replace') ||\r
882                                         ($row['primary_type']==4 && $_SESSION['prefs']['PREF_ALT_TO_VISUAL_APPEND_OR_REPLACE']=='replace'))\r
883                                         $pattern_replace_to = '${1}'."\n".$target."\n".'${3}';\r
884                 else\r
885                     $pattern_replace_to = '${1}${2}'."<br /><br />\n".$target."\n".'${3}';\r
886 \r
887                 // *** Alternative replace/append starts from here ***\r
888                 $processed = false;    // one primary resource is only processed once \r
889                 \r
890                 // append/replace target alternative to [media]source[/media]\r
891                 if (!$processed && preg_match("/".preg_quote("[media").".*".preg_quote("]".$row['resource']."[/media]", "/")."/sU", $content))\r
892                 {\r
893                     $processed = true;\r
894                                         if (!$info_only) {\r
895                                                 $content = preg_replace("/(.*)(".preg_quote("[media").".*".preg_quote("]".$row['resource']."[/media]", "/").")(.*)/sU", \r
896                                              $pattern_replace_to, $content);\r
897                                         } else {\r
898                                                 if ($row['secondary_type'] == 1) $has_audio_alternative = true;\r
899                                                 if ($row['secondary_type'] == 2) $has_sign_lang_alternative = true;\r
900                                                 if ($row['secondary_type'] == 3) $has_text_alternative = true;\r
901                                                 if ($row['secondary_type'] == 4) $has_visual_alternative = true;\r
902                                         }\r
903                                 }\r
904                                 \r
905                                 // append/replace target alternative to <img ... src="source" ...></a>\r
906                                 if (!$processed && preg_match("/\<img.*src=\"".preg_quote($row['resource'], "/")."\".*\/\>/sU", $content))\r
907                 {\r
908                     $processed = true;\r
909                                         if (!$info_only) {\r
910                                                 $content = preg_replace("/(.*)(\<img.*src=\"".preg_quote($row['resource'], "/")."\".*\/\>)(.*)/sU", \r
911                                                         $pattern_replace_to, $content);\r
912                                         } else {\r
913                                                 if ($row['secondary_type'] == 1) $has_audio_alternative = true;\r
914                                                 if ($row['secondary_type'] == 2) $has_sign_lang_alternative = true;\r
915                                                 if ($row['secondary_type'] == 3) $has_text_alternative = true;\r
916                                                 if ($row['secondary_type'] == 4) $has_visual_alternative = true;\r
917                                         }\r
918                                 }\r
919                                 \r
920                                 // append/replace target alternative to <object ... source ...></object>\r
921                 if (!$processed && preg_match("/\<object.*".preg_quote($row['resource'], "/").".*\<\/object\>/sU", $content))\r
922                 {\r
923                     $processed = true;\r
924                     if (!$info_only) {\r
925                         $content = preg_replace("/(.*)(\<object.*".preg_quote($row['resource'], "/").".*\<\/object\>)(.*)/sU", \r
926                                                         $pattern_replace_to, $content);\r
927                                         } else {\r
928                                                 if ($row['secondary_type'] == 1) $has_audio_alternative = true;\r
929                                                 if ($row['secondary_type'] == 2) $has_sign_lang_alternative = true;\r
930                                                 if ($row['secondary_type'] == 3) $has_text_alternative = true;\r
931                                                 if ($row['secondary_type'] == 4) $has_visual_alternative = true;\r
932                                         }\r
933                                 }\r
934         \r
935                                 // append/replace target alternative to <a>...source...</a> or <a ...source...>...</a>\r
936                 // skip this "if" when the source object has been processed in aboved <img> tag\r
937                 if (!$processed && preg_match("/\<a.*".preg_quote($row['resource'], "/").".*\<\/a\>/sU", $content))\r
938                 {\r
939                     $processed = true;\r
940                     if (!$info_only) {\r
941                         $content = preg_replace("/(.*)(\<a.*".preg_quote($row['resource'], "/").".*\<\/a\>)(.*)/sU",\r
942                                                         $pattern_replace_to, $content);\r
943                                         } else {\r
944                                                 if ($row['secondary_type'] == 1) $has_audio_alternative = true;\r
945                                                 if ($row['secondary_type'] == 2) $has_sign_lang_alternative = true;\r
946                                                 if ($row['secondary_type'] == 3) $has_text_alternative = true;\r
947                                                 if ($row['secondary_type'] == 4) $has_visual_alternative = true;\r
948                                         }\r
949                                 }\r
950         \r
951                                 // append/replace target alternative to <embed ... source ...>\r
952                                 if (!$processed && preg_match("/\<embed.*".preg_quote($row['resource'], "/").".*\>/sU", $content))\r
953                 {\r
954                     $processed = true;\r
955                                         if (!$info_only) {\r
956                                                 $content = preg_replace("/(.*)(\<embed.*".preg_quote($row['resource'], "/").".*\>)(.*)/sU", \r
957                                                         $pattern_replace_to, $content);\r
958                                         } else {\r
959                                                 if ($row['secondary_type'] == 1) $has_audio_alternative = true;\r
960                                                 if ($row['secondary_type'] == 2) $has_sign_lang_alternative = true;\r
961                                                 if ($row['secondary_type'] == 3) $has_text_alternative = true;\r
962                                                 if ($row['secondary_type'] == 4) $has_visual_alternative = true;\r
963                                         }\r
964                                 }\r
965                         }\r
966                 }\r
967                 \r
968                 if (!$info_only) {\r
969                         return $content;\r
970                 } else {\r
971                         return array($has_text_alternative, $has_audio_alternative, $has_visual_alternative, $has_sign_lang_alternative);\r
972                 }\r
973         }       \r
974                 \r
975         /**\r
976          * This function save the last content_id accessed by current user on a course into db and set $_SESSION['s_cid']\r
977          * @access: public\r
978          * @param: $content_id\r
979          * @return: save $content_id, the last visited one of the current user, into db and session\r
980          */\r
981         public static function saveLastCid($content_id)\r
982         {\r
983                 global $_course_id;\r
984                 \r
985                 if (!$content_id || !isset($_SESSION['user_id'])) return;\r
986                 \r
987                 include_once(TR_INCLUDE_PATH.'classes/DAO/UserCoursesDAO.class.php');\r
988                 \r
989                 $userCoursesDAO = new UserCoursesDAO();\r
990                 if ($userCoursesDAO->isExist($_SESSION['user_id'], $_course_id))\r
991                 {\r
992                         $userCoursesDAO->UpdateLastCid($_SESSION['user_id'], $_course_id, $content_id);\r
993                         $_SESSION['s_cid'] = $content_id;\r
994                 }\r
995         }\r
996 }\r
997 ?>