Version: current

      1 <?php
      2
      3 /**
      4  * This file is the Sapphire bootstrap.  It will get your environment ready to call Director::direct().
      5  *
      6  * It takes care of:
      7  *  - Including _ss_environment.php
      8  *  - Normalisation of $_SERVER values
      9  *  - Initialisation of TEMP_FOLDER, BASE_URL, BASE_PATH, and other SilverStripe defines
     10  *  - Checking of PHP memory limit
     11  *  - Including all the files needed to get the manifest built
     12  *  - Building and including the manifest
     13  *
     14  * @todo This file currently contains a lot of bits and pieces, and its various responsibilities should probably be
     15  * moved into different subsystems.
     16  * @todo A lot of this stuff is very order-independent; for example, the require_once calls have to happen after the defines.'
     17  * This could be decoupled.
     18  * @package sapphire
     19  * @subpackage core
     20  */
     21
     22 ///////////////////////////////////////////////////////////////////////////////
     23 // ENVIRONMENT CONFIG
     24
     25 if(defined('E_DEPRECATED')) error_reporting((E_ALL ^ E_DEPRECATED) & ~E_STRICT);
     26 else error_reporting(E_ALL & ~E_STRICT);
     27 /*
     28  * This is for versions of PHP prior to version 5.2
     29  * Creating this here will allow both web requests and cron jobs to inherit it.
     30  */
     31 if (!function_exists('array_fill_keys')) {
     32     function array_fill_keys($keys,$value) {
     33         //Sometimes we get passed an empty array, and if that's the case, you'll get an error message
     34         if(sizeof($keys)==0)
     35             return Array();
     36         else
     37             return array_combine($keys,array_fill(0,count($keys),$value));
     38     }
     39 }
     40
     41 /**
     42  * Include _ss_environment.php files
     43  */
     44 // Director not already loaded
     45 $rootDir = (isset($_SERVER['SCRIPT_FILENAME'])) ? dirname($_SERVER['SCRIPT_FILENAME']).'/' : dirname(__FILE__).'/';
     46 $envDir = dirname($rootDir);
     47 for ($i=0; $i<3; $i++) {
     48     $envFile = $envDir . '/_ss_environment.php';
     49
     50     if(@file_exists($envFile)) {
     51         define('SS_ENVIRONMENT_FILE', $envFile);
     52         include_once($envFile);
     53         break;
     54     }
     55     if (!$envDir || $envDir == '/') break;
     56     $envDir = dirname($envDir);
     57 }
     58
     59 ///////////////////////////////////////////////////////////////////////////////
     60 // GLOBALS AND DEFINE SETTING
     61
     62 /**
     63  * A blank HTTP_HOST value is used to detect command-line execution.
     64  * We update the $_SERVER variable to contain data consistent with the rest of the application.
     65  */
     66 if(!isset($_SERVER['HTTP_HOST'])) {
     67     global $_FILE_TO_URL_MAPPING;
     68     // HTTP_HOST, REQUEST_PORT, SCRIPT_NAME, and PHP_SELF
     69     if(isset($_FILE_TO_URL_MAPPING)) {
     70         $fullPath = $testPath = $_SERVER['SCRIPT_FILENAME'];
     71         while($testPath && $testPath != "/"  && !preg_match('/^[A-Z]:\\\\$/', $testPath)) {
     72             if(isset($_FILE_TO_URL_MAPPING[$testPath])) {
     73                 $url = $_FILE_TO_URL_MAPPING[$testPath]
     74                     . str_replace(DIRECTORY_SEPARATOR,'/',substr($fullPath,strlen($testPath)));
     75
     76                 $_SERVER['HTTP_HOST'] = parse_url($url, PHP_URL_HOST);
     77                 $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'] = parse_url($url, PHP_URL_PATH);
     78                 $_SERVER['REQUEST_PORT'] = parse_url($url, PHP_URL_PORT);
     79                 break;
     80             }
     81             $testPath = dirname($testPath);
     82         }
     83     }
     84
     85     // Everything else
     86     $serverDefaults = array(
     87         'SERVER_PROTOCOL' => 'HTTP/1.1',
     88         'HTTP_ACCEPT' => 'text/plain;q=0.5',
     89         'HTTP_ACCEPT_LANGUAGE' => '*;q=0.5',
     90         'HTTP_ACCEPT_ENCODING' => '',
     91         'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1;q=0.5',
     92         'SERVER_SIGNATURE' => 'Command-line PHP/' . phpversion(),
     93         'SERVER_SOFTWARE' => 'PHP/' . phpversion(),
     94         'SERVER_ADDR' => '127.0.0.1',
     95         'REMOTE_ADDR' => '127.0.0.1',
     96         'REQUEST_METHOD' => 'GET',
     97         'HTTP_USER_AGENT' => 'CLI',
     98     );
     99
    100     $_SERVER = array_merge($serverDefaults, $_SERVER);
    101
    102 /**
    103  * If we have an HTTP_HOST value, then we're being called from the webserver and there are some things that
    104  * need checking
    105  */
    106 } else {
    107     /**
    108      * Fix magic quotes setting
    109      */
    110     if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
    111         if($_REQUEST) stripslashes_recursively($_REQUEST);
    112         if($_GET) stripslashes_recursively($_GET);
    113         if($_POST) stripslashes_recursively($_POST);
    114     }
    115
    116     /**
    117      * Fix HTTP_HOST from reverse proxies
    118      */
    119     if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
    120         $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_X_FORWARDED_HOST'];
    121     }
    122 }
    123
    124 /**
    125  * Define system paths
    126  */
    127 if(!defined('BASE_PATH')) {
    128     // Assuming that this file is sapphire/core/Core.php we can then determine the base path
    129     // DVP: изменено определение BASE_PATH чтобы работало через symlinks
    130     define('BASE_PATH', rtrim(dirname($rootDir), DIRECTORY_SEPARATOR));
    131 }
    132
    133 if(!defined('BASE_URL')) {
    134     // Determine the base URL by comparing SCRIPT_NAME to SCRIPT_FILENAME and getting the common
    135     // elements
    136     if(substr($_SERVER['SCRIPT_FILENAME'],0,strlen(BASE_PATH)) == BASE_PATH) {
    137         $urlSegmentToRemove = substr($_SERVER['SCRIPT_FILENAME'],strlen(BASE_PATH));
    138         if(substr($_SERVER['SCRIPT_NAME'],-strlen($urlSegmentToRemove)) == $urlSegmentToRemove) {
    139             $baseURL = substr($_SERVER['SCRIPT_NAME'], 0, -strlen($urlSegmentToRemove));
    140             define('BASE_URL', rtrim($baseURL, DIRECTORY_SEPARATOR));
    141         }
    142     }
    143
    144     // If that didn't work, failover to the old syntax.  Hopefully this isn't necessary, and maybe
    145     // if can be phased out?
    146     if(!defined('BASE_URL')) {
    147         $dir = (strpos($_SERVER['SCRIPT_NAME'], 'index.php') !== false)
    148             ? dirname($_SERVER['SCRIPT_NAME'])
    149             : dirname(dirname($_SERVER['SCRIPT_NAME']));
    150         define('BASE_URL', rtrim($dir, DIRECTORY_SEPARATOR));
    151     }
    152 }
    153 define('MODULES_DIR', 'modules');
    154 define('MODULES_PATH', BASE_PATH . '/' . MODULES_DIR);
    155 define('THEMES_DIR', 'themes');
    156 define('THEMES_PATH', BASE_PATH . '/' . THEMES_DIR);
    157 define('SAPPHIRE_DIR', 'sapphire');
    158 define('SAPPHIRE_PATH', BASE_PATH . '/' . SAPPHIRE_DIR);
    159 define('CMS_DIR', 'cms');
    160 define('CMS_PATH', BASE_PATH . '/' . CMS_DIR);
    161 define('THIRDPARTY_DIR', SAPPHIRE_DIR . '/thirdparty');
    162 define('THIRDPARTY_PATH', BASE_PATH . '/' . THIRDPARTY_DIR);
    163 define('ASSETS_DIR', 'assets');
    164 define('ASSETS_PATH', BASE_PATH . '/' . ASSETS_DIR);
    165
    166 /**
    167  * Define the temporary folder if it wasn't defined yet
    168  */
    169 if(!defined('TEMP_FOLDER')) {
    170     define('TEMP_FOLDER', getTempFolder());
    171 }
    172
    173 /**
    174  * Priorities definition. These constants are used in calls to _t() as an optional argument
    175  */
    176 define('PR_HIGH',100);
    177 define('PR_MEDIUM',50);
    178 define('PR_LOW',10);
    179
    180 /**
    181  * Ensure we have enough memory
    182  */
    183
    184 increase_memory_limit_to('64M');
    185
    186 ///////////////////////////////////////////////////////////////////////////////
    187 // INCLUDES
    188
    189 /**
    190  * Add sapphire/parsers and sapphire/thirdparty include paths, as well as adding a fixed reference
    191  * to BASEPATH/sapphrie in case we chdir()
    192  */
    193
    194 // Add after the "." path but before other paths (so that they take precedence over the PEAR
    195 // include paths)
    196 set_include_path(str_replace('.' . PATH_SEPARATOR, '.' . PATH_SEPARATOR
    197     . BASE_PATH . '/sapphire' . PATH_SEPARATOR
    198     . BASE_PATH . '/sapphire/parsers' . PATH_SEPARATOR
    199     . BASE_PATH . '/sapphire/thirdparty' . PATH_SEPARATOR
    200     , get_include_path()));
    201
    202 require_once("core/ManifestBuilder.php");
    203 require_once("core/ClassInfo.php");
    204 require_once('core/Object.php');
    205 require_once('core/control/Director.php');
    206 require_once('filesystem/Filesystem.php');
    207 require_once("core/Session.php");
    208
    209 ///////////////////////////////////////////////////////////////////////////////
    210 // MANIFEST
    211
    212 /**
    213  * Include the manifest
    214  */
    215 ManifestBuilder::include_manifest();
    216
    217 /**
    218  * ?debugmanifest=1 hook
    219  */
    220 if(isset($_GET['debugmanifest'])) Debug::show(file_get_contents(MANIFEST_FILE));
    221
    222 // If this is a dev site, enable php error reporting
    223 // This is necessary to force developers to acknowledge and fix
    224 // notice level errors (you can override this directive in your _config.php)
    225 if (Director::isLive()) {
    226     if(defined('E_DEPRECATED')) error_reporting(((E_ALL ^ E_NOTICE) ^ E_DEPRECATED) & ~E_STRICT);
    227     else error_reporting((E_ALL ^ E_NOTICE) & ~E_STRICT);
    228 }
    229 ///////////////////////////////////////////////////////////////////////////////
    230 // POST-MANIFEST COMMANDS
    231
    232 /**
    233  * Load error handlers
    234  */
    235 Debug::loadErrorHandlers();
    236
    237 ///////////////////////////////////////////////////////////////////////////////
    238 // HELPER FUNCTIONS
    239
    240 function getSysTempDir() {
    241     if(function_exists('sys_get_temp_dir')) {
    242         $sysTmp = sys_get_temp_dir();
    243     } elseif(isset($_ENV['TMP'])) {
    244         $sysTmp = $_ENV['TMP'];
    245     } else {
    246         $tmpFile = tempnam('adfadsfdas','');
    247         unlink($tmpFile);
    248         $sysTmp = dirname($tmpFile);
    249     }
    250     return $sysTmp;
    251 }
    252
    253 /**
    254  * Returns the temporary folder that sapphire/silverstripe should use for its cache files
    255  * This is loaded into the TEMP_FOLDER define on start up
    256  *
    257  * @param $base The base path to use as the basis for the temp folder name.  Defaults to BASE_PATH,
    258  * which is usually fine; however, the $base argument can be used to help test.
    259  */
    260 function getTempFolder($base = null) {
    261     $ssTmp = BASE_PATH . "/silverstripe-cache";
    262     if(@file_exists($ssTmp)) {
    263         return $ssTmp;
    264     }
    265
    266     if(!$base) $base = BASE_PATH;
    267
    268     if($base) {
    269         $cachefolder = "silverstripe-cache" . str_replace(array(' ', "/", ":", "\\"), "-", $base);
    270     } else {
    271         $cachefolder = "silverstripe-cache";
    272     }
    273
    274     $sysTmp = getSysTempDir();
    275
    276     $worked = true;
    277     $ssTmp = "$sysTmp/$cachefolder";
    278     if(!@file_exists($ssTmp)) {
    279         @$worked = mkdir($ssTmp);
    280     }
    281     if(!$worked) {
    282         $ssTmp = BASE_PATH . "/silverstripe-cache";
    283         $worked = true;
    284         if(!@file_exists($ssTmp)) {
    285             @$worked = mkdir($ssTmp);
    286         }
    287     }
    288     if(!$worked) {
    289         user_error("Permission problem gaining access to a temp folder. " .
    290             "Please create a folder named silverstripe-cache in the base folder "  .
    291             "of the installation and ensure it has the correct permissions", E_USER_ERROR);
    292     }
    293
    294     return $ssTmp;
    295 }
    296
    297 /**
    298  * Sapphire class autoloader.  Requires the ManifestBuilder to work.
    299  * $_CLASS_MANIFEST must have been loaded up by ManifestBuilder for this to successfully load
    300  * classes.  Classes will be loaded from any PHP file within the application.
    301  * If your class contains an underscore, for example, Page_Controller, then the filename is
    302  * expected to be the stuff before the underscore.  In this case, Page.php.
    303  */
    304 function __autoload($className) {
    305     global $_CLASS_MANIFEST;
    306     $lClassName = strtolower($className);
    307     if(isset($_CLASS_MANIFEST[$lClassName])) include_once($_CLASS_MANIFEST[$lClassName]);
    308     else if(isset($_CLASS_MANIFEST[$className])) include_once($_CLASS_MANIFEST[$className]);
    309 }
    310
    311 /**
    312  * Return the file where that class is stored
    313  */
    314 function getClassFile($className) {
    315     global $_CLASS_MANIFEST;
    316     $lClassName = strtolower($className);
    317     if(isset($_CLASS_MANIFEST[$lClassName])) return $_CLASS_MANIFEST[$lClassName];
    318     else if(isset($_CLASS_MANIFEST[$className])) return $_CLASS_MANIFEST[$className];
    319 }
    320
    321 /**
    322  * Creates a class instance by the "singleton" design pattern.
    323  * It will always return the same instance for this class,
    324  * which can be used for performance reasons and as a simple
    325  * way to access instance methods which don't rely on instance
    326  * data (e.g. the custom SilverStripe static handling).
    327  *
    328  * @uses Object::strong_create()
    329  *
    330  * @param string $className
    331  * @return Object
    332  */
    333 function singleton($className) {
    334     global $_SINGLETONS;
    335     if(!isset($className)) user_error("singleton() Called without a class", E_USER_ERROR);
    336     if(!is_string($className)) user_error("singleton() passed bad class_name: " . var_export($className,true), E_USER_ERROR);
    337     if(!isset($_SINGLETONS[$className])) {
    338         if(!class_exists($className)) user_error("Bad class to singleton() - $className", E_USER_ERROR);
    339         $_SINGLETONS[$className] = Object::strong_create($className,null, true);
    340         if(!$_SINGLETONS[$className]) user_error("singleton() Unknown class '$className'", E_USER_ERROR);
    341     }
    342     return $_SINGLETONS[$className];
    343 }
    344
    345 function project() {
    346     global $project;
    347     return $project;
    348 }
    349
    350 function stripslashes_recursively(&$array) {
    351     foreach($array as $k => $v) {
    352         if(is_array($v)) stripslashes_recursively($array[$k]);
    353         else $array[$k] = stripslashes($v);
    354     }
    355 }
    356
    357 /**
    358  * @see i18n::_t()
    359  */
    360 function _t($entity, $string = "", $priority = 40, $context = "") {
    361     return i18n::_t($entity, $string, $priority, $context);
    362 }
    363
    364 /**
    365  * Increase the memory limit to the given level if it's currently too low.
    366  * @param A memory limit string, such as "64M".  If omitted, unlimited memory will be set.
    367  */
    368 function increase_memory_limit_to($memoryLimit = -1) {
    369     $curLimit = ini_get('memory_limit');
    370
    371     // Can't go higher than infinite
    372     if($curLimit == -1) return;
    373
    374     // Increase the memory limit if it's too low
    375     if($memoryLimit == -1 || translate_memstring($memoryLimit) > translate_memstring($curLimit)) {
    376         ini_set('memory_limit', $memoryLimit);
    377     }
    378 }
    379
    380 /**
    381  * Turn a memory string, such as 512M into an actual number of bytes.
    382  * @param A memory limit string, such as "64M"
    383  */
    384 function translate_memstring($memString) {
    385     switch(strtolower(substr($memString, -1))) {
    386         case "k": return round(substr($memString, 0, -1)*1024);
    387         case "m": return round(substr($memString, 0, -1)*1024*1024);
    388         case "g": return round(substr($memString, 0, -1)*1024*1024*1024);
    389         default: return round($memString);
    390     }
    391 }
    392
    393 /**
    394  * Increase the time limit of this script.  By default, the time will be unlimited.
    395  * @param $timeLimit The time limit in seconds.  If omitted, no time limit will be set.
    396  */
    397 function increase_time_limit_to($timeLimit = null) {
    398     if(!ini_get('safe_mode')) {
    399         if(!$timeLimit) {
    400             set_time_limit(0);
    401         } else {
    402             $currTimeLimit = ini_get('max_execution_time');
    403             if($currTimeLimit && $currTimeLimit < $timeLimit) {
    404                 set_time_limit($timeLimit);
    405             }
    406         }
    407     }
    408 }
    409
    410 ?>
    411

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -