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