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