source: trunk/lib/App.inc.php @ 499

Last change on this file since 499 was 499, checked in by anonymous, 10 years ago

Site version file include bug

File size: 59.7 KB
RevLine 
[1]1<?php
2/**
[362]3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
[396]5 * Copyright 2001-2012 Strangecode, LLC
[452]6 *
[362]7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
[452]13 *
[362]14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
[452]18 *
[362]19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
[1]24 * App.inc.php
25 *
26 * Primary application framework class.
27 *
28 * @author  Quinn Comendant <quinn@strangecode.com>
[136]29 * @version 2.1
[1]30 */
[42]31
[37]32// Message Types.
33define('MSG_ERR', 1);
34define('MSG_ERROR', MSG_ERR);
[1]35define('MSG_WARNING', 2);
[37]36define('MSG_NOTICE', 4);
37define('MSG_SUCCESS', 8);
[119]38define('MSG_ALL', MSG_SUCCESS | MSG_NOTICE | MSG_WARNING | MSG_ERROR);
[1]39
40require_once dirname(__FILE__) . '/Utilities.inc.php';
41
42class App {
[42]43
[487]44    // Minimum version of PHP required for this version of the Codebase.
45    const CODEBASE_MIN_PHP_VERSION = '5.3.0';
46
[468]47    // A place to keep an object instance for the singleton pattern.
[484]48    protected static $instance = null;
[468]49
[136]50    // Namespace of this application instance.
[484]51    protected $_ns;
[1]52
[136]53    // If $app->start has run successfully.
[468]54    public $running = false;
[1]55
56    // Instance of database object.
[468]57    public $db;
[42]58
[20]59    // Array of query arguments will be carried persistently between requests.
[484]60    protected $_carry_queries = array();
[1]61
[136]62    // Dictionary of global application parameters.
[484]63    protected $_params = array();
[1]64
65    // Default parameters.
[484]66    protected $_param_defaults = array(
[1]67
68        // Public name and email address for this application.
69        'site_name' => null,
[390]70        'site_email' => '', // Set to no-reply@HTTP_HOST if not set here.
[39]71        'site_url' => '', // URL automatically determined by _SERVER['HTTP_HOST'] if not set here.
[318]72        'images_path' => '', // Location for codebase-generated interface widgets (ex: "/admin/i").
[491]73        'site_version_file' => 'docs/version.txt', // File containing version number of this app, relative to the include path.
[1]74
[136]75        // The location the user will go if the system doesn't know where else to send them.
[1]76        'redirect_home_url' => '/',
[42]77
[136]78        // SSL URL used when redirecting with $app->sslOn().
[1]79        'ssl_domain' => null,
80        'ssl_enabled' => false,
[42]81
[20]82        // Character set for page output. Used in the Content-Type header and the HTML <meta content-type> tag.
[1]83        'character_set' => 'utf-8',
84
85        // Human-readable format used to display dates.
86        'date_format' => 'd M Y',
[101]87        'time_format' => 'h:i:s A',
[1]88        'sql_date_format' => '%e %b %Y',
89        'sql_time_format' => '%k:%i',
90
91        // Use php sessions?
92        'enable_session' => false,
[242]93        'session_name' => '_session',
[1]94        'session_use_cookies' => true,
[452]95
[293]96        // Pass the session-id through URLs if cookies are not enabled?
97        // Disable this to prevent session ID theft.
[242]98        'session_use_trans_sid' => false,
[42]99
[1]100        // Use database?
101        'enable_db' => false,
102
103        // Use db-based sessions?
104        'enable_db_session_handler' => false,
[42]105
[1]106        // DB passwords should be set as apache environment variables in httpd.conf, readable only by root.
107        'db_server' => 'localhost',
108        'db_name' => null,
109        'db_user' => null,
110        'db_pass' => null,
111
112        // Database debugging.
113        'db_always_debug' => false, // TRUE = display all SQL queries.
114        'db_debug' => false, // TRUE = display db errors.
115        'db_die_on_failure' => false, // TRUE = script stops on db error.
[42]116
[1]117        // For classes that require db tables, do we check that a table exists and create if missing?
[32]118        'db_create_tables' => true,
[1]119
[136]120        // The level of error reporting. Don't change this to suppress messages, instead use display_errors to control display.
[1]121        'error_reporting' => E_ALL,
122
123        // Don't display errors by default; it is preferable to log them to a file.
124        'display_errors' => false,
[42]125
[1]126        // Directory in which to store log files.
[19]127        'log_directory' => '',
[1]128
129        // PHP error log.
130        'php_error_log' => 'php_error_log',
131
132        // General application log.
[136]133        'log_filename' => 'app_log',
[1]134
[390]135        // Don't email or SMS duplicate messages that happen more often than this value (in seconds).
136        'log_multiple_timeout' => 3600, // Hourly
[341]137
[1]138        // Logging priority can be any of the following, or false to deactivate:
139        // LOG_EMERG     system is unusable
140        // LOG_ALERT     action must be taken immediately
141        // LOG_CRIT      critical conditions
142        // LOG_ERR       error conditions
143        // LOG_WARNING   warning conditions
144        // LOG_NOTICE    normal, but significant, condition
145        // LOG_INFO      informational message
146        // LOG_DEBUG     debug-level message
[174]147        'log_file_priority' => LOG_INFO,
[342]148        'log_email_priority' => false,
[1]149        'log_sms_priority' => false,
150        'log_screen_priority' => false,
[42]151
[390]152        // Email address to receive log event emails. Use multiple addresses by separating them with commas.
[342]153        'log_to_email_address' => null,
[42]154
[392]155        // SMS Email address to receive log event SMS messages. Use multiple addresses by separating them with commas.
[1]156        'log_to_sms_address' => null,
[42]157
[406]158        // Should we avoid logging repeated logMsg() events? You might want to set this false if you need to see more accurate logging, particularly for long-running scripts.
159        'log_ignore_repeated_events' => true,
160
[348]161        // Temporary files directory.
162        'tmp_dir' => '/tmp',
[343]163
[19]164        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
[136]165        // Existing password hashes rely on the same key/salt being used to compare encryptions.
166        // Don't change this unless you know existing hashes or signatures will not be affected!
[1]167        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
168    );
[42]169
[1]170    /**
171     * Constructor.
172     */
[468]173    public function __construct($namespace='')
[1]174    {
[136]175        // Set namespace of application instance.
[154]176        $this->_ns = $namespace;
[42]177
[1]178        // Initialize default parameters.
179        $this->_params = array_merge($this->_params, $this->_param_defaults);
[452]180
[172]181        // Begin timing script.
182        require_once dirname(__FILE__) . '/ScriptTimer.inc.php';
183        $this->timer = new ScriptTimer();
184        $this->timer->start('_app');
[1]185    }
186
187    /**
[468]188     * This method enforces the singleton pattern for this class. Only one application is running at a time.
189     *
190     * $param   string  $namespace  Name of this application.
191     * @return  object  Reference to the global Cache object.
192     * @access  public
193     * @static
194     */
195    public static function &getInstance($namespace='')
196    {
197        if (self::$instance === null) {
198            // TODO: Yep, having a namespace with one singletone instance is not very useful.
199            self::$instance = new self($namespace);
200        }
201
202        return self::$instance;
203    }
204
205    /**
[1]206     * Set (or overwrite existing) parameters by passing an array of new parameters.
207     *
208     * @access public
209     * @param  array    $param     Array of parameters (key => val pairs).
210     */
[468]211    public function setParam($param=null)
[1]212    {
213        if (isset($param) && is_array($param)) {
214            // Merge new parameters with old overriding only those passed.
[136]215            $this->_params = array_merge($this->_params, $param);
[1]216        }
217    }
218
219    /**
220     * Return the value of a parameter.
221     *
222     * @access  public
223     * @param   string  $param      The key of the parameter to return.
224     * @return  mixed               Parameter value, or null if not existing.
225     */
[468]226    public function getParam($param=null)
[1]227    {
228        if ($param === null) {
[136]229            return $this->_params;
[478]230        } else if (array_key_exists($param, $this->_params)) {
[136]231            return $this->_params[$param];
[1]232        } else {
233            return null;
234        }
235    }
[42]236
[1]237    /**
238     * Begin running this application.
239     *
240     * @access  public
241     * @author  Quinn Comendant <quinn@strangecode.com>
242     * @since   15 Jul 2005 00:32:21
243     */
[468]244    public function start()
[1]245    {
246        if ($this->running) {
247            return false;
248        }
[42]249
[1]250        // Error reporting.
251        ini_set('error_reporting', $this->getParam('error_reporting'));
252        ini_set('display_errors', $this->getParam('display_errors'));
253        ini_set('log_errors', true);
254        if (is_dir($this->getParam('log_directory')) && is_writable($this->getParam('log_directory'))) {
255            ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log'));
256        }
[42]257
[248]258        // Set character set to use for multi-byte string functions.
259        mb_internal_encoding($this->getParam('character_set'));
[249]260        switch (mb_strtolower($this->getParam('character_set'))) {
261        case 'utf-8' :
262            mb_language('uni');
263            break;
[42]264
[249]265        case 'iso-2022-jp' :
266            mb_language('ja');
267            break;
268
269        case 'iso-8859-1' :
270        default :
271            mb_language('en');
272            break;
273        }
274
[1]275        /**
276         * 1. Start Database.
277         */
[42]278
[103]279        if (true === $this->getParam('enable_db')) {
[42]280
[1]281            // DB connection parameters taken from environment variables in the httpd.conf file, readable only by root.
[468]282            if (!empty($_SERVER['DB_SERVER']) && !$this->getParam('db_server')) {
[1]283                $this->setParam(array('db_server' => $_SERVER['DB_SERVER']));
284            }
[468]285            if (!empty($_SERVER['DB_NAME']) && !$this->getParam('db_name')) {
[1]286                $this->setParam(array('db_name' => $_SERVER['DB_NAME']));
287            }
[468]288            if (!empty($_SERVER['DB_USER']) && !$this->getParam('db_user')) {
[1]289                $this->setParam(array('db_user' => $_SERVER['DB_USER']));
290            }
[468]291            if (!empty($_SERVER['DB_PASS']) && !$this->getParam('db_pass')) {
[1]292                $this->setParam(array('db_pass' => $_SERVER['DB_PASS']));
293            }
[42]294
[136]295            // There will ever only be one instance of the DB object, and here is where it is instantiated.
[1]296            require_once dirname(__FILE__) . '/DB.inc.php';
297            $this->db =& DB::getInstance();
298            $this->db->setParam(array(
299                'db_server' => $this->getParam('db_server'),
300                'db_name' => $this->getParam('db_name'),
301                'db_user' => $this->getParam('db_user'),
302                'db_pass' => $this->getParam('db_pass'),
303                'db_always_debug' => $this->getParam('db_always_debug'),
304                'db_debug' => $this->getParam('db_debug'),
305                'db_die_on_failure' => $this->getParam('db_die_on_failure'),
306            ));
307
308            // Connect to database.
309            $this->db->connect();
310        }
[42]311
312
[1]313        /**
314         * 2. Start PHP session.
315         */
[42]316
[433]317        // Skip sessions if disabled or automatically skip if run in a CLI script.
318        if (true === $this->getParam('enable_session') && !defined('_CLI')) {
[42]319
[373]320            // Session parameters.
321            ini_set('session.gc_probability', 1);
322            ini_set('session.gc_divisor', 1000);
323            ini_set('session.gc_maxlifetime', 43200); // 12 hours
324            ini_set('session.use_cookies', $this->getParam('session_use_cookies'));
325            ini_set('session.use_trans_sid', false);
326            ini_set('session.entropy_file', '/dev/urandom');
327            ini_set('session.entropy_length', '512');
[410]328            ini_set('session.cookie_httponly', true);
[373]329            session_name($this->getParam('session_name'));
330
[1]331            if (true === $this->getParam('enable_db_session_handler') && true === $this->getParam('enable_db')) {
332                // Database session handling.
333                require_once dirname(__FILE__) . '/DBSessionHandler.inc.php';
334                $db_save_handler = new DBSessionHandler($this->db, array(
335                    'db_table' => 'session_tbl',
336                    'create_table' => $this->getParam('db_create_tables'),
337                ));
338            }
[42]339
[22]340            // Start the session.
[1]341            session_start();
[42]342
[154]343            if (!isset($_SESSION['_app'][$this->_ns])) {
[22]344                // Access session data using: $_SESSION['...'].
345                // Initialize here _after_ session has started.
[154]346                $_SESSION['_app'][$this->_ns] = array(
[22]347                    'messages' => array(),
348                    'boomerang' => array('url'),
349                );
350            }
[1]351        }
[42]352
353
[1]354        /**
355         * 3. Misc setup.
356         */
357
358        // Script URI will be something like http://host.name.tld (no ending slash)
359        // and is used whenever a URL need be used to the current site.
360        // Not available on cli scripts obviously.
[41]361        if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_url')) {
[14]362            $this->setParam(array('site_url' => sprintf('%s://%s', ('on' == getenv('HTTPS') ? 'https' : 'http'), getenv('HTTP_HOST'))));
[1]363        }
[452]364
[390]365        // In case site_email isn't set, use something halfway presentable.
366        if (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST'] && '' == $this->getParam('site_email')) {
367            $this->setParam(array('site_email' => sprintf('no-reply@%s', getenv('HTTP_HOST'))));
368        }
[1]369
370        // A key for calculating simple cryptographic signatures.
371        if (isset($_SERVER['SIGNING_KEY'])) {
372            $this->setParam(array('signing_key' => $_SERVER['SIGNING_KEY']));
373        }
[42]374
[1]375        // Character set. This should also be printed in the html header template.
[476]376        if (!defined('_CLI')) {
377            header('Content-type: text/html; charset=' . $this->getParam('character_set'));
378        }
[452]379
[136]380        // Set the version of the codebase we're using.
381        $codebase_version_file = dirname(__FILE__) . '/../docs/version.txt';
[487]382        $codebase_version = '';
[491]383        if (is_readable($codebase_version_file) && !is_dir($codebase_version_file)) {
[136]384            $codebase_version = trim(file_get_contents($codebase_version_file));
[144]385            $this->setParam(array('codebase_version' => $codebase_version));
[476]386            if (!defined('_CLI')) {
387                header('X-Codebase-Version: ' . $codebase_version);
388            }
[136]389        }
[42]390
[487]391        if (version_compare(PHP_VERSION, self::CODEBASE_MIN_PHP_VERSION, '<')) {
392            $this->logMsg(sprintf('PHP %s required for Codebase %s, using %s; some things will break.', self::CODEBASE_MIN_PHP_VERSION, $codebase_version, PHP_VERSION), LOG_NOTICE, __FILE__, __LINE__);
393        }
394
[491]395        // Set the application version if defined.
[499]396        if (false !== stream_resolve_include_path($this->getParam('site_version_file'))) {
[491]397            $site_version = trim(file_get_contents($this->getParam('site_version_file'), true));
[499]398            $this->setParam(array('site_version' => $site_version));
399            if (!defined('_CLI')) {
400                header('X-Site-Version: ' . $site_version);
401            }
[491]402        }
403
[1]404        $this->running = true;
405    }
[42]406
[1]407    /**
408     * Stop running this application.
409     *
410     * @access  public
411     * @author  Quinn Comendant <quinn@strangecode.com>
412     * @since   17 Jul 2005 17:20:18
413     */
[468]414    public function stop()
[1]415    {
416        session_write_close();
417        $this->running = false;
[172]418        $num_queries = 0;
[103]419        if (true === $this->getParam('enable_db')) {
[172]420            $num_queries = $this->db->numQueries();
[103]421            $this->db->close();
422        }
[452]423        $mem_current = memory_get_usage();
424        $mem_peak = memory_get_peak_usage();
[172]425        $this->timer->stop('_app');
[452]426        $this->logMsg(sprintf('Script ended gracefully. Execution time: %s. Number of db queries: %s. Memory usage: %s. Peak memory: %s.', $this->timer->getTime('_app'), $num_queries, $mem_current, $mem_peak), LOG_DEBUG, __FILE__, __LINE__);
[1]427    }
[42]428
429
[1]430    /**
[84]431     * Add a message to the session, which is printed in the header.
[1]432     * Just a simple way to print messages to the user.
433     *
434     * @access public
435     *
436     * @param string $message The text description of the message.
437     * @param int    $type    The type of message: MSG_NOTICE,
438     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
439     * @param string $file    __FILE__.
440     * @param string $line    __LINE__.
441     */
[468]442    public function raiseMsg($message, $type=MSG_NOTICE, $file=null, $line=null)
[1]443    {
[32]444        $message = trim($message);
[1]445
[203]446        if (!$this->running) {
447            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
[1]448            return false;
449        }
[42]450
[203]451        if ('' == trim($message)) {
452            $this->logMsg(sprintf('Raised message is an empty string.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
453            return false;
454        }
[452]455
[406]456        // Avoid duplicate full-stops..
457        $message = trim(preg_replace('/\.{2}$/', '.', $message));
[203]458
[37]459        // Save message in session under unique key to avoid duplicate messages.
[177]460        $msg_id = md5($type . $message);
461        if (!isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id])) {
462            $_SESSION['_app'][$this->_ns]['messages'][$msg_id] = array(
463                'type'    => $type,
464                'message' => $message,
465                'file'    => $file,
466                'line'    => $line,
467                'count'   => (isset($_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) ? (1 + $_SESSION['_app'][$this->_ns]['messages'][$msg_id]['count']) : 1)
468            );
469        }
[42]470
[1]471        if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) {
[136]472            $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_NOTICE, __FILE__, __LINE__);
[1]473        }
474    }
[452]475
[46]476    /**
477     * Returns an array of the raised messages.
478     *
479     * @access  public
[334]480     * @return  array   List of messages in FIFO order.
[46]481     * @author  Quinn Comendant <quinn@strangecode.com>
482     * @since   21 Dec 2005 13:09:20
483     */
[468]484    public function getRaisedMessages()
[46]485    {
[136]486        if (!$this->running) {
487            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
488            return false;
[46]489        }
[154]490        return isset($_SESSION['_app'][$this->_ns]['messages']) ? $_SESSION['_app'][$this->_ns]['messages'] : array();
[46]491    }
[452]492
[1]493    /**
[46]494     * Resets the message list.
495     *
496     * @access  public
497     * @author  Quinn Comendant <quinn@strangecode.com>
498     * @since   21 Dec 2005 13:21:54
499     */
[468]500    public function clearRaisedMessages()
[46]501    {
[136]502        if (!$this->running) {
503            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
[46]504            return false;
505        }
[452]506
[154]507        $_SESSION['_app'][$this->_ns]['messages'] = array();
[46]508    }
509
510    /**
[1]511     * Prints the HTML for displaying raised messages.
512     *
[413]513     * @param   string  $above    Additional message to print above error messages (e.g. "Oops!").
514     * @param   string  $below    Additional message to print below error messages (e.g. "Please fix and resubmit").
515     * @param   string  $print_gotohash_js  Print a line of javascript that scrolls the browser window down to view any error messages.
516     * @param   string  $hash     The #hashtag to scroll to.
[1]517     * @access  public
518     * @author  Quinn Comendant <quinn@strangecode.com>
519     * @since   15 Jul 2005 01:39:14
520     */
[468]521    public function printRaisedMessages($above='', $below='', $print_gotohash_js=false, $hash='sc-msg')
[1]522    {
[468]523
[136]524        if (!$this->running) {
525            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
[1]526            return false;
527        }
[452]528
[136]529        $messages = $this->getRaisedMessages();
[167]530        if (!empty($messages)) {
[163]531            ?><div id="sc-msg" class="sc-msg"><?php
[413]532            if ('' != $above) {
533                ?><div class="sc-above"><?php echo oTxt($above); ?></div><?php
534            }
[167]535            foreach ($messages as $m) {
536                if (error_reporting() > 0 && $this->getParam('display_errors') && isset($m['file']) && isset($m['line'])) {
537                    echo "\n<!-- [" . $m['file'] . ' : ' . $m['line'] . '] -->';
538                }
539                switch ($m['type']) {
540                case MSG_ERR:
[497]541                    echo '<div data-alert class="sc-msg-error alert-box alert">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
[167]542                    break;
[42]543
[167]544                case MSG_WARNING:
[497]545                    echo '<div data-alert class="sc-msg-warning alert-box warning">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
[167]546                    break;
[42]547
[167]548                case MSG_SUCCESS:
[497]549                    echo '<div data-alert class="sc-msg-success alert-box success">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
[167]550                    break;
[42]551
[167]552                case MSG_NOTICE:
553                default:
[497]554                    echo '<div data-alert class="sc-msg-notice alert-box info">' . $m['message'] . '<a href="#" class="close">&times;</a></div>';
[167]555                    break;
556                }
[1]557            }
[413]558            if ('' != $below) {
559                ?><div class="sc-below"><?php echo oTxt($below); ?></div><?php
560            }
[1]561            ?></div><?php
[413]562            if ($print_gotohash_js) {
563                ?>
564                <script type="text/javascript">
565                /* <![CDATA[ */
566                window.location.hash = '#<?php echo urlencode($hash); ?>';
567                /* ]]> */
568                </script>
569                <?php
570            }
[1]571        }
[136]572        $this->clearRaisedMessages();
[1]573    }
[42]574
[1]575    /**
[44]576     * Logs messages to defined channels: file, email, sms, and screen. Repeated messages are
[390]577     * not repeated but printed once with count. Log events that match a sendable channel (email or SMS)
578     * are sent once per 'log_multiple_timeout' setting (to avoid a flood of error emails).
[1]579     *
580     * @access public
581     * @param string $message   The text description of the message.
582     * @param int    $priority  The type of message priority (in descending order):
[390]583     *                          LOG_EMERG     0 system is unusable
584     *                          LOG_ALERT     1 action must be taken immediately
585     *                          LOG_CRIT      2 critical conditions
586     *                          LOG_ERR       3 error conditions
587     *                          LOG_WARNING   4 warning conditions
588     *                          LOG_NOTICE    5 normal, but significant, condition
589     *                          LOG_INFO      6 informational message
590     *                          LOG_DEBUG     7 debug-level message
[1]591     * @param string $file      The file where the log event occurs.
592     * @param string $line      The line of the file where the log event occurs.
593     */
[468]594    public function logMsg($message, $priority=LOG_INFO, $file=null, $line=null)
[1]595    {
[44]596        static $previous_events = array();
597
[1]598        // If priority is not specified, assume the worst.
[136]599        if (!$this->logPriorityToString($priority)) {
600            $this->logMsg(sprintf('Log priority %s not defined. (Message: %s)', $priority, $message), LOG_EMERG, $file, $line);
[1]601            $priority = LOG_EMERG;
602        }
[42]603
[15]604        // If log file is not specified, don't log to a file.
[136]605        if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) {
606            $this->setParam(array('log_file_priority' => false));
607            // We must use trigger_error to report this problem rather than calling $app->logMsg, which might lead to an infinite loop.
608            trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE);
[1]609        }
[452]610
[390]611        // Before we get any further, let's see if ANY log events are configured to be reported.
612        if ((false === $this->getParam('log_file_priority') || $priority > $this->getParam('log_file_priority'))
613        && (false === $this->getParam('log_email_priority') || $priority > $this->getParam('log_email_priority'))
614        && (false === $this->getParam('log_sms_priority') || $priority > $this->getParam('log_sms_priority'))
615        && (false === $this->getParam('log_screen_priority') || $priority > $this->getParam('log_screen_priority'))) {
616            // This event would not be recorded, skip it entirely.
617            return false;
618        }
[42]619
[1]620        // Make sure to log in the system's locale.
621        $locale = setlocale(LC_TIME, 0);
622        setlocale(LC_TIME, 'C');
[42]623
[44]624        // Strip HTML tags except any with more than 7 characters because that's probably not a HTML tag, e.g. <email@address.com>.
625        preg_match_all('/(<[^>\s]{7,})[^>]*>/', $message, $strip_tags_allow);
626        $message = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null));
627
[479]628        // Serialize multi-line messages.
629        $message = preg_replace('/\s+/m', ' ', $message);
[477]630
[44]631        // Store this event under a unique key, counting each time it occurs so that it only gets reported a limited number of times.
632        $msg_id = md5($message . $priority . $file . $line);
[406]633        if ($this->getParam('log_ignore_repeated_events') && isset($previous_events[$msg_id])) {
[44]634            $previous_events[$msg_id]++;
635            if ($previous_events[$msg_id] == 2) {
[136]636                $this->logMsg(sprintf('%s (Event repeated %s or more times)', $message, $previous_events[$msg_id]), $priority, $file, $line);
[44]637            }
638            return false;
639        } else {
640            $previous_events[$msg_id] = 1;
641        }
[341]642
[390]643        // For email and SMS notification types use "lock" files to prevent sending email and SMS notices ad infinitum.
644        if ((false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority'))
645        || (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority'))) {
646            // This event will generate a "send" notification. Prepare lock file.
647            $site_hash = md5(empty($_SERVER['SERVER_NAME']) ? $_SERVER['SCRIPT_FILENAME'] : $_SERVER['SERVER_NAME']);
648            $lock_dir = $this->getParam('tmp_dir') . "/codebase_msgs_$site_hash/";
[452]649            // Just use the file and line for the msg_id to limit the number of possible messages
[390]650            // (the message string itself shan't be used as it may contain innumerable combinations).
651            $lock_file = $lock_dir . md5($file . ':' . $line);
652            if (!is_dir($lock_dir)) {
653                mkdir($lock_dir);
654            }
655            $send_notifications = true;
656            if (is_file($lock_file)) {
657                $msg_last_sent = filectime($lock_file);
658                // Has this message been sent more recently than the timeout?
659                if ((time() - $msg_last_sent) <= $this->getParam('log_multiple_timeout')) {
660                    // This message was already sent recently.
661                    $send_notifications = false;
662                } else {
663                    // Timeout has expired; send notifications again and reset timeout.
664                    touch($lock_file);
665                }
[341]666            } else {
[390]667                touch($lock_file);
[341]668            }
669        }
[452]670
[1]671        // Data to be stored for a log event.
[44]672        $event = array(
673            'date'      => date('Y-m-d H:i:s'),
674            'remote ip' => getRemoteAddr(),
[414]675            'pid'       => getmypid(),
[136]676            'type'      => $this->logPriorityToString($priority),
[44]677            'file:line' => "$file : $line",
[475]678            'url'       => mb_substr(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '', 0, 1024),
[44]679            'message'   => $message
680        );
[475]681        // Here's a shortened version of event data.
682        $event_short = $event;
683        $event_short['url'] = truncate($event_short['url'], 120);
[42]684
[475]685
[1]686        // FILE ACTION
[390]687        if (false !== $this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) {
[475]688            $event_str = '[' . join('] [', $event_short) . ']';
[247]689            error_log(mb_substr($event_str, 0, 1024) . "\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename'));
[1]690        }
[42]691
[390]692        // EMAIL ACTION
693        if (false !== $this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority') && $send_notifications) {
[422]694            $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n');
695            $subject = sprintf('[%s %s] %s', $hostname, $event['type'], mb_substr($message, 0, 64));
696            $email_msg = sprintf("A %s log event occurred on %s\n\n", $event['type'], $hostname);
[390]697            $headers = 'From: ' . $this->getParam('site_email');
698            foreach ($event as $k=>$v) {
699                $email_msg .= sprintf("%-11s%s\n", $k, $v);
[1]700            }
[390]701            mb_send_mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers);
[1]702        }
[390]703
704        // SMS ACTION
705        if (false !== $this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority') && $send_notifications) {
[422]706            $hostname = (isset($_SERVER['HTTP_HOST']) && '' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n');
707            $subject = sprintf('[%s %s]', $hostname, $priority);
[475]708            $sms_msg = sprintf('%s [%s:%s]', mb_substr($event_short['message'], 0, 64), basename($file), $line);
[390]709            $headers = 'From: ' . $this->getParam('site_email');
710            mb_send_mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers);
711        }
[452]712
[1]713        // SCREEN ACTION
[390]714        if (false !== $this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) {
[468]715            file_put_contents('php://stderr', "[{$event['type']}] [{$event['message']}]\n", FILE_APPEND);
[1]716        }
[42]717
[1]718        // Restore original locale.
719        setlocale(LC_TIME, $locale);
[452]720
[475]721        unset($event, $event_short);
722
[390]723        return true;
[1]724    }
[42]725
[1]726    /**
727     * Returns the string representation of a LOG_* integer constant.
728     *
729     * @param int  $priority  The LOG_* integer constant.
730     *
731     * @return                The string representation of $priority.
732     */
[468]733    public function logPriorityToString($priority) {
[1]734        $priorities = array(
735            LOG_EMERG   => 'emergency',
736            LOG_ALERT   => 'alert',
737            LOG_CRIT    => 'critical',
738            LOG_ERR     => 'error',
739            LOG_WARNING => 'warning',
740            LOG_NOTICE  => 'notice',
741            LOG_INFO    => 'info',
742            LOG_DEBUG   => 'debug'
743        );
744        if (isset($priorities[$priority])) {
745            return $priorities[$priority];
746        } else {
747            return false;
748        }
749    }
[42]750
[1]751    /**
[334]752     * Forcefully set a query argument even if one currently exists in the request.
[136]753     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
[20]754     * to hidden input values (via printHiddenSession()).
755     *
756     * @access  public
[282]757     * @param   mixed   $query_key  The key (or keys, as an array) of the query argument to save.
758     * @param   mixed   $val        The new value of the argument key.
759     * @author  Quinn Comendant <quinn@strangecode.com>
760     * @since   13 Oct 2007 11:34:51
761     */
[468]762    public function setQuery($query_key, $val)
[282]763    {
764        if (!is_array($query_key)) {
765            $query_key = array($query_key);
766        }
767        foreach ($query_key as $k) {
768            // Set the value of the specified query argument into the _carry_queries array.
769            $this->_carry_queries[$k] = $val;
770        }
771    }
772
773    /**
774     * Specify which query arguments will be carried persistently between requests.
775     * Values in the _carry_queries array will be copied to URLs (via $app->url()) and
776     * to hidden input values (via printHiddenSession()).
777     *
778     * @access  public
[259]779     * @param   mixed   $query_key   The key (or keys, as an array) of the query argument to save.
[170]780     * @param   mixed   $default    If the key is not available, set to this default value.
[20]781     * @author  Quinn Comendant <quinn@strangecode.com>
782     * @since   14 Nov 2005 19:24:52
783     */
[468]784    public function carryQuery($query_key, $default=false)
[20]785    {
[259]786        if (!is_array($query_key)) {
787            $query_key = array($query_key);
[20]788        }
[259]789        foreach ($query_key as $k) {
790            // If not already set, and there is a non-empty value provided in the request...
791            if (!isset($this->_carry_queries[$k]) && false !== getFormData($k, $default)) {
792                // Copy the value of the specified query argument into the _carry_queries array.
793                $this->_carry_queries[$k] = getFormData($k, $default);
[331]794                $this->logMsg(sprintf('Carrying query: %s => %s', $k, truncate(getDump($this->_carry_queries[$k], true), 128, 'end')), LOG_DEBUG, __FILE__, __LINE__);
[259]795            }
796        }
[20]797    }
[42]798
[20]799    /**
[452]800     * dropQuery() is the opposite of carryQuery(). The specified value will not appear in
[259]801     * url()/ohref()/printHiddenSession() modified URLs unless explicitly written in.
[452]802     *
[259]803     * @access  public
804     * @param   mixed   $query_key  The key (or keys, as an array) of the query argument to remove.
[407]805     * @param   bool    $unset      Remove any values set in the request matching the given $query_key.
[259]806     * @author  Quinn Comendant <quinn@strangecode.com>
807     * @since   18 Jun 2007 20:57:29
808     */
[468]809    public function dropQuery($query_key, $unset=false)
[259]810    {
811        if (!is_array($query_key)) {
812            $query_key = array($query_key);
813        }
814        foreach ($query_key as $k) {
[478]815            if (array_key_exists($k, $this->_carry_queries)) {
[259]816                // Remove the value of the specified query argument from the _carry_queries array.
[325]817                $this->logMsg(sprintf('Dropping carried query: %s => %s', $k, $this->_carry_queries[$k]), LOG_DEBUG, __FILE__, __LINE__);
[260]818                unset($this->_carry_queries[$k]);
[259]819            }
[480]820            if ($unset && (isset($_REQUEST) && array_key_exists($k, $_REQUEST))) {
[325]821                unset($_REQUEST[$k], $_GET[$k], $_POST[$k], $_COOKIE[$k]);
822            }
[259]823        }
824    }
825
826    /**
[1]827     * Outputs a fully qualified URL with a query of all the used (ie: not empty)
[42]828     * keys and values, including optional queries. This allows mindless retention
[32]829     * of query arguments across page requests. If cookies are not
[325]830     * used, the session id will be propagated in the URL.
[1]831     *
[32]832     * @param  string $url              The initial url
833     * @param  mixed  $carry_args       Additional url arguments to carry in the query,
834     *                                  or FALSE to prevent carrying queries. Can be any of the following formats:
835     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
836     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
837     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
[1]838     *
839     * @param  mixed  $always_include_sid  Always add the session id, even if using_trans_sid = true. This is required when
840     *                                     URL starts with http, since PHP using_trans_sid doesn't do those and also for
841     *                                     header('Location...') redirections.
842     *
843     * @return string url with attached queries and, if not using cookies, the session id
844     */
[468]845    public function url($url, $carry_args=null, $always_include_sid=false)
[1]846    {
[136]847        if (!$this->running) {
848            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
[1]849            return false;
850        }
[42]851
[20]852        // Get any provided query arguments to include in the final URL.
853        // If FALSE is a provided here, DO NOT carry the queries.
[1]854        $do_carry_queries = true;
855        $one_time_carry_queries = array();
856        if (!is_null($carry_args)) {
857            if (is_array($carry_args) && !empty($carry_args)) {
858                foreach ($carry_args as $key=>$arg) {
859                    // Get query from appropriate source.
860                    if (false === $arg) {
861                        $do_carry_queries = false;
862                    } else if (false !== getFormData($arg, false)) {
863                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
864                    } else if (!is_numeric($key) && '' != $arg) {
865                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
866                    }
867                }
868            } else if (false !== getFormData($carry_args, false)) {
869                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
870            } else if (false === $carry_args) {
871                $do_carry_queries = false;
872            }
873        }
[42]874
[1]875        // Get the first delimiter that is needed in the url.
[247]876        $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
[32]877
[1]878        $q = '';
879        if ($do_carry_queries) {
[20]880            // Join the global _carry_queries and local one_time_carry_queries.
[136]881            $query_args = urlEncodeArray(array_merge($this->_carry_queries, $one_time_carry_queries));
[1]882            foreach ($query_args as $key=>$val) {
883                // Check value is set and value does not already exist in the url.
884                if (!preg_match('/[?&]' . preg_quote($key) . '=/', $url)) {
885                    $q .= $delim . $key . '=' . $val;
886                    $delim = ini_get('arg_separator.output');
887                }
888            }
889        }
[42]890
[1]891        // Include the necessary SID if the following is true:
892        // - no cookie in http request OR cookies disabled in App
893        // - sessions are enabled
894        // - the link stays on our site
[334]895        // - transparent SID propagation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
[42]896        // OR
[1]897        // - 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)
898        // AND
899        // - the SID is not already in the query.
900        if (
901            (
902                (
903                    (
[42]904                        !isset($_COOKIE[session_name()])
[136]905                        || !$this->getParam('session_use_cookies')
[42]906                    )
[242]907                    && $this->getParam('session_use_trans_sid')
[136]908                    && $this->getParam('enable_session')
[42]909                    && isMyDomain($url)
[242]910                    && (
[20]911                        !ini_get('session.use_trans_sid')
[1]912                        || preg_match('!^(http|https)://!i', $url)
913                    )
[42]914                )
[1]915                || $always_include_sid
916            )
917            && !preg_match('/[?&]' . preg_quote(session_name()) . '=/', $url)
918        ) {
919            $url .= $q . $delim . session_name() . '=' . session_id();
920        } else {
921            $url .= $q;
922        }
[492]923
924        return $url;
[1]925    }
[32]926
927    /**
[136]928     * Returns a HTML-friendly URL processed with $app->url and & replaced with &amp;
[32]929     *
930     * @access  public
931     * @param   string  $url    Input URL to parse.
[334]932     * @return  string          URL passed through $app->url() and then & turned to $amp;.
[32]933     * @author  Quinn Comendant <quinn@strangecode.com>
934     * @since   09 Dec 2005 17:58:45
935     */
[468]936    public function oHREF($url, $carry_args=null, $always_include_sid=false)
[32]937    {
[136]938        $url = $this->url($url, $carry_args, $always_include_sid);
[42]939
[32]940        // Replace any & not followed by an html or unicode entity with it's &amp; equivalent.
941        $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&amp;', $url);
[42]942
[32]943        return $url;
944    }
[42]945
[492]946    /*
947    * Return a URL with a version number attached. This is useful for overriding network caches ("cache buster") for sourced media, e.g., /style.css?812763482
948    *
949    * @access   public
950    * @param    string  $url    URL to media (e.g., /foo.js)
951    * @return   string          URL with cache-busting version appended (/foo.js?v=1234567890)
952    * @author   Quinn Comendant <quinn@strangecode.com>
953    * @version  1.0
954    * @since    03 Sep 2014 22:40:24
955    */
956    public function cacheBustURL($url)
957    {
958        // Get the first delimiter that is needed in the url.
959        $delim = mb_strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
960        $v = crc32($this->getParam('codebase_version') . '|' . $this->getParam('site_version'));
961        return sprintf('%s%sv=%s', $url, $delim, $v);
962    }
963
[1]964    /**
965     * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
[42]966     * as hidden form elements for GET_VARS that might be in use.
[1]967     *
968     * @param  mixed  $carry_args        Additional url arguments to carry in the query,
969     *                                   or FALSE to prevent carrying queries. Can be any of the following formats:
[32]970     *                                      array('key1', key2', key3')  <-- to save these keys if in the form data.
971     *                                      array('key1'=>'value', key2'='value')  <-- to set keys to default values if not present in form data.
972     *                                      false  <-- To not carry any queries. If URL already has queries those will be retained.
[1]973     */
[468]974    public function printHiddenSession($carry_args=null)
[32]975    {
[136]976        if (!$this->running) {
977            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
[1]978            return false;
979        }
[42]980
[20]981        // Get any provided query arguments to include in the final hidden form data.
982        // If FALSE is a provided here, DO NOT carry the queries.
[1]983        $do_carry_queries = true;
984        $one_time_carry_queries = array();
985        if (!is_null($carry_args)) {
986            if (is_array($carry_args) && !empty($carry_args)) {
987                foreach ($carry_args as $key=>$arg) {
988                    // Get query from appropriate source.
989                    if (false === $arg) {
990                        $do_carry_queries = false;
991                    } else if (false !== getFormData($arg, false)) {
992                        $one_time_carry_queries[$arg] = getFormData($arg); // Set arg to form data if available.
993                    } else if (!is_numeric($key) && '' != $arg) {
994                        $one_time_carry_queries[$key] = getFormData($key, $arg); // Set to arg to default if specified (overwritten by form data).
995                    }
996                }
997            } else if (false !== getFormData($carry_args, false)) {
998                $one_time_carry_queries[$carry_args] = getFormData($carry_args);
999            } else if (false === $carry_args) {
1000                $do_carry_queries = false;
1001            }
1002        }
[42]1003
[313]1004        // For each existing request value, we create a hidden input to carry it through a form.
[1]1005        if ($do_carry_queries) {
[20]1006            // Join the global _carry_queries and local one_time_carry_queries.
1007            // urlencode is not used here, not for form data!
[136]1008            $query_args = array_merge($this->_carry_queries, $one_time_carry_queries);
[453]1009            foreach ($query_args as $key => $val) {
1010                if (is_array($val)) {
1011                    foreach ($val as $subval) {
1012                        printf('<input type="hidden" name="%s[]" value="%s" />', $key, $subval);
1013                    }
1014                } else {
1015                    printf('<input type="hidden" name="%s" value="%s" />', $key, $val);
1016                }
[1]1017            }
[453]1018            unset($query_args, $key, $val, $subval);
[1]1019        }
[42]1020
[1]1021        // Include the SID if cookies are disabled.
[20]1022        if (!isset($_COOKIE[session_name()]) && !ini_get('session.use_trans_sid')) {
[136]1023            printf('<input type="hidden" name="%s" value="%s" />', session_name(), session_id());
[1]1024        }
1025    }
[42]1026
[1]1027    /**
1028     * Uses an http header to redirect the client to the given $url. If sessions are not used
1029     * and the session is not already defined in the given $url, the SID is appended as a URI query.
1030     * As with all header generating functions, make sure this is called before any other output.
1031     *
1032     * @param   string  $url                    The URL the client will be redirected to.
1033     * @param   mixed   $carry_args             Additional url arguments to carry in the query,
1034     *                                          or FALSE to prevent carrying queries. Can be any of the following formats:
1035     *                                          -array('key1', key2', key3')  <-- to save these keys if in the form data.
[136]1036     *                                          -array('key1' => 'value', key2' => 'value')  <-- to set keys to default values if not present in form data.
[1]1037     *                                          -false  <-- To not carry any queries. If URL already has queries those will be retained.
1038     * @param   bool    $always_include_sid     Force session id to be added to Location header.
1039     */
[468]1040    public function dieURL($url, $carry_args=null, $always_include_sid=false)
[1]1041    {
[136]1042        if (!$this->running) {
1043            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
[1]1044            return false;
1045        }
[42]1046
[1]1047        if ('' == $url) {
1048            // If URL is not specified, use the redirect_home_url.
[136]1049            $url = $this->getParam('redirect_home_url');
[1]1050        }
[42]1051
[1]1052        if (preg_match('!^/!', $url)) {
1053            // If relative URL is given, prepend correct local hostname.
[22]1054            $scheme = 'on' == getenv('HTTPS') ? 'https' : 'http';
1055            $host = getenv('HTTP_HOST');
1056            $url = sprintf('%s://%s%s', $scheme, $host, $url);
[1]1057        }
[22]1058
[136]1059        $url = $this->url($url, $carry_args, $always_include_sid);
[42]1060
[202]1061        // Should we send a "303 See Other" header here instead of relying on the 302 sent automatically by PHP?
[1]1062        header(sprintf('Location: %s', $url));
[136]1063        $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
[42]1064
[202]1065        // End application.
[1]1066        // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close
[136]1067        $this->stop();
[1]1068        die;
1069    }
[42]1070
[84]1071    /*
[136]1072    * Redirects a user by calling $app->dieURL(). It will use:
[84]1073    * 1. the stored boomerang URL, it it exists
1074    * 2. a specified $default_url, it it exists
1075    * 3. the referring URL, it it exists.
1076    * 4. redirect_home_url configuration variable.
1077    *
1078    * @access   public
1079    * @param    string  $id             Identifier for this script.
[136]1080    * @param    mixed   $carry_args     Additional arguments to carry in the URL automatically (see $app->oHREF()).
[84]1081    * @param    string  $default_url    A default URL if there is not a valid specified boomerang URL.
[159]1082    * @param    bool    $queryless_referrer_comparison   Exclude the URL query from the refererIsMe() comparison.
[84]1083    * @return   bool                    False if the session is not running. No return otherwise.
1084    * @author   Quinn Comendant <quinn@strangecode.com>
1085    * @since    31 Mar 2006 19:17:00
1086    */
[468]1087    public function dieBoomerangURL($id=null, $carry_args=null, $default_url=null, $queryless_referrer_comparison=false)
[1]1088    {
[136]1089        if (!$this->running) {
1090            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
[1]1091            return false;
1092        }
[42]1093
[1]1094        // Get URL from stored boomerang. Allow non specific URL if ID not valid.
[136]1095        if ($this->validBoomerangURL($id, true)) {
[154]1096            if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1097                $url = $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id];
[136]1098                $this->logMsg(sprintf('dieBoomerangURL(%s) found: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
[1]1099            } else {
[154]1100                $url = end($_SESSION['_app'][$this->_ns]['boomerang']['url']);
[136]1101                $this->logMsg(sprintf('dieBoomerangURL(%s) using: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
[1]1102            }
[22]1103            // Delete stored boomerang.
[136]1104            $this->deleteBoomerangURL($id);
[84]1105        } else if (isset($default_url)) {
1106            $url = $default_url;
[159]1107        } else if (!refererIsMe(true === $queryless_referrer_comparison)) {
[1]1108            // Ensure that the redirecting page is not also the referrer.
1109            $url = getenv('HTTP_REFERER');
[136]1110            $this->logMsg(sprintf('dieBoomerangURL(%s) using referrer: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
[1]1111        } else {
[22]1112            // If URL is not specified, use the redirect_home_url.
[136]1113            $url = $this->getParam('redirect_home_url');
[203]1114            $this->logMsg(sprintf('dieBoomerangURL(%s) using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
[1]1115        }
[42]1116
[84]1117        // A redirection will never happen immediately twice.
[1]1118        // Set the time so ensure this doesn't happen.
[154]1119        $_SESSION['_app'][$this->_ns]['boomerang']['time'] = time();
[136]1120        $this->dieURL($url, $carry_args);
[1]1121    }
[42]1122
[1]1123    /**
[136]1124     * Set the URL to return to when $app->dieBoomerangURL() is called.
[1]1125     *
1126     * @param string  $url  A fully validated URL.
1127     * @param bool  $id     An identification tag for this url.
1128     * FIXME: url garbage collection?
1129     */
[468]1130    public function setBoomerangURL($url=null, $id=null)
[1]1131    {
[136]1132        if (!$this->running) {
1133            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
[1]1134            return false;
1135        }
[84]1136        // A redirection will never happen immediately after setting the boomerangURL.
[136]1137        // Set the time so ensure this doesn't happen. See $app->validBoomerangURL for more.
[42]1138
[22]1139        if ('' != $url && is_string($url)) {
[242]1140            // Delete any boomerang request keys in the query string (along with any trailing delimiters after the deletion).
1141            $url = preg_replace(array('/([&?])boomerang=\w+[&?]?/', '/[&?]$/'), array('$1', ''), $url);
[42]1142
[154]1143            if (isset($_SESSION['_app'][$this->_ns]['boomerang']['url']) && is_array($_SESSION['_app'][$this->_ns]['boomerang']['url']) && !empty($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
[1]1144                // If the URL currently exists in the boomerang array, delete.
[154]1145                while ($existing_key = array_search($url, $_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1146                    unset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$existing_key]);
[1]1147                }
1148            }
[42]1149
[1]1150            if (isset($id)) {
[154]1151                $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id] = $url;
[1]1152            } else {
[154]1153                $_SESSION['_app'][$this->_ns]['boomerang']['url'][] = $url;
[1]1154            }
[136]1155            $this->logMsg(sprintf('setBoomerangURL(%s): %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
[1]1156            return true;
1157        } else {
[136]1158            $this->logMsg(sprintf('setBoomerangURL(%s) is empty!', $id, $url), LOG_NOTICE, __FILE__, __LINE__);
[1]1159            return false;
1160        }
1161    }
[42]1162
[1]1163    /**
[333]1164     * Return the URL set for the specified $id, or an empty string if one isn't set.
[1]1165     *
1166     * @param string  $id     An identification tag for this url.
1167     */
[468]1168    public function getBoomerangURL($id=null)
[1]1169    {
[136]1170        if (!$this->running) {
1171            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
[1]1172            return false;
1173        }
[42]1174
[1]1175        if (isset($id)) {
[154]1176            if (isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1177                return $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id];
[1]1178            } else {
1179                return '';
1180            }
[154]1181        } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1182            return end($_SESSION['_app'][$this->_ns]['boomerang']['url']);
[1]1183        } else {
1184            return false;
1185        }
1186    }
[42]1187
[1]1188    /**
1189     * Delete the URL set for the specified $id.
1190     *
1191     * @param string  $id     An identification tag for this url.
1192     */
[468]1193    public function deleteBoomerangURL($id=null)
[1]1194    {
[136]1195        if (!$this->running) {
1196            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
[1]1197            return false;
1198        }
[42]1199
[136]1200        $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $this->getBoomerangURL($id)), LOG_DEBUG, __FILE__, __LINE__);
[22]1201
[154]1202        if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1203            unset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id]);
1204        } else if (is_array($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
1205            array_pop($_SESSION['_app'][$this->_ns]['boomerang']['url']);
[1]1206        }
1207    }
[42]1208
[1]1209    /**
[103]1210     * Check if a valid boomerang URL value has been set. A boomerang URL is considered
1211     * valid if: 1) it is not empty, 2) it is not the current URL, and 3) has not been accessed within n seconds.
[1]1212     *
[103]1213     * @return bool  True if it is set and valid, false otherwise.
[1]1214     */
[468]1215    public function validBoomerangURL($id=null, $use_nonspecificboomerang=false)
[1]1216    {
[136]1217        if (!$this->running) {
1218            $this->logMsg(sprintf('Canceled method call %s, application not running.', __FUNCTION__), LOG_NOTICE, __FILE__, __LINE__);
[1]1219            return false;
1220        }
[42]1221
[154]1222        if (!isset($_SESSION['_app'][$this->_ns]['boomerang']['url'])) {
[136]1223            $this->logMsg(sprintf('validBoomerangURL(%s) no boomerang URL set.', $id), LOG_DEBUG, __FILE__, __LINE__);
[1]1224            return false;
1225        }
[42]1226
[334]1227        // Time is the time stamp of a boomerangURL redirection, or setting of a boomerangURL.
[1]1228        // a boomerang redirection will always occur at least several seconds after the last boomerang redirect
1229        // or a boomerang being set.
[154]1230        $boomerang_time = isset($_SESSION['_app'][$this->_ns]['boomerang']['time']) ? $_SESSION['_app'][$this->_ns]['boomerang']['time'] : 0;
[42]1231
[22]1232        $url = '';
[154]1233        if (isset($id) && isset($_SESSION['_app'][$this->_ns]['boomerang']['url'][$id])) {
1234            $url = $_SESSION['_app'][$this->_ns]['boomerang']['url'][$id];
[1]1235        } else if (!isset($id) || $use_nonspecificboomerang) {
1236            // Use non specific boomerang if available.
[154]1237            $url = end($_SESSION['_app'][$this->_ns]['boomerang']['url']);
[1]1238        }
[42]1239
[136]1240        $this->logMsg(sprintf('validBoomerangURL(%s) testing: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
[22]1241
1242        if ('' == $url) {
[136]1243            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, empty!', $id), LOG_DEBUG, __FILE__, __LINE__);
[1]1244            return false;
1245        }
1246        if ($url == absoluteMe()) {
1247            // The URL we are directing to is the current page.
[136]1248            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, same as absoluteMe: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
[1]1249            return false;
1250        }
1251        if ($boomerang_time >= (time() - 2)) {
[159]1252            // Last boomerang direction was less than 2 seconds ago.
1253            $this->logMsg(sprintf('validBoomerangURL(%s) not valid, boomerang_time too short: %s seconds', $id, time() - $boomerang_time), LOG_DEBUG, __FILE__, __LINE__);
[1]1254            return false;
1255        }
[42]1256
[136]1257        $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
[1]1258        return true;
1259    }
1260
1261    /**
1262     * Force the user to connect via https (port 443) by redirecting them to
1263     * the same page but with https.
1264     */
[468]1265    public function sslOn()
[1]1266    {
[38]1267        if (function_exists('apache_get_modules')) {
[42]1268            $modules = apache_get_modules();
[38]1269        } else {
1270            // It's safe to assume we have mod_ssl if we can't determine otherwise.
1271            $modules = array('mod_ssl');
1272        }
[42]1273
[136]1274        if ('' == getenv('HTTPS') && $this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) {
1275            $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
[1]1276            // Always append session because some browsers do not send cookie when crossing to SSL URL.
[136]1277            $this->dieURL('https://' . $this->getParam('ssl_domain') . getenv('REQUEST_URI'), null, true);
[1]1278        }
1279    }
[42]1280
[1]1281    /**
1282     * to enforce the user to connect via http (port 80) by redirecting them to
1283     * a http version of the current url.
1284     */
[468]1285    public function sslOff()
[1]1286    {
[53]1287        if ('' != getenv('HTTPS')) {
[1]1288            $this->dieURL('http://' . getenv('HTTP_HOST') . getenv('REQUEST_URI'), null, true);
1289        }
1290    }
[477]1291
[479]1292    /*
1293    * Sets a cookie, with error checking and some sane defaults.
1294    *
1295    * @access   public
1296    * @param    string  $name       The name of the cookie.
1297    * @param    string  $value      The value of the cookie.
1298    * @param    string  $expire     The time the cookie expires, as a unix timestamp or string value passed to strtotime.
[489]1299    * @param    string  $path       The path on the server in which the cookie will be available on.
1300    * @param    string  $domain     The domain that the cookie is available to.
[479]1301    * @param    bool    $secure     Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client.
1302    * @param    bool    $httponly   When TRUE the cookie will be made accessible only through the HTTP protocol (makes cookies unreadable to javascript).
1303    * @return   bool                True on success, false on error.
1304    * @author   Quinn Comendant <quinn@strangecode.com>
1305    * @version  1.0
1306    * @since    02 May 2014 16:36:34
1307    */
[489]1308    public function setCookie($name, $value, $expire='+10 years', $path='/', $domain=null, $secure=null, $httponly=null)
[479]1309    {
1310        if (!is_scalar($name)) {
1311            $this->logMsg(sprintf('Cookie name must be scalar, is not: %s', getDump($name)), LOG_NOTICE, __FILE__, __LINE__);
1312            return false;
1313        }
1314        if (!is_scalar($value)) {
1315            $this->logMsg(sprintf('Cookie "%s" value must be scalar, is not: %s', $name, getDump($value)), LOG_NOTICE, __FILE__, __LINE__);
1316            return false;
1317        }
[477]1318
[479]1319        // Defaults.
1320        $expire = (is_numeric($expire) ? $expire : (is_string($expire) ? strtotime($expire) : $expire));
1321        $secure = $secure ?: ('' != getenv('HTTPS') && $this->getParam('ssl_enabled'));
1322        $httponly = $httponly ?: true;
[477]1323
[479]1324        // Make sure the expiration date is a valid 32bit integer.
1325        if (is_int($expire) && $expire > 2147483647) {
1326            $this->logMsg(sprintf('Cookie "%s" expire time exceeds a 32bit integer (%s)', $key, date('r', $expire)), LOG_NOTICE, __FILE__, __LINE__);
1327        }
[477]1328
[479]1329        // Measure total cookie length and warn if larger than max recommended size of 4093.
1330        // https://stackoverflow.com/questions/640938/what-is-the-maximum-size-of-a-web-browsers-cookies-key
1331        // The date the header name include 51 bytes: Set-Cookie: ; expires=Fri, 03-May-2024 00:04:47 GMT
1332        $cookielen = strlen($name . $value . $path . $domain . ($secure ? '; secure' : '') . ($httponly ? '; httponly' : '')) + 51;
1333        if ($cookielen > 4093) {
1334            $this->logMsg(sprintf('Cookie "%s" has a size greater than 4093 bytes (is %s bytes)', $key, $cookielen), LOG_NOTICE, __FILE__, __LINE__);
1335        }
[477]1336
[479]1337        // Ensure PHP version allow use of httponly.
1338        if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
1339            $ret = setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
1340        } else {
1341            $ret = setcookie($name, $value, $expire, $path, $domain, $secure);
1342        }
[477]1343
[479]1344        if (false === $ret) {
1345            $this->logMsg(sprintf('Failed to set cookie (%s=%s) probably due to output before headers.', $name, $value), LOG_NOTICE, __FILE__, __LINE__);
1346        }
1347        return $ret;
1348    }
[1]1349} // End.
Note: See TracBrowser for help on using the repository browser.