83db8a2aa6ed6b992ab8fa85c18004dda0d21387
[acontent.git] / docs / 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 // define as constants. more constants are defined in include/constants.inc.php
111 define('EMAIL', $_config['contact_email']);
112 define('SITE_NAME', $_config['site_name']);
113 $MaxFileSize = $_config['max_file_size']; 
114 $MaxCourseSize = $_config['max_course_size'];
115 $MaxFileSize = $_config['max_file_size']; 
116 $IllegalExtentions = explode('|',$_config['illegal_extentions']);
117 /***** end loading $_config *****/
118
119 /***** 5. start language block *****/
120 // set current language
121 require(TR_INCLUDE_PATH . 'classes/Language/LanguageManager.class.php');
122 $languageManager = new LanguageManager();
123
124 $myLang = $languageManager->getMyLanguage();
125
126 if ($myLang === FALSE) {
127         echo 'There are no languages installed!';
128         exit;
129 }
130
131 $myLang->saveToSession();
132
133 /* set right-to-left language */
134 $rtl = '';
135 if ($myLang->isRTL()) {
136         $rtl = 'rtl_'; /* basically the prefix to a rtl variant directory/filename. eg. rtl_atee */
137 }
138 /***** end language block ****/
139
140 /***** 6. load common libraries *****/
141         require(TR_INCLUDE_PATH.'lib/output.inc.php');           /* output functions */
142 /***** end load common libraries ****/
143
144 /***** 7. initialize theme and template management *****/
145         require(TR_INCLUDE_PATH.'classes/Savant2/Savant2.php');
146
147         // set default template paths:
148         $savant = new Savant2();
149
150         if (isset($_SESSION['prefs']['PREF_THEME']) && file_exists(TR_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME']) && $_SESSION['user_id']>0) 
151         {
152                 if (!is_dir(TR_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME']))
153                 {
154                         $_SESSION['prefs']['PREF_THEME'] = 'default';
155                 } 
156                 else 
157                 {
158                         //check if enabled
159                         $themesDAO = new ThemesDAO();
160                         $row = $themesDAO->getByID($_SESSION['prefs']['PREF_THEME']);
161
162                         if ($row['status'] == 0) 
163                         {
164                                 // get default
165                                 $_SESSION['prefs']['PREF_THEME'] = get_default_theme();
166                         }
167                 }
168         } else 
169         {
170                 $_SESSION['prefs']['PREF_THEME'] = get_default_theme();
171         }
172
173         $savant->addPath('template', TR_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME'] . '/');
174
175         require(TR_INCLUDE_PATH . '../themes/' . $_SESSION['prefs']['PREF_THEME'] . '/theme.cfg.php');
176
177         require(TR_INCLUDE_PATH.'classes/Message/Message.class.php');
178         $msg = new Message($savant);
179
180 /***** end of initialize theme and template management *****/
181
182 /***** 8. initialize user instance *****/
183 // used as global var
184 if (isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0)
185 {
186         // check if $_SESSION['user_id'] is valid
187         include_once(TR_INCLUDE_PATH.'classes/DAO/UsersDAO.class.php');
188         $usersDAO = new UsersDAO();
189         $user = $usersDAO->getUserByID($_SESSION['user_id']);
190         
191         if (!$user)  // invalid user
192                 unset($_SESSION['user_id']);
193         else
194         {
195                 include_once(TR_INCLUDE_PATH.'classes/User.class.php');
196                 $_current_user = new User($_SESSION['user_id']);
197         }
198 }
199 /***** end of initialize user instance *****/
200
201 /* 9. initialize course information if $course_id or $cid is set 
202  * This section generates global variables: 
203  * $_content_id if set, 
204  * $_course_id if set or $cid is set
205  * $_SESSION['s_cid']: record the last content_id on (user_id + course_id) basis
206  * $_sequence_links: resume/first/next/previous content links
207  */ 
208 if (intval($_REQUEST['_cid']) > 0) $_content_id = intval($_REQUEST['_cid']);
209 else if (intval($_POST['_cid']) > 0) $_content_id = intval($_POST['_cid']);
210
211 if (intval($_REQUEST['_course_id']) > 0) $_course_id = intval($_REQUEST['_course_id']);
212 else if (intval($_POST['_course_id']) > 0) $_course_id = intval($_POST['_course_id']);
213
214 // find course_id thru content_id
215 if ($_content_id > 0)
216 {
217         include_once(TR_INCLUDE_PATH.'classes/DAO/ContentDAO.class.php');
218         $contentDAO = new ContentDAO();
219         $content_row = $contentDAO->get($_content_id);
220         $_course_id = $content_row['course_id'];
221 }
222
223 // Generate $_SESSION['s_cid']: record the last visited content_id
224 // for authors and the users who have the current course in "my courses" list, 
225 //     save the last visited content_id into user_courses and set the session var.
226 //     @see ContentUtility::saveLastCid()
227 // for the users who don't have the current course in "my courses" list,
228 //     set the session var as $_GET['cid']
229 if ($_course_id > 0)
230 {
231         if ($_SESSION['user_id'] > 0)
232         {
233                 include_once(TR_INCLUDE_PATH.'classes/DAO/UserCoursesDAO.class.php');
234                 $userCoursesDAO = new UserCoursesDAO();
235                 $user_courses_row = $userCoursesDAO->get($_SESSION['user_id'], $_course_id);
236                 
237                 if ($user_courses_row && $user_courses_row['last_cid'] > 0) 
238                         $_SESSION['s_cid'] = $user_courses_row['last_cid'];
239                 else if ($_content_id > 0)
240                         $_SESSION['s_cid'] = $_content_id;
241                 else // first time accessing this course, no last cid yet
242                         unset($_SESSION['s_cid']);
243         }
244         else // guest
245         {
246                 $_SESSION['s_cid'] = $_content_id;
247         }
248 }
249
250 // Generate contentManager. 
251 // Must be called after generating $_SESSION['s_cid'] as it's used in contentManager class
252 if ($_course_id > 0)
253 {
254         global $contentManager;
255         
256         include_once(TR_INCLUDE_PATH. '../home/classes/ContentManager.class.php');
257         
258         $contentManager = new ContentManager($_course_id);
259         $_sequence_links = $contentManager->generateSequenceCrumbs($_content_id);
260 }
261
262 /*** 10. register pages based on user's priviledge ***/
263 require_once(TR_INCLUDE_PATH.'page_constants.inc.php');
264
265 /**
266  * This function is used for printing variables for debugging.
267  * @access  public
268  * @param   mixed $var  The variable to output
269  * @param   string $title       The name of the variable, or some mark-up identifier.
270  * @author  Joel Kronenberg
271  */
272 function debug($var, $title='') {
273         if (!defined('TR_DEVEL') || !TR_DEVEL) {
274                 return;
275         }
276         
277         echo '<pre style="border: 1px black solid; padding: 0px; margin: 10px;" title="debugging box">';
278         if ($title) {
279                 echo '<h4>'.$title.'</h4>';
280         }
281         
282         ob_start();
283         print_r($var);
284         $str = ob_get_contents();
285         ob_end_clean();
286
287         $str = str_replace('<', '&lt;', $str);
288
289         $str = str_replace('[', '<span style="color: red; font-weight: bold;">[', $str);
290         $str = str_replace(']', ']</span>', $str);
291         $str = str_replace('=>', '<span style="color: blue; font-weight: bold;">=></span>', $str);
292         $str = str_replace('Array', '<span style="color: purple; font-weight: bold;">Array</span>', $str);
293         echo $str;
294         echo '</pre>';
295 }
296
297 /**
298 * This function is used for printing variables into log file for debugging.
299 * @access  public
300 * @param   mixed $var   The variable to output
301 * @param   string $log  The location of the log file. If not provided, use the default one.
302 * @author  Cindy Qi Li
303 */
304 function debug_to_log($var, $log='') {
305         if (!defined('TR_DEVEL') || !TR_DEVEL) {
306                 return;
307         }
308         
309         if ($log == '') $log = TR_CONTENT_DIR. 'debug.log';
310         $handle = fopen($log, 'a');
311         fwrite($handle, "\n\n");
312         fwrite($handle, date("F j, Y, g:i a"));
313         fwrite($handle, "\n");
314         fwrite($handle, var_export($var,1));
315         
316         fclose($handle);
317 }
318
319 /****************************************************/
320 /* compute the $_my_uri variable                                        */
321         $bits     = explode(SEP, getenv('QUERY_STRING'));
322         $num_bits = count($bits);
323         $_my_uri  = '';
324
325         for ($i=0; $i<$num_bits; $i++) {
326 //              if (    (strpos($bits[$i], 'enable=')   === 0) 
327 //                      ||      (strpos($bits[$i], 'disable=')  === 0)
328 //                      ||      (strpos($bits[$i], 'expand=')   === 0)
329 //                      ||      (strpos($bits[$i], 'collapse=') === 0)
330 //                      ||      (strpos($bits[$i], 'lang=')             === 0)
331 //                      ) {
332                 if (    (strpos($bits[$i], 'lang=')             === 0)
333                         ) {
334                         /* we don't want this variable added to $_my_uri */
335                         continue;
336                 }
337
338                 if (($_my_uri == '') && ($bits[$i] != '')) {
339                         $_my_uri .= '?';
340                 } else if ($bits[$i] != ''){
341                         $_my_uri .= SEP;
342                 }
343                 $_my_uri .= $bits[$i];
344         }
345         if ($_my_uri == '') {
346                 $_my_uri .= '?';
347         } else {
348                 $_my_uri .= SEP;
349         }
350         $_my_uri = $_SERVER['PHP_SELF'].$_my_uri;
351
352 function my_add_null_slashes( $string ) {
353 //    return mysql_real_escape_string(stripslashes($string));
354     return addslashes(stripslashes($string));
355 }
356
357 function my_null_slashes($string) {
358         return $string;
359 }
360
361 if ( get_magic_quotes_gpc() == 1 ) {
362         $addslashes   = 'my_add_null_slashes';
363         $stripslashes = 'stripslashes';
364 } else {
365         $addslashes   = 'mysql_real_escape_string';
366         $stripslashes = 'my_null_slashes';
367 }
368
369 /**
370  * If MBString extension is loaded, then use it.
371  * Otherwise we will have to use include/utf8 library
372  */
373  if (extension_loaded('mbstring')){
374          $strtolower = 'mb_strtolower';
375          $strtoupper = 'mb_strtoupper';
376          $substr = 'mb_substr';
377          $strpos = 'mb_strpos';
378          $strrpos = 'mb_strrpos';
379          $strlen = 'mb_strlen';
380  } else {
381          $strtolower = 'utf8_strtolower';
382          $strtoupper = 'utf8_strtoupper';
383          $substr = 'utf8_substr';
384          $strpos = 'utf8_strpos';
385          $strrpos = 'utf8_strrpos';
386          $strlen = 'utf8_strlen';
387  }
388
389 function get_default_theme() {
390         $themesDAO = new ThemesDAO();
391         
392         $rows = $themesDAO->getDefaultTheme();
393
394         if (!is_dir(TR_INCLUDE_PATH . '../themes/' . $rows[0]['dir_name']))
395                 return 'default';
396         else
397                 return $rows[0]['dir_name'];
398 }
399
400 ?>