ATutor 2.0
[atutor.git] / include / lib / output.inc.php
1 <?php
2 /****************************************************************/
3 /* ATutor                                                                                                               */
4 /****************************************************************/
5 /* Copyright (c) 2002-2009                                                                              */
6 /* Inclusive Design Institute                                   */
7 /* http://atutor.ca                                                                                             */
8 /*                                                              */
9 /* This program is free software. You can redistribute it and/or*/
10 /* modify it under the terms of the GNU General Public License  */
11 /* as published by the Free Software Foundation.                                */
12 /****************************************************************/
13 // $Id$
14 if (!defined('AT_INCLUDE_PATH')) { exit; }
15 //require_once(AT_INCLUDE_PATH . 'classes/ContentOutputUtils.class.php');
16
17 /**********************************************************************************/
18 /* Output functions found in this file, in order:
19 /*
20 /*      - AT_date(format, timestamp, format_type)
21 /*
22 /*      - _AT([...])
23 /*      - AT_print(input, name, Boolean runtime_html)
24 /*
25 /*      - smile_replace(text)
26 /*      - myCodes(text)
27 /*      - make_clickable(text)
28 /*      - image_replace(text)
29 /*      - format_final_output(text, Boolean nl2br)
30 /*      - highlight (input, var)
31 /*      - format_content(input, Boolean html, glossary)
32 /*      - find_terms(find_text)
33 /*
34 /**********************************************************************************/
35
36
37 /**
38 * Returns a formatted date string - Uses the same options as date(), but requires a % infront of each argument and the
39 * textual values are language dependent (unlike date()).
40 * @access  public
41 * @param   string $format               preferred date format 
42 * @param   string $timestamp    value of timestamp
43 * @param   int $format_type             timestamp format, an AT_DATE constant
44 * @return  string                               formatted date
45 * @see     AT_DATE constants    in include/lib/constants.inc.php
46 * @author  Joel Kronenberg
47 */
48
49 /* 
50         The following options were added as language dependant:
51         %D: A textual representation of a week, three letters Mon through Sun
52         %F: A full textual representation of a month, such as January or March January through December
53         %l (lowercase 'L'): A full textual representation of the day of the week Sunday through Saturday
54         %M: A short textual representation of a month, three letters Jan through Dec
55
56         Support for the following maybe added later:
57         ?? %S: English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
58         ?? %a: Lowercase Ante meridiem and Post meridiem am or pm 
59         ?? %A: Uppercase Ante meridiem and Post meridiem AM or PM 
60
61         valid format_types:
62         AT_DATE_MYSQL_DATETIME:         YYYY-MM-DD HH:MM:SS
63         AT_DATE_MYSQL_TIMESTAMP_14:     YYYYMMDDHHMMSS
64         AT_DATE_UNIX_TIMESTAMP:         seconds since epoch
65         AT_DATE_INDEX_VALUE:            0-x, index into a date array
66 */
67 function AT_date($format='%Y-%M-%d', $timestamp = '', $format_type=AT_DATE_MYSQL_DATETIME) {    
68         static $day_name_ext, $day_name_con, $month_name_ext, $month_name_con;
69         global $_config;
70
71         if (!isset($day_name_ext)) {
72                 $day_name_ext = array(  'date_sunday', 
73                                                                 'date_monday', 
74                                                                 'date_tuesday', 
75                                                                 'date_wednesday', 
76                                                                 'date_thursday', 
77                                                                 'date_friday',
78                                                                 'date_saturday');
79
80                 $day_name_con = array(  'date_sun', 
81                                                                 'date_mon', 
82                                                                 'date_tue', 
83                                                                 'date_wed',
84                                                                 'date_thu', 
85                                                                 'date_fri', 
86                                                                 'date_sat');
87
88                 $month_name_ext = array('date_january', 
89                                                                 'date_february', 
90                                                                 'date_march', 
91                                                                 'date_april', 
92                                                                 'date_may',
93                                                                 'date_june', 
94                                                                 'date_july', 
95                                                                 'date_august', 
96                                                                 'date_september', 
97                                                                 'date_october', 
98                                                                 'date_november',
99                                                                 'date_december');
100
101                 $month_name_con = array('date_jan', 
102                                                                 'date_feb', 
103                                                                 'date_mar', 
104                                                                 'date_apr', 
105                                                                 'date_may_short',
106                                                                 'date_jun', 
107                                                                 'date_jul', 
108                                                                 'date_aug', 
109                                                                 'date_sep', 
110                                                                 'date_oct', 
111                                                                 'date_nov',
112                                                                 'date_dec');
113         }
114
115         if ($format_type == AT_DATE_INDEX_VALUE) {
116                 // apply timezone offset
117 //              $timestamp = apply_timezone($timestamp);
118         
119                 if ($format == '%D') {
120                         return _AT($day_name_con[$timestamp-1]);
121                 } else if ($format == '%l') {
122                         return _AT($day_name_ext[$timestamp-1]);
123                 } else if ($format == '%F') {
124                         return _AT($month_name_ext[$timestamp-1]);
125                 } else if ($format == '%M') {
126                         return _AT($month_name_con[$timestamp-1]);
127                 }
128         }
129
130         if ($timestamp == '') {
131                 $timestamp = time();
132                 $format_type = AT_DATE_UNIX_TIMESTAMP;
133         }
134
135         /* convert the date to a Unix timestamp before we do anything with it */
136         if ($format_type == AT_DATE_MYSQL_DATETIME) {
137                 $year   = substr($timestamp,0,4);
138                 $month  = substr($timestamp,5,2);
139                 $day    = substr($timestamp,8,2);
140                 $hour   = substr($timestamp,11,2);
141                 $min    = substr($timestamp,14,2);
142                 $sec    = substr($timestamp,17,2);
143             $timestamp  = mktime($hour, $min, $sec, $month, $day, $year);
144
145         } else if ($format_type == AT_DATE_MYSQL_TIMESTAMP_14) {
146             $year               = substr($timestamp,0,4);
147             $month              = substr($timestamp,4,2);
148             $day                = substr($timestamp,6,2);
149                 $hour           = substr($timestamp,8,2);
150             $minute             = substr($timestamp,10,2);
151             $second             = substr($timestamp,12,2);
152             $timestamp  = mktime($hour, $minute, $second, $month, $day, $year);  
153         }
154
155         // apply timezone offset
156         $timestamp = apply_timezone($timestamp);
157
158         /* pull out all the %X items from $format */
159         $first_token = strpos($format, '%');
160         if ($first_token === false) {
161                 /* no tokens found */
162                 return $timestamp;
163         } else {
164                 $tokened_format = substr($format, $first_token);
165         }
166         $tokens = explode('%', $tokened_format);
167         array_shift($tokens);
168         $num_tokens = count($tokens);
169
170         $output = $format;
171         for ($i=0; $i<$num_tokens; $i++) {
172                 $tokens[$i] = substr($tokens[$i],0,1);
173
174                 if ($tokens[$i] == 'D') {
175                         $output = str_replace('%D', _AT($day_name_con[date('w', $timestamp)]),$output);
176                 
177                 } else if ($tokens[$i] == 'l') {
178                         $output = str_replace('%l', _AT($day_name_ext[date('w', $timestamp)]),$output);
179                 
180                 } else if ($tokens[$i] == 'F') {
181                         $output = str_replace('%F', _AT($month_name_ext[date('n', $timestamp)-1]),$output);             
182                 
183                 } else if ($tokens[$i] == 'M') {
184                         $output = str_replace('%M', _AT($month_name_con[date('n', $timestamp)-1]),$output);
185
186                 } else {
187
188                         /* this token doesn't need translating */
189                         $value = date($tokens[$i], $timestamp);
190                         if ($value != $tokens[$i]) {
191                                 $output = str_replace('%'.$tokens[$i], $value, $output);
192                         } /* else: this token isn't valid. so don't replace it. Eg. try %q */
193                 }
194         }
195
196         return $output;
197 }
198
199 /**
200 * Converts language code to actual language message, caches them according to page url
201 * @access       public
202 * @param        args                            unlimited number of arguments allowed but first arg MUST be name of the language variable/term
203 *                                                               i.e             $args[0] = the term to the format string $_template[term]
204 *                                                                               $args[1..x] = optional arguments to the formatting string 
205 * @return       string|array            full resulting message
206 * @see          $db                             in include/vitals.inc.php
207 * @see          cache()                         in include/phpCache/phpCache.inc.php
208 * @see          cache_variable()        in include/phpCache/phpCache.inc.php
209 * @author       Joel Kronenberg
210 */
211 function _AT() {
212         global $_cache_template, $lang_et, $_rel_url;
213         static $_template;
214         
215         $args = func_get_args();
216         
217         // a feedback msg
218         if (!is_array($args[0])) {
219                 /**
220                  * Added functionality for translating language code String (AT_ERROR|AT_INFOS|AT_WARNING|AT_FEEDBACK|AT_HELP).*
221                  * to its text and returning the result. No caching needed.
222                  * @author Jacek Materna
223                  */
224
225                 // Check for specific language prefix, extendible as needed
226                 // 0002767:  a substring+in_array test should be faster than a preg_match test.
227                 // replaced the preg_match with a test of the substring.
228                 $sub_arg = substr($args[0], 0, 7); // 7 is the shortest type of msg (AT_HELP)
229                 if (in_array($sub_arg, array('AT_ERRO','AT_INFO','AT_WARN','AT_FEED','AT_HELP','AT_CONF'))) {
230                         global $db;
231                         global $_base_path, $addslashes;
232
233                         $args[0] = $addslashes($args[0]);
234                                         
235                         /* get $_msgs_new from the DB */
236                         $sql    = 'SELECT text FROM '.TABLE_PREFIX.'language_text WHERE term="' . $args[0] . '" AND (variable="_msgs" OR variable="_c_msgs") AND language_code="'.$_SESSION['lang'].'" ORDER BY variable ASC LIMIT 1';
237
238                         $result = @mysql_query($sql, $db);
239                         $i = 1;
240                         $msgs = '';
241                                         
242                         if ($row = @mysql_fetch_assoc($result)) {
243                                 // do not cache key as a digit (no contstant(), use string)
244                                 $msgs = str_replace('SITE_URL/', $_base_path, $row['text']);
245                                 if (defined('AT_DEVEL') && AT_DEVEL) {
246                                         $msgs .= ' <small><small>('. $args[0] .')</small></small>';
247                                 }
248                         }
249
250                         $sql = 'INSERT INTO '.TABLE_PREFIX.'language_pages (`term`, `page`) VALUES ("'.$args[0].'", "'.$_rel_url.'")';
251                         mysql_query($sql, $db);
252
253                         return $msgs;
254                 }
255         }
256         
257         // a template variable
258         if (!isset($_template)) {
259                 $url_parts = parse_url(AT_BASE_HREF);
260                 $name = substr($_SERVER['PHP_SELF'], strlen($url_parts['path'])-1);
261
262                 if ( !($lang_et = cache(120, 'lang', $_SESSION['lang'].'_'.$name)) ) {
263                         global $db;
264
265                         /* get $_template from the DB */
266                         
267                         $sql = "SELECT L.* FROM ".TABLE_PREFIX."language_text L, ".TABLE_PREFIX."language_pages P WHERE L.language_code='{$_SESSION['lang']}' AND L.variable<>'_msgs' AND L.term=P.term AND P.page='$_rel_url' ORDER BY L.variable ASC";
268                         $result = mysql_query($sql, $db);
269                         while ($row = mysql_fetch_assoc($result)) {
270                                 //Do not overwrite the variable that existed in the cache_template already.
271                                 //The edited terms (_c_template) will always be at the top of the resultset
272                                 //0003279
273                                 if (isset($_cache_template[$row['term']])){
274                                         continue;
275                                 }
276
277                                 // saves us from doing an ORDER BY
278                                 if ($row['language_code'] == $_SESSION['lang']) {
279                                         $_cache_template[$row['term']] = stripslashes($row['text']);
280                                 } else if (!isset($_cache_template[$row['term']])) {
281                                         $_cache_template[$row['term']] = stripslashes($row['text']);
282                                 }
283                         }
284                 
285                         cache_variable('_cache_template');
286                         endcache(true, false);
287                 }
288                 $_template = $_cache_template;
289         }
290         $num_args = func_num_args();
291         if (is_array($args[0])) {
292                 $args = $args[0];
293                 $num_args = count($args);
294         }
295         $format   = array_shift($args);
296
297         if (isset($_template[$format])) {
298                 /*
299                 var_dump($_template);
300                 var_dump($format);
301                 var_dump($args);
302                 exit;
303                 */
304                 $outString      = vsprintf($_template[$format], $args);
305                 $str = ob_get_contents();
306         } else {
307                 $outString = '';
308         }
309
310
311         if ($outString === false) {
312                 return ('[Error parsing language. Variable: <code>'.$format.'</code>. Language: <code>'.$_SESSION['lang'].'</code> ]');
313         }
314
315         if (empty($outString)) {
316                 global $db;
317                 $sql    = 'SELECT L.* FROM '.TABLE_PREFIX.'language_text L WHERE L.language_code="'.$_SESSION['lang'].'" AND L.variable<>"_msgs" AND L.term="'.$format.'"';
318
319                 $result = mysql_query($sql, $db);
320                 $row = mysql_fetch_assoc($result);
321
322                 $_template[$row['term']] = stripslashes($row['text']);
323                 $outString = $_template[$row['term']];
324                 if (empty($outString)) {
325                         return ('[ '.$format.' ]');
326                 }
327                 $outString = $_template[$row['term']];
328                 $outString = vsprintf($outString, $args);
329
330                 /* update the locations */
331                 $sql = 'INSERT INTO '.TABLE_PREFIX.'language_pages (`term`, `page`) VALUES ("'.$format.'", "'.$_rel_url.'")';
332                 mysql_query($sql, $db);
333         }
334
335         return $outString;
336 }
337
338 /**********************************************************************************************************/
339         /**
340         *       Transforms text based on formatting preferences.  Original $input is also changed (passed by reference).
341         *       Can be called as:
342         *       1) $output = AT_print($input, $name);
343         *          echo $output;
344         *
345         *       2) echo AT_print($input, $name); // prefered method
346         *
347         * @access       public
348         * @param        string $input                   text being transformed
349         * @param        string $name                    the unique name of this field (convension: table_name.field_name)
350         * @param        boolean $runtime_html   forcefully disables html formatting for $input (only used by fields that 
351         *                                                                       have the 'formatting' option
352         * @return       string                                  transformed $input
353         * @see          AT_FORMAT constants             in include/lib/constants.inc.php
354         * @see          query_bit()                             in include/vitals.inc.php
355         * @author       Joel Kronenberg
356         */
357         function AT_print($input, $name, $runtime_html = true) {
358                 global $_field_formatting, $_config;
359
360                 if (!isset($_field_formatting[$name])) {
361                         /* field not set, check if there's a global setting */
362                         $parts = explode('.', $name);
363                         
364                         /* check if wildcard is set: */
365                         if (isset($_field_formatting[$parts[0].'.*'])) {
366                                 $name = $parts[0].'.*';
367                         } else {
368                                 /* field not set, and there's no global setting */
369                                 /* same as AT_FORMAT_NONE */
370                                 return $input;
371                         }
372                 }
373
374                 if (query_bit($_field_formatting[$name], AT_FORMAT_QUOTES)) {
375                         $input = str_replace('"', '&quot;', $input);
376                 }
377
378                 if (query_bit($_field_formatting[$name], AT_FORMAT_CONTENT_DIR)) {
379                         $input = str_replace('CONTENT_DIR/', '', $input);
380                 }
381
382                 if (query_bit($_field_formatting[$name], AT_FORMAT_HTML) && $runtime_html) {
383                         /* what special things do we have to do if this is HTML ? remove unwanted HTML? validate? */
384                 } else {
385                         $input = str_replace('<', '&lt;', $input);
386                         $input = nl2br($input);
387                 }
388
389                 if (isset($_config['latex_server']) && $_config['latex_server']) {
390                         $input = preg_replace('/\[tex\](.*?)\[\/tex\]/sie', "'<img src=\"'.\$_config['latex_server'].rawurlencode('$1').'\" align=\"middle\" alt=\"'.'$1'.'\" title=\"'.'$1'.'\">'", $input);
391                 }
392
393                 /* this has to be here, only because AT_FORMAT_HTML is the only check that has an else-block */
394                 if ($_field_formatting[$name] === AT_FORMAT_NONE) {
395                         return $input;
396                 }
397
398                 if (query_bit($_field_formatting[$name], AT_FORMAT_EMOTICONS)) {
399                         $input = smile_replace($input);
400                 }
401
402                 if (query_bit($_field_formatting[$name], AT_FORMAT_ATCODES)) {
403                         $input = trim(myCodes(' ' . $input . ' '));
404                 }
405
406                 if (query_bit($_field_formatting[$name], AT_FORMAT_LINKS)) {
407                         $input = trim(make_clickable(' ' . $input . ' '));
408                 }
409
410                 if (query_bit($_field_formatting[$name], AT_FORMAT_IMAGES)) {
411                         $input = trim(image_replace(' ' . $input . ' '));
412                 }
413
414         
415                 return $input;
416         }
417
418 /********************************************************************************************/
419 // Global variables for emoticons
420  
421 global $smile_pics;
422 global $smile_codes;
423 if (!isset($smile_pics)) {
424         $smile_pics[0] = $_base_path.'images/forum/smile.gif';
425         $smile_pics[1] = $_base_path.'images/forum/wink.gif';
426         $smile_pics[2] = $_base_path.'images/forum/frown.gif';
427         $smile_pics[3] = $_base_path.'images/forum/ohwell.gif';
428         $smile_pics[4] = $_base_path.'images/forum/tongue.gif';
429         $smile_pics[5] = $_base_path.'images/forum/51.gif';
430         $smile_pics[6] = $_base_path.'images/forum/52.gif';
431         $smile_pics[7] = $_base_path.'images/forum/54.gif';
432         $smile_pics[8] = $_base_path.'images/forum/27.gif';
433         $smile_pics[9] = $_base_path.'images/forum/19.gif';
434         $smile_pics[10] = $_base_path.'images/forum/3.gif';
435         $smile_pics[11] = $_base_path.'images/forum/56.gif';
436 }
437
438 if (!isset($smile_codes)) {
439         $smile_codes[0] = ':)';
440         $smile_codes[1] = ';)';
441         $smile_codes[2] = ':(';
442         $smile_codes[3] = '::ohwell::';
443         $smile_codes[4] = ':P';
444         $smile_codes[5] = '::evil::';
445         $smile_codes[6] = '::angry::';
446         $smile_codes[7] = '::lol::';
447         $smile_codes[8] = '::crazy::';
448         $smile_codes[9] = '::tired::';
449         $smile_codes[10] = '::confused::';
450         $smile_codes[11] = '::muah::';
451 }
452
453 /**
454 * Replaces smile-code text into smilie image.
455 * @access       public
456 * @param        string $text            smile text to be transformed
457 * @return       string                          transformed $text
458 * @see          $smile_pics                     in include/lib/output.inc.php (above)
459 * @see          $smile_codes            in include/lib/output.inc.php (above)
460 * @author       Joel Kronenberg
461 */
462 function smile_replace($text) {
463         global $smile_pics;
464         global $smile_codes;
465         static $smiles;
466
467         $smiles[0] = '<img src="'.$smile_pics[0].'" border="0" height="15" width="15" align="bottom" alt="'._AT('smile_smile').'" />';
468         $smiles[1] = '<img src="'.$smile_pics[1].'" border="0" height="15" width="15" align="bottom" alt="'._AT('smile_wink').'" />';
469         $smiles[2] = '<img src="'.$smile_pics[2].'" border="0" height="15" width="15" align="bottom" alt="'._AT('smile_frown').'" />';
470         $smiles[3]= '<img src="'.$smile_pics[3].'" border="0" height="15" width="15" align="bottom" alt="'._AT('smile_oh_well').'" />';
471         $smiles[4]= '<img src="'.$smile_pics[4].'" border="0" height="15" width="15" align="bottom" alt="'._AT('smile_tongue').'" />';
472         $smiles[5]= '<img src="'.$smile_pics[5].'" border="0" height="15" width="15" align="bottom" alt="'._AT('smile_evil').'" />';
473         $smiles[6]= '<img src="'.$smile_pics[6].'" border="0" height="15" width="15" align="bottom" alt="'._AT('smile_angry').'" />';
474         $smiles[7]= '<img src="'.$smile_pics[7].'" border="0" height="15" width="15" align="bottom" alt="'._AT('smile_lol').'" />';
475         $smiles[8]= '<img src="'.$smile_pics[8].'" border="0" height="15" width="15" align="bottom" alt="'._AT('smile_crazy').'" />';
476         $smiles[9]= '<img src="'.$smile_pics[9].'" border="0" height="15" width="15" align="bottom" alt="'._AT('smile_tired').'" />';
477         $smiles[10]= '<img src="'.$smile_pics[10].'" border="0" height="17" width="19" align="bottom" alt="'._AT('smile_confused').'" />';
478         $smiles[11]= '<img src="'.$smile_pics[11].'" border="0" height="15" width="15" align="bottom" alt="'._AT('smile_muah').'" />';
479
480         $text = str_replace($smile_codes[0],$smiles[0],$text);
481         $text = str_replace($smile_codes[1],$smiles[1],$text);
482         $text = str_replace($smile_codes[2],$smiles[2],$text);
483         $text = str_replace($smile_codes[3],$smiles[3],$text);
484         $text = str_replace($smile_codes[4],$smiles[4],$text);
485         $text = str_replace($smile_codes[5],$smiles[5],$text);
486         $text = str_replace($smile_codes[6],$smiles[6],$text);
487         $text = str_replace($smile_codes[7],$smiles[7],$text);
488         $text = str_replace($smile_codes[8],$smiles[8],$text);
489         $text = str_replace($smile_codes[9],$smiles[9],$text);
490         $text = str_replace($smile_codes[10],$smiles[10],$text);
491         $text = str_replace($smile_codes[11],$smiles[11],$text);
492
493         return $text;
494 }
495
496
497 /* Used specifically for the visual editor
498 */
499 function smile_javascript () {
500         global $_base_path;
501         global $smile_pics;
502         global $smile_codes;
503
504         static $i = 0;
505
506         while ($smile_pics [$i]) {
507                 echo 'case "'.$smile_codes[$i].'":'."\n";
508                 echo 'pic = "'.$smile_pics[$i].'";'."\n";
509                 echo 'break;'."\n";
510                 $i++;
511         }
512 }
513     
514 function myCodes($text, $html = false) {
515         global $_base_path;
516         global $HTTP_USER_AGENT;
517
518         if (substr($HTTP_USER_AGENT,0,11) == 'Mozilla/4.7') {
519                 $text = str_replace('[quote]','</p><p class="block">',$text);
520                 $text = str_replace('[/quote]','</p><p>',$text);
521
522                 $text = str_replace('[reply]','</p><p class="block">',$text);
523                 $text = str_replace('[/reply]','</p><p>',$text);
524         } else {
525                 $text = str_replace('[quote]','<blockquote>',$text);
526                 $text = str_replace('[/quote]','</blockquote><p>',$text);
527
528                 $text = str_replace('[reply]','</p><blockquote class="block"><p>',$text);
529                 $text = str_replace('[/reply]','</p></blockquote><p>',$text);
530         }
531
532         $text = str_replace('[b]','<strong>',$text);
533         $text = str_replace('[/b]','</strong>',$text);
534
535         $text = str_replace('[i]','<em>',$text);
536         $text = str_replace('[/i]','</em>',$text);
537
538         $text = str_replace('[u]','<u>',$text);
539         $text = str_replace('[/u]','</u>',$text);
540
541         $text = str_replace('[center]','<center>',$text);
542         $text = str_replace('[/center]','</center><p>',$text);
543
544         /* colours */
545         $text = str_replace('[blue]','<span style="color: blue;">',$text);
546         $text = str_replace('[/blue]','</span>',$text);
547
548         $text = str_replace('[orange]','<span style="color: orange;">',$text);
549         $text = str_replace('[/orange]','</span>',$text);
550
551         $text = str_replace('[red]','<span style="color: red;">',$text);
552         $text = str_replace('[/red]','</span>',$text);
553
554         $text = str_replace('[purple]','<span style="color: purple;">',$text);
555         $text = str_replace('[/purple]','</span>',$text);
556
557         $text = str_replace('[green]','<span style="color: green;">',$text);
558         $text = str_replace('[/green]','</span>',$text);
559
560         $text = str_replace('[gray]','<span style="color: gray;">',$text);
561         $text = str_replace('[/gray]','</span>',$text);
562
563         $text = str_replace('[op]','<span class="bigspacer"></span> <a href="',$text);
564         $text = str_replace('[/op]','">'._AT('view_entire_post').'</a>',$text);
565
566         $text = str_replace('[head1]','<h2>',$text);
567         $text = str_replace('[/head1]','</h2>',$text);
568
569         $text = str_replace('[head2]','<h3>',$text);
570         $text = str_replace('[/head2]','</h3>',$text);
571
572         $text = str_replace('[cid]',$_base_path.'content.php?cid='.$_SESSION['s_cid'],$text);
573
574         // fix for http://www.atutor.ca/atutor/mantis/view.php?id=4104
575         global $sequence_links;
576         if ($_SESSION['course_id'] > 0 && !isset($sequence_links) && $_REQUEST['cid'] > 0) {
577                 global $contentManager;
578                 $sequence_links = $contentManager->generateSequenceCrumbs($_REQUEST['cid']);
579         }
580         if (isset($sequence_links['previous']) && $sequence_links['previous']['url']) {
581                 $text = str_replace('[pid]', $sequence_links['previous']['url'], $text);
582         }
583         if (isset($sequence_links['next']) && $sequence_links['next']['url']) {
584                 $text = str_replace('[nid]', $sequence_links['next']['url'], $text);
585         }
586         if (isset($sequence_links['resume']) && $sequence_links['resume']['url']) {
587                 $text = str_replace('[nid]', $sequence_links['resume']['url'], $text);
588         }
589         if (isset($sequence_links['first']) && $sequence_links['first']['url']) {
590                 $text = str_replace('[fid]', $sequence_links['first']['url'], $text);
591         }
592
593 //LAW - replace </p><p> tags in [code] tags with <br />
594 //http://www.atutor.ca/atutor/mantis/view.php?id=4134 - attempt to fix this bug - does not work as required
595 //      $outputUtils = new ContentOutputUtils();
596 //      $text = $outputUtils ->stripPtags($text);
597         
598         /* contributed by Thomas M. Duffey <tduffey at homeboyz.com> */
599     $html = !$html ? 0 : 1;
600     
601         // little hack added by greg to add syntax highlighting without using <?php \?\>
602         
603         $text = str_replace("[code]","[code]<?php",$text);
604         $text = str_replace("[/code]","?>[/code]",$text);
605
606         $text = preg_replace("/\[code\]\s*(.*)\s*\[\\/code\]/Usei", "highlight_code(fix_quotes('\\1'), $html)", $text);
607         // now remove the <?php added above and leave the syntax colour behind.
608         $text = str_replace("&lt;?php", "", $text);
609         $text = str_replace("?&gt;", "", $text);
610
611         return $text;
612 }
613
614 /* contributed by Thomas M. Duffey <tduffey at homeboyz.com> */
615 function highlight_code($code, $html) {
616         // XHTMLize PHP highlight_string output until it gets fixed in PHP
617         static $search = array(
618                 '<br>',
619                 '<font',
620                 '</font>',
621                 'color="');
622
623         static $replace = array(
624                 '<br />',
625                 '<span',
626                 '</span>',
627                 'style="color:');
628         if (!$html) {
629                 $code = str_replace('&lt;', '<', $code);
630                 $code = str_replace("\r", '', $code);
631         }
632
633         return str_replace($search, $replace, highlight_string($code, true));
634 }
635
636 /* contributed by Thomas M. Duffey <tduffey at homeboyz.com> */
637 function fix_quotes($text){
638         return str_replace('\\"', '"', $text);
639 }
640
641 function embed_media($text) {
642         if (preg_match("/\[media(\|[0-9]+\|[0-9]+)?\]*/", $text)==0){
643                 return $text;
644         }
645
646         $media_matches = Array();
647         
648         /*
649                 First, we search though the text for all different kinds of media defined by media tags and store the results in $media_matches.
650                 
651                 Then the different replacements for the different media tags are stored in $media_replace.
652                 
653                 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.
654                 
655         */
656         
657         // youtube videos
658         preg_match_all("#\[media[0-9a-z\|]*\]http://([a-z0-9\.]*)?youtube.com/watch\?v=([a-z0-9_-]+)\[/media\]#i",$text,$media_matches[1],PREG_SET_ORDER);
659         $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>';
660                 
661         // .mpg
662         preg_match_all("#\[media[0-9a-z\|]*\]([.\w\d]+[^\s\"]+).mpg\[/media\]#i",$text,$media_matches[2],PREG_SET_ORDER);
663         $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>";
664         
665         // .avi
666         preg_match_all("#\[media[0-9a-z\|]*\]([.\w\d]+[^\s\"]+).avi\[/media\]#i",$text,$media_matches[3],PREG_SET_ORDER);
667         $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>";
668         
669         // .wmv
670         preg_match_all("#\[media[0-9a-z\|]*\]([.\w\d]+[^\s\"]+).wmv\[/media\]#i",$text,$media_matches[4],PREG_SET_ORDER);
671         $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>";
672         
673         // .mov
674         preg_match_all("#\[media[0-9a-z\|]*\]([.\w\d]+[^\s\"]+).mov\[/media\]#i",$text,$media_matches[5],PREG_SET_ORDER);
675         $media_replace[5] = "<object classid=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\" codebase=\"http://www.apple.com/qtactivex/qtplugin.cab\" width=\"##WIDTH##\" height=\"##HEIGHT##\"><param name=\"src\" value=\"##MEDIA1##.mov\"><param name=\"controller\" value=\"true\"><param name=\"autoplay\" value=\"false\"><!--[if gte IE 7]> <!--><object type=\"video/quicktime\" data=\"##MEDIA1##.mov\" width=\"##WIDTH##\" height=\"##HEIGHT##\"><param name=\"controller\" value=\"true\"><param name=\"autoplay\" value=\"false\"><a href=\"##MEDIA1##.mov\">##MEDIA1##.mov</a></object><!--<![endif]--><!--[if lt IE 7]><a href=\"##MEDIA1##.mov\">##MEDIA1##.mov</a><![endif]--></object>";
676         
677         // .swf
678         preg_match_all("#\[media[0-9a-z\|]*\]([.\w\d]+[^\s\"]+).swf\[/media\]#i",$text,$media_matches[6],PREG_SET_ORDER);
679         $media_replace[6] = "<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>";
680         
681         // .mp3
682         preg_match_all("#\[media[0-9a-z\|]*\](.+[^\s\"]+).mp3\[/media\]#i",$text,$media_matches[7],PREG_SET_ORDER);
683         $media_replace[7] = "<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>";
684         
685         // .wav
686         preg_match_all("#\[media[0-9a-z\|]*\](.+[^\s\"]+).wav\[/media\]#i",$text,$media_matches[8],PREG_SET_ORDER);
687         $media_replace[8] ="<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>";
688         
689         // .ogg
690         preg_match_all("#\[media[0-9a-z\|]*\](.+[^\s\"]+).ogg\[/media\]#i",$text,$media_matches[9],PREG_SET_ORDER);
691         $media_replace[9] ="<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>";
692         
693         // .mid
694         preg_match_all("#\[media[0-9a-z\|]*\](.+[^\s\"]+).mid\[/media\]#i",$text,$media_matches[10],PREG_SET_ORDER);
695         $media_replace[10] ="<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>";
696         
697         $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);
698
699         // Executing the replace
700         for ($i=1;$i<=count($media_replace);$i++){
701                 foreach($media_matches[$i] as $media)
702                 {
703                         
704                         //find width and height for each matched media
705                         if (preg_match("/\[media\|([0-9]*)\|([0-9]*)\]*/", $media[0], $matches)) 
706                         {
707                                 $width = $matches[1];
708                                 $height = $matches[2];
709                         }
710                         else
711                         {
712                                 $width = 425;
713                                 $height = 350;
714                         }
715                         
716                         //replace media tags with embedded media for each media tag
717                         $media_input = $media_replace[$i];
718                         $media_input = str_replace("##WIDTH##","$width",$media_input);
719                         $media_input = str_replace("##HEIGHT##","$height",$media_input);
720                         $media_input = str_replace("##MEDIA1##","$media[1]",$media_input);
721                         $media_input = str_replace("##MEDIA2##","$media[2]",$media_input);
722                         $text = str_replace($media[0],$media_input,$text);
723                 }
724         }
725                 
726         return $text;
727 }
728
729 function make_clickable($text) {
730         $text = embed_media($text);
731
732 //      $text = eregi_replace("([[:space:]])(http[s]?)://([^[:space:]<]*)([[:alnum:]#?/&=])", "\\1<a href=\"\\2://\\3\\4\">\\3\\4</a>", $text);
733 //
734 //      $text = eregi_replace(  '([_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]+)*'.
735 //                                                      '\@'.'[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]+)*'.'(\.[a-zA-Z]{1,6})+)',
736 //                                                      "<a href=\"mailto:\\1\">\\1</a>",
737 //                                                      $text);
738
739         $text = preg_replace("/([\s])(http[s]?):\/\/(.*)(\s|\$|<br\s\/\>)(.*)/U", 
740                              "\\1<a href=\"\\2://\\3\">\\3</a>\\4\\5", $text);
741         
742         $text = preg_replace('/([_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]+)*'.
743                                                 '\@'.'[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]+)*'.'(\.[a-zA-Z]{1,6})+)/i',
744                                                 "<a href=\"mailto:\\1\">\\1</a>",
745                                                 $text);
746         return $text;
747 }
748
749 function image_replace($text) {
750         /* image urls do not require http:// */
751         
752 //      $text = eregi_replace("\[image(\|)?([[:alnum:][:space:]]*)\]" .
753 //                                               "[:space:]*" .
754 //                                               "([[:alnum:]#?/&=:\"'_.-]+)" .
755 //                                               "[:space:]*" .
756 //                                               "((\[/image\])|(.*\[/image\]))",
757 //                                "<img src=\"\\3\" alt=\"\\2\" />",
758 //                                $text);
759          
760         $text = preg_replace("/\[image(\|)?([a-zA-Z0-9\s]*)\]".
761                              "[\s]*".
762                              "([a-zA-Z0-9\#\?\/\&\=\:\\\"\'\_\.\-]+)[\s]*".
763                              "((\[\/image\])|(.*\[\/image\]))/i",
764                                   "<img src=\"\\3\" alt=\"\\2\" />",
765                                   $text);
766                                   
767         return $text;
768 }
769
770 function format_final_output($text, $nl2br = true) {
771         global $_base_path;
772
773         $text = str_replace('CONTENT_DIR/', '', $text);
774         if ($nl2br) {
775                 return nl2br(image_replace(make_clickable(myCodes(' '.$text, false))));
776         }
777
778         return image_replace(make_clickable(myCodes(' '.$text, true)));
779 }
780
781 // 
782 function apply_customized_format($input) {
783         global $_input, $moduleFactory, $content_base_href, $_content_base_href;
784         
785         $_input = $input;
786         $_content_base_href = $content_base_href;
787         
788         $enabled_modules = $moduleFactory->getModules(AT_MODULE_STATUS_ENABLED);
789
790         if (is_array($enabled_modules))
791         {
792                 foreach ($enabled_modules as $dir_name => $mod)
793                 {
794                         $module_content_format_file = AT_INCLUDE_PATH . '../mods/'.$dir_name.'/module_format_content.php';
795                         if (file_exists($module_content_format_file))
796                         {
797                                 include($module_content_format_file);
798                         }
799                 }
800         }
801         
802         return $_input;
803 }
804 /****************************************************************************************/
805 /* @See: ./user/search.php & ./index.php */
806 function highlight($input, $var) {//$input is the string, $var is the text to be highlighted
807         if ($var != "") {
808                 $xtemp = "";
809                 $i=0;
810                 /*
811                         The following 'if' statement is a check to ensure that the search term is not part of the tag, '<strong class="highlight">'.  Words within this string are avoided in case a previously highlighted string is used for the haystack, $input.  To avoid any html breaks in the highlighted string, the search word is avoided completely.
812                 */
813                 if (strpos('<strong class="highlight">', $var) !== false) {
814                         return $input;
815                 }
816                 while($i<strlen($input)){
817                         if((($i + strlen($var)) <= strlen($input)) && (strcasecmp($var, substr($input, $i, strlen($var))) == 0)) {
818                                 $xtemp .= '<strong class="highlight">' . substr($input, $i , strlen($var)) . '</strong>';
819                                 $i += strlen($var);
820                         }
821                         else {
822                                 $xtemp .= $input{$i};
823                                 $i++;
824                         }
825                 }
826                 $input = $xtemp;
827         }
828         return $input;
829 }
830
831
832 /* @See: ./index.php */
833 function format_content($input, $html = 0, $glossary, $simple = false) {
834         global $_base_path, $_config;
835
836         if (!$html) {
837                 $input = str_replace('<', '&lt;', $input);
838                 $input = str_replace('&lt;?php', '<?php', $input); // for bug #2087
839         } elseif ($html==2) {
840                 $output = '<iframe width="100%" frameborder="0" id="content_frame" marginheight="0" marginwidth="0" src="'.$input.'"></iframe>';
841                 $output .=      '<script type="text/javascript">
842                                         function resizeIframe() {
843                                                 var height = document.documentElement.clientHeight;
844                                                 
845                                                 // not sure how to get this dynamically
846                                                 height -= 20; /* whatever you set your body bottom margin/padding to be */
847                                                 
848                                                 document.getElementById(\'content_frame\').style.height = height +"px";
849                                                 
850                                         };
851                                         document.getElementById(\'content_frame\').onload = resizeIframe;
852                                         window.onresize = resizeIframe;
853                                         </script>';
854                 return $output;
855         }
856
857         /* do the glossary search and replace: */
858         if (is_array($glossary)) {
859                 foreach ($glossary as $k => $v) {
860                         $k = urldecode($k);
861                         $v = str_replace("\n", '<br />', $v);
862                         $v = str_replace("\r", '', $v);
863
864                         /* escape special characters */
865                         $k = preg_quote($k);
866
867                         $k = str_replace('&lt;', '<', $k);
868                         $k = str_replace('/', '\/', $k);
869
870                         $original_term = $k;
871                         $term = $original_term;
872
873                         $term = '(\s*'.$term.'\s*)';
874                         $term = str_replace(' ','((<br \/>)*\s*)', $term); 
875
876                         $def = htmlspecialchars($v, ENT_QUOTES, 'UTF-8');               
877                         if ($simple) {
878                                 $input = preg_replace
879                                                 ("/(\[\?\])$term(\[\/\?\])/i",
880                                                 '<a href="'.$simple.'glossary.html#'.urlencode($original_term).'" target="body" class="at-term">\\2</a>',
881                                                 $input);
882                         } else {
883                                 $input = preg_replace
884                                                 ("/(\[\?\])$term(\[\/\?\])/i",
885                                                 '\\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.'"><span style="color: blue; text-decoration: none;font-size:small; font-weight:bolder;">?</span></a></sup>',$input);
886                         }
887                 }
888         } else if (!$user_glossary) {
889                 $input = str_replace(array('[?]','[/?]'), '', $input);
890         }
891         
892         $input = str_replace('CONTENT_DIR', '', $input);
893
894         if (isset($_config['latex_server']) && $_config['latex_server']) {
895                 $input = preg_replace('/\[tex\](.*?)\[\/tex\]/sie', "'<img src=\"'.\$_config['latex_server'].rawurlencode('$1').'\" align=\"middle\" alt=\"'.'$1'.'\" title=\"'.'$1'.'\">'", $input);
896         }
897
898         if ($html) {
899                 $x = apply_customized_format(format_final_output($input, false));
900                 return $x;
901         }
902
903         $output = apply_customized_format(format_final_output($input));
904
905         $output = '<p>'.$output.'</p>';
906
907         return $output;
908 }
909
910 function get_content_table($content)
911 {
912         preg_match_all("/<(h[\d]+)[^>]*>(.*)<\/(\s*)\\1(\s*)>/i", $content, $found_headers, PREG_SET_ORDER);
913         
914         if (count($found_headers) == 0) return array("", $content);
915         else
916         {
917                 $num_of_headers = 0;
918
919                 for ($i = 0; $i < count($found_headers); $i++)
920                 {
921                         $div_id = "_header_" . $num_of_headers++;
922                         
923                         if ($i == 0)
924                         {
925                                 $content_table = "<div id=\"toc\">\n<fieldset id=\"toc\"><legend>". _AT("table_of_contents")."</legend>\n";
926                         }
927
928                         $content = str_replace($found_headers[$i][0], '<div id="'.$div_id.'">'.$found_headers[$i][0].'</div>', $content);
929                         $content_table .= '<a href="'.$_SERVER["REQUEST_URI"].'#'.$div_id.'" class="'.$found_headers[$i][1].'">'. $found_headers[$i][2]."</a>\n";
930
931                         if ($i == count($found_headers) - 1)
932                         {
933                                 $content_table .= "</fieldset></div><br />";
934                         }
935                 }
936                 return array($content_table, $content);
937         }
938 }
939
940 function find_terms($find_text) {
941         preg_match_all("/(\[\?\])(.[^\?]*)(\[\/\?\])/i", $find_text, $found_terms, PREG_PATTERN_ORDER);
942         return $found_terms;
943 }
944
945 /***********************************************************************
946         @See /include/Classes/Message/Message.class.php
947         Jacek Materna
948 */
949
950 /**
951 * Take a code as input and grab its language specific message. Also cache the resulting 
952 * message. Return the message. Same as get_message but key value in cache is string
953 * @access  public
954 * @param   string $codes        Message Code to translate - > 'term' field in DB
955 * @return  string                       The translated language specific message for code $code
956 * @author  Jacek Materna
957 */
958 function getTranslatedCodeStr($codes) {
959         
960         /* this is where we want to get the msgs from the database inside a static variable */
961         global $_cache_msgs_new;
962         static $_msgs_new;
963
964         if (!isset($_msgs_new)) {
965                 if ( !($lang_et = cache(120, 'msgs_new', $_SESSION['lang'])) ) {
966                         global $db, $_base_path;
967
968                         $parent = Language::getParentCode($_SESSION['lang']);
969
970                         /* get $_msgs_new from the DB */
971                         $sql    = 'SELECT * FROM '.TABLE_PREFIX.'language_text WHERE variable="_msgs" AND (language_code="'.$_SESSION['lang'].'" OR language_code="'.$parent.'")';
972                         $result = @mysql_query($sql, $db);
973                         $i = 1;
974                         while ($row = @mysql_fetch_assoc($result)) {
975                                 // do not cache key as a digit (no contstant(), use string)
976                                 $_cache_msgs_new[$row['term']] = str_replace('SITE_URL/', $_base_path, $row['text']);
977                                 if (AT_DEVEL) {
978                                         $_cache_msgs_new[$row['term']] .= ' <small><small>('.$row['term'].')</small></small>';
979                                 }
980                         }
981
982                         cache_variable('_cache_msgs_new');
983                         endcache(true, false);
984                 }
985                 $_msgs_new = $_cache_msgs_new;
986         }
987
988         if (is_array($codes)) {
989                 /* this is an array with terms to replace */            
990                 $code           = array_shift($codes);
991
992                 $message        = $_msgs_new[$code];
993                 $terms          = $codes;
994
995                 /* replace the tokens with the terms */
996                 $message        = vsprintf($message, $terms);
997
998         } else {
999                 $message = $_msgs_new[$codes];
1000
1001                 if ($message == '') {
1002                         /* the language for this msg is missing: */
1003                 
1004                         $sql    = 'SELECT * FROM '.TABLE_PREFIX.'language_text WHERE variable="_msgs"';
1005                         $result = @mysql_query($sql, $db);
1006                         $i = 1;
1007                         while ($row = @mysql_fetch_assoc($result)) {
1008                                 if (($row['term']) === $codes) {
1009                                         $message = '['.$row['term'].']';
1010                                         break;
1011                                 }
1012                         }
1013                 }
1014                 $code = $codes;
1015         }
1016         return $message;
1017 }
1018
1019 function html_get_list($array) {
1020         $list = '';
1021         foreach ($array as $value) {
1022                 $list .= '<li>'.$value.'</li>';
1023         }
1024         return $list;
1025 }
1026
1027 /**
1028  * print_paginator
1029  *
1030  * print out list of page links
1031  */
1032 function print_paginator($current_page, $num_rows, $request_args, $rows_per_page = 50, $window = 5) {
1033         $num_pages = ceil($num_rows / $rows_per_page);
1034         $request_args = '?'.$request_args;
1035
1036     if ($num_rows) {
1037                 echo '<div class="paging">';
1038             echo '<ul>';
1039                 
1040                 $i=max($current_page-$window - max($window-$num_pages+$current_page,0), 1);
1041
1042                 if ($i > 1) {
1043                         echo '<li><a href="'.$_SERVER['PHP_SELF'].$request_args.htmlspecialchars(SEP).'p=1" title="'._AT('page').' 1">1</a></li>';
1044                         if ($i > 2) {
1045                         echo '<li>&hellip;</li>';
1046                         }
1047                 }
1048
1049                 for ($i; $i<= min($current_page+$window -min($current_page-$window,0),$num_pages); $i++) {
1050                         if ($current_page == $i) {
1051                                 echo '<li><a href="'.$_SERVER['PHP_SELF'].$request_args.htmlspecialchars(SEP).'p='.$i.'" class="current" title="'._AT('page').' '. $current_page.'"><em>'.$current_page.'</em></a></li>';
1052                         } else {
1053                                 echo '<li><a href="'.$_SERVER['PHP_SELF'].$request_args.htmlspecialchars(SEP).'p='.$i.'" title="'._AT('page').' '. $i.'">'.$i.'</a></li>';
1054                         }
1055                 }
1056         if ($i <= $num_pages) {
1057                         if ($i < $num_pages) {
1058                         echo '<li>&hellip;</li>';
1059                 }
1060                         echo '<li><a href="'.$_SERVER['PHP_SELF'].$request_args.htmlspecialchars(SEP).'p='.$num_pages.'" title="'._AT('page').' '. $num_pages.'">'.$num_pages.'</a></li>';
1061                 }
1062                 echo '</ul>';
1063                 echo '</div>';
1064         }
1065 }
1066
1067
1068 /**
1069 * According to user's preferences, it provides appropriated resources in the content page.
1070 * @access       public
1071 * @param        $cid:                           content id.
1072 * @param        $content_page:          the original content page ($content_row['text'], from content.php).
1073 * @return       string|array            $content: the content page with the appropriated resources.
1074 * @see          $db                             in include/vitals.inc.php
1075 * @author       Silvia Mirri
1076 */
1077 function provide_alternatives1($cid, $content_page){
1078         global $db;
1079         
1080         $vidoe_exts = array("mpg", "avi", "wmv", "mov", "swf", "mp3", "wav", "ogg", "mid");
1081
1082         $content = $content_page;
1083         
1084         if (($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_TEXT']==0) && ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_AUDIO']==0) && ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_VISUAL']==0)) 
1085         {
1086                 //No user's preferences related to content format are declared
1087                 return $content;
1088         }
1089         /*else if ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_TEXT']==1){
1090
1091                 $sql_primary = "SELECT * FROM ".TABLE_PREFIX."primary_resources WHERE content_id=".$cid." and resource='".mysql_real_escape_string($content_page)."'";
1092
1093                 $result = mysql_query($sql_primary, $db);
1094                 if (mysql_num_rows($result) > 0) {
1095                         while ($row = mysql_fetch_assoc($result)) {
1096                         $sql_type        = "SELECT * FROM ".TABLE_PREFIX."primary_resources_types WHERE primary_resource_id=$row[primary_resource_id]"; 
1097                         $result_type = mysql_query($sql_type, $db);
1098                                 if (mysql_num_rows($result_type) > 0) {
1099                                         while ($row_type = mysql_fetch_assoc($result_type)){
1100                                                 if (($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TEXT']==1) && ($row_type[type_id]==3)){
1101                                                                 $sql_text         = "SELECT * FROM ".TABLE_PREFIX."secondary_resources WHERE primary_resource_id=$row[primary_resource_id] and language_code='".$_SESSION['prefs']['PREF_ALT_TEXT_PREFER_LANG']."'";    
1102                                                         $result_text = mysql_query($sql_text, $db);
1103                                                         if (mysql_num_rows($result_text) > 0) {
1104                                                                 while ($row_text = mysql_fetch_assoc($result_text)){
1105                                                                         $sql_text_alt     = "SELECT * FROM ".TABLE_PREFIX."secondary_resources_types WHERE secondary_resource_id=$row_text[secondary_resource_id]";     
1106                                                                         $result_text_alt = mysql_query($sql_text_alt, $db);
1107                                                                         if (mysql_num_rows($result_text_alt) > 0) {
1108                                                                                 while ($row_text_alt = mysql_fetch_assoc($result_text_alt)){
1109                                                                                         if ((($_SESSION['prefs']['PREF_ALT_TO_TEXT']==visual) && ($row_text_alt[type_id]==4)) || (($_SESSION['prefs']['PREF_ALT_TO_TEXT']==audio) && ($row_audio_alt[type_id]==1)) || (($_SESSION['prefs']['PREF_ALT_TO_TEXT']==sign_lang) && ($row_text_alt[type_id]==2))) {
1110                                                                                                 if (($_SESSION['prefs']['PREF_ALT_TO_TEXT_APPEND_OR_REPLACE']=='replace'))
1111                                                                                                         $content = $row_text_alt['secondary_resource'];
1112                                                                                                 else 
1113                                                                                                         $content = $content.'<br/>'.$row_text_alt['secondary_resource'];
1114                                                                                         }
1115                                                                                 }       
1116                                                                         }
1117                                                                 }
1118                                                         }
1119                                                 }
1120                                         }
1121                                 }
1122                         }
1123
1124                 }
1125                 return $content;                                                                
1126         }*/
1127         else
1128         {
1129         $sql_primary = "SELECT * FROM ".TABLE_PREFIX."primary_resources WHERE content_id=".$cid." ORDER BY primary_resource_id";
1130         $result          = mysql_query($sql_primary, $db);
1131         
1132         if (mysql_num_rows($result) > 0) 
1133         {
1134                 while ($row = mysql_fetch_assoc($result)) 
1135                 {
1136                         $sql_type        = "SELECT * FROM ".TABLE_PREFIX."primary_resources_types WHERE primary_resource_id=$row[primary_resource_id]"; 
1137                         $result_type = mysql_query($sql_type, $db);
1138                         
1139                         if (mysql_num_rows($result_type) > 0) 
1140                         {
1141                                 while ($row_type = mysql_fetch_assoc($result_type))
1142                                 {
1143                                         if (($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_AUDIO']==1) && ($row_type[type_id]==1))
1144                                         {
1145                                                 $sql_audio        = "SELECT * FROM ".TABLE_PREFIX."secondary_resources WHERE primary_resource_id=$row[primary_resource_id] and language_code='".$_SESSION['prefs']['PREF_ALT_AUDIO_PREFER_LANG']."'";   
1146                                                 $result_audio = mysql_query($sql_audio, $db);
1147                                                 if (mysql_num_rows($result_audio) > 0) 
1148                                                 {
1149                                                         while ($row_audio = mysql_fetch_assoc($result_audio))
1150                                                         {
1151                                                                 $sql_audio_alt    = "SELECT * FROM ".TABLE_PREFIX."secondary_resources_types WHERE secondary_resource_id=$row_audio[secondary_resource_id]";    
1152                                                                 $result_audio_alt = mysql_query($sql_audio_alt, $db);
1153                                                                 if (mysql_num_rows($result_audio_alt) > 0) 
1154                                                                 {
1155                                                                         while ($row_audio_alt = mysql_fetch_assoc($result_audio_alt))
1156                                                                         {
1157                                                                                 if ((($_SESSION['prefs']['PREF_ALT_TO_AUDIO']=="visual") && ($row_audio_alt[type_id]==4)) || (($_SESSION['prefs']['PREF_ALT_TO_AUDIO']==text) && ($row_audio_alt[type_id]==3)) || (($_SESSION['prefs']['PREF_ALT_TO_AUDIO']==sign_lang) && ($row_audio_alt[type_id]==2))) 
1158                                                                                 {
1159                                                                                         if (($_SESSION['prefs']['PREF_ALT_TO_AUDIO_APPEND_OR_REPLACE']=='replace'))
1160                                                                                         {
1161                                                                                                 $before  = explode($row['resource'], $content);
1162                                                                                                 $last_c  = substr($before[0], -1, 1);
1163                                                                                                 if ($last_c=="]")
1164                                                                                                         $shift   = strripos($before[0], '[');
1165                                                                                                 else
1166                                                                                                         $shift   = strripos($before[0], '<');
1167
1168                                                                                                 $len     = strlen($before[0]);
1169                                                                                                 $shift   = $len-$shift;
1170                                                                                                 $first   = substr($before[0], 0, -$shift);
1171                                                                                                 $ext     = substr($row_audio['secondary_resource'], -3);
1172                                                                                                 if (in_array($ext, $vidoe_exts))
1173                                                                                                 {
1174                                                                                                         $content = $first.'[media]'.$row_audio['secondary_resource'];
1175                                                                                                         if ($last_c=="]")
1176                                                                                                         {
1177                                                                                                                 $after   = substr($before[1], 8);
1178                                                                                                                 $after   = '[/media]'.$after;
1179                                                                                                         }
1180                                                                                                         else
1181                                                                                                         {
1182                                                                                                                 $shift   = strpos($before[1], '</');
1183                                                                                                                 $after   = substr($before[1], $shift);
1184                                                                                                                 $after   = substr($after, 4);
1185                                                                                                                 $after   = '[/media]'.$after;
1186                                                                                                         }
1187                                                                                                 }
1188                                                                                                 else
1189                                                                                                 {
1190                                                                                                         $new     = '<a href="';
1191                                                                                                         $content = $first.$new.$row_audio['secondary_resource'].'">'.$row_audio['secondary_resource'];
1192                                                                                                         if ($last_c=="]")
1193                                                                                                         {
1194                                                                                                                 $after   = substr($before[1], 8);
1195                                                                                                                 $after   = '</a>'.$after;
1196                                                                                                         }
1197                                                                                                         else
1198                                                                                                         {
1199                                                                                                                 $shift   = strpos($before[1], '</');
1200                                                                                                                 $after   = substr($before[1], $shift);
1201                                                                                                         }
1202                                                                                                 }
1203                                                                                                 $content = $content.$after;
1204                                                                                         }
1205                                                                                         else
1206                                                                                         {
1207                                                                                                 $before = explode($row['resource'], $content);
1208                                                                                                 $content   = $before[0].$row['resource'];
1209                                                                                                 $last_c  = substr($before[0], -1, 1);
1210                                                                                                 $ext     = substr($row_audio['secondary_resource'], -3);
1211                                                                                                 if (in_array($ext, $vidoe_exts))
1212                                                                                                 {
1213                                                                                                         if ($last_c=="]")
1214                                                                                                         {
1215                                                                                                                 $after     = substr($before[1], 8);
1216                                                                                                                 $content   = $content.'[/media][media]'.$row_audio['secondary_resource'].'[/media]'.$after;
1217                                                                                                         }
1218                                                                                                         else
1219                                                                                                         {
1220                                                                                                                 $shift     = strpos($before[1], '</a>');
1221                                                                                                                 $alt_shift = $len-$shift;
1222                                                                                                                 $res       = substr($before[1], 0, -$alt_shift);
1223                                                                                                                 $shift     = $shift+4;
1224                                                                                                                 $after     = substr($before[1], $shift);
1225                                                                                                                 $content   = $content.$res.'</a><br/>[media]'.$row_audio['secondary_resource'].'[/media]'.$after;
1226                                                                                                         }
1227                                                                                                 }
1228                                                                                                 else 
1229                                                                                                 {
1230                                                                                                         if ($last_c=="]")
1231                                                                                                         {
1232                                                                                                                 $after     = substr($before[1], 8);
1233                                                                                                                 $content   = $content.'[/media]'.'<p><a href="'.$row_audio['secondary_resource'].'">'.$row_audio['secondary_resource'].'</a></p>'.$after;
1234                                                                                                         }
1235                                                                                                         else
1236                                                                                                         {
1237                                                                                                                 $shift     = strpos($before[1], '</a>');
1238                                                                                                                 $alt_shift = $len-$shift;
1239                                                                                                                 $res       = substr($before[1], 0, -$alt_shift);
1240                                                                                                                 $shift     = $shift+4;
1241                                                                                                                 $after     = substr($before[1], $shift);
1242                                                                                                                 $content   = $content.$res.'</a><p><a href="'.$row_audio['secondary_resource'].'">'.$row_audio['secondary_resource'].'</a></p>'.$after;
1243                                                                                                         }
1244                                                                                                 }       
1245                                                                                         }
1246                                                                                 }
1247                                                                         }       
1248                                                                 }
1249                                                         }
1250                                                 }
1251                                         }
1252                                         if (($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_TEXT']==1) && ($row_type[type_id]==3))
1253                                         {
1254                                                 $sql_text          = "SELECT * FROM ".TABLE_PREFIX."secondary_resources WHERE primary_resource_id=$row[primary_resource_id] and language_code='".$_SESSION['prefs']['PREF_ALT_VISUAL_PREFER_LANG']."'"; 
1255                                                 $result_text = mysql_query($sql_text, $db);
1256                                                 if (mysql_num_rows($result_text) > 0) 
1257                                                 {
1258                                                         while ($row_text = mysql_fetch_assoc($result_text))
1259                                                         {
1260                                                                 $sql_text_alt    = "SELECT * FROM ".TABLE_PREFIX."secondary_resources_types WHERE secondary_resource_id=$row_text[secondary_resource_id]";      
1261                                                                 $result_text_alt         = mysql_query($sql_text_alt, $db);
1262                                                                 if (mysql_num_rows($result_text_alt) > 0) 
1263                                                                 {
1264                                                                         while ($row_text_alt = mysql_fetch_assoc($result_text_alt))
1265                                                                         {
1266                                                                                 if ((($_SESSION['prefs']['PREF_ALT_TO_TEXT']==audio) && ($row_text_alt[type_id]==1)) || 
1267                                                                                     (($_SESSION['prefs']['PREF_ALT_TO_TEXT']==visual) && ($row_text_alt[type_id]==4)) || 
1268                                                                                     (($_SESSION['prefs']['PREF_ALT_TO_TEXT']==sign_lang) && ($row_text_alt[type_id]==2)))
1269                                                                                 {
1270                                                                                         if ($_SESSION['prefs']['PREF_ALT_TO_TEXT_APPEND_OR_REPLACE']=='replace')
1271                                                                                         {
1272                                                                                                 $before  = explode($row['resource'], $content);
1273                                                                                                 $shift   = strripos($before[0], '<');
1274                                                                                                 $len     = strlen($before[0]);
1275                                                                                                 $shift   = $len-$shift;
1276                                                                                                 $first   = substr($before[0], 0, -$shift);
1277                                                                                                 $ext     = substr($row_text['secondary_resource'], -3);
1278                                                                                                 if (in_array($ext, $vidoe_exts))
1279                                                                                                 {
1280                                                                                                         $content = $first.'[media]'.$row_text['secondary_resource'];
1281                                                                                                         if ($last_c=="]")
1282                                                                                                         {
1283                                                                                                                 $after   = substr($before[1], 8);
1284                                                                                                                 $after   = '[/media]'.$after;
1285                                                                                                         }
1286                                                                                                         else
1287                                                                                                         {
1288                                                                                                                 $shift   = strpos($before[1], '</');
1289                                                                                                                 $after   = substr($before[1], $shift);
1290                                                                                                                 $after   = substr($after, 4);
1291                                                                                                                 $after   = '[/media]'.$after;
1292                                                                                                         }
1293                                                                                                 }
1294                                                                                                 else
1295                                                                                                 {
1296                                                                                                         if (($_SESSION['prefs']['PREF_ALT_TO_TEXT']==visual) && ($row_text_alt[type_id]==4))
1297                                                                                                         {
1298                                                                                                                 $new     = '<img border="0" alt="Alternate Text" src="';
1299                                                                                                                 $content = $first.$new.$row_text['secondary_resource'].'"/>';
1300                                                                                                                 $shift   = strpos($before[1], '</');
1301                                                                                                                 $after   = substr($before[1], $shift);
1302                                                                                                                 $media   = substr($after, 0, 8);
1303                                                                                                                 if ($media == '[/media]')
1304                                                                                                                         $after   = substr($after, 8);
1305                                                                                                                 else
1306                                                                                                                         $after   = substr($after, 4);
1307                                                                                                         }
1308                                                                                                         else
1309                                                                                                         {
1310                                                                                                                 $new     = '<a href="';
1311                                                                                                                 $content = $first.$new.$row_text['secondary_resource'].'">'.$row_text['secondary_resource'];
1312                                                                                                                 $shift   = strpos($before[1], '</');
1313                                                                                                                 $after   = substr($before[1], $shift);
1314                                                                                                         }
1315                                                                                                 }
1316                                                                                                 $content = $content.$after;
1317                                                                                         }
1318                                                                                         else 
1319                                                                                         {
1320                                                                                                 $before    = explode($row['resource'], $content);
1321                                                                                                 $content   = $before[0].$row['resource'];
1322                                                                                                 $ext       = substr($row_text['secondary_resource'], -3);
1323                                                                                                 if (in_array($ext, $vidoe_exts))
1324                                                                                                 {
1325 //                                                                                                      $shift     = strpos($before[1], '</a>');
1326                                                                                                         $shift     = strpos($before[1], '>') + 1;
1327                                                                                                         $alt_shift = $len-$shift;
1328                                                                                                         $res       = substr($before[1], 0, -$alt_shift);
1329                                                                                                         //$shift     = $shift;
1330                                                                                                         $after     = substr($before[1], $shift);
1331                                                                                                         $af        = strpos($after, '<');
1332                                                                                                         $str       = substr($after, $af, 4);
1333                                                                                                         if ($str != '</a>')
1334                                                                                                                 $content   = $content.$res.'<br/>[media]'.$row_text['secondary_resource'].'[/media]'.$after;
1335                                                                                                         else 
1336                                                                                                         {
1337                                                                                                                 $shift     = strpos($before[1], '</a>');
1338                                                                                                                 $alt_shift = $len-$shift;
1339                                                                                                                 $res       = substr($before[1], 0, -$alt_shift);
1340                                                                                                                 $shift     = $shift+4;
1341                                                                                                                 $after     = substr($before[1], $shift);
1342                                                                                                                 $content   = $content.$res.'</a><br/>[media]'.$row_text['secondary_resource'].'[/media]'.$after;
1343                                                                                                         }
1344                                                                                                 }
1345                                                                                                 else 
1346                                                                                                 {
1347                                                                                                         if (($_SESSION['prefs']['PREF_ALT_TO_TEXT']==visual) && ($row_text_alt[type_id]==4))
1348                                                                                                         {
1349                                                                                                                 $shift     = strpos($before[1], '</a>');
1350                                                                                                                 $alt_shift = $len-$shift;
1351                                                                                                                 $res       = substr($before[1], 0, -$alt_shift);
1352                                                                                                                 $shift     = $shift+4;
1353                                                                                                                 $after     = substr($before[1], $shift);
1354                                                                                                                 $content   = $content.$res.'</a><img border="0" alt="Alternate Text" src="'.$row_text['secondary_resource'].'"/>'.$after;
1355                                                                                                         }
1356                                                                                                         else 
1357                                                                                                         {
1358                                                                                                                 $shift     = strpos($before[1], '</a>');
1359                                                                                                                 $alt_shift = $len-$shift;
1360                                                                                                                 $res       = substr($before[1], 0, -$alt_shift);
1361                                                                                                                 $shift     = $shift+4;
1362                                                                                                                 $after     = substr($before[1], $shift);
1363                                                                                                                 $content   = $content.$res.'</a><p><a href="'.$row_text['secondary_resource'].'">'.$row_text['secondary_resource'].'</a></p>'.$after;
1364                                                                                                         }
1365                                                                                                 }
1366                                                                                         }
1367                                                                                 }
1368                                                                         }
1369                                                                 } 
1370                                                         }
1371                                                 }
1372                                         }
1373                                         if (($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_VISUAL']==1) && ($row_type[type_id]==4))
1374                                         {
1375                                                 $sql_visual        = "SELECT * FROM ".TABLE_PREFIX."secondary_resources WHERE primary_resource_id=$row[primary_resource_id] and language_code='".$_SESSION['prefs']['PREF_ALT_VISUAL_PREFER_LANG']."'"; 
1376                                                 $result_visual = mysql_query($sql_visual, $db);
1377                                                 
1378                                                 if (mysql_num_rows($result_visual) > 0) 
1379                                                 {
1380                                                         while ($row_visual = mysql_fetch_assoc($result_visual))
1381                                                         {
1382                                                                 $sql_visual_alt          = "SELECT * FROM ".TABLE_PREFIX."secondary_resources_types WHERE secondary_resource_id=$row_visual[secondary_resource_id]";    
1383                                                                 $result_visual_alt       = mysql_query($sql_visual_alt, $db);
1384                                                                 
1385                                                                 if (mysql_num_rows($result_visual_alt) > 0) 
1386                                                                 {
1387                                                                         while ($row_visual_alt = mysql_fetch_assoc($result_visual_alt))
1388                                                                         {
1389                                                                                 if ((($_SESSION['prefs']['PREF_ALT_TO_VISUAL']==audio) && ($row_visual_alt[type_id]==1)) || 
1390                                                                                     (($_SESSION['prefs']['PREF_ALT_TO_VISUAL']==text) && ($row_visual_alt[type_id]==3)) || 
1391                                                                                     (($_SESSION['prefs']['PREF_ALT_TO_VISUAL']==sign_lang) && ($row_visual_alt[type_id]==2)))
1392                                                                                 {
1393                                                                                         if ($_SESSION['prefs']['PREF_ALT_TO_VISUAL_APPEND_OR_REPLACE']=='replace')
1394                                                                                         {
1395                                                                                                 $before  = explode($row['resource'], $content);
1396                                                                                                 $last_c  = substr($before[0], -1, 1);
1397                                                                                                 if ($last_c=="]"){
1398                                                                                                         $shift   = strripos($before[0], '[');
1399                                                                                                 }
1400                                                                                                 else
1401                                                                                                 {
1402                                                                                                         $shift   = strripos($before[0], '<');
1403                                                                                                 }
1404                                                                                                 $len     = strlen($before[0]);
1405                                                                                                 $shift   = $len-$shift;
1406                                                                                                 $first   = substr($before[0], 0, -$shift);
1407                                                                                                 $ext     = substr($row_visual['secondary_resource'], -3);
1408                                                                                                 if (in_array($ext, $vidoe_exts))
1409                                                                                                 {
1410                                                                                                         $content = $first.'[media]'.$row_visual['secondary_resource'];
1411                                                                                                         if ($last_c=="]")
1412                                                                                                         {
1413                                                                                                                 $after   = substr($before[1], 8);
1414                                                                                                                 $after   = '[/media]'.$after;
1415                                                                                                         }
1416                                                                                                         else
1417                                                                                                         {
1418                                                                                                                 $shift   = strpos($before[1], '/>');
1419                                                                                                                 $after   = substr($before[1], $shift);
1420                                                                                                                 $after   = substr($after, 2);
1421                                                                                                                 $after   = '[/media]'.$after;
1422                                                                                                         }
1423                                                                                                 }
1424                                                                                                 else
1425                                                                                                 {
1426                                                                                                         $new     = '<a href="';
1427                                                                                                         $content = $first.$new.$row_visual['secondary_resource'].'">'.$row_visual['secondary_resource'].'</a>';
1428                                                                                                         if ($last_c=="]")
1429                                                                                                         {
1430                                                                                                                 $after   = substr($before[1], 8);
1431                                                                                                                 $content = $content.$after;
1432                                                                                                         }
1433                                                                                                         else
1434                                                                                                         {
1435                                                                                                                 $shift     = strpos($before[1], '/>');
1436                                                                                                                 $alt_shift = $len-$shift;
1437                                                                                                                 $res       = substr($before[1], 0, -$alt_shift);
1438                                                                                                                 $shift     = $shift+2;
1439                                                                                                                 $after     = substr($before[1], $shift);
1440                                                                                                         }
1441                                                                                                 }
1442                                                                                                 $content = $content.$after;
1443                                                                                         }
1444                                                                                         else 
1445                                                                                         {
1446                                                                                                 $before    = explode($row['resource'], $content);
1447                                                                                                 $content   = $before[0].$row['resource'];
1448                                                                                                 $last_c    = substr($before[0], -1, 1);
1449                                                                                                 $ext       = substr($row_visual['secondary_resource'], -3);
1450                                                                                                 if (in_array($ext, $vidoe_exts))
1451                                                                                                 {
1452                                                                                                         if ($last_c=="]")
1453                                                                                                         {
1454                                                                                                                 $after     = substr($before[1], 8);
1455                                                                                                                 $content   = $content.'[/media][media]'.$row_visual['secondary_resource'].'[/media]'.$after;
1456                                                                                                         }
1457                                                                                                         else
1458                                                                                                         {
1459                                                                                                                 $shift     = strpos($before[1], '/>');
1460                                                                                                                 $alt_shift = $len-$shift;
1461                                                                                                                 $res       = substr($before[1], 0, -$alt_shift);
1462                                                                                                                 $shift     = $shift+2;
1463                                                                                                                 $after     = substr($before[1], $shift);
1464                                                                                                                 $content   = $content.$res.'/>[media]'.$row_visual['secondary_resource'].'[/media]'.$after;
1465                                                                                                         }
1466                                                                                                 }
1467                                                                                                 else 
1468                                                                                                 {
1469                                                                                                         if ($last_c=="]")
1470                                                                                                         {
1471                                                                                                                 $after     = substr($before[1], 8);
1472                                                                                                                 $content   = $content.'[/media]'.'<p><a href="'.$row_visual['secondary_resource'].'">'.$row_visual['secondary_resource'].'</a></p>'.$after;
1473                                                                                                         }
1474                                                                                                         else
1475                                                                                                         {
1476                                                                                                                 $shift     = strpos($before[1], '/>');
1477                                                                                                                 $alt_shift = $len-$shift;
1478                                                                                                                 $res       = substr($before[1], 0, -$alt_shift);
1479                                                                                                                 $shift     = $shift+2;
1480                                                                                                                 $after     = substr($before[1], $shift);
1481                                                                                                                 $content   = $content.$res.'/><p><a href="'.$row_visual['secondary_resource'].'">'.$row_visual['secondary_resource'].'</a></p>'.$after;
1482                                                                                                         }
1483                                                                                                 }
1484                                                                                         }
1485                                                                                 }
1486                                                                         }
1487                                                                 }
1488                                                         }
1489                                                 }
1490                                         }
1491                                 }
1492                         }
1493                 }
1494                 
1495                 return $content;
1496                 }
1497                 else 
1498                 {
1499                         //No alternatives are declared by content authors
1500                         $content=$content_page;
1501                         return $content;
1502                 }
1503         }
1504 }       
1505         
1506 /**
1507 * replace source object with alternatives according to user's preferences
1508 * @access       public
1509 * @param        $cid:                           content id.
1510 * @param        $content:                       the original content page ($content_row['text'], from content.php).
1511 * @param    $info_only:         boolean. Default value is "false". When it's "true", returns an array of 4 values:
1512 *                               $has_text_alternative, $has_audio_alternative, $has_visual_alternative, $has_sign_lang_alternative
1513 * @param    $only_on_secondary_type: Default value is "". Accept one of the values: 1(auditory), 2(sign_language), 3(text), 4(visual)
1514 *                               When the value is given, ignore the alternative preference settings and only replace/append 
1515 *                               (replace or append is still from session preference) the objects with the alternatives with
1516 *                               the given alternative types.
1517 * @return       string                          $content: the content page with the appropriated resources.
1518 * @see          $db                             from include/vitals.inc.php
1519 * @author       Cindy Qi Li
1520 */
1521 function provide_alternatives($cid, $content, $info_only = false, $only_on_secondary_type = 0){
1522         global $db;
1523         
1524         $video_exts = array("mpg", "avi", "wmv", "mov", "swf", "mp3", "wav", "ogg", "mid", "mp4", "flv");
1525         $txt_exts = array("txt", "html", "htm");
1526         $image_exts = array("gif", "bmp", "png", "jpg", "jpeg", "png", "tif");
1527         $only_on_secondary_type = intval($only_on_secondary_type);
1528         
1529         // intialize the 4 returned values when $info_only is on
1530         if ($info_only)
1531         {
1532                 $has_text_alternative = false;
1533                 $has_audio_alternative = false;
1534                 $has_visual_alternative = false;
1535                 $has_sign_lang_alternative = false;
1536         }
1537
1538         if (!$info_only && !$only_on_secondary_type && 
1539             ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_TEXT']==0) && 
1540             ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_AUDIO']==0) && 
1541             ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_VISUAL']==0)) 
1542         {
1543                 //No user's preferences related to content format are declared
1544                 if (!$info_only) {
1545                         return $content;
1546                 } else {
1547                         return array($has_text_alternative, $has_audio_alternative, $has_visual_alternative, $has_sign_lang_alternative);
1548                 }
1549         }
1550         
1551         // get all relations between primary resources and their alternatives
1552         $sql = "SELECT c.content_path, pr.resource, prt.type_id primary_type, sr.secondary_resource, srt.type_id secondary_type
1553                   FROM ".TABLE_PREFIX."primary_resources pr, ".
1554                          TABLE_PREFIX."primary_resources_types prt,".
1555                          TABLE_PREFIX."secondary_resources sr,".
1556                          TABLE_PREFIX."secondary_resources_types srt,".
1557                          TABLE_PREFIX."content c
1558                  WHERE pr.content_id=".$cid."
1559                        AND pr.primary_resource_id = prt.primary_resource_id
1560                        AND pr.primary_resource_id = sr.primary_resource_id
1561                        AND sr.language_code='".$_SESSION['lang']."'
1562                        AND sr.secondary_resource_id = srt.secondary_resource_id
1563                    AND pr.content_id = c.content_id";
1564         if ($only_on_secondary_type > 0) {
1565                 $sql .= " AND srt.type_id=".$only_on_secondary_type;
1566         }
1567         $sql .= " ORDER BY pr.primary_resource_id, prt.type_id";
1568         
1569         $result = mysql_query($sql, $db);
1570 //debug($sql);
1571         if (mysql_num_rows($result) == 0) {
1572                 if (!$info_only) {
1573                         return $content;
1574                 } else {
1575                         return array($has_text_alternative, $has_audio_alternative, $has_visual_alternative, $has_sign_lang_alternative);
1576                 }
1577         }
1578         
1579         while ($row = mysql_fetch_assoc($result)) 
1580         {
1581                 if ($info_only || $only_on_secondary_type ||
1582                     ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_TEXT']==1 && $row['primary_type']==3 &&
1583                     ($_SESSION['prefs']['PREF_ALT_TO_TEXT']=="audio" && $row['secondary_type']==1 || 
1584                      $_SESSION['prefs']['PREF_ALT_TO_TEXT']=="visual" && $row['secondary_type']==4 || 
1585                      $_SESSION['prefs']['PREF_ALT_TO_TEXT']=="sign_lang" && $row['secondary_type']==2)) ||
1586                      
1587                      ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_AUDIO']==1 && $row['primary_type']==1 &&
1588                      ($_SESSION['prefs']['PREF_ALT_TO_AUDIO']=="visual" && $row['secondary_type']==4 || 
1589                       $_SESSION['prefs']['PREF_ALT_TO_AUDIO']=="text" && $row['secondary_type']==3 || 
1590                       $_SESSION['prefs']['PREF_ALT_TO_AUDIO']=="sign_lang" && $row['secondary_type']==2)) ||
1591                       
1592                      ($_SESSION['prefs']['PREF_USE_ALTERNATIVE_TO_VISUAL']==1 && $row['primary_type']==4 &&
1593                      ($_SESSION['prefs']['PREF_ALT_TO_VISUAL']=="audio" && $row['secondary_type']==1 || 
1594                       $_SESSION['prefs']['PREF_ALT_TO_VISUAL']=="text" && $row['secondary_type']==3 || 
1595                       $_SESSION['prefs']['PREF_ALT_TO_VISUAL']=="sign_lang" && $row['secondary_type']==2))
1596                     )
1597                 {
1598                         $ext = substr($row['secondary_resource'], strrpos($row['secondary_resource'], '.')+1);
1599                         
1600                         // alternative is video
1601                         if (in_array($ext, $video_exts))
1602                                 $target = '[media]'.$row['secondary_resource'].'[/media]';
1603                         // a text primary to be replaced by a visual alternative 
1604                         else if (in_array($ext, $txt_exts))
1605                         {
1606                                 if ($row['content_path'] <> '') 
1607                                         $file_location = $row['content_path'].'/'.$row['secondary_resource'];
1608                                 else 
1609                                         $file_location = $row['secondary_resource'];
1610                                 
1611                                 $file = AT_CONTENT_DIR.$_SESSION['course_id'] . '/'.$file_location;
1612                                 $target = '<br />'.file_get_contents($file);
1613                                 
1614                                 // check whether html file
1615                                 if (preg_match('/.*\<html.*\<\/html\>.*/s', $target))
1616                                 { // is a html file, use iframe to display
1617                                         // get real path to the text file
1618                                         if (defined('AT_FORCE_GET_FILE') && AT_FORCE_GET_FILE) {
1619                                                 $course_base_href = 'get.php/';
1620                                         } else {
1621                                                 $course_base_href = 'content/' . $_SESSION['course_id'] . '/';
1622                                         }
1623         
1624                                         $file = AT_BASE_HREF . $course_base_href.$file_location;
1625                                                 
1626                                         $target = '<iframe width="100%" frameborder="0" class="autoHeight" scrolling="auto" src="'.$file.'"></iframe>';
1627                                 }
1628                                 else
1629                                 { // is a text file, insert/replace into content
1630                                         $target = nl2br($target);
1631                                 }
1632                         } 
1633                         else if (in_array($ext, $image_exts))
1634                                 $target = '<img border="0" alt="'._AT('alternate_text').'" src="'.$row['secondary_resource'].'"/>';
1635                         // otherwise
1636                         else
1637                                 $target = '<p><a href="'.$row['secondary_resource'].'">'.$row['secondary_resource'].'</a></p>';
1638
1639                         // replace or append the target alternative to the source
1640                         if (($row['primary_type']==3 && $_SESSION['prefs']['PREF_ALT_TO_TEXT_APPEND_OR_REPLACE'] == 'replace') ||
1641                                 ($row['primary_type']==1 && $_SESSION['prefs']['PREF_ALT_TO_AUDIO_APPEND_OR_REPLACE']=='replace') ||
1642                                 ($row['primary_type']==4 && $_SESSION['prefs']['PREF_ALT_TO_VISUAL_APPEND_OR_REPLACE']=='replace'))
1643                                 $pattern_replace_to = '${1}'.$target.'${3}';
1644                         else
1645                                 $pattern_replace_to = '${1}${2}'.$target.'${3}';
1646
1647                         // *** Alternative replace/append starts from here ***
1648                         $img_processed = false;    // The indicator to tell the source image is found (or not) 
1649                                                    // and processed (or not) in an <img> tag. If found and processed, 
1650                                                    // SKIP the found/process for <a> tag because the source is a image
1651                                                    // and <a> is very likely the tag wrapping around <img>
1652                                                     
1653                         // append/replace target alternative to [media]source[/media]
1654                         if (preg_match("/".preg_quote("[media").".*".preg_quote("]".$row['resource']."[/media]", "/")."/sU", $content))
1655                         {
1656                                 if (!$info_only) {
1657                                         $content = preg_replace("/(.*)(".preg_quote("[media").".*".preg_quote("]".$row['resource']."[/media]", "/").")(.*)/sU", 
1658                                      $pattern_replace_to, $content);
1659                                 } else {
1660                                         if ($row['secondary_type'] == 1) $has_audio_alternative = true;
1661                                         if ($row['secondary_type'] == 2) $has_sign_lang_alternative = true;
1662                                         if ($row['secondary_type'] == 3) $has_text_alternative = true;
1663                                         if ($row['secondary_type'] == 4) $has_visual_alternative = true;
1664                                 }
1665                         }
1666                         
1667                         // append/replace target alternative to <img ... src="source" ...></a>
1668                         if (preg_match("/\<img.*src=\"".preg_quote($row['resource'], "/")."\".*\/\>/sU", $content))
1669                         {
1670                                 $img_processed = true;
1671                                 if (!$info_only) {
1672                                         $content = preg_replace("/(.*)(\<img.*src=\"".preg_quote($row['resource'], "/")."\".*\/\>)(.*)/sU", 
1673                                                 $pattern_replace_to, $content);
1674                                 } else {
1675                                         if ($row['secondary_type'] == 1) $has_audio_alternative = true;
1676                                         if ($row['secondary_type'] == 2) $has_sign_lang_alternative = true;
1677                                         if ($row['secondary_type'] == 3) $has_text_alternative = true;
1678                                         if ($row['secondary_type'] == 4) $has_visual_alternative = true;
1679                                 }
1680                         }
1681                         
1682                         // append/replace target alternative to <a>...source...</a> or <a ...source...>...</a>
1683                         // skip this "if" when the source object has been processed in aboved <img> tag
1684                         if (!$img_processed && preg_match("/\<a.*".preg_quote($row['resource'], "/").".*\<\/a\>/sU", $content))
1685                         {
1686                                 if (!$info_only) {
1687                                         $content = preg_replace("/(.*)(\<a.*".preg_quote($row['resource'], "/").".*\<\/a\>)(.*)/sU", 
1688                                                 $pattern_replace_to, $content);
1689                                 } else {
1690                                         if ($row['secondary_type'] == 1) $has_audio_alternative = true;
1691                                         if ($row['secondary_type'] == 2) $has_sign_lang_alternative = true;
1692                                         if ($row['secondary_type'] == 3) $has_text_alternative = true;
1693                                         if ($row['secondary_type'] == 4) $has_visual_alternative = true;
1694                                 }
1695                         }
1696
1697                         // append/replace target alternative to <object ... source ...></object>
1698                         if (preg_match("/\<object.*".preg_quote($row['resource'], "/").".*\<\/object\>/sU", $content))
1699                         {
1700                                 if (!$info_only) {
1701                                         $content = preg_replace("/(.*)(\<object.*".preg_quote($row['resource'], "/").".*\<\/object\>)(.*)/sU", 
1702                                                 $pattern_replace_to, $content);
1703                                 } else {
1704                                         if ($row['secondary_type'] == 1) $has_audio_alternative = true;
1705                                         if ($row['secondary_type'] == 2) $has_sign_lang_alternative = true;
1706                                         if ($row['secondary_type'] == 3) $has_text_alternative = true;
1707                                         if ($row['secondary_type'] == 4) $has_visual_alternative = true;
1708                                 }
1709                         }
1710
1711                         // append/replace target alternative to <embed ... source ...>
1712                         if (preg_match("/\<embed.*".preg_quote($row['resource'], "/").".*\>/sU", $content))
1713                         {
1714                                 if (!$info_only) {
1715                                         $content = preg_replace("/(.*)(\<embed.*".preg_quote($row['resource'], "/").".*\>)(.*)/sU", 
1716                                                 $pattern_replace_to, $content);
1717                                 } else {
1718                                         if ($row['secondary_type'] == 1) $has_audio_alternative = true;
1719                                         if ($row['secondary_type'] == 2) $has_sign_lang_alternative = true;
1720                                         if ($row['secondary_type'] == 3) $has_text_alternative = true;
1721                                         if ($row['secondary_type'] == 4) $has_visual_alternative = true;
1722                                 }
1723                         }
1724                 }
1725         }
1726         
1727         if (!$info_only) {
1728                 return $content;
1729         } else {
1730                 return array($has_text_alternative, $has_audio_alternative, $has_visual_alternative, $has_sign_lang_alternative);
1731         }
1732 }       
1733                 
1734 /**
1735 * apply_timezone
1736 * converts a unix timestamp into another UNIX timestamp with timezone offset added up.
1737 * Adds the user's timezone offset, then converts back to a MYSQL timestamp
1738 * Available both as a system config option, and a user preference, if both are set
1739 * they are added together
1740 * @param   date  MYSQL timestamp.
1741 * @return  date  MYSQL timestamp plus user's and/or system's timezone offset.
1742 * @author  Greg Gay  .
1743 */
1744 function apply_timezone($timestamp){
1745         global $_config;
1746
1747         if($_config['time_zone']){
1748                 $timestamp = ($timestamp + ($_config['time_zone']*3600));
1749         }
1750
1751         if(isset($_SESSION['prefs']['PREF_TIMEZONE'])){
1752                 $timestamp = ($timestamp + ($_SESSION['prefs']['PREF_TIMEZONE']*3600));
1753         }
1754
1755         return $timestamp;
1756 }
1757 ?>