2 /************************************************************************/
4 /************************************************************************/
5 /* Copyright (c) 2002 - 2009 */
6 /* Inclusive Design Institute */
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 /************************************************************************/
14 if (!defined('AT_INCLUDE_PATH')) { exit; }
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);
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; }
24 // Might want to change this perhaps to a nicer error
25 if (isset($_REQUEST['GLOBALS'])) { die('GLOBALS overwrite attempt detected'); }
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());
31 foreach ($input as $k => $v) {
32 if (!in_array($k, $noUnset) && isset($GLOBALS[$k])) { unset($GLOBALS[$k]); }
36 //functions for properly escaping input strings
37 function my_add_null_slashes( $string ) {
38 return mysql_real_escape_string(stripslashes($string));
40 function my_null_slashes($string) {
44 if ( get_magic_quotes_gpc() == 1 ) {
45 $addslashes = 'my_add_null_slashes';
46 $stripslashes = 'stripslashes';
48 $addslashes = 'mysql_real_escape_string';
49 $stripslashes = 'my_null_slashes';
53 * structure of this document (in order):
55 * 0. load config.inc.php
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
66 /**** 0. start system configuration options block ****/
68 if (!defined('AT_REDIRECT_LOADED')){
69 include_once(AT_INCLUDE_PATH.'config.inc.php');
71 error_reporting(AT_ERROR_REPORTING);
73 if (!defined('AT_INSTALL') || !AT_INSTALL) {
74 header('Cache-Control: no-store, no-cache, must-revalidate');
75 header('Pragma: no-cache');
77 $relative_path = substr(AT_INCLUDE_PATH, 0, -strlen('include/'));
78 header('Location: ' . $relative_path . 'install/not_installed.php');
81 /*** end system config block ****/
83 /*** 1. constants ***/
84 if (!defined('AT_REDIRECT_LOADED')){
85 require_once(AT_INCLUDE_PATH.'lib/constants.inc.php');
88 /***** 2. start session initilization block ****/
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);
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);
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);
110 session_set_cookie_params(0, $_base_path);
112 $str = ob_get_contents();
114 unregister_GLOBALS();
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);
126 /***** end session initilization block ****/
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);
133 /* 5. database connection */
134 if (!defined('AT_REDIRECT_LOADED')){
135 require_once(AT_INCLUDE_PATH.'lib/mysql_connect.inc.php');
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'];
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);
153 header('Location: '.AT_BASE_HREF.'login.php');
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'] : '');
178 require(AT_INCLUDE_PATH.'phpCache/phpCache.inc.php'); // cache library
179 require(AT_INCLUDE_PATH.'lib/utf8.php'); //UTF-8 multibyte library
181 //set the timezone, php 5.3+ problem. http://atutor.ca/atutor/mantis/view.php?id=4409
182 date_default_timezone_set('UTC');
184 if ($_config['time_zone']) {
185 //$sql = "SET time_zone='{$_config['time_zone']}'";
186 //mysql_query($sql, $db);
188 if (function_exists('date_default_timezone_set')) {
189 foreach($utc_timezones as $zone){
191 if($zone[1] == $_config['time_zone']){
192 $zone_name = $zone[2];
196 date_default_timezone_set($zone_name);
198 @putenv("TZ={$_config['time_zone']}");
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();
206 $myLang =& $languageManager->getMyLanguage();
208 if ($myLang === FALSE) {
209 echo 'There are no languages installed!';
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
217 $myLang->saveToPreferences($_SESSION['member_id'], 0); //0 for non-admin
220 $myLang->sendContentTypeHeader();
222 /* set right-to-left language */
224 if ($myLang->isRTL()) {
225 $rtl = 'rtl_'; /* basically the prefix to a rtl variant directory/filename. eg. rtl_tree */
227 /***** end language block ****/
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 */
235 require(AT_INCLUDE_PATH.'classes/Savant2/Savant2.php'); /* for the theme and template management */
237 // set default template paths:
238 $savant = new Savant2();
239 $savant->addPath('template', AT_INCLUDE_PATH . '../themes/'.get_system_default_theme().'/');
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';
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']))) {
257 $default_theme = get_default_theme();
259 if (!is_dir(AT_INCLUDE_PATH . '../themes/' . $default_theme['dir_name']) || $default_theme == '') {
260 $default_theme = array('dir_name' => get_system_default_theme());
262 $_SESSION['prefs']['PREF_THEME'] = $default_theme['dir_name'];
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();
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) {
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());
284 $_SESSION['prefs']['PREF_THEME'] = $default_theme['dir_name'];
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');
292 require(AT_INCLUDE_PATH.'classes/Message/Message.class.php');
293 $msg = new Message($savant);
295 $contentManager = new ContentManager($db, isset($_SESSION['course_id']) ? $_SESSION['course_id'] : $_GET['p_course']);
296 $contentManager->initContent();
297 /**************************************************/
299 if (isset($_user_location) && ($_user_location == 'users') && $_SESSION['valid_user'] && ($_SESSION['course_id'] > 0)) {
300 $_SESSION['course_id'] = 0;
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');
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
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']))) {
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']));
316 header('Location: '.AT_BASE_HREF.'bounce.php?course='.$_pretty_url_course_id.SEP.'pu='.$_SERVER['PATH_INFO']);
322 * This function is used for printing variables into log file for debugging.
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
328 function debug_to_log($var, $log='') {
329 if (!defined('AT_DEVEL') || !AT_DEVEL) {
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));
344 * This function is used for printing variables for debugging.
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
350 function debug($var, $title='') {
351 if (!defined('AT_DEVEL') || !AT_DEVEL) {
355 echo '<pre style="border: 1px black solid; padding: 0px; margin: 10px;" title="debugging box">';
357 echo '<h4>'.$title.'</h4>';
362 $str = ob_get_contents();
365 $str = str_replace('<', '<', $str);
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);
375 /********************************************************************/
376 /* the system course information */
377 /* system_courses[course_id] = array(title, description, subject) */
378 $system_courses = array();
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;
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']).'
395 $result = mysql_query($sql, $db);
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'];
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'];
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('>');
419 $text = substr($text, $end_pos);
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));
431 function get_html_head ($text) {
432 /* make all text lower case */
433 // $text = strtolower($text);
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('>');
442 $text = substr($text, $end_pos);
445 /* strip everything after </head> */
446 $end_pos = stripos($text, '</head');
447 if ($end_pos !== false) {
448 $text = trim(substr($text, 0, $end_pos));
454 * This function cuts out requested tag information from html head
456 * @param $text html text
457 * @param $tags a string or an array of requested tags
458 * @author Cindy Qi Li
460 function get_html_head_by_tag($text, $tags)
462 $head = get_html_head($text);
465 if (!is_array($tags) && strlen(trim($tags)) > 0)
467 $tags = array(trim($tags));
469 foreach ($tags as $tag)
471 $tag = strtolower($tag);
473 /* strip everything before <{tag}> */
474 $start_pos = stripos($head, '<'.$tag);
477 while ($start_pos !== false)
479 $temp_text = substr($temp_head, $start_pos);
481 /* strip everything after </{tag}> or />*/
482 $end_pos = stripos($temp_text, '</' . $tag . '>');
484 if ($end_pos !== false)
486 $end_pos += strlen('</' . $tag . '>');
488 // add an empty line after each tag information
489 $rtn_text .= trim(substr($temp_text, 0, $end_pos)) . '
493 else // match /> as ending tag if </tag> is not found
495 $end_pos = stripos($temp_text, '/>');
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('>');
503 $end_pos += strlen('/>');
505 // add an empty line after each tag information
506 $rtn_text .= trim(substr($temp_text, 0, $end_pos)) . '
511 // initialize vars for next round of matching
512 $temp_head = substr($temp_text, $end_pos);
513 $start_pos = stripos($temp_head, '<'.$tag);
519 if (version_compare(phpversion(), '4.3.0') < 0) {
520 function file_get_contents($filename) {
521 $fd = @fopen($filename, 'rb');
525 $content = @fread($fd, filesize($filename));
532 function mysql_real_escape_string($input) {
533 return mysql_escape_string($input);
538 function add_user_online() {
539 if (!isset($_SESSION['member_id']) || !($_SESSION['member_id'] > 0)) {
542 global $db, $addslashes;
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);
548 /* garbage collect and optimize the table every so often */
549 mt_srand((double) microtime() * 1000000);
550 $rand = mt_rand(1, 20);
552 $sql = 'DELETE FROM '.TABLE_PREFIX.'users_online WHERE expiry<'.time();
553 $result = @mysql_query($sql, $db);
558 * Returns the login name of a member.
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
564 function get_login($id){
565 global $db, $_config_defaults;
568 $id = implode(',',$id);
569 $sql = 'SELECT login, member_id FROM '.TABLE_PREFIX.'members WHERE member_id IN ('.$id.') ORDER BY login';
572 $result = mysql_query($sql, $db);
573 while( $row = mysql_fetch_assoc($result)) {
574 $rows[$row['member_id']] = $row['login'];
579 $sql = 'SELECT login FROM '.TABLE_PREFIX.'members WHERE member_id='.$id;
581 $result = mysql_query($sql, $db);
582 $row = mysql_fetch_assoc($result);
584 return $row['login'];
589 function get_display_name($id) {
590 static $db, $_config, $display_name_formats;
592 return $_SESSION['login'];
595 if (!isset($db, $_config)) {
596 global $db, $_config, $display_name_formats;
599 if (substr($id, 0, 2) == 'g_' || substr($id, 0, 2) == 'G_')
601 $sql = "SELECT name FROM ".TABLE_PREFIX."guests WHERE guest_id='".$id."'";
602 $result = mysql_query($sql, $db);
603 $row = mysql_fetch_assoc($result);
605 return _AT($display_name_formats[$_config['display_name_format']], '', $row['name'], '', '');
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);
613 return _AT($display_name_formats[$_config['display_name_format']], $row['login'], $row['first_name'], $row['second_name'], $row['last_name']);
617 function get_forum_name($fid){
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'];
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']);
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;
649 if (is_mobile_device() && $switch_mobile_theme) {
650 $_SESSION['prefs']['PREF_THEME'] = $_SESSION['prefs']['PREF_MOBILE_THEME'];
654 function save_prefs( ) {
655 global $db, $addslashes;
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);
664 function save_email_notification($mnot) {
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);
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
676 * @param int $cid the content page id
678 * @see $db in include/vitals.inc.php
679 * @author Joel Kronenberg
681 function save_last_cid($cid) {
682 if ($_SESSION['enroll'] == AT_ENROLL_NO) {
687 $_SESSION['s_cid'] = intval($_GET['cid']);
689 if (!$_SESSION['is_admin'] &&
690 !$_SESSION['privileges'] &&
692 !$_SESSION['cid_time'] &&
693 ($_SESSION['course_id'] > 0) )
695 $_SESSION['cid_time'] = time();
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);
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']) &&
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) )
713 $diff = time() - $_SESSION['cid_time'];
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]";
717 $result = mysql_query($sql, $db);
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);
725 $_SESSION['cid_time'] = 0;
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
734 * @return bool true if is instructor, false otherwise.
735 * @see $db in include/vitals.inc.php
736 * @author Joel Kronenberg
738 function get_instructor_status() {
739 static $is_instructor;
741 if (isset($is_instructor)) {
742 return $is_instructor;
747 $is_instructor = false;
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;
756 if ($row['status'] == AT_STATUS_INSTRUCTOR) {
757 $is_instructor = TRUE;
761 $is_instructor = FALSE;
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;
772 $diff = abs($_SESSION['last_updated'] - $new_minute);
773 if ($diff > ONLINE_UPDATE) {
774 $_SESSION['last_updated'] = $new_minute;
779 /****************************************************/
780 /* compute the $_my_uri variable */
781 $bits = explode(SEP, getenv('QUERY_STRING'));
782 $num_bits = count($bits);
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)
792 /* we don't want this variable added to $_my_uri */
796 if (($_my_uri == '') && ($bits[$i] != '')) {
797 $_my_uri .= htmlentities('?');
798 } else if ($bits[$i] != ''){
799 $_my_uri .= htmlentities(SEP);
801 $_my_uri .= $bits[$i];
803 if ($_my_uri == '') {
804 $_my_uri .= htmlentities('?');
806 $_my_uri .= htmlentities(SEP);
808 $_my_uri = $_SERVER['PHP_SELF'].$_my_uri;
811 * If MBString extension is loaded, 4.3.0+, then use it.
812 * Otherwise we will have to use include/utf8 library
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';
825 $strtolower = 'utf8_strtolower';
826 $strtoupper = 'utf8_strtoupper';
827 $substr = 'utf8_substr';
828 $strpos = 'utf8_strpos';
829 $strrpos = 'utf8_strrpos';
830 $strlen = 'utf8_strlen';
834 /*~~~~~~~~~~~~~~~~~flash detection~~~~~~~~~~~~~~~~*/
835 if(isset($_COOKIE["flash"])){
836 $_SESSION['flash'] = $_COOKIE["flash"];
839 ATutor.setcookie("flash",'',time()-3600);
842 if (!isset($_SESSION["flash"])) {
844 <script type="text/javascript">
847 //VB-Script for InternetExplorer
848 function iExploreCheck()
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");
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)))
872 flash_detect = "flash=yes";
874 flash_detect = "flash=no";
877 flash_detect = "flash=yes";
879 flash_detect = "flash=no";
881 writeCookie(flash_detect);
883 function writeCookie(value)
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;
898 /*~~~~~~~~~~~~~~end flash detection~~~~~~~~~~~~~~~*/
903 * Checks if the data exceeded the database predefined length, if so,
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.
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
916 function validate_length($input, $len, $forDisplay=0){
917 global $strlen, $substr;
918 $input_bytes_len = strlen($input);
919 $input_len = $strlen($input);
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);
928 if ($forDisplay===1){
929 return $substr($input, 0, $suitable_len).'...';
931 return $substr($input, 0, $suitable_len);
937 * Instead of blindly cutting off the input from the given param
939 global $strlen, $substr;
940 if ($strlen($input) > $len) {
941 if ($forDisplay===1){
942 return $substr($input, 0, $len).'...';
944 return $substr($input, 0, $len);
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
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();
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
974 if ($force || (isset($_SESSION['course_id']) && $_SESSION['course_id'] > 0)) {
975 //if course id is defined, apply pretty url.
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)){
984 //if we allow pretty url in the system
985 if ($_config['pretty_url'] > 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
992 $course_id = $url_parser->getCourseDirName($matches[1]);
993 } elseif (isset($_REQUEST['course'])){
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']);
1003 $course_id = $_SESSION['course_id'];
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
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']);
1020 $url = $pathinfo[1]->convertToPrettyUrl($course_id, $url);
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;
1035 * Applies $addslashes or intval() recursively.
1037 * @param mixed $input The input to clean.
1038 * @return A safe version of $input
1039 * @author Joel Kronenberg
1041 function sql_quote($input) {
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]);
1051 $input[$key] = $addslashes(trim($input[$key]));
1055 if (!empty($input) && is_numeric($input)) {
1056 $input = intval($input);
1058 $input = $addslashes(trim($input));
1064 function query_bit( $bitfield, $bit ) {
1065 if (!is_int($bitfield)) {
1066 $bitfield = intval($bitfield);
1068 if (!is_int($bit)) {
1069 $bit = intval($bit);
1071 return ( $bitfield & $bit ) ? true : false;
1075 * Authenticates the current user against the specified privilege.
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
1083 function authenticate($privilege, $check = false) {
1084 if ($_SESSION['is_admin']) {
1088 $auth = query_bit($_SESSION['privileges'], $privilege);
1090 if (!$_SESSION['valid_user'] || !$auth) {
1093 $msg->addInfo('NO_PERMISSION');
1094 require(AT_INCLUDE_PATH.'header.inc.php');
1095 require(AT_INCLUDE_PATH.'footer.inc.php');
1104 function admin_authenticate($privilege = 0, $check = false) {
1105 if (!isset($_SESSION['valid_user']) || !$_SESSION['valid_user'] || ($_SESSION['course_id'] != -1)) {
1109 header('Location: '.AT_BASE_HREF.'login.php');
1113 if ($_SESSION['privileges'] == AT_ADMIN_PRIV_ADMIN) {
1118 $auth = query_bit($_SESSION['privileges'], $privilege);
1125 $msg->addError('ACCESS_DENIED');
1126 require(AT_INCLUDE_PATH.'header.inc.php');
1127 require(AT_INCLUDE_PATH.'footer.inc.php');
1134 function get_default_theme() {
1137 if (is_mobile_device()) {
1138 $default_status = 3;
1140 $default_status = 2;
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);
1149 function get_system_default_theme() {
1150 if (is_mobile_device()) {
1157 function is_mobile_theme($theme) {
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;
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'])]);
1176 * Writes present action to admin log db
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
1183 function write_to_log($operation_type, $table_name, $num_affected, $details) {
1184 global $db, $addslashes;
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);
1193 function get_group_title($group_id) {
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'];
1203 function get_status_name($status_id) {
1204 switch ($status_id) {
1205 case AT_STATUS_DISABLED:
1206 return _AT('disabled');
1208 case AT_STATUS_UNCONFIRMED:
1209 return _AT('unconfirmed');
1211 case AT_STATUS_STUDENT:
1212 return _AT('student');
1214 case AT_STATUS_INSTRUCTOR:
1215 return _AT('instructor');
1220 function profile_image_exists($id) {
1221 $extensions = array('gif', 'jpg', 'png');
1223 foreach ($extensions as $extension) {
1224 if (file_exists(AT_CONTENT_DIR.'profile_pictures/originals/'. $id.'.'.$extension)) {
1231 * print thumbnails or profile pic
1232 * @param int image id
1233 * @param int 1 for thumbnail, 2 for profile
1235 function print_profile_img($id, $type=1) {
1236 global $moduleFactory;
1237 $mod = $moduleFactory->getModule('_standard/profile_pictures');
1238 if ($mod->isEnabled() === FALSE) {
1241 if (profile_image_exists($id)) {
1243 echo '<img src="get_profile_img.php?id='.$id.'" class="profile-picture" alt="" />';
1245 echo '<img src="get_profile_img.php?id='.$id.SEP.'size=p" class="profile-picture" alt="" />';
1248 echo '<img src="images/clr.gif" height="100" width="100" class="profile-picture" alt="" />';
1252 function profile_image_delete($id) {
1253 $extensions = array('gif', 'jpg', 'png');
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);
1259 if (file_exists(AT_CONTENT_DIR.'profile_pictures/profile/'. $id.'.'.$extension)) {
1260 unlink(AT_CONTENT_DIR.'profile_pictures/profile/'. $id.'.'.$extension);
1262 if (file_exists(AT_CONTENT_DIR.'profile_pictures/thumbs/'. $id.'.'.$extension)) {
1263 unlink(AT_CONTENT_DIR.'profile_pictures/thumbs/'. $id.'.'.$extension);
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.
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'];
1283 $_config['mysql_group_concat_max_len'] = 0;
1285 $sql = "REPLACE INTO ".TABLE_PREFIX."config VALUES ('mysql_group_concat_max_len', '{$_config['mysql_group_concat_max_len']}')";
1286 mysql_query($sql, $db);
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']) {
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
1298 // doesn't actually get here.
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'] . ',';
1310 return substr($list, 0, -1); }
1314 function get_human_time($seconds) {
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');
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');
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))
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) {
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;
1353 return UNKNOWN_DEVICE;
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
1365 function htmlentities_utf8($str, $use_nl2br=true){
1366 $return = htmlentities($str, ENT_QUOTES, 'UTF-8');
1368 return nl2br($return);
1375 * Convert all '&' to '&' from the input
1376 * @param string any string input, mainly URLs.
1377 * @return input with & replaced to '&'
1378 * @author Harris Wong
1381 function convert_amp($input){
1382 $input = str_replace('&', '&', $input); //convert everything to '&' first
1383 return str_replace('&', '&', $input);
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
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);
1399 if ( !function_exists('json_decode') ){
1400 function json_decode($content, $assoc=false){
1401 require_once (AT_INCLUDE_PATH.'lib/json.inc.php');
1403 $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
1405 $json = new Services_JSON;
1407 return $json->decode($content);
1412 require(AT_INCLUDE_PATH . '../mods/_core/modules/classes/Module.class.php');
1414 $moduleFactory = new ModuleFactory(TRUE); // TRUE is for auto_loading the module.php files
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);
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);
1426 if (isset($_SESSION['course_id']) && $_SESSION['course_id'] > 0) {
1427 $_custom_head .= '<script type="text/javascript" src="'.$_base_path.'jscripts/ATutorCourse.js"></script>';