1 | <?php |
---|
2 | /** |
---|
3 | * App.inc.php |
---|
4 | * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information |
---|
5 | */ |
---|
6 | |
---|
7 | /****************************************************************************** |
---|
8 | * CONFIG |
---|
9 | ****************************************************************************** |
---|
10 | |
---|
11 | This library has some functions that require globally defined values. |
---|
12 | These are defined here. |
---|
13 | */ |
---|
14 | |
---|
15 | // Message Types |
---|
16 | /** @constant MSG_NOTICE |
---|
17 | An informational message: Welcome to asdf, Logout successful, etc. */ |
---|
18 | define('MSG_NOTICE', 0); |
---|
19 | |
---|
20 | /** @constant MSG_SUCCESS |
---|
21 | A success message: Message sent, You are logged-in, etc. */ |
---|
22 | define('MSG_SUCCESS', 1); |
---|
23 | |
---|
24 | /** @constant MSG_WARNING |
---|
25 | A warning message: Access denied, Email address invalid, Article not found, etc. */ |
---|
26 | define('MSG_WARNING', 2); |
---|
27 | |
---|
28 | /** @constant MSG_ERR |
---|
29 | Unrecoverable failure: Message could not be sent, File not found, etc. */ |
---|
30 | define('MSG_ERR', 4); // PHP user error style. |
---|
31 | define('MSG_ERROR', 4); |
---|
32 | |
---|
33 | |
---|
34 | |
---|
35 | /****************************************************************************** |
---|
36 | * FUNCTIONS |
---|
37 | ****************************************************************************** |
---|
38 | |
---|
39 | /** |
---|
40 | * Add a message to the string globalmessage, which is printed in the header. |
---|
41 | * Just a simple way to print messages to the user. |
---|
42 | * |
---|
43 | * @access public |
---|
44 | * |
---|
45 | * @param string $message The text description of the message. |
---|
46 | * @param int $type The type of message: MSG_NOTICE, |
---|
47 | * MSG_SUCCESS, MSG_WARNING, or MSG_ERR. |
---|
48 | * @param string $file __FILE__. |
---|
49 | * @param string $line __LINE__. |
---|
50 | */ |
---|
51 | function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null) |
---|
52 | { |
---|
53 | $_SESSION['_messages'][] = array( |
---|
54 | 'type' => $type, |
---|
55 | 'message' => $message, |
---|
56 | 'file' => $file, |
---|
57 | 'line' => $line |
---|
58 | ); |
---|
59 | } |
---|
60 | |
---|
61 | /** |
---|
62 | * Logs a message to a user defined log file. Additional actions to take for |
---|
63 | * different types of message types can be specified (ERROR, NOTICE, etc). |
---|
64 | * |
---|
65 | * @access public |
---|
66 | * |
---|
67 | * @param string $message The text description of the message. |
---|
68 | * @param int $priority The type of message priority (in descending order): |
---|
69 | * LOG_EMERG system is unusable |
---|
70 | * LOG_ALERT action must be taken immediately |
---|
71 | * LOG_CRIT critical conditions |
---|
72 | * LOG_ERR error conditions |
---|
73 | * LOG_WARNING warning conditions |
---|
74 | * LOG_NOTICE normal, but significant, condition |
---|
75 | * LOG_INFO informational message |
---|
76 | * LOG_DEBUG debug-level message |
---|
77 | * @param string $file The file where the log event occurs. |
---|
78 | * @param string $line The line of the file where the log event occurs. |
---|
79 | */ |
---|
80 | function logMsg($message, $priority=LOG_INFO, $file=null, $line=null) |
---|
81 | { |
---|
82 | global $CFG; |
---|
83 | static $previous_events = array(); |
---|
84 | |
---|
85 | // If priority is not specified, assume the worst. |
---|
86 | if (!priorityToString($priority)) { |
---|
87 | logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line); |
---|
88 | $priority = LOG_EMERG; |
---|
89 | } |
---|
90 | |
---|
91 | // If log file is not specified, create one in the codebase root. |
---|
92 | if (!is_dir($CFG->log_directory) || !is_writable($CFG->log_directory)) { |
---|
93 | // We must use trigger_error rather than calling logMsg, which might lead to an infinite loop. |
---|
94 | trigger_error(sprintf('Codebase error: log directory not found or writable: %s', $CFG->log_directory), E_USER_NOTICE); |
---|
95 | $CFG->log_directory = '/tmp'; |
---|
96 | $CFG->log_filename = sprintf('%s_%s.log', getenv('USER'), getenv('HTTP_HOST')); |
---|
97 | } |
---|
98 | |
---|
99 | // In case __FILE__ and __LINE__ are not provided, note that fact. |
---|
100 | $file = '' == $file ? 'unknown-file' : $file; |
---|
101 | $line = '' == $line ? 'unknown-line' : $line; |
---|
102 | |
---|
103 | // Strip HTML tags except any with more than 7 characters because that's probably not a HTML tag, e.g. <email@address.com>. |
---|
104 | preg_match_all('/(<[^>\s]{7,})[^>]*>/', $message, $strip_tags_allow); |
---|
105 | $message = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null)); |
---|
106 | |
---|
107 | // Serialize multi-line messages. |
---|
108 | $message = preg_replace('/\s+/m', ' ', trim($message)); |
---|
109 | |
---|
110 | // Store this event under a unique key, counting each time it occurs so that it only gets reported a limited number of times. |
---|
111 | $msg_id = md5($message . $priority . $file . $line); |
---|
112 | if ($CFG->log_ignore_repeated_events && isset($previous_events[$msg_id])) { |
---|
113 | $previous_events[$msg_id]++; |
---|
114 | if ($previous_events[$msg_id] == 2) { |
---|
115 | logMsg(sprintf('%s (Event repeated %s or more times)', $message, $previous_events[$msg_id]), $priority, $file, $line); |
---|
116 | } |
---|
117 | return false; |
---|
118 | } else { |
---|
119 | $previous_events[$msg_id] = 1; |
---|
120 | } |
---|
121 | |
---|
122 | // Make sure to log in the system's locale. |
---|
123 | $locale = setlocale(LC_TIME, 0); |
---|
124 | setlocale(LC_TIME, 'C'); |
---|
125 | |
---|
126 | // Data to be stored for a log event. |
---|
127 | $event = array( |
---|
128 | 'date' => date('Y-m-d H:i:s'), |
---|
129 | 'remote ip' => getRemoteAddr(), |
---|
130 | 'pid' => getmypid(), |
---|
131 | 'type' => priorityToString($priority), |
---|
132 | 'file:line' => "$file : $line", |
---|
133 | 'url' => (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''), |
---|
134 | 'message' => $message |
---|
135 | ); |
---|
136 | // Here's a shortened version of event data. |
---|
137 | $event_short = $event; |
---|
138 | $event_short['url'] = truncate($event_short['url'], 120); |
---|
139 | |
---|
140 | // Restore original locale. |
---|
141 | setlocale(LC_TIME, $locale); |
---|
142 | |
---|
143 | // FILE ACTION |
---|
144 | if ($CFG->log_file_priority && $priority <= $CFG->log_file_priority) { |
---|
145 | $event_str = '[' . join('] [', $event_short) . ']'; |
---|
146 | error_log($event_str . "\n", 3, $CFG->log_directory . '/' . $CFG->log_filename); |
---|
147 | } |
---|
148 | |
---|
149 | // EMAIL ACTION |
---|
150 | if ($CFG->log_email_priority && $priority <= $CFG->log_email_priority) { |
---|
151 | if (empty($CFG->log_to_email)) { |
---|
152 | $CFG->log_to_email = 'bug@strangecode.com'; |
---|
153 | } |
---|
154 | $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n'); |
---|
155 | $subject = sprintf('[%s %s] %s', $hostname, $event['type'], mb_substr($event['message'], 0, 64)); |
---|
156 | $email_msg = sprintf("A log event of type '%s' occurred on %s\n\n", $event['type'], $hostname); |
---|
157 | $headers = "From: codebase@strangecode.com\r\n"; |
---|
158 | foreach ($event as $k=>$v) { |
---|
159 | $email_msg .= sprintf("%-11s%s\n", $k, $v); |
---|
160 | } |
---|
161 | mb_send_mail($CFG->log_to_email, $subject, $email_msg, $headers, '-f codebase@strangecode.com'); |
---|
162 | } |
---|
163 | |
---|
164 | // SMS ACTION |
---|
165 | if ($CFG->log_sms_priority && $priority <= $CFG->log_sms_priority) { |
---|
166 | if (empty($CFG->log_to_email)) { |
---|
167 | $CFG->log_to_sms = 'bug@strangecode.com'; |
---|
168 | } |
---|
169 | $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n'); |
---|
170 | $subject = sprintf('[%s %s]', $hostname, $priority); |
---|
171 | $sms_msg = sprintf('%s [%s:%s]', mb_substr($event_short['message'], 0, 64), basename($file), $line); |
---|
172 | $headers = 'From: ' . $CFG->site_email; |
---|
173 | mb_send_mail($CFG->log_to_sms, $subject, $sms_msg, $headers); |
---|
174 | } |
---|
175 | |
---|
176 | // SCREEN ACTION |
---|
177 | if ($CFG->log_screen_priority && $priority <= $CFG->log_screen_priority) { |
---|
178 | echo "[{$event['date']}] [{$event['type']}] [{$event['file:line']}] [{$event['message']}]\n"; |
---|
179 | } |
---|
180 | } |
---|
181 | |
---|
182 | /** |
---|
183 | * Returns the string representation of a LOG_* integer constant. |
---|
184 | * |
---|
185 | * @param int $priority The LOG_* integer constant. |
---|
186 | * |
---|
187 | * @return The string representation of $priority. |
---|
188 | */ |
---|
189 | function priorityToString ($priority) { |
---|
190 | $priorities = array( |
---|
191 | LOG_EMERG => 'emergency', |
---|
192 | LOG_ALERT => 'alert', |
---|
193 | LOG_CRIT => 'critical', |
---|
194 | LOG_ERR => 'error', |
---|
195 | LOG_WARNING => 'warning', |
---|
196 | LOG_NOTICE => 'notice', |
---|
197 | LOG_INFO => 'info', |
---|
198 | LOG_DEBUG => 'debug' |
---|
199 | ); |
---|
200 | if (isset($priorities[$priority])) { |
---|
201 | return $priorities[$priority]; |
---|
202 | } else { |
---|
203 | return false; |
---|
204 | } |
---|
205 | } |
---|
206 | |
---|
207 | /** |
---|
208 | * Set the URL to return to when dieBoomerangURL() is called. |
---|
209 | * |
---|
210 | * @param string $url A fully validated URL. |
---|
211 | * @param bool $id An identification tag for this url. |
---|
212 | * FIXME: url garbage collection? |
---|
213 | */ |
---|
214 | function setBoomerangURL($url=null, $id=null) |
---|
215 | { |
---|
216 | // A redirection will never happen immediately after setting the boomerangURL. |
---|
217 | // Set the time so ensure this doesn't happen. See validBoomerangURL for more. |
---|
218 | |
---|
219 | if (isset($url) && is_string($url)) { |
---|
220 | // Delete any boomerang request keys in the query string (along with any trailing delimiters after the deletion). |
---|
221 | $url = preg_replace(array('/([&?])boomerang=[^&?]+[&?]?/', '/[&?]$/'), array('$1', ''), $url); |
---|
222 | |
---|
223 | if (isset($_SESSION['_boomerang']['url']) && is_array($_SESSION['_boomerang']['url']) && !empty($_SESSION['_boomerang']['url'])) { |
---|
224 | // If the URL currently exists in the boomerang array, delete. |
---|
225 | while ($existing_key = array_search($url, $_SESSION['_boomerang']['url'])) { |
---|
226 | unset($_SESSION['_boomerang']['url'][$existing_key]); |
---|
227 | } |
---|
228 | } |
---|
229 | |
---|
230 | if (isset($id)) { |
---|
231 | $_SESSION['_boomerang']['url'][$id] = $url; |
---|
232 | } else { |
---|
233 | $_SESSION['_boomerang']['url'][] = $url; |
---|
234 | } |
---|
235 | logMsg(sprintf('setBoomerangURL added URL %s to session %s=%s', $url, session_name(), session_id()), LOG_DEBUG, __FILE__, __LINE__); |
---|
236 | return true; |
---|
237 | } else { |
---|
238 | return false; |
---|
239 | } |
---|
240 | } |
---|
241 | |
---|
242 | /** |
---|
243 | * Return the URL set for the specified $id. |
---|
244 | * |
---|
245 | * @param string $id An identification tag for this url. |
---|
246 | */ |
---|
247 | function getBoomerangURL($id=null) |
---|
248 | { |
---|
249 | if (isset($id)) { |
---|
250 | if (isset($_SESSION['_boomerang']['url'][$id])) { |
---|
251 | return $_SESSION['_boomerang']['url'][$id]; |
---|
252 | } else { |
---|
253 | return ''; |
---|
254 | } |
---|
255 | } else if (is_array($_SESSION['_boomerang']['url'])) { |
---|
256 | return end($_SESSION['_boomerang']['url']); |
---|
257 | } else { |
---|
258 | return false; |
---|
259 | } |
---|
260 | } |
---|
261 | |
---|
262 | /** |
---|
263 | * Delete the URL set for the specified $id. |
---|
264 | * |
---|
265 | * @param string $id An identification tag for this url. |
---|
266 | */ |
---|
267 | function deleteBoomerangURL($id=null) |
---|
268 | { |
---|
269 | if (isset($id) && isset($_SESSION['_boomerang']['url'][$id])) { |
---|
270 | unset($_SESSION['_boomerang']['url'][$id]); |
---|
271 | } else if (is_array($_SESSION['_boomerang']['url'])) { |
---|
272 | array_pop($_SESSION['_boomerang']['url']); |
---|
273 | } |
---|
274 | } |
---|
275 | |
---|
276 | /** |
---|
277 | * Check if a valid boomerang URL value has been set. |
---|
278 | * if it is not the current url, and has not been accessed within n seconds. |
---|
279 | * |
---|
280 | * @return bool True if it is set and not the current URL. |
---|
281 | */ |
---|
282 | function validBoomerangURL($id=null, $use_nonspecific_boomerang=false) |
---|
283 | { |
---|
284 | if (!isset($_SESSION['_boomerang']['url'])) { |
---|
285 | logMsg(sprintf('validBoomerangURL no URL set in session %s=%s', session_name(), session_id()), LOG_DEBUG, __FILE__, __LINE__); |
---|
286 | return false; |
---|
287 | } |
---|
288 | |
---|
289 | // Time is the timestamp of a boomerangURL redirection, or setting of a boomerangURL. |
---|
290 | // a boomerang redirection will always occur at least several seconds after the last boomerang redirect |
---|
291 | // or a boomerang being set. |
---|
292 | $boomerang_time = isset($_SESSION['_boomerang']['time']) ? $_SESSION['_boomerang']['time'] : 0; |
---|
293 | |
---|
294 | if (isset($id) && isset($_SESSION['_boomerang']['url'][$id])) { |
---|
295 | $url = $_SESSION['_boomerang']['url'][$id]; |
---|
296 | } else if (!isset($id) || $use_nonspecific_boomerang) { |
---|
297 | // Use non specific boomerang if available. |
---|
298 | $url = end($_SESSION['_boomerang']['url']); |
---|
299 | } else { |
---|
300 | // If URL is not specified, use the $CFG->redirect_home config value. |
---|
301 | $url = $CFG->redirect_home; |
---|
302 | } |
---|
303 | |
---|
304 | logMsg(sprintf('validBoomerangURL testing url: %s', $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
305 | if (empty($url)) { |
---|
306 | return false; |
---|
307 | } |
---|
308 | if ($url == absoluteMe()) { |
---|
309 | // The URL we are directing to is not the current page. |
---|
310 | logMsg(sprintf('Boomerang URL not valid, same as absoluteMe: %s', $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
311 | return false; |
---|
312 | } |
---|
313 | if ($boomerang_time >= (time() - 2)) { |
---|
314 | // Last boomerang direction was more than 2 seconds ago. |
---|
315 | logMsg(sprintf('Boomerang URL not valid, boomerang_time too short: %s', time() - $boomerang_time), LOG_DEBUG, __FILE__, __LINE__); |
---|
316 | return false; |
---|
317 | } |
---|
318 | |
---|
319 | return true; |
---|
320 | } |
---|
321 | |
---|
322 | /* |
---|
323 | * Redirects a user by calling App::dieURL(). It will use: |
---|
324 | * 1. the stored boomerang URL, it it exists |
---|
325 | * 2. a specified $default_url, it it exists |
---|
326 | * 3. the referring URL, it it exists. |
---|
327 | * 4. redirect_home_url configuration variable. |
---|
328 | * |
---|
329 | * @access public |
---|
330 | * @param string $id Identifier for this script. |
---|
331 | * @param mixed $carry_args Additional arguments to carry in the URL automatically (see App::oHREF()). |
---|
332 | * @param string $default_url A default URL if there is not a valid specified boomerang URL. |
---|
333 | * @return bool False if the session is not running. No return otherwise. |
---|
334 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
335 | * @since 31 Mar 2006 19:17:00 |
---|
336 | */ |
---|
337 | function dieBoomerangURL($id=null, $carry_args=null, $default_url=null) |
---|
338 | { |
---|
339 | // Get URL from stored boomerang. Allow non specific URL if ID not valid. |
---|
340 | if (validBoomerangURL($id, true)) { |
---|
341 | if (isset($id) && isset($_SESSION['_boomerang']['url'][$id])) { |
---|
342 | $url = $_SESSION['_boomerang']['url'][$id]; |
---|
343 | } else { |
---|
344 | $url = end($_SESSION['_boomerang']['url']); |
---|
345 | } |
---|
346 | } else if (isset($default_url)) { |
---|
347 | $url = $default_url; |
---|
348 | } else if (!refererIsMe()) { |
---|
349 | // Ensure that the redirecting page is not also the referrer. |
---|
350 | $url = getenv('HTTP_REFERER'); |
---|
351 | } else { |
---|
352 | $url = ''; |
---|
353 | } |
---|
354 | |
---|
355 | logMsg(sprintf('dieBoomerangURL found URL: %s', $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
356 | |
---|
357 | // Delete stored boomerang. |
---|
358 | deleteBoomerangURL($id); |
---|
359 | |
---|
360 | // A redirection will never happen immediately twice. |
---|
361 | // Set the time so ensure this doesn't happen. |
---|
362 | $_SESSION['_boomerang']['time'] = time(); |
---|
363 | dieURL($url, $carry_args); |
---|
364 | } |
---|
365 | |
---|
366 | /** |
---|
367 | * Uses an http header to redirect the client to the given $url. If sessions are not used |
---|
368 | * and the session is not already defined in the given $url, the SID is appended as a URI query. |
---|
369 | * As with all header generating functions, make sure this is called before any other output. |
---|
370 | * |
---|
371 | * @param string $url The URL the client will be redirected to. |
---|
372 | * @param mixed $carry_args Additional url arguments to carry in the query, |
---|
373 | * or FALSE to prevent carrying queries. Can be any of the following formats: |
---|
374 | * -array('key1', key2', key3') <-- to save these keys if in the form data. |
---|
375 | * -array('key1'=>'value', key2'='value') <-- to set keys to default values if not present in form data. |
---|
376 | * -false <-- To not carry any queries. If URL already has queries those will be retained. |
---|
377 | * @param bool $always_include_sid Force session id to be added to Location header. |
---|
378 | */ |
---|
379 | function dieURL($url, $carry_args=null, $always_include_sid=false) |
---|
380 | { |
---|
381 | global $CFG; |
---|
382 | |
---|
383 | if ('' == $url) { |
---|
384 | // If URL is not specified, use the redirect_home. |
---|
385 | $url = $CFG->redirect_home; |
---|
386 | } |
---|
387 | |
---|
388 | if (preg_match('!^/!', $url)) { |
---|
389 | // If relative URL is given, prepend correct local hostname. |
---|
390 | $hostname = ('on' == getenv('HTTPS')) ? 'https://' . getenv('HTTP_HOST') : 'http://' . getenv('HTTP_HOST'); |
---|
391 | $url = $hostname . $url; |
---|
392 | } |
---|
393 | |
---|
394 | $url = url($url, $carry_args, $always_include_sid); |
---|
395 | |
---|
396 | header(sprintf('Location: %s', $url)); |
---|
397 | logMsg(sprintf('dieURL dying to URL: %s', $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
398 | die; |
---|
399 | } |
---|
400 | |
---|
401 | /** |
---|
402 | * Prints a hidden form element with the PHPSESSID when cookies are not used, as well |
---|
403 | * as hidden form elements for GET_VARS that might be in use. |
---|
404 | * |
---|
405 | * @global string $carry_queries An array of keys to define which values to |
---|
406 | * carry through from the POST or GET. |
---|
407 | * $carry_queries = array('qry'); for example |
---|
408 | * |
---|
409 | * @param mixed $carry_args Additional url arguments to carry in the query, |
---|
410 | * or FALSE to prevent carrying queries. Can be any of the following formats: |
---|
411 | * -array('key1', key2', key3') <-- to save these keys if in the form data. |
---|
412 | * -array('key1'=>'value', key2'='value') <-- to set keys to default values if not present in form data. |
---|
413 | * -false <-- To not carry any queries. If URL already has queries those will be retained. |
---|
414 | */ |
---|
415 | function printHiddenSession($carry_args=null, $include_csrf_token=false) |
---|
416 | { |
---|
417 | static $_using_trans_sid; |
---|
418 | global $carry_queries; |
---|
419 | |
---|
420 | // Save the trans_sid setting. |
---|
421 | if (!isset($_using_trans_sid)) { |
---|
422 | $_using_trans_sid = ini_get('session.use_trans_sid'); |
---|
423 | } |
---|
424 | |
---|
425 | // Initialize the carried queries. |
---|
426 | if (!isset($carry_queries['_carry_queries_init'])) { |
---|
427 | if (!is_array($carry_queries)) { |
---|
428 | $carry_queries = array($carry_queries); |
---|
429 | } |
---|
430 | $tmp = $carry_queries; |
---|
431 | $carry_queries = array(); |
---|
432 | foreach ($tmp as $key) { |
---|
433 | if (!empty($key) && getFormData($key, false)) { |
---|
434 | $carry_queries[$key] = getFormData($key); |
---|
435 | } |
---|
436 | } |
---|
437 | $carry_queries['_carry_queries_init'] = true; |
---|
438 | } |
---|
439 | |
---|
440 | // Get any additional query names to add to the $carry_queries array |
---|
441 | // that are found as function arguments. |
---|
442 | // If FALSE is a function argument, DO NOT carry the queries. |
---|
443 | $do_carry_queries = true; |
---|
444 | $one_time_carry_queries = array(); |
---|
445 | if (!is_null($carry_args)) { |
---|
446 | if (is_array($carry_args) && !empty($carry_args)) { |
---|
447 | foreach ($carry_args as $key=>$arg) { |
---|
448 | // Get query from appropriate source. |
---|
449 | if (false === $arg) { |
---|
450 | $do_carry_queries = false; |
---|
451 | } else if (false !== getFormData($arg, false)) { |
---|
452 | $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available. |
---|
453 | } else if (!is_numeric($key) && '' != $arg) { |
---|
454 | $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data). |
---|
455 | } |
---|
456 | } |
---|
457 | } else if (false !== getFormData($carry_args, false)) { |
---|
458 | $one_time_carry_queries[$carry_args] = getFormData($carry_args); |
---|
459 | } else if (false === $carry_args) { |
---|
460 | $do_carry_queries = false; |
---|
461 | } |
---|
462 | } |
---|
463 | |
---|
464 | // For each existing POST value, we create a hidden input to carry it through a form. |
---|
465 | if ($do_carry_queries) { |
---|
466 | // Join the perm and temp carry_queries and filter out the _carry_queries_init element for the final query args. |
---|
467 | $query_args = array_diff_assoc(array_merge($carry_queries, $one_time_carry_queries), array('_carry_queries_init' => true)); |
---|
468 | foreach ($query_args as $key=>$val) { |
---|
469 | echo '<input type="hidden" name="' . $key . '" value="' . $val . '" />'; |
---|
470 | } |
---|
471 | } |
---|
472 | |
---|
473 | // Include the SID if cookies are disabled. |
---|
474 | if (!isset($_COOKIE[session_name()]) && !$_using_trans_sid) { |
---|
475 | echo '<input type="hidden" name="' . session_name() . '" value="' . session_id() . '" />'; |
---|
476 | } |
---|
477 | |
---|
478 | // Include the csrf_token in the form. |
---|
479 | // This token can be validated upon form submission with $app->verifyCSRFToken() or $app->requireValidCSRFToken() |
---|
480 | if ($include_csrf_token) { |
---|
481 | printf('<input type="hidden" name="csrf_token" value="%s" />', getCSRFToken()); |
---|
482 | } |
---|
483 | } |
---|
484 | |
---|
485 | /** |
---|
486 | * Outputs a fully qualified URL with a query of all the used (ie: not empty) |
---|
487 | * keys and values, including optional queries. This allows simple printing of |
---|
488 | * links without needing to know which queries to add to it. If cookies are not |
---|
489 | * used, the session id will be propogated in the URL. |
---|
490 | * |
---|
491 | * @global string $carry_queries An array of keys to define which values to |
---|
492 | * carry through from the POST or GET. |
---|
493 | * $carry_queries = array('qry'); for example. |
---|
494 | * |
---|
495 | * @param string $url The initial url |
---|
496 | * @param mixed $carry_args Additional url arguments to carry in the query, |
---|
497 | * or FALSE to prevent carrying queries. Can be any of the following formats: |
---|
498 | * -array('key1', key2', key3') <-- to save these keys if in the form data. |
---|
499 | * -array('key1'=>'value', key2'='value') <-- to set keys to default values if not present in form data. |
---|
500 | * -false <-- To not carry any queries. If URL already has queries those will be retained. |
---|
501 | * |
---|
502 | * @param mixed $always_include_sid Always add the session id, even if using_trans_sid = true. This is required when |
---|
503 | * URL starts with http, since PHP using_trans_sid doesn't do those and also for |
---|
504 | * header('Location...') redirections. |
---|
505 | * |
---|
506 | * @return string url with attached queries and, if not using cookies, the session id |
---|
507 | */ |
---|
508 | function url($url='', $carry_args=null, $always_include_sid=false) |
---|
509 | { |
---|
510 | static $_using_trans_sid; |
---|
511 | global $carry_queries; |
---|
512 | global $CFG; |
---|
513 | |
---|
514 | // Save the trans_sid setting. |
---|
515 | if (!isset($_using_trans_sid)) { |
---|
516 | $_using_trans_sid = ini_get('session.use_trans_sid'); |
---|
517 | } |
---|
518 | |
---|
519 | // Initialize the carried queries. |
---|
520 | if (!isset($carry_queries['_carry_queries_init'])) { |
---|
521 | if (!is_array($carry_queries)) { |
---|
522 | $carry_queries = array($carry_queries); |
---|
523 | } |
---|
524 | $tmp = $carry_queries; |
---|
525 | $carry_queries = array(); |
---|
526 | foreach ($tmp as $key) { |
---|
527 | if (!empty($key) && getFormData($key, false)) { |
---|
528 | $carry_queries[$key] = getFormData($key); |
---|
529 | } |
---|
530 | } |
---|
531 | $carry_queries['_carry_queries_init'] = true; |
---|
532 | } |
---|
533 | |
---|
534 | // Get any additional query arguments to add to the $carry_queries array. |
---|
535 | // If FALSE is a function argument, DO NOT carry the queries. |
---|
536 | $do_carry_queries = true; |
---|
537 | $one_time_carry_queries = array(); |
---|
538 | if (!is_null($carry_args)) { |
---|
539 | if (is_array($carry_args) && !empty($carry_args)) { |
---|
540 | foreach ($carry_args as $key=>$arg) { |
---|
541 | // Get query from appropriate source. |
---|
542 | if (false === $arg) { |
---|
543 | $do_carry_queries = false; |
---|
544 | } else if (false !== getFormData($arg, false)) { |
---|
545 | $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available. |
---|
546 | } else if (!is_numeric($key) && '' != $arg) { |
---|
547 | $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data). |
---|
548 | } |
---|
549 | } |
---|
550 | } else if (false !== getFormData($carry_args, false)) { |
---|
551 | $one_time_carry_queries[$carry_args] = getFormData($carry_args); |
---|
552 | } else if (false === $carry_args) { |
---|
553 | $do_carry_queries = false; |
---|
554 | } |
---|
555 | } |
---|
556 | |
---|
557 | // Get the first delimiter that is needed in the url. |
---|
558 | $delim = preg_match('/\?/', $url) ? ini_get('arg_separator.output') : '?'; |
---|
559 | |
---|
560 | $q = ''; |
---|
561 | if ($do_carry_queries) { |
---|
562 | // Join the perm and temp carry_queries and filter out the _carry_queries_init element for the final query args. |
---|
563 | $query_args = array_diff_assoc(urlEncodeArray(array_merge($carry_queries, $one_time_carry_queries)), array('_carry_queries_init' => true)); |
---|
564 | foreach ($query_args as $key=>$val) { |
---|
565 | // Check value is set and value does not already exist in the url. |
---|
566 | if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) { |
---|
567 | $q .= $delim . $key . '=' . $val; |
---|
568 | $delim = ini_get('arg_separator.output'); |
---|
569 | } |
---|
570 | } |
---|
571 | } |
---|
572 | |
---|
573 | // Include the necessary SID if the following is true: |
---|
574 | // - no cookie in http request OR cookies disabled in config |
---|
575 | // - sessions are enabled |
---|
576 | // - the link stays on our site |
---|
577 | // - transparent SID propagation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here) |
---|
578 | // OR |
---|
579 | // - we must include the SID because we say so (it's used in a context where cookies will not be effective, ie. moving from http to https) |
---|
580 | // AND |
---|
581 | // - the SID is not already in the query. |
---|
582 | if ( |
---|
583 | ( |
---|
584 | ( |
---|
585 | ( |
---|
586 | !isset($_COOKIE[session_name()]) |
---|
587 | || !$CFG->session_use_cookies |
---|
588 | ) |
---|
589 | && $CFG->session_use_trans_sid |
---|
590 | && $CFG->enable_session |
---|
591 | && isMyDomain($url) |
---|
592 | && |
---|
593 | ( |
---|
594 | !$_using_trans_sid |
---|
595 | || preg_match('!^(http|https)://!i', $url) |
---|
596 | ) |
---|
597 | ) |
---|
598 | || $always_include_sid |
---|
599 | ) |
---|
600 | && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url) |
---|
601 | ) { |
---|
602 | $url .= $q . $delim . session_name() . '=' . session_id(); |
---|
603 | // logMsg(sprintf('oHREF appending session id to URL: %s', $url), LOG_DEBUG, __FILE__, __LINE__); |
---|
604 | } else { |
---|
605 | $url .= $q; |
---|
606 | } |
---|
607 | |
---|
608 | return $url; |
---|
609 | } |
---|
610 | |
---|
611 | /** |
---|
612 | * Returns a URL processed with App::url and htmlentities for printing in html. |
---|
613 | * |
---|
614 | * @access public |
---|
615 | * @param string $url Input URL to parse. |
---|
616 | * @return string URL with App::url() and htmlentities() applied. |
---|
617 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
618 | * @since 09 Dec 2005 17:58:45 |
---|
619 | */ |
---|
620 | function oHREF($url, $carry_args=null, $always_include_sid=false) |
---|
621 | { |
---|
622 | $url = url($url, $carry_args, $always_include_sid); |
---|
623 | // Replace any & not followed by an html or unicode entity with it's & equivalent. |
---|
624 | $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&', $url); |
---|
625 | return $url; |
---|
626 | } |
---|
627 | |
---|
628 | /* |
---|
629 | * Generate a csrf_token if it doesn't exist or is expired, save it to the session and return its value. |
---|
630 | * Otherwise just return the current token. |
---|
631 | * Details on the synchronizer token pattern: |
---|
632 | * https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#General_Recommendation:_Synchronizer_Token_Pattern |
---|
633 | * |
---|
634 | * @access public |
---|
635 | * @param bool $force_new_token Generate a new token, replacing any existing token in the session (used by $app->resetCSRFToken()) |
---|
636 | * @return string The new or current csrf_token |
---|
637 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
638 | * @version 1.0 |
---|
639 | * @since 15 Nov 2014 17:57:17 |
---|
640 | */ |
---|
641 | function getCSRFToken($force_new_token=false) |
---|
642 | { |
---|
643 | if ($force_new_token || !isset($_SESSION['csrf_token']) || (removeSignature($_SESSION['csrf_token']) + 86400 < time())) { |
---|
644 | // No token, or token is expired; generate one and return it. |
---|
645 | return $_SESSION['csrf_token'] = addSignature(time(), null, 64); |
---|
646 | } |
---|
647 | // Current token is not expired; return it. |
---|
648 | return $_SESSION['csrf_token']; |
---|
649 | } |
---|
650 | |
---|
651 | /* |
---|
652 | * Generate a new token, replacing any existing token in the session. Call this function after $app->requireValidCSRFToken() for a new token to be required for each request. |
---|
653 | * |
---|
654 | * @access public |
---|
655 | * @return void |
---|
656 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
657 | * @since 14 Oct 2021 17:35:19 |
---|
658 | */ |
---|
659 | function resetCSRFToken() |
---|
660 | { |
---|
661 | getCSRFToken(true); |
---|
662 | } |
---|
663 | |
---|
664 | /* |
---|
665 | * Compares the given csrf_token with the current or previous one saved in the session. |
---|
666 | * |
---|
667 | * @access public |
---|
668 | * @param string $user_submitted_csrf_token The user-submitted token to compare with the session token. |
---|
669 | * @return bool True if the tokens match, false otherwise. |
---|
670 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
671 | * @version 1.0 |
---|
672 | * @since 15 Nov 2014 18:06:55 |
---|
673 | */ |
---|
674 | function verifyCSRFToken($user_submitted_csrf_token) |
---|
675 | { |
---|
676 | |
---|
677 | if ('' == trim($user_submitted_csrf_token)) { |
---|
678 | logMsg(sprintf('Empty string failed CSRF verification.', null), LOG_NOTICE, __FILE__, __LINE__); |
---|
679 | return false; |
---|
680 | } |
---|
681 | if (!verifySignature($user_submitted_csrf_token, null, 64)) { |
---|
682 | logMsg(sprintf('Input failed CSRF verification (invalid signature in %s).', $user_submitted_csrf_token), LOG_WARNING, __FILE__, __LINE__); |
---|
683 | return false; |
---|
684 | } |
---|
685 | $csrf_token = getCSRFToken(); |
---|
686 | if ($user_submitted_csrf_token != $csrf_token) { |
---|
687 | logMsg(sprintf('Input failed CSRF verification (%s not in %s).', $user_submitted_csrf_token, $csrf_token), LOG_WARNING, __FILE__, __LINE__); |
---|
688 | return false; |
---|
689 | } |
---|
690 | logMsg(sprintf('Verified CSRF token %s', $user_submitted_csrf_token), LOG_DEBUG, __FILE__, __LINE__); |
---|
691 | return true; |
---|
692 | } |
---|
693 | |
---|
694 | /* |
---|
695 | * Bounce user if they submit a token that doesn't match the one saved in the session. |
---|
696 | * Because this function calls dieURL() it must be called before any other HTTP header output. |
---|
697 | * |
---|
698 | * @access public |
---|
699 | * @param string $message Optional message to display to the user (otherwise default message will display). Set to an empty string to display no message. |
---|
700 | * @param int $type The type of message: MSG_NOTICE, |
---|
701 | * MSG_SUCCESS, MSG_WARNING, or MSG_ERR. |
---|
702 | * @param string $file __FILE__. |
---|
703 | * @param string $line __LINE__. |
---|
704 | * @return void |
---|
705 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
706 | * @version 1.0 |
---|
707 | * @since 15 Nov 2014 18:10:17 |
---|
708 | */ |
---|
709 | function requireValidCSRFToken($message=null, $type=MSG_NOTICE, $file=null, $line=null) |
---|
710 | { |
---|
711 | if (!verifyCSRFToken(getFormData('csrf_token'))) { |
---|
712 | $message = isset($message) ? $message : _("Sorry, the form token expired. Please try again."); |
---|
713 | raiseMsg($message, $type, $file, $line); |
---|
714 | dieBoomerangURL(); |
---|
715 | } |
---|
716 | } |
---|
717 | |
---|
718 | /** |
---|
719 | * This function has changed to do nothing. SSL redirection should happen at the server layer, doing so here may result in a redirect loop. |
---|
720 | */ |
---|
721 | function sslOn() |
---|
722 | { |
---|
723 | logMsg(sprintf('sslOn was called and ignored.', null), LOG_DEBUG, __FILE__, __LINE__); |
---|
724 | } |
---|
725 | |
---|
726 | /** |
---|
727 | * This function has changed to do nothing. There is no reason to prefer a non-SSL connection, and doing so may result in a redirect loop. |
---|
728 | */ |
---|
729 | function sslOff() |
---|
730 | { |
---|
731 | logMsg(sprintf('sslOff was called and ignored.', null), LOG_DEBUG, __FILE__, __LINE__); |
---|
732 | } |
---|
733 | |
---|
734 | /** |
---|
735 | * If the given $url is on the same web site, return true. This can be used to |
---|
736 | * prevent from sending sensitive info in a get query (like the SID) to another |
---|
737 | * domain. $method can be "ip" or "domain". The domain method might be preferred |
---|
738 | * if your domain spans mutiple IP's (load sharing servers) |
---|
739 | * |
---|
740 | * @param string $url the URI to test. |
---|
741 | * @param mixed $method the method to use. Either 'domain' or 'ip'. |
---|
742 | * |
---|
743 | * @return bool true if given $url is this domain or has no domain (is a |
---|
744 | * relative url), false if it's another |
---|
745 | */ |
---|
746 | function isMyDomain($url) |
---|
747 | { |
---|
748 | if (!preg_match('|\w{1,}\.\w{2,5}/|', $url)) { |
---|
749 | // If we can't find a domain we assume the URL is relative. |
---|
750 | return true; |
---|
751 | } else { |
---|
752 | return preg_match('/' . preg_quote(getenv('HTTP_HOST')) . '/', $url); |
---|
753 | } |
---|
754 | } |
---|
755 | |
---|
756 | /** |
---|
757 | * Loads a list of tables in the current database into an array, and returns |
---|
758 | * true if the requested table is found. Use this function to enable/disable |
---|
759 | * funtionality based upon the current available db tables. |
---|
760 | * |
---|
761 | * @param string $table The name of the table to search. |
---|
762 | * |
---|
763 | * @return bool true if given $table exists. |
---|
764 | */ |
---|
765 | function dbTableExists($table) |
---|
766 | { |
---|
767 | static $existing_tables; |
---|
768 | |
---|
769 | // Save the trans_sid setting. |
---|
770 | if (!isset($existing_tables)) { |
---|
771 | // Get DB tables. |
---|
772 | $existing_tables = array(); |
---|
773 | $qid = dbQuery("SHOW TABLES"); |
---|
774 | while (list($row) = mysql_fetch_row($qid)) { |
---|
775 | $existing_tables[] = $row; |
---|
776 | } |
---|
777 | } |
---|
778 | |
---|
779 | // Test if requested table is in database. |
---|
780 | return in_array($table, $existing_tables); |
---|
781 | } |
---|
782 | |
---|
783 | /** |
---|
784 | * Takes a URL and returns it without the query or anchor portion |
---|
785 | * |
---|
786 | * @param string $url any kind of URI |
---|
787 | * |
---|
788 | * @return string the URI with ? or # and everything after removed |
---|
789 | */ |
---|
790 | function stripQuery($url) |
---|
791 | { |
---|
792 | return preg_replace('![?#].*!', '', $url); |
---|
793 | } |
---|
794 | |
---|
795 | /** |
---|
796 | * Returns the remote IP address, taking into consideration proxy servers. |
---|
797 | * |
---|
798 | * @param bool $dolookup If true we resolve to IP to a host name, |
---|
799 | * if false we don't. |
---|
800 | * |
---|
801 | * @return string IP address if $dolookup is false or no arg |
---|
802 | * Hostname if $dolookup is true |
---|
803 | */ |
---|
804 | function getRemoteAddr($dolookup=false) |
---|
805 | { |
---|
806 | $ip = getenv('HTTP_CLIENT_IP'); |
---|
807 | if (empty($ip) || $ip == 'unknown' || $ip == 'localhost' || $ip == '127.0.0.1') { |
---|
808 | $ip = getenv('HTTP_X_FORWARDED_FOR'); |
---|
809 | if (empty($ip) || $ip == 'unknown' || $ip == 'localhost' || $ip == '127.0.0.1') { |
---|
810 | $ip = getenv('REMOTE_ADDR'); |
---|
811 | } |
---|
812 | } |
---|
813 | return $dolookup && '' != $ip ? gethostbyaddr($ip) : $ip; |
---|
814 | } |
---|
815 | |
---|
816 | /** |
---|
817 | * Tests whether a given iP address can be found in an array of IP address networks. |
---|
818 | * Elements of networks array can be single IP addresses or an IP address range in CIDR notation |
---|
819 | * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing |
---|
820 | * |
---|
821 | * @access public |
---|
822 | * |
---|
823 | * @param string IP address to search for. |
---|
824 | * @param array Array of networks to search within. |
---|
825 | * |
---|
826 | * @return mixed Returns the network that matched on success, false on failure. |
---|
827 | */ |
---|
828 | function ipInRange($my_ip, $ip_pool) |
---|
829 | { |
---|
830 | if (!is_array($ip_pool)) { |
---|
831 | $ip_pool = array($ip_pool); |
---|
832 | } |
---|
833 | |
---|
834 | $my_ip_binary = sprintf('%032b', ip2long($my_ip)); |
---|
835 | foreach ($ip_pool as $ip) { |
---|
836 | if (preg_match('![\d\.]{7,15}/\d{1,2}!', $ip)) { |
---|
837 | // IP is in CIDR notation. |
---|
838 | list($cidr_ip, $cidr_bitmask) = split('/', $ip); |
---|
839 | $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip)); |
---|
840 | if (substr($my_ip_binary, 0, $cidr_bitmask) === substr($cidr_ip_binary, 0, $cidr_bitmask)) { |
---|
841 | // IP address is within the specified IP range. |
---|
842 | return $ip; |
---|
843 | } |
---|
844 | } else { |
---|
845 | if ($my_ip === $ip) { |
---|
846 | // IP address exactly matches. |
---|
847 | return $ip; |
---|
848 | } |
---|
849 | } |
---|
850 | } |
---|
851 | |
---|
852 | return false; |
---|
853 | } |
---|
854 | |
---|
855 | /** |
---|
856 | * Returns a fully qualified URL to the current script, including the query. |
---|
857 | * |
---|
858 | * @return string a full url to the current script |
---|
859 | */ |
---|
860 | function absoluteMe() |
---|
861 | { |
---|
862 | $protocol = ('on' == getenv('HTTPS')) ? 'https://' : 'http://'; |
---|
863 | return $protocol . getenv('HTTP_HOST') . getenv('REQUEST_URI'); |
---|
864 | } |
---|
865 | |
---|
866 | /** |
---|
867 | * Compares the current url with the referring url. |
---|
868 | * |
---|
869 | * @param string $compary_query Include the query string in the comparison. |
---|
870 | * |
---|
871 | * @return bool true if the current script (or specified valid_referer) |
---|
872 | * is the referrer. false otherwise. |
---|
873 | */ |
---|
874 | function refererIsMe($exclude_query=false) |
---|
875 | { |
---|
876 | if ($exclude_query) { |
---|
877 | return (stripQuery(absoluteMe()) == stripQuery(getenv('HTTP_REFERER'))); |
---|
878 | } else { |
---|
879 | return (absoluteMe() == getenv('HTTP_REFERER')); |
---|
880 | } |
---|
881 | } |
---|
882 | |
---|
883 | ?> |
---|