(no commit message)
[atutor.git] / include / vitals.inc.php
1 <?php
2 /************************************************************************/
3 /* ATutor                                                               */
4 /************************************************************************/
5 /* Copyright (c) 2002 - 2009                                            */
6 /* Inclusive Design Institute                                           */
7 /*                                                                      */
8 /* This program is free software. You can redistribute it and/or        */
9 /* modify it under the terms of the GNU General Public License          */
10 /* as published by the Free Software Foundation.                        */
11 /************************************************************************/
12 // $Id$
13
14 if (!defined('AT_INCLUDE_PATH')) { exit; }
15
16 define('AT_DEVEL', 1);
17 define('AT_ERROR_REPORTING', E_ALL ^ E_NOTICE); // default is E_ALL ^ E_NOTICE, use E_ALL or E_ALL + E_STRICT for developing
18 define('AT_DEVEL_TRANSLATE', 0);
19
20 // Emulate register_globals off. src: http://php.net/manual/en/faq.misc.php#faq.misc.registerglobals
21 function unregister_GLOBALS() {
22    if (!ini_get('register_globals')) { return; }
23
24    // Might want to change this perhaps to a nicer error
25    if (isset($_REQUEST['GLOBALS'])) { die('GLOBALS overwrite attempt detected'); }
26
27    // Variables that shouldn't be unset
28    $noUnset = array('GLOBALS','_GET','_POST','_COOKIE','_REQUEST','_SERVER','_ENV', '_FILES');
29    $input = array_merge($_GET,$_POST,$_COOKIE,$_SERVER,$_ENV,$_FILES,isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());
30   
31    foreach ($input as $k => $v) {
32        if (!in_array($k, $noUnset) && isset($GLOBALS[$k])) { unset($GLOBALS[$k]); }
33    }
34 }
35
36 //functions for properly escaping input strings
37 function my_add_null_slashes( $string ) {
38     return mysql_real_escape_string(stripslashes($string));
39 }
40 function my_null_slashes($string) {
41     return $string;
42 }
43
44 if ( get_magic_quotes_gpc() == 1 ) {
45     $addslashes   = 'my_add_null_slashes';
46     $stripslashes = 'stripslashes';
47 } else {
48     $addslashes   = 'mysql_real_escape_string';
49     $stripslashes = 'my_null_slashes';
50 }
51
52 /*
53  * structure of this document (in order):
54  *
55  * 0. load config.inc.php
56  * 1. load constants
57  * 2. initilize session
58  * 3. load language constants
59  * 4. enable output compression
60  * 5. initilize db connection
61  * 6. load cache library
62  * 7. initilize session localization
63  * 8. load ContentManagement/output/Savant/Message libraries
64  ***/
65
66 /**** 0. start system configuration options block ****/
67         error_reporting(0);
68         if (!defined('AT_REDIRECT_LOADED')){
69                 include_once(AT_INCLUDE_PATH.'config.inc.php');
70         }
71         error_reporting(AT_ERROR_REPORTING);
72
73         if (!defined('AT_INSTALL') || !AT_INSTALL) {
74                 header('Cache-Control: no-store, no-cache, must-revalidate');
75                 header('Pragma: no-cache');
76
77                 $relative_path = substr(AT_INCLUDE_PATH, 0, -strlen('include/'));
78                 header('Location: ' . $relative_path . 'install/not_installed.php');
79                 exit;
80         }
81 /*** end system config block ****/
82
83 /*** 1. constants ***/
84         if (!defined('AT_REDIRECT_LOADED')){
85                 require_once(AT_INCLUDE_PATH.'lib/constants.inc.php');
86         }
87
88 /***** 2. start session initilization block ****/
89         if (headers_sent()) {
90                 require_once(AT_INCLUDE_PATH . 'classes/ErrorHandler/ErrorHandler.class.php');
91                 $err = new ErrorHandler();
92                 trigger_error('VITAL#<br /><br /><code><strong>An error occurred. Output sent before it should have. Please correct the above error(s).' . '</strong></code><br /><hr /><br />', E_USER_ERROR);
93         }
94
95         @set_time_limit(0);
96         @ini_set('session.gc_maxlifetime', '36000'); /* 10 hours */
97         @session_cache_limiter('private, must-revalidate');
98         session_name('ATutorID');
99         error_reporting(AT_ERROR_REPORTING);
100
101         if (headers_sent()) {
102                 require_once(AT_INCLUDE_PATH . 'classes/ErrorHandler/ErrorHandler.class.php');
103                 $err = new ErrorHandler();
104                 trigger_error('VITAL#<br /><code><strong>Headers already sent. ' .
105                                                 'Cannot initialise session.</strong></code><br /><hr /><br />', E_USER_ERROR);
106                 exit;
107         }
108
109         ob_start();
110         session_set_cookie_params(0, $_base_path);
111         session_start();
112         $str = ob_get_contents();
113         ob_end_clean();
114         unregister_GLOBALS();
115
116         if ($str) {
117                 require_once(AT_INCLUDE_PATH . 'classes/ErrorHandler/ErrorHandler.class.php');
118                 $err = new ErrorHandler();
119                 trigger_error('VITAL#<br /><code><strong>Error initializing session. ' .
120                                                 'Please varify that session.save_path is correctly set in your php.ini file ' .
121                                                 'and the directory exists.</strong></code><br /><hr /><br />', E_USER_ERROR);
122                 exit;
123         }
124
125
126 /***** end session initilization block ****/
127
128 // 4. enable output compression, if it isn't already enabled:
129 if ((@ini_get('output_handler') == '') && (@ini_get('zlib.output_handler') == '')) {
130         @ini_set('zlib.output_compression', 1);
131 }
132
133 /* 5. database connection */
134 if (!defined('AT_REDIRECT_LOADED')){
135         require_once(AT_INCLUDE_PATH.'lib/mysql_connect.inc.php');
136 }
137
138 /* get config variables. if they're not in the db then it uses the installation default value in constants.inc.php */
139 $sql    = "SELECT * FROM ".TABLE_PREFIX."config";
140 $result = mysql_query($sql, $db);
141 while ($row = mysql_fetch_assoc($result)) { 
142         $_config[$row['name']] = $row['value'];
143 }
144
145 //Check if users=valid
146 if (!isset($_SESSION['course_id']) && !isset($_SESSION['valid_user']) && (!isset($_user_location) || $_user_location != 'public') && !isset($_pretty_url_course_id)) {
147         if (isset($in_get) && $in_get && (($pos = strpos($_SERVER['PHP_SELF'], 'get.php/')) !== FALSE)) {
148                 $redirect = substr($_SERVER['PHP_SELF'], 0, $pos) . 'login.php';
149                 header('Location: '.$redirect);
150                 exit;
151         }
152
153         header('Location: '.AT_BASE_HREF.'login.php');
154         exit;
155 }
156
157 /* following is added as a transition period and backwards compatability: */
158 define('EMAIL',                     $_config['contact_email']);
159 define('EMAIL_NOTIFY',              $_config['email_notification']);
160 define('ALLOW_INSTRUCTOR_REQUESTS', $_config['allow_instructor_requests']);
161 define('AUTO_APPROVE_INSTRUCTORS',  $_config['auto_approve_instructors']);
162 define('SITE_NAME',                 $_config['site_name']);
163 define('HOME_URL',                  $_config['home_url']);
164 define('DEFAULT_LANGUAGE',          $_config['default_language']);
165 define('CACHE_DIR',                 $_config['cache_dir']);
166 define('AT_ENABLE_CATEGORY_THEMES', $_config['theme_categories']);
167 define('AT_COURSE_BACKUPS',         $_config['course_backups']);
168 define('AT_EMAIL_CONFIRMATION',     $_config['email_confirmation']);
169 define('AT_MASTER_LIST',            $_config['master_list']);
170 $MaxFileSize       = $_config['max_file_size']; 
171 $MaxCourseSize     = $_config['max_course_size'];
172 $MaxCourseFloat    = $_config['max_course_float'];
173 $IllegalExtentions = explode('|',$_config['illegal_extentions']);
174 define('AT_DEFAULT_PREFS',  isset($_config['prefs_default']) ? $_config['prefs_default'] : '');
175 $_config['home_defaults'] .= (isset($_config['home_defaults_2']) ? $_config['home_defaults_2'] : '');
176 $_config['main_defaults'] .= (isset($_config['main_defaults_2']) ? $_config['main_defaults_2'] : '');
177
178 require(AT_INCLUDE_PATH.'phpCache/phpCache.inc.php'); // cache library
179 require(AT_INCLUDE_PATH.'lib/utf8.php');                        //UTF-8 multibyte library
180
181 //set the timezone, php 5.3+ problem. http://atutor.ca/atutor/mantis/view.php?id=4409
182 date_default_timezone_set('UTC');
183
184 if ($_config['time_zone']) {
185         //$sql = "SET time_zone='{$_config['time_zone']}'";
186         //mysql_query($sql, $db);
187
188         if (function_exists('date_default_timezone_set')) {
189         foreach($utc_timezones as $zone){
190
191                 if($zone[1] ==  $_config['time_zone']){
192                 $zone_name = $zone[2];
193                 break;
194                 }
195         }
196                 date_default_timezone_set($zone_name);
197         } else {
198                 @putenv("TZ={$_config['time_zone']}");
199         }
200 }
201 /***** 7. start language block *****/
202         // set current language
203         require(AT_INCLUDE_PATH . '../mods/_core/languages/classes/LanguageManager.class.php');
204         $languageManager = new LanguageManager();
205
206         $myLang =& $languageManager->getMyLanguage();
207
208         if ($myLang === FALSE) {
209                 echo 'There are no languages installed!';
210                 exit;
211         }
212         $myLang->saveToSession();
213         if (isset($_GET['lang']) && $_SESSION['valid_user']) {
214                 if ($_SESSION['course_id'] == -1) {
215                         $myLang->saveToPreferences($_SESSION['login'], 1);      //1 for admin                   
216                 } else {
217                         $myLang->saveToPreferences($_SESSION['member_id'], 0);  //0 for non-admin
218                 }
219         }
220         $myLang->sendContentTypeHeader();
221
222         /* set right-to-left language */
223         $rtl = '';
224         if ($myLang->isRTL()) {
225                 $rtl = 'rtl_'; /* basically the prefix to a rtl variant directory/filename. eg. rtl_tree */
226         }
227 /***** end language block ****/
228
229 /* 8. load common libraries */
230         require(AT_INCLUDE_PATH.'classes/ContentManager.class.php');  /* content management class */
231         require_once(AT_INCLUDE_PATH.'lib/output.inc.php');           /* output functions */
232         if (!(defined('AT_REDIRECT_LOADED'))){
233                 require_once(AT_INCLUDE_PATH . 'classes/UrlRewrite/UrlParser.class.php');       /* pretty url tool */
234         }
235         require(AT_INCLUDE_PATH.'classes/Savant2/Savant2.php');       /* for the theme and template management */
236
237         // set default template paths:
238         $savant = new Savant2();
239         $savant->addPath('template', AT_INCLUDE_PATH . '../themes/'.get_system_default_theme().'/');
240
241         //if user has requested theme change, make the change here
242         if (($_POST['theme'] || $_POST['mobile_theme']) && $_POST['submit']) {
243             $_SESSION['prefs']['PREF_THEME'] = $addslashes($_POST['theme']);
244             $_SESSION['prefs']['PREF_MOBILE_THEME'] = $addslashes($_POST['mobile_theme']);
245         } else if ($_POST['set_default']) {
246             $_SESSION['prefs']['PREF_THEME'] = 'default';
247             $_SESSION['prefs']['PREF_MOBILE_THEME'] = 'mobile';
248         }
249         
250         // Reset PREF_THEME when:
251         // 1. If PREF_THEME is not set 
252         // 2. The request is from the mobile device but PREF_THEME is not a mobile theme 
253         if (!isset($_SESSION['prefs']['PREF_THEME']) ||
254             $_SESSION['prefs']['PREF_THEME'] == "" ||
255             (is_mobile_device() && !is_mobile_theme($_SESSION['prefs']['PREF_THEME']))) {
256                 // get default
257                 $default_theme = get_default_theme();
258                 
259                 if (!is_dir(AT_INCLUDE_PATH . '../themes/' . $default_theme['dir_name']) || $default_theme == '') {
260                         $default_theme = array('dir_name' => get_system_default_theme());
261                 }
262                 $_SESSION['prefs']['PREF_THEME'] = $default_theme['dir_name'];
263         }
264         
265         // use "mobile" theme for mobile devices. For now, there's only one mobile theme and it's hardcoded.
266         // When more mobile themes come in, this should be changed.
267         if (isset($_SESSION['prefs']['PREF_THEME']) && file_exists(AT_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME']) && isset($_SESSION['valid_user']) && $_SESSION['valid_user']) {
268                 if ($_SESSION['course_id'] == -1) {
269                         if ($_SESSION['prefs']['PREF_THEME'] == '' || !is_dir(AT_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME'])) {
270                                 $_SESSION['prefs']['PREF_THEME'] = get_system_default_theme();
271                         }
272                 } else {
273                         //check if enabled
274                         $sql    = "SELECT status FROM ".TABLE_PREFIX."themes WHERE dir_name = '".$_SESSION['prefs']['PREF_THEME']."'";
275                         $result = mysql_query($sql, $db);
276                         $row = mysql_fetch_assoc($result);
277                         if ($row['status'] > 0) {
278                         } else {
279                                 // get default
280                                 $default_theme = get_default_theme();
281                                 if (!is_dir(AT_INCLUDE_PATH . '../themes/' . $default_theme['dir_name'])) {
282                                         $default_theme = array('dir_name' => get_system_default_theme());
283                                 }
284                                 $_SESSION['prefs']['PREF_THEME'] = $default_theme['dir_name'];
285                         }
286                 }
287         }
288         
289         $savant->addPath('template', AT_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME'] . '/');
290         require(AT_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME'] . '/theme.cfg.php');
291
292         require(AT_INCLUDE_PATH.'classes/Message/Message.class.php');
293         $msg = new Message($savant);
294
295         $contentManager = new ContentManager($db, isset($_SESSION['course_id']) ? $_SESSION['course_id'] : $_GET['p_course']);
296         $contentManager->initContent();
297 /**************************************************/
298
299 if (isset($_user_location) && ($_user_location == 'users') && $_SESSION['valid_user'] && ($_SESSION['course_id'] > 0)) {
300         $_SESSION['course_id'] = 0;
301 }
302
303 if ((!isset($_SESSION['course_id']) || $_SESSION['course_id'] == 0) && ($_user_location != 'users') && ($_user_location != 'prog') && !isset($_GET['h']) && ($_user_location != 'public') && (!isset($_pretty_url_course_id) || $_pretty_url_course_id == 0)) {
304         header('Location:'.AT_BASE_HREF.'users/index.php');
305         exit;
306 }
307 /* check if we are in the requested course, if not, bounce to it.
308  * @author harris, for pretty url, read AT_PRETTY_URL_HANDLER
309  */ 
310 if ((isset($_SESSION['course_id']) && isset($_pretty_url_course_id) && $_SESSION['course_id'] != $_pretty_url_course_id) ||
311         (isset($_pretty_url_course_id) && !isset($_SESSION['course_id']) && !isset($_REQUEST['ib']))) {
312
313         if($_config['pretty_url'] == 0){
314                 header('Location: '.AT_BASE_HREF.'bounce.php?course='.$_pretty_url_course_id.SEP.'pu='.$_SERVER['PATH_INFO'].urlencode('?'.$_SERVER['QUERY_STRING']));
315         } else {
316                 header('Location: '.AT_BASE_HREF.'bounce.php?course='.$_pretty_url_course_id.SEP.'pu='.$_SERVER['PATH_INFO']);
317         }
318         exit;
319 }
320
321    /**
322    * This function is used for printing variables into log file for debugging.
323    * @access  public
324    * @param   mixed $var        The variable to output
325    * @param   string $log       The location of the log file. If not provided, use the default one.
326    * @author  Cindy Qi Li
327    */
328 function debug_to_log($var, $log='') {
329         if (!defined('AT_DEVEL') || !AT_DEVEL) {
330                 return;
331         }
332         
333         if ($log == '') $log = AT_CONTENT_DIR. 'atutor.log';
334         $handle = fopen($log, 'a');
335         fwrite($handle, "\n\n");
336         fwrite($handle, date("F j, Y, g:i a"));
337         fwrite($handle, "\n");
338         fwrite($handle, var_export($var,1));
339         
340         fclose($handle);
341 }
342
343    /**
344    * This function is used for printing variables for debugging.
345    * @access  public
346    * @param   mixed $var        The variable to output
347    * @param   string $title     The name of the variable, or some mark-up identifier.
348    * @author  Joel Kronenberg
349    */
350 function debug($var, $title='') {
351         if (!defined('AT_DEVEL') || !AT_DEVEL) {
352                 return;
353         }
354         
355         echo '<pre style="border: 1px black solid; padding: 0px; margin: 10px;" title="debugging box">';
356         if ($title) {
357                 echo '<h4>'.$title.'</h4>';
358         }
359         
360         ob_start();
361         print_r($var);
362         $str = ob_get_contents();
363         ob_end_clean();
364
365         $str = str_replace('<', '&lt;', $str);
366
367         $str = str_replace('[', '<span style="color: red; font-weight: bold;">[', $str);
368         $str = str_replace(']', ']</span>', $str);
369         $str = str_replace('=>', '<span style="color: blue; font-weight: bold;">=></span>', $str);
370         $str = str_replace('Array', '<span style="color: purple; font-weight: bold;">Array</span>', $str);
371         echo $str;
372         echo '</pre>';
373 }
374
375 /********************************************************************/
376 /* the system course information                                                                        */
377 /* system_courses[course_id] = array(title, description, subject)       */
378 $system_courses = array();
379
380 // temporary set to a low number
381 $sql = 'SELECT * FROM '.TABLE_PREFIX.'courses ORDER BY title';
382 $result = mysql_query($sql, $db);
383 while ($row = mysql_fetch_assoc($result)) {
384         $course = $row['course_id'];
385         unset($row['course_id']);
386         $system_courses[$course] = $row;
387 }
388 /*                                                                                                                                      */
389 /********************************************************************/
390 // p_course is set when pretty url is on and guests access a public course. @see bounce.php
391 if (isset($_SESSION['course_id']) && $_SESSION['course_id'] > 0 || $_REQUEST['p_course'] > 0) {
392         $sql = 'SELECT * FROM '.TABLE_PREFIX.'glossary 
393                  WHERE course_id='.($_SESSION['course_id']>0 ? $_SESSION['course_id'] : $_REQUEST['p_course']).' 
394                  ORDER BY word';
395         $result = mysql_query($sql, $db);
396         $glossary = array();
397         $glossary_ids = array();
398         while ($row_g = mysql_fetch_assoc($result)) {           
399                 $row_g['word'] = htmlspecialchars($row_g['word'], ENT_QUOTES, 'UTF-8');
400                 $glossary[$row_g['word']] = str_replace("'", "\'",$row_g['definition']);
401                 $glossary_ids[$row_g['word_id']] = $row_g['word'];
402
403                 /* a kludge to get the related id's for when editing content */
404                 /* it's ugly, but beats putting this query AGAIN on the edit_content.php page */
405                 if (isset($get_related_glossary)) {
406                         $glossary_ids_related[$row_g['word']] = $row_g['related_word_id'];
407                 }
408         }
409 }
410
411 function get_html_body($text) {
412         /* strip everything before <body> */
413         $start_pos      = strpos(strtolower($text), '<body');
414         if ($start_pos !== false) {
415                 $start_pos      += strlen('<body');
416                 $end_pos        = strpos(strtolower($text), '>', $start_pos);
417                 $end_pos        += strlen('>');
418
419                 $text = substr($text, $end_pos);
420         }
421
422         /* strip everything after </body> */
423         $end_pos        = strpos(strtolower($text), '</body>');
424         if ($end_pos !== false) {
425                 $text = trim(substr($text, 0, $end_pos));
426         }
427
428         return $text;
429 }
430
431 function get_html_head ($text) {
432         /* make all text lower case */
433 //      $text = strtolower($text);
434
435         /* strip everything before <head> */
436         $start_pos      = stripos($text, '<head');
437         if ($start_pos !== false) {
438                 $start_pos      += strlen('<head');
439                 $end_pos        = stripos($text, '>', $start_pos);
440                 $end_pos        += strlen('>');
441
442                 $text = substr($text, $end_pos);
443         }
444
445         /* strip everything after </head> */
446         $end_pos        = stripos($text, '</head');
447         if ($end_pos !== false) {
448                 $text = trim(substr($text, 0, $end_pos));
449         }
450         return $text;
451 }
452
453 /**
454 * This function cuts out requested tag information from html head
455 * @access  public
456 * @param   $text  html text
457 * @param   $tags  a string or an array of requested tags
458 * @author  Cindy Qi Li
459 */
460 function get_html_head_by_tag($text, $tags)
461 {
462         $head = get_html_head($text);
463         $rtn_text = "";
464         
465         if (!is_array($tags) && strlen(trim($tags)) > 0)
466         {
467                 $tags = array(trim($tags));
468         }
469         foreach ($tags as $tag)
470         {
471                 $tag = strtolower($tag);
472
473                 /* strip everything before <{tag}> */
474                 $start_pos      = stripos($head, '<'.$tag);
475                 $temp_head = $head;
476                 
477                 while ($start_pos !== false) 
478                 {
479                         $temp_text = substr($temp_head, $start_pos);
480         
481                         /* strip everything after </{tag}> or />*/
482                         $end_pos        = stripos($temp_text, '</' . $tag . '>');
483         
484                         if ($end_pos !== false) 
485                         {
486                                 $end_pos += strlen('</' . $tag . '>');
487                                 
488                                 // add an empty line after each tag information
489                                 $rtn_text .= trim(substr($temp_text, 0, $end_pos)) . '
490         
491 ';
492                         }
493                         else  // match /> as ending tag if </tag> is not found
494                         {
495                                 $end_pos        = stripos($temp_text, '/>');
496                                 
497                                 if($end_pos === false && stripos($temp_text, $tag.'>')===false){
498                                         //if /> is not found, then this is not a valid XHTML
499                                         //text iff it's not tag>
500                                         $end_pos = stripos($temp_text, '>');
501                                         $end_pos += strlen('>');
502                                 } else {
503                                         $end_pos += strlen('/>');
504                                 }
505                                 // add an empty line after each tag information
506                                 $rtn_text .= trim(substr($temp_text, 0, $end_pos)) . '
507         
508 ';
509                         }
510                         
511                         // initialize vars for next round of matching
512                         $temp_head = substr($temp_text, $end_pos);
513                         $start_pos = stripos($temp_head, '<'.$tag);
514                 }
515         }
516         return $rtn_text;
517 }
518
519 if (version_compare(phpversion(), '4.3.0') < 0) {
520         function file_get_contents($filename) {
521                 $fd = @fopen($filename, 'rb');
522                 if ($fd === false) {
523                         $content = false;
524                 } else {
525                         $content = @fread($fd, filesize($filename));
526                         @fclose($fd);
527                 }
528
529                 return $content;
530         }
531
532         function mysql_real_escape_string($input) {
533                 return mysql_escape_string($input);
534         }
535 }
536
537
538 function add_user_online() {
539         if (!isset($_SESSION['member_id']) || !($_SESSION['member_id'] > 0)) {
540                 return;
541         }
542         global $db, $addslashes;
543
544     $expiry = time() + 900; // 15min
545     $sql    = 'REPLACE INTO '.TABLE_PREFIX.'users_online VALUES ('.$_SESSION['member_id'].', '.$_SESSION['course_id'].', "'.$addslashes(get_display_name($_SESSION['member_id'])).'", '.$expiry.')';
546     $result = mysql_query($sql, $db);
547
548         /* garbage collect and optimize the table every so often */
549         mt_srand((double) microtime() * 1000000);
550         $rand = mt_rand(1, 20);
551         if ($rand == 1) {
552                 $sql = 'DELETE FROM '.TABLE_PREFIX.'users_online WHERE expiry<'.time();
553                 $result = @mysql_query($sql, $db);
554         }
555 }
556
557 /**
558  * Returns the login name of a member.
559  * @access  public
560  * @param   int $id     The ID of the member.
561  * @return  Returns the login name of the member whose ID is $id.
562  * @author  Joel Kronenberg
563  */
564 function get_login($id){
565         global $db, $_config_defaults;
566
567         if (is_array($id)) {
568                 $id             = implode(',',$id);
569                 $sql    = 'SELECT login, member_id FROM '.TABLE_PREFIX.'members WHERE member_id IN ('.$id.') ORDER BY login';
570
571                 $rows = array();
572                 $result = mysql_query($sql, $db);
573                 while( $row     = mysql_fetch_assoc($result)) {
574                         $rows[$row['member_id']] = $row['login'];
575                 }
576                 return $rows;
577         } else {
578                 $id             = intval($id);
579                 $sql    = 'SELECT login FROM '.TABLE_PREFIX.'members WHERE member_id='.$id;
580
581                 $result = mysql_query($sql, $db);
582                 $row    = mysql_fetch_assoc($result);
583
584                 return $row['login'];
585         }
586
587 }
588
589 function get_display_name($id) {
590         static $db, $_config, $display_name_formats;
591         if (!$id) {
592                 return $_SESSION['login'];
593         }
594
595         if (!isset($db, $_config)) {
596                 global $db, $_config, $display_name_formats;
597         }
598
599         if (substr($id, 0, 2) == 'g_' || substr($id, 0, 2) == 'G_')
600         {
601                 $sql    = "SELECT name FROM ".TABLE_PREFIX."guests WHERE guest_id='".$id."'";
602                 $result = mysql_query($sql, $db);
603                 $row    = mysql_fetch_assoc($result);
604
605                 return _AT($display_name_formats[$_config['display_name_format']], '', $row['name'], '', '');
606         }
607         else
608         {
609                 $sql    = 'SELECT login, first_name, second_name, last_name FROM '.TABLE_PREFIX.'members WHERE member_id='.$id;
610                 $result = mysql_query($sql, $db);
611                 $row    = mysql_fetch_assoc($result);
612
613                 return _AT($display_name_formats[$_config['display_name_format']], $row['login'], $row['first_name'], $row['second_name'], $row['last_name']);
614         }
615 }
616
617 function get_forum_name($fid){
618         global $db;
619
620         $fid = intval($fid);
621
622         $sql    = 'SELECT title FROM '.TABLE_PREFIX.'forums WHERE forum_id='.$fid;
623         $result = mysql_query($sql, $db);
624         if (($row = mysql_fetch_assoc($result)) && $row['title']) {
625                 return $row['title'];           
626         }
627
628         $sql = "SELECT group_id FROM ".TABLE_PREFIX."forums_groups WHERE forum_id=$fid";
629         $result = mysql_query($sql, $db);
630         if ($row = mysql_fetch_assoc($result)) {
631                 return get_group_title($row['group_id']);
632         }
633
634         return FALSE;
635 }
636
637 // takes the array of valid prefs and assigns them to the current session 
638 // @params: prefs - an array of preferences
639 // @params: optional. Values are 0 or 1. Default value is 0
640 //          when 1, assign PREF_MOBILE_THEME to PREF_THEME if the request is from a mobile device
641 //                  this value is to set when the prefs values are set for display
642 //                  if this function is used as a front shot for save_prefs(), the value should be 0
643 function assign_session_prefs($prefs, $switch_mobile_theme = 0) {
644         if (is_array($prefs)) {
645                 foreach($prefs as $pref_name => $value) {
646                         $_SESSION['prefs'][$pref_name] = $value;
647                 }
648         }
649         if (is_mobile_device() && $switch_mobile_theme) {
650                 $_SESSION['prefs']['PREF_THEME'] = $_SESSION['prefs']['PREF_MOBILE_THEME'];
651         }
652 }
653
654 function save_prefs( ) {
655         global $db, $addslashes;
656
657         if ($_SESSION['valid_user']) {
658                 $data   = $addslashes(serialize($_SESSION['prefs']));
659                 $sql    = 'UPDATE '.TABLE_PREFIX.'members SET preferences="'.$data.'", creation_date=creation_date, last_login=last_login WHERE member_id='.$_SESSION['member_id'];
660                 $result = mysql_query($sql, $db); 
661         }
662 }
663
664 function save_email_notification($mnot) {
665     global $db;
666     
667     if ($_SESSION['valid_user']) {
668         $sql = "UPDATE ".TABLE_PREFIX."members SET inbox_notify =". $mnot .", creation_date=creation_date, last_login=last_login WHERE member_id =".$_SESSION['member_id'];
669         $result = mysql_query($sql, $db);
670     }
671 }
672
673 /**
674 * Saves the last viewed content page in a user's course so that on next visit, user can start reading where they left off
675 * @access  public
676 * @param   int $cid             the content page id
677 * @return  none
678 * @see     $db                  in include/vitals.inc.php
679 * @author  Joel Kronenberg
680 */
681 function save_last_cid($cid) {
682         if ($_SESSION['enroll'] == AT_ENROLL_NO) {
683                 return;
684         }
685         global $db;
686
687         $_SESSION['s_cid']    = intval($_GET['cid']);
688
689         if (!$_SESSION['is_admin']   && 
690                 !$_SESSION['privileges'] && 
691                 !isset($in_get)          && 
692                 !$_SESSION['cid_time']   && 
693                 ($_SESSION['course_id'] > 0) ) 
694                 {
695                         $_SESSION['cid_time'] = time();
696         }
697
698         $sql = "UPDATE ".TABLE_PREFIX."course_enrollment SET last_cid=$cid WHERE course_id=$_SESSION[course_id] AND member_id=$_SESSION[member_id]";
699         mysql_query($sql, $db);
700 }
701
702 // there has to be a better way of expressing this if-statement!
703 // and, does it really have to be here?
704 if ((!isset($_SESSION['is_admin']) || !$_SESSION['is_admin'])       && 
705         (!isset($_SESSION['privileges']) || !$_SESSION['privileges'])     &&
706         !isset($in_get)              && 
707         isset($_SESSION['s_cid']) && $_SESSION['s_cid'] && 
708         isset($_SESSION['cid_time']) && $_SESSION['cid_time'] &&
709     ($_SESSION['course_id'] > 0) && 
710         ($_SESSION['s_cid'] != $_GET['cid']) && 
711         ($_SESSION['enroll'] != AT_ENROLL_NO) )  
712         {
713                 $diff = time() - $_SESSION['cid_time'];
714                 if ($diff > 0) {
715                         $sql = "UPDATE ".TABLE_PREFIX."member_track SET counter=counter+1, duration=duration+$diff, last_accessed=NOW() WHERE member_id=$_SESSION[member_id] AND content_id=$_SESSION[s_cid]";
716
717                         $result = mysql_query($sql, $db);
718
719                         if (mysql_affected_rows($db) == 0) {
720                                 $sql = "INSERT INTO ".TABLE_PREFIX."member_track VALUES ($_SESSION[member_id], $_SESSION[course_id], $_SESSION[s_cid], 1, $diff, NOW())";
721                                 $result = mysql_query($sql, $db);
722                         }
723                 }
724
725                 $_SESSION['cid_time'] = 0;
726 }
727
728
729 /**
730 * Checks if the $_SESSION[member_id] is an instructor (true) or not (false)
731 * The result is only fetched once - it is then available via a static variable, $is_instructor
732 * @access  public
733 * @param   none
734 * @return  bool true if is instructor, false otherwise.
735 * @see     $db   in include/vitals.inc.php
736 * @author  Joel Kronenberg
737 */      
738 function get_instructor_status() {
739         static $is_instructor;
740
741         if (isset($is_instructor)) {
742                 return $is_instructor;
743         }
744
745         global $db;
746
747         $is_instructor = false;
748
749         $sql = 'SELECT status FROM '.TABLE_PREFIX.'members WHERE member_id='.$_SESSION['member_id'];
750         $result = mysql_query($sql, $db);
751         if (!($row = @mysql_fetch_assoc($result))) {
752                 $is_instructor = FALSE;
753                 return FALSE;
754         }
755
756         if ($row['status'] == AT_STATUS_INSTRUCTOR) {
757                 $is_instructor = TRUE;
758                 return TRUE;
759         }
760
761         $is_instructor = FALSE;
762         return FALSE;
763 }
764
765 /****************************************************/
766 /* update the user online list                                          */
767 if (isset($_SESSION['valid_user']) && $_SESSION['valid_user']) {
768         $new_minute = time()/60;
769         if (!isset($_SESSION['last_updated'])) {
770                 $_SESSION['last_updated'] = $new_minute;
771         }
772         $diff       = abs($_SESSION['last_updated'] - $new_minute);
773         if ($diff > ONLINE_UPDATE) {
774                 $_SESSION['last_updated'] = $new_minute;
775                 add_user_online();
776         }
777 }
778
779 /****************************************************/
780 /* compute the $_my_uri variable                                        */
781         $bits     = explode(SEP, getenv('QUERY_STRING'));
782         $num_bits = count($bits);
783         $_my_uri  = '';
784
785         for ($i=0; $i<$num_bits; $i++) {
786                 if (    (strpos($bits[$i], 'enable=')   === 0) 
787                         ||      (strpos($bits[$i], 'disable=')  === 0)
788                         ||      (strpos($bits[$i], 'expand=')   === 0)
789                         ||      (strpos($bits[$i], 'collapse=') === 0)
790                         ||      (strpos($bits[$i], 'lang=')             === 0)
791                         ) {
792                         /* we don't want this variable added to $_my_uri */
793                         continue;
794                 }
795
796                 if (($_my_uri == '') && ($bits[$i] != '')) {
797                         $_my_uri .= htmlentities('?');
798                 } else if ($bits[$i] != ''){
799                         $_my_uri .= htmlentities(SEP);
800                 }
801                 $_my_uri .= $bits[$i];
802         }
803         if ($_my_uri == '') {
804                 $_my_uri .= htmlentities('?');
805         } else {
806                 $_my_uri .= htmlentities(SEP);
807         }
808         $_my_uri = $_SERVER['PHP_SELF'].$_my_uri;
809
810 /**
811  * If MBString extension is loaded, 4.3.0+, then use it.
812  * Otherwise we will have to use include/utf8 library
813  * @author      Harris
814  * @date Oct 10, 2007
815  * @version     1.5.6
816  */
817  if (extension_loaded('mbstring')){
818          $strtolower = 'mb_strtolower';
819          $strtoupper = 'mb_strtoupper';
820          $substr = 'mb_substr';
821          $strpos = 'mb_strpos';
822          $strrpos = 'mb_strrpos';
823          $strlen = 'mb_strlen';
824  } else {
825          $strtolower = 'utf8_strtolower';
826          $strtoupper = 'utf8_strtoupper';
827          $substr = 'utf8_substr';
828          $strpos = 'utf8_strpos';
829          $strrpos = 'utf8_strrpos';
830          $strlen = 'utf8_strlen';
831  }
832
833
834 /*~~~~~~~~~~~~~~~~~flash detection~~~~~~~~~~~~~~~~*/
835 if(isset($_COOKIE["flash"])){
836     $_SESSION['flash'] = $_COOKIE["flash"];
837
838     //delete the cookie
839     ATutor.setcookie("flash",'',time()-3600);
840 }
841
842 if (!isset($_SESSION["flash"])) {
843         $_custom_head .= '
844                 <script type="text/javascript">
845                 <!--
846
847                         //VB-Script for InternetExplorer
848                         function iExploreCheck()
849                         {
850                                 document.writeln("<scr" + "ipt language=\'VBscript\'>");
851                                 //document.writeln("\'Test to see if VBScripting works");
852                                 document.writeln("detectableWithVB = False");
853                                 document.writeln("If ScriptEngineMajorVersion >= 2 then");
854                                 document.writeln("   detectableWithVB = True");
855                                 document.writeln("End If");
856                                 //document.writeln("\'This will check for the plugin");
857                                 document.writeln("Function detectActiveXControl(activeXControlName)");
858                                 document.writeln("   on error resume next");
859                                 document.writeln("   detectActiveXControl = False");
860                                 document.writeln("   If detectableWithVB Then");
861                                 document.writeln("      detectActiveXControl = IsObject(CreateObject(activeXControlName))");
862                                 document.writeln("   End If");
863                                 document.writeln("End Function");
864                                 document.writeln("</scr" + "ipt>");
865                                 return detectActiveXControl("ShockwaveFlash.ShockwaveFlash.1");
866                         }
867
868
869                         var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : false;
870                         if(!(plugin) && (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.appVersion.indexOf("Win") != -1)))
871                                 if (iExploreCheck())
872                                         flash_detect = "flash=yes";
873                                 else
874                                         flash_detect = "flash=no";
875
876                         else if(plugin)
877                                 flash_detect = "flash=yes";
878                         else
879                                 flash_detect = "flash=no";
880
881                         writeCookie(flash_detect);
882
883                         function writeCookie(value)
884                         {
885                                 var today = new Date();
886                                 var the_date = new Date("December 31, 2099");
887                                 var the_cookie_date = the_date.toGMTString();
888                                 var the_cookie = value + ";expires=" + the_cookie_date;
889                                 document.cookie = the_cookie;
890                         }
891                 //-->
892                 </script>
893 ';
894 }
895
896
897
898 /*~~~~~~~~~~~~~~end flash detection~~~~~~~~~~~~~~~*/
899
900
901
902 /**
903 * Checks if the data exceeded the database predefined length, if so,
904 * truncate it.
905 * This is used on data that are being inserted into the database.
906 * If this function is used for display purposes, you may want to add the '...' 
907 *  at the end of the string by setting the $forDisplay=1
908 * @param        the mbstring that needed to be checked
909 * @param        the byte length of what the input should be in the database.
910 * @param        (OPTIONAL)
911 *                       append '...' at the end of the string.  Should not use this when 
912 *                       dealing with database.  This should only be set for display purposes.
913 * @return       the mbstring safe sql entry
914 * @author       Harris Wong
915 */
916 function validate_length($input, $len, $forDisplay=0){
917         global $strlen, $substr;
918         $input_bytes_len = strlen($input);
919         $input_len = $strlen($input);
920
921         //If the input has exceeded the db column limit
922         if ($input_bytes_len > $len){
923                 //calculate where to chop off the string
924                 $percentage = $input_bytes_len / $input_len;
925                 //Get the suitable length that should be stored in the db
926                 $suitable_len = floor($len / $percentage);
927
928                 if ($forDisplay===1){
929                         return $substr($input, 0, $suitable_len).'...';
930                 }
931                 return $substr($input, 0, $suitable_len);
932         }
933         //if valid length
934         return $input;
935
936 /*
937  * Instead of blindly cutting off the input from the given param
938  * 
939         global $strlen, $substr;
940         if ($strlen($input) > $len) {
941                 if ($forDisplay===1){
942                         return $substr($input, 0, $len).'...';
943                 }
944                 return $substr($input, 0, $len);
945         }
946         return $input;
947 */
948 }
949
950 /**
951  * If pretty URL within admin config is switched on.  We will apply pretty URL 
952  * to all the links in ATutor.  This function will authenticate itself towards the current pages.
953  * In our definition, admins, login, registration pages shouldn't have pretty url applied.  However,
954  * if one want to use url_rewrite on these pages, please force it by using the third parameter.  
955  * Note: If system config has turned off this feature, $force will have no effect.
956  * @param       string  the Url should be a relative link, have to improve this later on, to check if 
957  *                                      it's a relative link, if not, truncate it.
958  * @param       boolean Available values are AT_PRETTY_URL_IS_HEADER, AT_PRETTY_URL_NOT_HEADER(default)
959  *                      use AT_PRETTY_URL_IS_HEADER if url_rewrite is used in php header('Location:..'), absolute path is needed for this.
960  * @param       boolean true to force the url_rewrite, false otheriwse.  False is the default.
961  * @author      Harris Wong
962  */
963 function url_rewrite($url, $is_rewriting_header=AT_PRETTY_URL_NOT_HEADER, $force=false){
964         global $_config, $db;
965         $url_parser = new UrlParser();
966         $pathinfo = $url_parser->getPathArray();
967
968         /* If this is any kind of admins, don't prettify the url
969          * $_SESSION['is_guest'] is used to check against login/register/browse page, the links on this page will 
970          * only be prettified when a user has logged in.
971          * Had used $_SESSION[valid_user] before but it created this problem: 
972          * http://www.atutor.ca/atutor/mantis/view.php?id=3426
973          */
974         if ($force || (isset($_SESSION['course_id']) && $_SESSION['course_id'] > 0)) {
975                 //if course id is defined, apply pretty url.
976         } 
977         //if this is something that is displayed on the login page, don't modify the urls.
978         else if ( (admin_authenticate(AT_ADMIN_PRIV_ADMIN, AT_PRIV_RETURN) 
979                         || (isset($_SESSION['privileges']) && admin_authenticate($_SESSION['privileges'], AT_PRIV_RETURN))) 
980                         || (isset($_SESSION['is_guest']) && $_SESSION['is_guest']==1)){
981                 return $url;
982         } 
983
984         //if we allow pretty url in the system
985         if ($_config['pretty_url'] > 0){
986                 $course_id = 0;
987                 //If we allow course dir name from sys perf             
988                 if ($_config['course_dir_name'] > 0){
989                         if (preg_match('/bounce.php\?course=([\d]+)$/', $url, $matches) == 1){
990                                 // bounce has the highest priority, even if session is set, work on 
991                                 // bounce first.
992                                 $course_id = $url_parser->getCourseDirName($matches[1]);
993                         } elseif (isset($_REQUEST['course'])){
994                                 //jump menu
995                                 $course_id = $url_parser->getCourseDirName($_REQUEST['course']);
996                         } elseif (isset($_REQUEST['p_course'])){
997                                 // is set when guests access public course. @see bounce.php
998                                 $course_id = $url_parser->getCourseDirName($_REQUEST['p_course']);
999                         } elseif (isset($_SESSION['course_id']) && $_SESSION['course_id'] > 0){
1000                                 $course_id = $url_parser->getCourseDirName($_SESSION['course_id']);
1001                         } 
1002                 } else {
1003                         $course_id = $_SESSION['course_id'];
1004                 }
1005                 $url = $pathinfo[1]->convertToPrettyUrl($course_id, $url);
1006         } elseif ($_config['course_dir_name'] > 0) {
1007                 //enabled course directory name, disabled pretty url
1008                 if (preg_match('/bounce.php\?course=([\d]+)$/', $url, $matches) == 1){
1009                         // bounce has the highest priority, even if session is set, work on 
1010                         // bounce first.
1011                         $course_id = $url_parser->getCourseDirName($matches[1]);
1012                 } elseif (isset($_REQUEST['course'])){
1013                         $course_id = $url_parser->getCourseDirName($_REQUEST['course']);
1014                 } elseif (isset($_REQUEST['p_course'])){
1015                         // is set when guests access public course. @see bounce.php
1016                         $course_id = $url_parser->getCourseDirName($_REQUEST['p_course']);
1017                 } elseif (isset($_SESSION['course_id']) && $_SESSION['course_id'] > 0){
1018                         $course_id = $url_parser->getCourseDirName($_SESSION['course_id']);
1019                 } 
1020                 $url = $pathinfo[1]->convertToPrettyUrl($course_id, $url);
1021         }
1022
1023         //instead of putting AT_BASE_HREF in all the headers location, we will put it here.
1024         //Abs paths are required for pretty url because otherwise the url location will be appeneded.
1025         //ie.   ATutor_161/blogs/CoURSe_rOAd/blogs/view.php/ot/1/oid/1/ instead of 
1026         //              ATutor_161/CoURSe_rOAd/blogs/view.php/ot/1/oid/1/
1027         if ($is_rewriting_header==true){
1028                 return AT_BASE_HREF.$url;
1029         } 
1030         return $url;
1031 }
1032
1033
1034 /**
1035 * Applies $addslashes or intval() recursively.
1036 * @access  public
1037 * @param   mixed $input The input to clean.
1038 * @return  A safe version of $input
1039 * @author  Joel Kronenberg
1040 */
1041 function sql_quote($input) {
1042         global $addslashes;
1043
1044         if (is_array($input)) {
1045                 foreach ($input as $key => $value) {
1046                         if (is_array($input[$key])) {
1047                                 $input[$key] = sql_quote($input[$key]);
1048                         } else if (!empty($input[$key]) && is_numeric($input[$key])) {
1049                                 $input[$key] = intval($input[$key]);
1050                         } else {
1051                                 $input[$key] = $addslashes(trim($input[$key]));
1052                         }
1053                 }
1054         } else {
1055                 if (!empty($input) && is_numeric($input)) {
1056                         $input = intval($input);
1057                 } else {
1058                         $input = $addslashes(trim($input));
1059                 }
1060         }
1061         return $input;
1062 }
1063
1064 function query_bit( $bitfield, $bit ) {
1065         if (!is_int($bitfield)) {
1066                 $bitfield = intval($bitfield);
1067         }
1068         if (!is_int($bit)) {
1069                 $bit = intval($bit);
1070         }
1071         return ( $bitfield & $bit ) ? true : false;
1072
1073
1074 /**
1075 * Authenticates the current user against the specified privilege.
1076 * @access  public
1077 * @param   int  $privilege              privilege to check against.
1078 * @param   bool $check                  whether or not to return the result or to abort/exit.
1079 * @return  bool true if this user is authenticated, false otherwise.
1080 * @see     query_bit() in include/vitals.inc.php
1081 * @author  Joel Kronenberg
1082 */
1083 function authenticate($privilege, $check = false) {
1084         if ($_SESSION['is_admin']) {
1085                 return true;
1086         }
1087
1088         $auth = query_bit($_SESSION['privileges'], $privilege);
1089         
1090         if (!$_SESSION['valid_user'] || !$auth) {
1091                 if (!$check){
1092                         global $msg;
1093                         $msg->addInfo('NO_PERMISSION');
1094                         require(AT_INCLUDE_PATH.'header.inc.php'); 
1095                         require(AT_INCLUDE_PATH.'footer.inc.php'); 
1096                         exit;
1097                 } else {
1098                         return false;
1099                 }
1100         }
1101         return true;
1102 }
1103
1104 function admin_authenticate($privilege = 0, $check = false) {
1105         if (!isset($_SESSION['valid_user']) || !$_SESSION['valid_user'] || ($_SESSION['course_id'] != -1)) {
1106                 if ($check) {
1107                         return false;
1108                 }
1109                 header('Location: '.AT_BASE_HREF.'login.php');
1110                 exit;
1111         }
1112
1113         if ($_SESSION['privileges'] == AT_ADMIN_PRIV_ADMIN) {
1114                 return true;
1115         }
1116
1117         if ($privilege) {
1118                 $auth = query_bit($_SESSION['privileges'], $privilege);
1119
1120                 if (!$auth) {
1121                         if ($check) {
1122                                 return false;
1123                         }
1124                         global $msg;
1125                         $msg->addError('ACCESS_DENIED');
1126                         require(AT_INCLUDE_PATH.'header.inc.php'); 
1127                         require(AT_INCLUDE_PATH.'footer.inc.php'); 
1128                         exit;
1129                 }
1130         }
1131         return true;
1132 }
1133
1134 function get_default_theme() {
1135         global $db;
1136
1137         if (is_mobile_device()) {
1138                 $default_status = 3;
1139         } else {
1140                 $default_status = 2;
1141         }
1142         $sql    = "SELECT dir_name FROM ".TABLE_PREFIX."themes WHERE status=".$default_status;
1143         $result = mysql_query($sql, $db);
1144         $row = mysql_fetch_assoc($result);
1145
1146         return $row;
1147 }
1148
1149 function get_system_default_theme() {
1150         if (is_mobile_device()) {
1151                 return 'mobile';
1152         } else {
1153                 return 'default';
1154         }
1155 }
1156
1157 function is_mobile_theme($theme) {
1158         global $db;
1159
1160         $sql    = "SELECT dir_name FROM ".TABLE_PREFIX."themes WHERE type='".MOBILE_DEVICE."'";
1161         $result = mysql_query($sql, $db);
1162         while ($row = mysql_fetch_assoc($result)) {
1163                 if ($row['dir_name'] == $theme && is_dir(AT_INCLUDE_PATH . '../themes/' . $theme)) return true;
1164         }
1165
1166         return false;
1167 }
1168
1169 if (isset($_GET['expand'])) {
1170         $_SESSION['menu'][intval($_GET['expand'])] = 1;
1171 } else if (isset($_GET['collapse'])) {
1172         unset($_SESSION['menu'][intval($_GET['collapse'])]);
1173 }
1174
1175 /**
1176 * Writes present action to admin log db
1177 * @access  private
1178 * @param   string $operation_type       The type of operation
1179 * @param   string $table_name           The table affected
1180 * @param   string $num_affected         The number of rows in the table affected
1181 * @author  Shozub Qureshi
1182 */
1183 function write_to_log($operation_type, $table_name, $num_affected, $details) {
1184         global $db, $addslashes;
1185
1186         if ($num_affected > 0) {
1187                 $details = $addslashes(stripslashes($details));
1188                 $sql    = "INSERT INTO ".TABLE_PREFIX."admin_log VALUES ('$_SESSION[login]', NULL, $operation_type, '$table_name', $num_affected, '$details')";
1189                 $result = mysql_query($sql, $db);
1190         }
1191 }
1192
1193 function get_group_title($group_id) {
1194         global $db;
1195         $sql = "SELECT title FROM ".TABLE_PREFIX."groups WHERE group_id=$group_id";
1196         $result = mysql_query($sql, $db);
1197         if ($row = mysql_fetch_assoc($result)) {
1198                 return $row['title'];
1199         }
1200         return FALSE;
1201 }
1202
1203 function get_status_name($status_id) {
1204         switch ($status_id) {
1205                 case AT_STATUS_DISABLED:
1206                                 return _AT('disabled');
1207                                 break;
1208                 case AT_STATUS_UNCONFIRMED:
1209                         return _AT('unconfirmed');
1210                         break;
1211                 case AT_STATUS_STUDENT:
1212                         return _AT('student');
1213                         break;
1214                 case AT_STATUS_INSTRUCTOR:
1215                         return _AT('instructor');
1216                         break;
1217         }
1218 }
1219
1220 function profile_image_exists($id) {
1221         $extensions = array('gif', 'jpg', 'png');
1222
1223         foreach ($extensions as $extension) {
1224                 if (file_exists(AT_CONTENT_DIR.'profile_pictures/originals/'. $id.'.'.$extension)) {
1225                         return true;
1226                 }
1227         }
1228 }
1229
1230 /**
1231  * print thumbnails or profile pic
1232  * @param       int             image id
1233  * @param       int             1 for thumbnail, 2 for profile
1234  */
1235 function print_profile_img($id, $type=1) {
1236         global $moduleFactory;
1237         $mod = $moduleFactory->getModule('_standard/profile_pictures');
1238         if ($mod->isEnabled() === FALSE) {
1239                 return;
1240         }
1241         if (profile_image_exists($id)) {
1242                 if ($type==1){
1243                         echo '<img src="get_profile_img.php?id='.$id.'" class="profile-picture" alt="" />';
1244                 } elseif($type==2){
1245                         echo '<img src="get_profile_img.php?id='.$id.SEP.'size=p" class="profile-picture" alt="" />';
1246                 }
1247         } else {
1248                 echo '<img src="images/clr.gif" height="100" width="100" class="profile-picture" alt="" />';
1249         }
1250 }
1251
1252 function profile_image_delete($id) {
1253         $extensions = array('gif', 'jpg', 'png');
1254
1255         foreach ($extensions as $extension) {
1256                 if (file_exists(AT_CONTENT_DIR.'profile_pictures/originals/'. $id.'.'.$extension)) {
1257                         unlink(AT_CONTENT_DIR.'profile_pictures/originals/'. $id.'.'.$extension);
1258                 }
1259                 if (file_exists(AT_CONTENT_DIR.'profile_pictures/profile/'. $id.'.'.$extension)) {
1260                         unlink(AT_CONTENT_DIR.'profile_pictures/profile/'. $id.'.'.$extension);
1261                 }
1262                 if (file_exists(AT_CONTENT_DIR.'profile_pictures/thumbs/'. $id.'.'.$extension)) {
1263                         unlink(AT_CONTENT_DIR.'profile_pictures/thumbs/'. $id.'.'.$extension);
1264                 }               
1265         }
1266 }
1267
1268 /**
1269  * get_group_concat
1270  * returns a list of $field values from $table using $where_clause, separated by $separator.
1271  * uses mysql's GROUP_CONCAT() if available and if within the limit (default is 1024), otherwise
1272  * it does it the old school way.
1273  * returns the list (as a string) or (int) 0, if none found.
1274  */
1275 function get_group_concat($table, $field, $where_clause = 1, $separator = ',') {
1276         global $_config, $db;
1277         if (!isset($_config['mysql_group_concat_max_len'])) {
1278                 $sql = "SELECT  @@global.group_concat_max_len AS max";
1279                 $result = mysql_query($sql, $db);
1280                 if ($result && ($row = mysql_fetch_assoc($result))) {
1281                         $_config['mysql_group_concat_max_len'] = $row['max'];
1282                 } else {
1283                         $_config['mysql_group_concat_max_len'] = 0;
1284                 }
1285                 $sql = "REPLACE INTO ".TABLE_PREFIX."config VALUES ('mysql_group_concat_max_len', '{$_config['mysql_group_concat_max_len']}')";
1286                 mysql_query($sql, $db);
1287         }
1288         if ($_config['mysql_group_concat_max_len'] > 0) {
1289                 $sql = "SELECT GROUP_CONCAT($field SEPARATOR '$separator') AS list FROM ".TABLE_PREFIX."$table WHERE $where_clause";
1290                 $result = mysql_query($sql, $db);
1291                 if ($row = mysql_fetch_assoc($result)) {
1292                         if (!$row['list']) {
1293                                 return 0; // empty
1294                         } else if ($row['list'] && strlen($row['list']) < $_config['mysql_group_concat_max_len']) {
1295                                 return $row['list'];
1296                         } // else: list is truncated, do it the old way
1297                 } else {
1298                         // doesn't actually get here.
1299                         return 0; // empty
1300                 }
1301         } // else:
1302
1303         $list = '';
1304         $sql = "SELECT $field AS id FROM ".TABLE_PREFIX."$table WHERE $where_clause";
1305         $result = mysql_query($sql, $db);
1306         while ($row = mysql_fetch_assoc($result)) {
1307                 $list .= $row['id'] . ',';
1308         }
1309         if ($list) {
1310                 return substr($list, 0, -1); }
1311         return 0;
1312 }
1313
1314 function get_human_time($seconds) {
1315         if ($seconds < 0) { 
1316                 $out = '0'._AT('second_short'); 
1317         } else if ($seconds > 60 * 60) { // more than 60 minutes.
1318                 $hours = floor($seconds / 60 / 60);
1319                 $minutes = floor(($seconds - $hours * 60 * 60) / 60);
1320                 $out = $hours ._AT('hour_short').' '.$minutes._AT('minute_short');
1321
1322                 //$out = ($seconds
1323         } else if ($seconds > 60) { // more than a minute
1324                 $minutes = floor($seconds / 60);
1325                 $out = $minutes ._AT('minute_short').' '.($seconds - $minutes * 60)._AT('second_short');
1326         } else { // less than a minute
1327                 $out = $seconds . _AT('second_short');
1328         }
1329
1330         return $out;
1331 }
1332
1333 function is_mobile_device() {
1334         $http_user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
1335         return ((stripos($http_user_agent, IPOD_DEVICE) !== false && stripos($http_user_agent, IPOD_DEVICE) >= 0) ||
1336                         (stripos($http_user_agent, IPHONE_DEVICE) !== false && stripos($http_user_agent, IPHONE_DEVICE) >= 0) ||
1337                 (stripos($http_user_agent, BLACKBERRY_DEVICE) !== false && stripos($http_user_agent, BLACKBERRY_DEVICE) >= 0) ||
1338                 (stripos($http_user_agent, ANDROID_DEVICE) !== false && stripos($http_user_agent, ANDROID_DEVICE) >= 0)) 
1339                 ? true : false;
1340 }
1341
1342 function get_mobile_device_type() {
1343         $http_user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
1344         if (stripos($http_user_agent, IPOD_DEVICE) !== false && stripos($http_user_agent, IPOD_DEVICE) >= 0) {
1345                 return IPOD_DEVICE;
1346         } else if (stripos($http_user_agent, IPHONE_DEVICE) !== false && stripos($http_user_agent, IPHONE_DEVICE) >= 0) {
1347                 return IPHONE_DEVICE;
1348         } else if (stripos($http_user_agent, BLACKBERRY_DEVICE) !== false && stripos($http_user_agent, BLACKBERRY_DEVICE) >= 0) {
1349                 return BLACKBERRY_DEVICE;
1350         } else if (stripos($http_user_agent, ANDROID_DEVICE) !== false && stripos($http_user_agent, ANDROID_DEVICE) >= 0) {
1351                 return ANDROID_DEVICE;
1352         } else {
1353                 return UNKNOWN_DEVICE;
1354         }
1355 }
1356
1357 /**
1358  * Convert all input to htmlentities output, in UTF-8.
1359  * @param       string  input to be convert
1360  * @param       boolean true if we wish to change all newlines(\r\n) to a <br/> tag, false otherwise.  
1361  *                      ref: http://php.net/manual/en/function.nl2br.php
1362  * @author      Harris Wong
1363  * @date        March 12, 2010
1364  */
1365 function htmlentities_utf8($str, $use_nl2br=true){
1366         $return = htmlentities($str, ENT_QUOTES, 'UTF-8');
1367         if ($use_nl2br){
1368                 return nl2br($return);
1369         } 
1370         return $return;
1371 }
1372
1373
1374 /**
1375  * Convert all '&' to '&amp;' from the input
1376  * @param   string  any string input, mainly URLs.
1377  * @return  input with & replaced to '&amp;'
1378  * @author  Harris Wong
1379  * @date    Oct 7, 2010
1380  */
1381 function convert_amp($input){
1382     $input = str_replace('&amp;', '&', $input); //convert everything to '&' first
1383     return str_replace('&', '&amp;', $input);
1384 }
1385
1386 /**
1387  * Check if json_encode/json_decode exists, if not, use the json service library.
1388  * NOTE:  json_encode(), json_decode() are NOT available piror to php 5.2
1389  * @author      Harris Wong
1390  * @date        April 21, 2010
1391  */
1392  if ( !function_exists('json_encode') ){
1393     function json_encode($content){
1394                 require_once (AT_INCLUDE_PATH.'lib/json.inc.php');
1395                 $json = new Services_JSON;               
1396         return $json->encode($content);
1397     }
1398 }
1399 if ( !function_exists('json_decode') ){
1400     function json_decode($content, $assoc=false){
1401                 require_once (AT_INCLUDE_PATH.'lib/json.inc.php');
1402                 if ( $assoc ){
1403                         $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
1404         } else {
1405                         $json = new Services_JSON;
1406                 }
1407         return $json->decode($content);
1408     }
1409 }
1410
1411
1412 require(AT_INCLUDE_PATH . '../mods/_core/modules/classes/Module.class.php');
1413
1414 $moduleFactory = new ModuleFactory(TRUE); // TRUE is for auto_loading the module.php files
1415
1416 if (isset($_GET['submit_language']) && $_SESSION['valid_user']) {
1417         if ($_SESSION['course_id'] == -1) {
1418                 $sql = "UPDATE ".TABLE_PREFIX."admins SET language = '$_SESSION[lang]' WHERE login = '$_SESSION[login]'";
1419                 $result = mysql_query($sql, $db);
1420         } else {
1421                 $sql = "UPDATE ".TABLE_PREFIX."members SET language = '$_SESSION[lang]', creation_date=creation_date, last_login=last_login WHERE member_id = $_SESSION[member_id]";
1422                 $result = mysql_query($sql, $db);
1423         }
1424 }
1425
1426 if (isset($_SESSION['course_id']) && $_SESSION['course_id'] > 0) {
1427     $_custom_head .= '<script type="text/javascript" src="'.$_base_path.'jscripts/ATutorCourse.js"></script>';
1428 }
1429 ?>