moved code up one level to eliminate the docs subdirectory
[acontent.git] / include / vitals.inc.php
1 <?php
2 /************************************************************************/
3 /* AContent                                                             */
4 /************************************************************************/
5 /* Copyright (c) 2010                                                   */
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
13 if (!defined('TR_INCLUDE_PATH')) { exit; }
14
15 define('TR_DEVEL', 1);
16 define('TR_ERROR_REPORTING', E_ALL ^ E_NOTICE); // default is E_ALL ^ E_NOTICE, use E_ALL or E_ALL + E_STRICT for developing
17
18 // Emulate register_globals off. src: http://php.net/manual/en/faq.misc.php#faq.misc.registerglobals
19 function unregister_GLOBALS() {
20    if (!ini_get('register_globals')) { return; }
21
22    // Might want to change this perhaps to a nicer error
23    if (isset($_REQUEST['GLOBALS'])) { die('GLOBALS overwrite attempt detected'); }
24
25    // Variables that shouldn't be unset
26    $noUnset = array('GLOBALS','_GET','_POST','_COOKIE','_REQUEST','_SERVER','_ENV', '_FILES');
27    $input = array_merge($_GET,$_POST,$_COOKIE,$_SERVER,$_ENV,$_FILES,isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());
28   
29    foreach ($input as $k => $v) {
30        if (!in_array($k, $noUnset) && isset($GLOBALS[$k])) { unset($GLOBALS[$k]); }
31    }
32 }
33
34 /*
35  * structure of this document (in order):
36  *
37  * 0. load config.inc.php
38  * 1. initilize db connection
39  * 2. load constants
40  * 3. initilize session
41  * 4. load $_config from table 'config'
42  * 5. start language block
43  * 6. load common libraries
44  * 7. initialize theme and template management
45  * 8. initialize a user instance without user id. 
46  *    if $_SESSION['user_id'] is set, it's assigned to instance in include/header.inc.php
47  * 9. register pages based on current user's priviledge
48  * 10. initialize course information if $_SESSION['course_id'] is set 
49  ***/
50
51 /**** 0. start system configuration options block ****/
52 error_reporting(0);
53 include_once(TR_INCLUDE_PATH.'config.inc.php');
54 error_reporting(TR_ERROR_REPORTING);
55
56 if (!defined('TR_INSTALL') || !TR_INSTALL) {
57         header('Cache-Control: no-store, no-cache, must-revalidate');
58         header('Pragma: no-cache');
59
60         $relative_path = substr(TR_INCLUDE_PATH, 0, -strlen('include/'));
61         header('Location: ' . $relative_path . 'install/not_installed.php');
62         exit;
63 }
64 /*** end system config block ****/
65
66 /***** 1. database connection *****/
67 //if (!defined('TR_REDIRECT_LOADED')){
68 //      require_once(TR_INCLUDE_PATH.'lib/mysql_connect.inc.php');
69 //}
70 /***** end database connection ****/
71
72 /*** 2. constants ***/
73 require_once(TR_INCLUDE_PATH.'constants.inc.php');
74
75 /*** 3. initilize session ***/
76 @set_time_limit(0);
77 @ini_set('session.gc_maxlifetime', '36000'); /* 10 hours */
78 @session_cache_limiter('private, must-revalidate');
79
80 session_name('TransformableID');
81 error_reporting(TR_ERROR_REPORTING);
82
83 ob_start();
84 session_set_cookie_params(0, $_base_path);
85 session_start();
86 $str = ob_get_contents();
87 ob_end_clean();
88 unregister_GLOBALS();
89
90 // $_user_id could be set in home/ims/ims_import.php
91 // @see home/ims/ims_import.php
92 if (isset($_user_id) && $_user_id > 0) $_SESSION['user_id'] = $_user_id;
93 /***** end session initilization block ****/
94
95 /***** 4. load $_config from table 'config' *****/
96 require(TR_INCLUDE_PATH.'phpCache/phpCache.inc.php'); // cache library
97 require(TR_INCLUDE_PATH.'classes/DAO/ThemesDAO.class.php');
98 require(TR_INCLUDE_PATH.'classes/DAO/ConfigDAO.class.php');
99
100 $configDAO = new ConfigDAO();
101 $rows = $configDAO->getAll();
102 if (is_array($rows))
103 {
104         foreach ($rows as $id => $row)
105         {
106                 $_config[$row['name']] = $row['value'];
107         }
108 }
109
110 //set the timezone, php 5.3+ problem. http://atutor.ca/atutor/mantis/view.php?id=4409
111 date_default_timezone_set('UTC');
112
113 // define as constants. more constants are defined in include/constants.inc.php
114 define('EMAIL', $_config['contact_email']);
115 define('SITE_NAME', $_config['site_name']);
116 $MaxFileSize = $_config['max_file_size']; 
117 $MaxCourseSize = $_config['max_course_size'];
118 $MaxFileSize = $_config['max_file_size']; 
119 $IllegalExtentions = explode('|',$_config['illegal_extentions']);
120 /***** end loading $_config *****/
121
122 /***** 5. start language block *****/
123 // set current language
124 require(TR_INCLUDE_PATH . 'classes/Language/LanguageManager.class.php');
125 $languageManager = new LanguageManager();
126
127 $myLang = $languageManager->getMyLanguage();
128
129 if ($myLang === FALSE) {
130         echo 'There are no languages installed!';
131         exit;
132 }
133
134 $myLang->saveToSession();
135
136 /* set right-to-left language */
137 $rtl = '';
138 if ($myLang->isRTL()) {
139         $rtl = 'rtl_'; /* basically the prefix to a rtl variant directory/filename. eg. rtl_atee */
140 }
141 /***** end language block ****/
142
143 /***** 6. load common libraries *****/
144         require(TR_INCLUDE_PATH.'lib/output.inc.php');           /* output functions */
145 /***** end load common libraries ****/
146
147 /***** 7. initialize theme and template management *****/
148         require(TR_INCLUDE_PATH.'classes/Savant2/Savant2.php');
149
150         // set default template paths:
151         $savant = new Savant2();
152
153         if (isset($_SESSION['prefs']['PREF_THEME']) && file_exists(TR_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME']) && $_SESSION['user_id']>0) 
154         {
155                 if (!is_dir(TR_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME']))
156                 {
157                         $_SESSION['prefs']['PREF_THEME'] = 'default';
158                 } 
159                 else 
160                 {
161                         //check if enabled
162                         $themesDAO = new ThemesDAO();
163                         $row = $themesDAO->getByID($_SESSION['prefs']['PREF_THEME']);
164
165                         if ($row['status'] == 0) 
166                         {
167                                 // get default
168                                 $_SESSION['prefs']['PREF_THEME'] = get_default_theme();
169                         }
170                 }
171         } else 
172         {
173                 $_SESSION['prefs']['PREF_THEME'] = get_default_theme();
174         }
175
176         $savant->addPath('template', TR_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME'] . '/');
177
178         require(TR_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME'] . '/theme.cfg.php');
179
180         require(TR_INCLUDE_PATH.'classes/Message/Message.class.php');
181         $msg = new Message($savant);
182
183 /***** end of initialize theme and template management *****/
184
185 /***** 8. initialize user instance *****/
186 // used as global var
187 if (isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0)
188 {
189         // check if $_SESSION['user_id'] is valid
190         include_once(TR_INCLUDE_PATH.'classes/DAO/UsersDAO.class.php');
191         $usersDAO = new UsersDAO();
192         $user = $usersDAO->getUserByID($_SESSION['user_id']);
193         
194         if (!$user)  // invalid user
195                 unset($_SESSION['user_id']);
196         else
197         {
198                 include_once(TR_INCLUDE_PATH.'classes/User.class.php');
199                 $_current_user = new User($_SESSION['user_id']);
200         }
201 }
202 /***** end of initialize user instance *****/
203
204 /* 9. initialize course information if $course_id or $cid is set 
205  * This section generates global variables: 
206  * $_content_id if set, 
207  * $_course_id if set or $cid is set
208  * $_SESSION['s_cid']: record the last content_id on (user_id + course_id) basis
209  * $_sequence_links: resume/first/next/previous content links
210  */ 
211 if (intval($_REQUEST['_cid']) > 0) $_content_id = intval($_REQUEST['_cid']);
212 else if (intval($_POST['_cid']) > 0) $_content_id = intval($_POST['_cid']);
213
214 if (intval($_REQUEST['_course_id']) > 0) $_course_id = intval($_REQUEST['_course_id']);
215 else if (intval($_POST['_course_id']) > 0) $_course_id = intval($_POST['_course_id']);
216
217 // find course_id thru content_id
218 if ($_content_id > 0)
219 {
220         include_once(TR_INCLUDE_PATH.'classes/DAO/ContentDAO.class.php');
221         $contentDAO = new ContentDAO();
222         $content_row = $contentDAO->get($_content_id);
223         $_course_id = $content_row['course_id'];
224 }
225
226 // Generate $_SESSION['s_cid']: record the last visited content_id
227 // for authors and the users who have the current course in "my courses" list, 
228 //     save the last visited content_id into user_courses and set the session var.
229 //     @see ContentUtility::saveLastCid()
230 // for the users who don't have the current course in "my courses" list,
231 //     set the session var as $_GET['cid']
232 if ($_course_id > 0)
233 {
234         if ($_SESSION['user_id'] > 0)
235         {
236                 include_once(TR_INCLUDE_PATH.'classes/DAO/UserCoursesDAO.class.php');
237                 $userCoursesDAO = new UserCoursesDAO();
238                 $user_courses_row = $userCoursesDAO->get($_SESSION['user_id'], $_course_id);
239                 
240                 if ($user_courses_row && $user_courses_row['last_cid'] > 0) 
241                         $_SESSION['s_cid'] = $user_courses_row['last_cid'];
242                 else if ($_content_id > 0)
243                         $_SESSION['s_cid'] = $_content_id;
244                 else // first time accessing this course, no last cid yet
245                         unset($_SESSION['s_cid']);
246         }
247         else // guest
248         {
249                 $_SESSION['s_cid'] = $_content_id;
250         }
251 }
252
253 // Generate contentManager. 
254 // Must be called after generating $_SESSION['s_cid'] as it's used in contentManager class
255 if ($_course_id > 0)
256 {
257         global $contentManager;
258         
259         include_once(TR_INCLUDE_PATH. '../home/classes/ContentManager.class.php');
260         
261         $contentManager = new ContentManager($_course_id);
262         $_sequence_links = $contentManager->generateSequenceCrumbs($_content_id);
263 }
264
265 /*** 10. register pages based on user's priviledge ***/
266 require_once(TR_INCLUDE_PATH.'page_constants.inc.php');
267
268 /*~~~~~~~~~~~~~~~~~flash detection~~~~~~~~~~~~~~~~*/
269 if(isset($_COOKIE["flash"])){
270     $_SESSION['flash'] = $_COOKIE["flash"];
271
272     //delete the cookie
273     AContent.setcookie("flash",'',time()-3600);
274 }
275
276 if (!isset($_SESSION["flash"])) {
277         $_custom_head .= '
278                 <script type="text/javascript">
279                 <!--
280
281                         //VB-Script for InternetExplorer
282                         function iExploreCheck()
283                         {
284                                 document.writeln("<scr" + "ipt language=\'VBscript\'>");
285                                 //document.writeln("\'Test to see if VBScripting works");
286                                 document.writeln("detectableWithVB = False");
287                                 document.writeln("If ScriptEngineMajorVersion >= 2 then");
288                                 document.writeln("   detectableWithVB = True");
289                                 document.writeln("End If");
290                                 //document.writeln("\'This will check for the plugin");
291                                 document.writeln("Function detectActiveXControl(activeXControlName)");
292                                 document.writeln("   on error resume next");
293                                 document.writeln("   detectActiveXControl = False");
294                                 document.writeln("   If detectableWithVB Then");
295                                 document.writeln("      detectActiveXControl = IsObject(CreateObject(activeXControlName))");
296                                 document.writeln("   End If");
297                                 document.writeln("End Function");
298                                 document.writeln("</scr" + "ipt>");
299                                 return detectActiveXControl("ShockwaveFlash.ShockwaveFlash.1");
300                         }
301
302
303                         var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : false;
304                         if(!(plugin) && (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.appVersion.indexOf("Win") != -1)))
305                                 if (iExploreCheck())
306                                         flash_detect = "flash=yes";
307                                 else
308                                         flash_detect = "flash=no";
309
310                         else if(plugin)
311                                 flash_detect = "flash=yes";
312                         else
313                                 flash_detect = "flash=no";
314
315                         writeCookie(flash_detect);
316
317                         function writeCookie(value)
318                         {
319                                 var today = new Date();
320                                 var the_date = new Date("December 31, 2099");
321                                 var the_cookie_date = the_date.toGMTString();
322                                 var the_cookie = value + ";expires=" + the_cookie_date;
323                                 document.cookie = the_cookie;
324                         }
325                 //-->
326                 </script>
327 ';
328 }
329
330
331
332 /*~~~~~~~~~~~~~~end flash detection~~~~~~~~~~~~~~~*/
333
334 /**
335  * This function is used for printing variables for debugging.
336  * @access  public
337  * @param   mixed $var  The variable to output
338  * @param   string $title       The name of the variable, or some mark-up identifier.
339  * @author  Joel Kronenberg
340  */
341 function debug($var, $title='') {
342         if (!defined('TR_DEVEL') || !TR_DEVEL) {
343                 return;
344         }
345         
346         echo '<pre style="border: 1px black solid; padding: 0px; margin: 10px;" title="debugging box">';
347         if ($title) {
348                 echo '<h4>'.$title.'</h4>';
349         }
350         
351         ob_start();
352         print_r($var);
353         $str = ob_get_contents();
354         ob_end_clean();
355
356         $str = str_replace('<', '&lt;', $str);
357
358         $str = str_replace('[', '<span style="color: red; font-weight: bold;">[', $str);
359         $str = str_replace(']', ']</span>', $str);
360         $str = str_replace('=>', '<span style="color: blue; font-weight: bold;">=></span>', $str);
361         $str = str_replace('Array', '<span style="color: purple; font-weight: bold;">Array</span>', $str);
362         echo $str;
363         echo '</pre>';
364 }
365
366 /**
367 * This function is used for printing variables into log file for debugging.
368 * @access  public
369 * @param   mixed $var   The variable to output
370 * @param   string $log  The location of the log file. If not provided, use the default one.
371 * @author  Cindy Qi Li
372 */
373 function debug_to_log($var, $log='') {
374         if (!defined('TR_DEVEL') || !TR_DEVEL) {
375                 return;
376         }
377         
378         if ($log == '') $log = TR_CONTENT_DIR. 'debug.log';
379         $handle = fopen($log, 'a');
380         fwrite($handle, "\n\n");
381         fwrite($handle, date("F j, Y, g:i a"));
382         fwrite($handle, "\n");
383         fwrite($handle, var_export($var,1));
384         
385         fclose($handle);
386 }
387
388 /****************************************************/
389 /* compute the $_my_uri variable                                        */
390         $bits     = explode(SEP, getenv('QUERY_STRING'));
391         $num_bits = count($bits);
392         $_my_uri  = '';
393
394         for ($i=0; $i<$num_bits; $i++) {
395 //              if (    (strpos($bits[$i], 'enable=')   === 0) 
396 //                      ||      (strpos($bits[$i], 'disable=')  === 0)
397 //                      ||      (strpos($bits[$i], 'expand=')   === 0)
398 //                      ||      (strpos($bits[$i], 'collapse=') === 0)
399 //                      ||      (strpos($bits[$i], 'lang=')             === 0)
400 //                      ) {
401                 if (    (strpos($bits[$i], 'lang=')             === 0)
402                         ) {
403                         /* we don't want this variable added to $_my_uri */
404                         continue;
405                 }
406
407                 if (($_my_uri == '') && ($bits[$i] != '')) {
408                         $_my_uri .= '?';
409                 } else if ($bits[$i] != ''){
410                         $_my_uri .= SEP;
411                 }
412                 $_my_uri .= $bits[$i];
413         }
414         if ($_my_uri == '') {
415                 $_my_uri .= '?';
416         } else {
417                 $_my_uri .= SEP;
418         }
419         $_my_uri = $_SERVER['PHP_SELF'].$_my_uri;
420
421 function my_add_null_slashes( $string ) {
422 //    return mysql_real_escape_string(stripslashes($string));
423     return addslashes(stripslashes($string));
424 }
425
426 function my_null_slashes($string) {
427         return $string;
428 }
429
430 if ( get_magic_quotes_gpc() == 1 ) {
431         $addslashes   = 'my_add_null_slashes';
432         $stripslashes = 'stripslashes';
433 } else {
434         $addslashes   = 'mysql_real_escape_string';
435         $stripslashes = 'my_null_slashes';
436 }
437
438 /**
439  * If MBString extension is loaded, then use it.
440  * Otherwise we will have to use include/utf8 library
441  */
442  if (extension_loaded('mbstring')){
443          $strtolower = 'mb_strtolower';
444          $strtoupper = 'mb_strtoupper';
445          $substr = 'mb_substr';
446          $strpos = 'mb_strpos';
447          $strrpos = 'mb_strrpos';
448          $strlen = 'mb_strlen';
449  } else {
450          $strtolower = 'utf8_strtolower';
451          $strtoupper = 'utf8_strtoupper';
452          $substr = 'utf8_substr';
453          $strpos = 'utf8_strpos';
454          $strrpos = 'utf8_strrpos';
455          $strlen = 'utf8_strlen';
456  }
457
458 function get_default_theme() {
459         $themesDAO = new ThemesDAO();
460         
461         $rows = $themesDAO->getDefaultTheme();
462
463         if (!is_dir(TR_INCLUDE_PATH . '../themes/' . $rows[0]['dir_name']))
464                 return 'default';
465         else
466                 return $rows[0]['dir_name'];
467 }
468
469 /**
470  * Convert all input to htmlentities output, in UTF-8.
471  * @param       string  input to be convert
472  * @param       boolean true if we wish to change all newlines(\r\n) to a <br/> tag, false otherwise.  
473  *                      ref: http://php.net/manual/en/function.nl2br.php
474  * @author      Harris Wong
475  * @date        March 12, 2010
476  */
477 function htmlentities_utf8($str, $use_nl2br=true){
478         $return = htmlentities($str, ENT_QUOTES, 'UTF-8');
479         if ($use_nl2br){
480                 return nl2br($return);
481         } 
482         return $return;
483 }
484
485 /**
486  * Convert all '&' to '&amp;' from the input
487  * @param   string  any string input, mainly URLs.
488  * @return  input with & replaced to '&amp;'
489  * @author  Harris Wong
490  * @date    Oct 7, 2010
491  */
492 function convertAmp($input){
493     $input = str_replace('&amp;', '&', $input); //convert everything to '&' first
494     return str_replace('&', '&amp;', $input);
495 }
496
497 function query_bit( $bitfield, $bit ) {
498         if (!is_int($bitfield)) {
499                 $bitfield = intval($bitfield);
500         }
501         if (!is_int($bit)) {
502                 $bit = intval($bit);
503         }
504         return ( $bitfield & $bit ) ? true : false;
505 }
506 ?>