Changeset 42 for trunk/lib/App.inc.php


Ignore:
Timestamp:
Dec 18, 2005 12:16:03 AM (18 years ago)
Author:
scdev
Message:

detabbed all files ;P

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/lib/App.inc.php

    r41 r42  
    99 * @version 1.0
    1010 */
    11  
     11
    1212// Message Types.
    1313define('MSG_ERR', 1);
     
    2020
    2121class App {
    22    
     22
    2323    // Name of this application.
    2424    var $app = '_app_';
     
    2929    // Instance of database object.
    3030    var $db;
    31    
     31
    3232    // Array of query arguments will be carried persistently between requests.
    3333    var $_carry_queries = array();
     
    4646        // The location the user will go if the system doesn't knew where else to send them.
    4747        'redirect_home_url' => '/',
    48        
     48
    4949        // SSL URL used when redirecting with App::sslOn().
    5050        'ssl_domain' => null,
    5151        'ssl_enabled' => false,
    52    
     52
    5353        // Character set for page output. Used in the Content-Type header and the HTML <meta content-type> tag.
    5454        'character_set' => 'utf-8',
     
    6363        'session_name' => 'Strangecode',
    6464        'session_use_cookies' => true,
    65    
     65
    6666        // Use database?
    6767        'enable_db' => false,
     
    6969        // Use db-based sessions?
    7070        'enable_db_session_handler' => false,
    71    
     71
    7272        // DB passwords should be set as apache environment variables in httpd.conf, readable only by root.
    7373        'db_server' => 'localhost',
     
    8080        'db_debug' => false, // TRUE = display db errors.
    8181        'db_die_on_failure' => false, // TRUE = script stops on db error.
    82        
     82
    8383        // For classes that require db tables, do we check that a table exists and create if missing?
    8484        'db_create_tables' => true,
     
    8989        // Don't display errors by default; it is preferable to log them to a file.
    9090        'display_errors' => false,
    91    
     91
    9292        // Directory in which to store log files.
    9393        'log_directory' => '',
     
    112112        'log_sms_priority' => false,
    113113        'log_screen_priority' => false,
    114    
     114
    115115        // Email address to receive log event emails.
    116116        'log_to_email_address' => null,
    117        
     117
    118118        // SMS Email address to receive log event SMS messages.
    119119        'log_to_sms_address' => null,
    120        
     120
    121121        // A key for calculating simple cryptographic signatures. Set using as an environment variables in the httpd.conf with 'SetEnv SIGNING_KEY <key>'.
    122122        'signing_key' => 'aae6abd6209d82a691a9f96384a7634a',
    123123    );
    124    
     124
    125125    /**
    126126     * This method enforces the singleton pattern for this class. Only one application is running at a time.
     
    140140        return $instance;
    141141    }
    142    
     142
    143143    /**
    144144     * Constructor.
     
    149149            $this->app .= $app;
    150150        }
    151        
     151
    152152        // Initialize default parameters.
    153153        $this->_params = array_merge($this->_params, $this->_param_defaults);
     
    184184            $this =& App::getInstance();
    185185        }
    186        
     186
    187187        if ($param === null) {
    188188            return $this->_params;
     
    194194        }
    195195    }
    196    
     196
    197197    /**
    198198     * Begin running this application.
     
    207207            return false;
    208208        }
    209        
     209
    210210        // Error reporting.
    211211        ini_set('error_reporting', $this->getParam('error_reporting'));
     
    215215            ini_set('error_log', $this->getParam('log_directory') . '/' . $this->getParam('php_error_log'));
    216216        }
    217        
    218        
     217
     218
    219219        /**
    220220         * 1. Start Database.
    221221         */
    222        
     222
    223223        if ($this->getParam('enable_db')) {
    224        
     224
    225225            // DB connection parameters taken from environment variables in the httpd.conf file, readable only by root.
    226226            if (!empty($_SERVER['DB_SERVER'])) {
     
    236236                $this->setParam(array('db_pass' => $_SERVER['DB_PASS']));
    237237            }
    238            
     238
    239239            // The only instance of the DB object.
    240240            require_once dirname(__FILE__) . '/DB.inc.php';
    241            
     241
    242242            $this->db =& DB::getInstance();
    243            
     243
    244244            $this->db->setParam(array(
    245245                'db_server' => $this->getParam('db_server'),
     
    255255            $this->db->connect();
    256256        }
    257        
    258        
     257
     258
    259259        /**
    260260         * 2. Start PHP session.
    261261         */
    262    
     262
    263263        // Skip session for some user agents.
    264264        if (preg_match('/Atomz|ApacheBench|Wget/i', getenv('HTTP_USER_AGENT'))) {
    265265            $this->setParam(array('enable_session' => false));
    266266        }
    267        
     267
    268268        if (true === $this->getParam('enable_session')) {
    269        
     269
    270270            // Set the session ID to one provided in GET/POST. This is necessary for linking
    271271            // between domains and keeping the same session.
     
    273273                session_id($ses);
    274274            }
    275        
     275
    276276            if (true === $this->getParam('enable_db_session_handler') && true === $this->getParam('enable_db')) {
    277277                // Database session handling.
     
    282282                ));
    283283            }
    284            
     284
    285285            // Session parameters.
    286286            ini_set('session.use_cookies', $this->getParam('session_use_cookies'));
     
    289289            ini_set('session.entropy_length', '512');
    290290            session_name($this->getParam('session_name'));
    291            
     291
    292292            // Start the session.
    293293            session_start();
    294            
     294
    295295            if (!isset($_SESSION[$this->app])) {
    296296                // Access session data using: $_SESSION['...'].
     
    302302            }
    303303        }
    304        
    305        
     304
     305
    306306        /**
    307307         * 3. Misc setup.
     
    319319            $this->setParam(array('signing_key' => $_SERVER['SIGNING_KEY']));
    320320        }
    321        
     321
    322322        // Character set. This should also be printed in the html header template.
    323323        header('Content-type: text/html; charset=' . $this->getParam('character_set'));
    324        
     324
    325325        $this->running = true;
    326326    }
    327    
     327
    328328    /**
    329329     * Stop running this application.
     
    340340        $this->running = false;
    341341    }
    342    
    343    
     342
     343
    344344    /**
    345345     * Add a message to the string globalmessage, which is printed in the header.
     
    359359            $this =& App::getInstance();
    360360        }
    361        
     361
    362362        $message = trim($message);
    363363
     
    365365            return false;
    366366        }
    367        
     367
    368368        // Save message in session under unique key to avoid duplicate messages.
    369369        $_SESSION[$this->app]['messages'][md5($type . $message . $file . $line)] = array(
    370             'type'    => $type, 
     370            'type'    => $type,
    371371            'message' => $message,
    372372            'file'    => $file,
    373373            'line'    => $line
    374374        );
    375        
     375
    376376        if (!in_array($type, array(MSG_NOTICE, MSG_SUCCESS, MSG_WARNING, MSG_ERR))) {
    377             $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_DEBUG, __FILE__, __LINE__);
    378         }
    379     }
    380    
     377            $this->logMsg(sprintf('Invalid MSG_* type: %s', $type), LOG_DEBUG, __FILE__, __LINE__);
     378        }
     379    }
     380
    381381    /**
    382382     * Prints the HTML for displaying raised messages.
     
    405405                echo '<div class="error">' . $message['message'] . '</div>';
    406406                break;
    407    
     407
    408408            case MSG_WARNING:
    409409                echo '<div class="warning">' . $message['message'] . '</div>';
    410410                break;
    411    
     411
    412412            case MSG_SUCCESS:
    413413                echo '<div class="success">' . $message['message'] . '</div>';
    414414                break;
    415    
     415
    416416            case MSG_NOTICE:
    417417            default:
    418418                echo '<div class="notice">' . $message['message'] . '</div>';
    419419                break;
    420    
     420
    421421            }
    422422            ?></div><?php
    423423        }
    424424    }
    425    
     425
    426426    /**
    427427     * Logs a message to a user defined log file. Additional actions to take for
     
    448448            $this =& App::getInstance();
    449449        }
    450        
     450
    451451        // If priority is not specified, assume the worst.
    452452        if (!$this->logPriorityToString($priority)) {
     
    454454            $priority = LOG_EMERG;
    455455        }
    456    
     456
    457457        // If log file is not specified, don't log to a file.
    458458        if (!$this->getParam('log_directory') || !$this->getParam('log_filename') || !is_dir($this->getParam('log_directory')) || !is_writable($this->getParam('log_directory'))) {
     
    461461            trigger_error(sprintf('Codebase error: log directory (%s) not found or writable.', $this->getParam('log_directory')), E_USER_NOTICE);
    462462        }
    463        
     463
    464464        // Make sure to log in the system's locale.
    465465        $locale = setlocale(LC_TIME, 0);
    466466        setlocale(LC_TIME, 'C');
    467        
     467
    468468        // Data to be stored for a log event.
    469469        $event = array();
     
    478478        $event['message'] = strip_tags(preg_replace('/\s+/', ' ', $message), (!empty($strip_tags_allow[1]) ? join('> ', $strip_tags_allow[1]) . '>' : null));
    479479        $event_str = '[' . join('] [', $event) . ']';
    480        
     480
    481481        // FILE ACTION
    482482        if ($this->getParam('log_file_priority') && $priority <= $this->getParam('log_file_priority')) {
    483483            error_log($event_str . "\n", 3, $this->getParam('log_directory') . '/' . $this->getParam('log_filename'));
    484484        }
    485    
     485
    486486        // EMAIL ACTION
    487487        if ($this->getParam('log_email_priority') && $priority <= $this->getParam('log_email_priority')) {
     
    494494            mail($this->getParam('log_to_email_address'), $subject, $email_msg, $headers, '-f codebase@strangecode.com');
    495495        }
    496        
     496
    497497        // SMS ACTION
    498498        if ($this->getParam('log_sms_priority') && $priority <= $this->getParam('log_sms_priority')) {
     
    502502            mail($this->getParam('log_to_sms_address'), $subject, $sms_msg, $headers, '-f codebase@strangecode.com');
    503503        }
    504    
     504
    505505        // SCREEN ACTION
    506506        if ($this->getParam('log_screen_priority') && $priority <= $this->getParam('log_screen_priority')) {
    507507            echo "[{$event['date']}] [{$event['type']}] [{$event['file:line']}] [{$event['message']}]\n";
    508508        }
    509    
     509
    510510        // Restore original locale.
    511511        setlocale(LC_TIME, $locale);
    512512    }
    513    
     513
    514514    /**
    515515     * Returns the string representation of a LOG_* integer constant.
     
    536536        }
    537537    }
    538    
     538
    539539    /**
    540540     * Sets which query arguments will be carried persistently between requests.
    541      * Values in the _carry_queries array will be copied to URLs (via App::url()) and 
     541     * Values in the _carry_queries array will be copied to URLs (via App::url()) and
    542542     * to hidden input values (via printHiddenSession()).
    543543     *
    544544     * @access  public
    545      * @param   string  $query_key  The key of the query argument to save. 
     545     * @param   string  $query_key  The key of the query argument to save.
    546546     * @author  Quinn Comendant <quinn@strangecode.com>
    547547     * @since   14 Nov 2005 19:24:52
     
    552552            $this =& App::getInstance();
    553553        }
    554        
     554
    555555        // If not already set, and there is a non-empty value provided in the request...
    556556        if (!isset($this->_carry_queries[$query_key]) && getFormData($query_key, false)) {
    557557            // Copy the value of the specified query argument into the _carry_queries array.
    558             $this->_carry_queries[$query_key] = getFormData($query_key);
    559         }
    560     }
    561    
     558            $this->_carry_queries[$query_key] = getFormData($query_key);
     559        }
     560    }
     561
    562562    /**
    563563     * Outputs a fully qualified URL with a query of all the used (ie: not empty)
    564      * keys and values, including optional queries. This allows mindless retention 
     564     * keys and values, including optional queries. This allows mindless retention
    565565     * of query arguments across page requests. If cookies are not
    566566     * used, the session id will be propogated in the URL.
     
    588588            return false;
    589589        }
    590    
     590
    591591        // Get any provided query arguments to include in the final URL.
    592592        // If FALSE is a provided here, DO NOT carry the queries.
     
    611611            }
    612612        }
    613        
     613
    614614        // Get the first delimiter that is needed in the url.
    615615        $delim = strpos($url, '?') !== false ? ini_get('arg_separator.output') : '?';
    616616
    617        
     617
    618618        $q = '';
    619619        if ($do_carry_queries) {
     
    628628            }
    629629        }
    630    
     630
    631631        // Include the necessary SID if the following is true:
    632632        // - no cookie in http request OR cookies disabled in App
     
    634634        // - the link stays on our site
    635635        // - transparent SID propogation with session.use_trans_sid is not being used OR url begins with protocol (using_trans_sid has no effect here)
    636         // OR 
     636        // OR
    637637        // - 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)
    638638        // AND
     
    642642                (
    643643                    (
    644                         !isset($_COOKIE[session_name()]) 
     644                        !isset($_COOKIE[session_name()])
    645645                        || !$this->getParam('session_use_cookies')
    646                     ) 
     646                    )
    647647                    && $this->getParam('enable_session')
    648                     && isMyDomain($url) 
    649                     && 
     648                    && isMyDomain($url)
     649                    &&
    650650                    (
    651651                        !ini_get('session.use_trans_sid')
    652652                        || preg_match('!^(http|https)://!i', $url)
    653653                    )
    654                 ) 
     654                )
    655655                || $always_include_sid
    656656            )
     
    679679            $this =& App::getInstance();
    680680        }
    681        
     681
    682682        $url = $this->url($url, $carry_args, $always_include_sid);
    683        
     683
    684684        // Replace any & not followed by an html or unicode entity with it's &amp; equivalent.
    685685        $url = preg_replace('/&(?![\w\d#]{1,10};)/', '&amp;', $url);
    686        
     686
    687687        return $url;
    688688    }
    689    
     689
    690690    /**
    691691     * Prints a hidden form element with the PHPSESSID when cookies are not used, as well
    692      * as hidden form elements for GET_VARS that might be in use. 
     692     * as hidden form elements for GET_VARS that might be in use.
    693693     *
    694694     * @param  mixed  $carry_args        Additional url arguments to carry in the query,
     
    707707            return false;
    708708        }
    709    
     709
    710710        // Get any provided query arguments to include in the final hidden form data.
    711711        // If FALSE is a provided here, DO NOT carry the queries.
     
    730730            }
    731731        }
    732        
     732
    733733        // For each existing POST value, we create a hidden input to carry it through a form.
    734734        if ($do_carry_queries) {
     
    740740            }
    741741        }
    742        
     742
    743743        // Include the SID if cookies are disabled.
    744744        if (!isset($_COOKIE[session_name()]) && !ini_get('session.use_trans_sid')) {
     
    746746        }
    747747    }
    748    
     748
    749749    /**
    750750     * Uses an http header to redirect the client to the given $url. If sessions are not used
     
    769769            return false;
    770770        }
    771        
     771
    772772        if ('' == $url) {
    773773            // If URL is not specified, use the redirect_home_url.
    774774            $url = $this->getParam('redirect_home_url');
    775775        }
    776    
     776
    777777        if (preg_match('!^/!', $url)) {
    778778            // If relative URL is given, prepend correct local hostname.
     
    783783
    784784        $url = $this->url($url, $carry_args, $always_include_sid);
    785        
     785
    786786        header(sprintf('Location: %s', $url));
    787787        $this->logMsg(sprintf('dieURL: %s', $url), LOG_DEBUG, __FILE__, __LINE__);
    788        
     788
    789789        // End this application.
    790790        // Recommended, although I'm not sure it's necessary: http://cn2.php.net/session_write_close
     
    792792        die;
    793793    }
    794    
     794
    795795    /**
    796796     * Redirects a user by calling the App::dieURL(). It will use:
     
    808808            return false;
    809809        }
    810        
     810
    811811        // Get URL from stored boomerang. Allow non specific URL if ID not valid.
    812812        if ($this->validBoomerangURL($id, true)) {
     
    829829            $this->logMsg(sprintf('dieBoomerangURL(%s) not found, using redirect_home_url: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
    830830        }
    831    
    832            
     831
     832
    833833        // A redirection will never happen immediatly twice.
    834834        // Set the time so ensure this doesn't happen.
     
    836836        $this->dieURL($url, $carry_args);
    837837    }
    838    
     838
    839839    /**
    840840     * Set the URL to return to when App::dieBoomerangURL() is called.
     
    855855        // A redirection will never happen immediatly after setting the boomerangURL.
    856856        // Set the time so ensure this doesn't happen. See App::validBoomerangURL for more.
    857    
     857
    858858        if ('' != $url && is_string($url)) {
    859859            // Delete any boomerang request keys in the query string.
    860860            $url = preg_replace('/boomerang=[\w]+/', '', $url);
    861            
     861
    862862            if (isset($_SESSION[$this->app]['boomerang']['url']) && is_array($_SESSION[$this->app]['boomerang']['url']) && !empty($_SESSION[$this->app]['boomerang']['url'])) {
    863863                // If the URL currently exists in the boomerang array, delete.
     
    866866                }
    867867            }
    868            
     868
    869869            if (isset($id)) {
    870870                $_SESSION[$this->app]['boomerang']['url'][$id] = $url;
     
    879879        }
    880880    }
    881    
     881
    882882    /**
    883883     * Return the URL set for the specified $id.
     
    894894            return false;
    895895        }
    896        
     896
    897897        if (isset($id)) {
    898898            if (isset($_SESSION[$this->app]['boomerang']['url'][$id])) {
     
    907907        }
    908908    }
    909    
     909
    910910    /**
    911911     * Delete the URL set for the specified $id.
     
    922922            return false;
    923923        }
    924        
     924
    925925        $this->logMsg(sprintf('deleteBoomerangURL(%s): %s', $id, $this->getBoomerangURL($id)), LOG_DEBUG, __FILE__, __LINE__);
    926926
     
    931931        }
    932932    }
    933    
     933
    934934    /**
    935935     * Check if a valid boomerang URL value has been set.
     
    947947            return false;
    948948        }
    949        
     949
    950950        if (!isset($_SESSION[$this->app]['boomerang']['url'])) {
    951951            return false;
    952952        }
    953    
     953
    954954        // Time is the timestamp of a boomerangURL redirection, or setting of a boomerangURL.
    955955        // a boomerang redirection will always occur at least several seconds after the last boomerang redirect
    956956        // or a boomerang being set.
    957957        $boomerang_time = isset($_SESSION[$this->app]['boomerang']['time']) ? $_SESSION[$this->app]['boomerang']['time'] : 0;
    958        
     958
    959959        $url = '';
    960960        if (isset($id) && isset($_SESSION[$this->app]['boomerang']['url'][$id])) {
     
    964964            $url = end($_SESSION[$this->app]['boomerang']['url']);
    965965        }
    966    
     966
    967967        $this->logMsg(sprintf('validBoomerangURL(%s) testing: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
    968968
     
    981981            return false;
    982982        }
    983        
     983
    984984        $this->logMsg(sprintf('validBoomerangURL(%s) is valid: %s', $id, $url), LOG_DEBUG, __FILE__, __LINE__);
    985985        return true;
     
    995995            $this =& App::getInstance();
    996996        }
    997        
     997
    998998        if (function_exists('apache_get_modules')) {
    999             $modules = apache_get_modules();
     999            $modules = apache_get_modules();
    10001000        } else {
    10011001            // It's safe to assume we have mod_ssl if we can't determine otherwise.
    10021002            $modules = array('mod_ssl');
    10031003        }
    1004        
     1004
    10051005        if ('on' != getenv('HTTPS') && $this->getParam('ssl_enabled') && in_array('mod_ssl', $modules)) {
    10061006            $this->raiseMsg(sprintf(_("Secure SSL connection made to %s"), $this->getParam('ssl_domain')), MSG_NOTICE, __FILE__, __LINE__);
     
    10091009        }
    10101010    }
    1011        
    1012    
     1011
     1012
    10131013    /**
    10141014     * to enforce the user to connect via http (port 80) by redirecting them to
     
    10221022    }
    10231023
    1024    
     1024
    10251025} // End.
    10261026
Note: See TracChangeset for help on using the changeset viewer.