raiseMemoryLimitIfNecessary() public static method

Raise PHP memory limit if below the minimum required
public static raiseMemoryLimitIfNecessary ( ) : boolean
return boolean true if set; false otherwise
Beispiel #1
0
 public function execute()
 {
     $label = $this->translator->translate('Installation_SystemCheckMemoryLimit');
     SettingsServer::raiseMemoryLimitIfNecessary();
     $memoryLimit = SettingsServer::getMemoryLimitValue();
     $comment = $memoryLimit . 'M';
     if ($memoryLimit >= $this->minimumMemoryLimit) {
         $status = DiagnosticResult::STATUS_OK;
     } else {
         $status = DiagnosticResult::STATUS_WARNING;
         $comment .= sprintf('<br />%s<br />%s', $this->translator->translate('Installation_SystemCheckMemoryLimitHelp'), $this->translator->translate('Installation_RestartWebServer'));
     }
     return array(DiagnosticResult::singleResult($label, $status, $comment));
 }
 /**
  * Must be called before dispatch()
  * - checks that directories are writable,
  * - loads the configuration file,
  * - loads the plugin,
  * - inits the DB connection,
  * - etc.
  *
  * @throws Exception
  * @return void
  */
 public function init()
 {
     static $initialized = false;
     if ($initialized) {
         return;
     }
     $initialized = true;
     $tmpPath = StaticContainer::get('path.tmp');
     $directoriesToCheck = array($tmpPath, $tmpPath . '/assets/', $tmpPath . '/cache/', $tmpPath . '/logs/', $tmpPath . '/tcpdf/', $tmpPath . '/templates_c/');
     Filechecks::dieIfDirectoriesNotWritable($directoriesToCheck);
     $this->handleMaintenanceMode();
     $this->handleProfiler();
     $this->handleSSLRedirection();
     Plugin\Manager::getInstance()->loadPluginTranslations();
     Plugin\Manager::getInstance()->loadActivatedPlugins();
     // try to connect to the database
     try {
         Db::createDatabaseObject();
         Db::fetchAll("SELECT DATABASE()");
     } catch (Exception $exception) {
         if (self::shouldRethrowException()) {
             throw $exception;
         }
         Log::debug($exception);
         /**
          * Triggered when Piwik cannot connect to the database.
          *
          * This event can be used to start the installation process or to display a custom error
          * message.
          *
          * @param Exception $exception The exception thrown from creating and testing the database
          *                             connection.
          */
         Piwik::postEvent('Db.cannotConnectToDb', array($exception), $pending = true);
         throw $exception;
     }
     // try to get an option (to check if data can be queried)
     try {
         Option::get('TestingIfDatabaseConnectionWorked');
     } catch (Exception $exception) {
         if (self::shouldRethrowException()) {
             throw $exception;
         }
         Log::debug($exception);
         /**
          * Triggered when Piwik cannot access database data.
          *
          * This event can be used to start the installation process or to display a custom error
          * message.
          *
          * @param Exception $exception The exception thrown from trying to get an option value.
          */
         Piwik::postEvent('Config.badConfigurationFile', array($exception), $pending = true);
         throw $exception;
     }
     // Init the Access object, so that eg. core/Updates/* can enforce Super User and use some APIs
     Access::getInstance();
     /**
      * Triggered just after the platform is initialized and plugins are loaded.
      *
      * This event can be used to do early initialization.
      *
      * _Note: At this point the user is not authenticated yet._
      */
     Piwik::postEvent('Request.dispatchCoreAndPluginUpdatesScreen');
     $this->throwIfPiwikVersionIsOlderThanDBSchema();
     \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins();
     // ensure the current Piwik URL is known for later use
     if (method_exists('Piwik\\SettingsPiwik', 'getPiwikUrl')) {
         SettingsPiwik::getPiwikUrl();
     }
     /**
      * Triggered before the user is authenticated, when the global authentication object
      * should be created.
      *
      * Plugins that provide their own authentication implementation should use this event
      * to set the global authentication object (which must derive from {@link Piwik\Auth}).
      *
      * **Example**
      *
      *     Piwik::addAction('Request.initAuthenticationObject', function() {
      *         StaticContainer::getContainer()->set('Piwik\Auth', new MyAuthImplementation());
      *     });
      */
     Piwik::postEvent('Request.initAuthenticationObject');
     try {
         $authAdapter = StaticContainer::get('Piwik\\Auth');
     } catch (Exception $e) {
         $message = "Authentication object cannot be found in the container. Maybe the Login plugin is not activated?\n                        <br />You can activate the plugin by adding:<br />\n                        <code>Plugins[] = Login</code><br />\n                        under the <code>[Plugins]</code> section in your config/config.ini.php";
         $ex = new AuthenticationFailedException($message);
         $ex->setIsHtmlMessage();
         throw $ex;
     }
     Access::getInstance()->reloadAccess($authAdapter);
     // Force the auth to use the token_auth if specified, so that embed dashboard
     // and all other non widgetized controller methods works fine
     if (Common::getRequestVar('token_auth', false, 'string') !== false) {
         Request::reloadAuthUsingTokenAuth();
     }
     SettingsServer::raiseMemoryLimitIfNecessary();
     \Piwik\Plugin\Manager::getInstance()->postLoadPlugins();
     /**
      * Triggered after the platform is initialized and after the user has been authenticated, but
      * before the platform has handled the request.
      *
      * Piwik uses this event to check for updates to Piwik.
      */
     Piwik::postEvent('Platform.initialized');
 }
Beispiel #3
0
 /**
  * If the token_auth is found in the $request parameter,
  * the current session will be authenticated using this token_auth.
  * It will overwrite the previous Auth object.
  *
  * @param array $request If null, uses the default request ($_GET)
  * @return void
  * @ignore
  */
 public static function reloadAuthUsingTokenAuth($request = null)
 {
     // if a token_auth is specified in the API request, we load the right permissions
     $token_auth = Common::getRequestVar('token_auth', '', 'string', $request);
     if ($token_auth) {
         /**
          * Triggered when authenticating an API request, but only if the **token_auth**
          * query parameter is found in the request.
          *
          * Plugins that provide authentication capabilities should subscribe to this event
          * and make sure the global authentication object (the object returned by `Registry::get('auth')`)
          * is setup to use `$token_auth` when its `authenticate()` method is executed.
          *
          * @param string $token_auth The value of the **token_auth** query parameter.
          */
         Piwik::postEvent('API.Request.authenticate', array($token_auth));
         Access::getInstance()->reloadAccess();
         SettingsServer::raiseMemoryLimitIfNecessary();
     }
 }
Beispiel #4
0
 /**
  * Get system information
  */
 public static function getSystemInformation()
 {
     global $piwik_minimumPHPVersion;
     $minimumMemoryLimit = Config::getInstance()->General['minimum_memory_limit'];
     $infos = array();
     $directoriesToCheck = array('/tmp/', '/tmp/assets/', '/tmp/cache/', '/tmp/climulti/', '/tmp/latest/', '/tmp/logs/', '/tmp/sessions/', '/tmp/tcpdf/', '/tmp/templates_c/');
     if (!DbHelper::isInstalled()) {
         // at install, need /config to be writable (so we can create config.ini.php)
         $directoriesToCheck[] = '/config/';
     }
     $infos['directories'] = Filechecks::checkDirectoriesWritable($directoriesToCheck);
     $infos['can_auto_update'] = Filechecks::canAutoUpdate();
     self::initServerFilesForSecurity();
     $infos['phpVersion_minimum'] = $piwik_minimumPHPVersion;
     $infos['phpVersion'] = PHP_VERSION;
     $infos['phpVersion_ok'] = self::isPhpVersionValid($infos['phpVersion']);
     // critical errors
     $extensions = @get_loaded_extensions();
     $needed_extensions = array('zlib', 'SPL', 'iconv', 'json', 'mbstring');
     // HHVM provides the required subset of Reflection but lists Reflections as missing
     if (!defined('HHVM_VERSION')) {
         $needed_extensions[] = 'Reflection';
     }
     $infos['needed_extensions'] = $needed_extensions;
     $infos['missing_extensions'] = array();
     foreach ($needed_extensions as $needed_extension) {
         if (!in_array($needed_extension, $extensions)) {
             $infos['missing_extensions'][] = $needed_extension;
         }
     }
     // Special case for mbstring
     if (!function_exists('mb_get_info') || (int) ini_get('mbstring.func_overload') != 0) {
         $infos['missing_extensions'][] = 'mbstring';
     }
     $infos['pdo_ok'] = false;
     if (in_array('PDO', $extensions)) {
         $infos['pdo_ok'] = true;
     }
     $infos['adapters'] = Adapter::getAdapters();
     $needed_functions = array('debug_backtrace', 'create_function', 'eval', 'gzcompress', 'gzuncompress', 'pack');
     $infos['needed_functions'] = $needed_functions;
     $infos['missing_functions'] = array();
     foreach ($needed_functions as $needed_function) {
         if (!self::functionExists($needed_function)) {
             $infos['missing_functions'][] = $needed_function;
         }
     }
     // warnings
     $desired_extensions = array('json', 'libxml', 'dom', 'SimpleXML');
     $infos['desired_extensions'] = $desired_extensions;
     $infos['missing_desired_extensions'] = array();
     foreach ($desired_extensions as $desired_extension) {
         if (!in_array($desired_extension, $extensions)) {
             $infos['missing_desired_extensions'][] = $desired_extension;
         }
     }
     $desired_functions = array('set_time_limit', 'mail', 'parse_ini_file', 'glob', 'gzopen');
     $infos['missing_desired_functions'] = array();
     foreach ($desired_functions as $desired_function) {
         if (!self::functionExists($desired_function)) {
             $infos['missing_desired_functions'][] = $desired_function;
         }
     }
     $sessionAutoStarted = (int) ini_get('session.auto_start');
     if ($sessionAutoStarted) {
         $infos['missing_desired_functions'][] = 'session.auto_start';
     }
     $desired_settings = array('session.auto_start');
     $infos['desired_functions'] = array_merge($desired_functions, $desired_settings);
     $infos['openurl'] = Http::getTransportMethod();
     $infos['gd_ok'] = SettingsServer::isGdExtensionEnabled();
     $serverSoftware = isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : '';
     $infos['serverVersion'] = addslashes($serverSoftware);
     $infos['serverOs'] = @php_uname();
     $infos['serverTime'] = date('H:i:s');
     $infos['memoryMinimum'] = $minimumMemoryLimit;
     $infos['memory_ok'] = true;
     $infos['memoryCurrent'] = '';
     $raised = SettingsServer::raiseMemoryLimitIfNecessary();
     if (($memoryValue = SettingsServer::getMemoryLimitValue()) > 0) {
         $infos['memoryCurrent'] = $memoryValue . 'M';
         $infos['memory_ok'] = $memoryValue >= $minimumMemoryLimit;
     }
     $infos['isWindows'] = SettingsServer::isWindows();
     $integrityInfo = Filechecks::getFileIntegrityInformation();
     $infos['integrity'] = $integrityInfo[0];
     $infos['integrityErrorMessages'] = array();
     if (isset($integrityInfo[1])) {
         if ($infos['integrity'] == false) {
             $infos['integrityErrorMessages'][] = Piwik::translate('General_FileIntegrityWarningExplanation');
         }
         $infos['integrityErrorMessages'] = array_merge($infos['integrityErrorMessages'], array_slice($integrityInfo, 1));
     }
     $infos['timezone'] = SettingsServer::isTimezoneSupportEnabled();
     $process = new CliMulti();
     $infos['cli_process_ok'] = $process->supportsAsync();
     $infos['tracker_status'] = Common::getRequestVar('trackerStatus', 0, 'int');
     // check if filesystem is NFS, if it is file based sessions won't work properly
     $infos['is_nfs'] = Filesystem::checkIfFileSystemIsNFS();
     $infos = self::enrichSystemChecks($infos);
     return $infos;
 }
 /**
  * Must be called before dispatch()
  * - checks that directories are writable,
  * - loads the configuration file,
  * - loads the plugin,
  * - inits the DB connection,
  * - etc.
  *
  * @throws Exception
  * @return void
  */
 public function init()
 {
     static $initialized = false;
     if ($initialized) {
         return;
     }
     $initialized = true;
     try {
         Registry::set('timer', new Timer());
         $directoriesToCheck = array('/tmp/', '/tmp/assets/', '/tmp/cache/', '/tmp/logs/', '/tmp/tcpdf/', '/tmp/templates_c/');
         Filechecks::dieIfDirectoriesNotWritable($directoriesToCheck);
         self::assignCliParametersToRequest();
         Translate::loadEnglishTranslation();
         $exceptionToThrow = self::createConfigObject();
         if (Session::isFileBasedSessions()) {
             Session::start();
         }
         $this->handleMaintenanceMode();
         $this->handleSSLRedirection();
         $this->handleProfiler();
         $pluginsManager = \Piwik\Plugin\Manager::getInstance();
         $pluginsToLoad = Config::getInstance()->Plugins['Plugins'];
         $pluginsManager->loadPlugins($pluginsToLoad);
         if ($exceptionToThrow) {
             throw $exceptionToThrow;
         }
         try {
             Db::createDatabaseObject();
             Option::get('TestingIfDatabaseConnectionWorked');
         } catch (Exception $exception) {
             if (self::shouldRethrowException()) {
                 throw $exception;
             }
             /**
              * Triggered if the INI config file has the incorrect format or if certain required configuration
              * options are absent.
              * 
              * This event can be used to start the installation process or to display a custom error message.
              * 
              * @param Exception $exception The exception thrown from creating and testing the database
              *                             connection.
              */
             Piwik::postEvent('Config.badConfigurationFile', array($exception), $pending = true);
             throw $exception;
         }
         // Init the Access object, so that eg. core/Updates/* can enforce Super User and use some APIs
         Access::getInstance();
         /**
          * Triggered just after the platform is initialized and plugins are loaded.
          * 
          * This event can be used to do early initialization.
          * 
          * _Note: At this point the user is not authenticated yet._
          */
         Piwik::postEvent('Request.dispatchCoreAndPluginUpdatesScreen');
         \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins();
         // ensure the current Piwik URL is known for later use
         if (method_exists('Piwik\\SettingsPiwik', 'getPiwikUrl')) {
             $host = SettingsPiwik::getPiwikUrl();
         }
         /**
          * Triggered before the user is authenticated, when the global authentication object
          * should be created.
          * 
          * Plugins that provide their own authentication implementation should use this event
          * to set the global authentication object (which must derive from {@link Piwik\Auth}).
          * 
          * **Example**
          * 
          *     Piwik::addAction('Request.initAuthenticationObject', function() {
          *         Piwik\Registry::set('auth', new MyAuthImplementation());
          *     });
          */
         Piwik::postEvent('Request.initAuthenticationObject');
         try {
             $authAdapter = Registry::get('auth');
         } catch (Exception $e) {
             throw new Exception("Authentication object cannot be found in the Registry. Maybe the Login plugin is not activated?\n                                <br />You can activate the plugin by adding:<br />\n                                <code>Plugins[] = Login</code><br />\n                                under the <code>[Plugins]</code> section in your config/config.ini.php");
         }
         Access::getInstance()->reloadAccess($authAdapter);
         // Force the auth to use the token_auth if specified, so that embed dashboard
         // and all other non widgetized controller methods works fine
         if (($token_auth = Common::getRequestVar('token_auth', false, 'string')) !== false) {
             Request::reloadAuthUsingTokenAuth();
         }
         SettingsServer::raiseMemoryLimitIfNecessary();
         Translate::reloadLanguage();
         $pluginsManager->postLoadPlugins();
         /**
          * Triggered after the platform is initialized and after the user has been authenticated, but
          * before the platform has handled the request.
          * 
          * Piwik uses this event to check for updates to Piwik.
          */
         Piwik::postEvent('Updater.checkForUpdates');
     } catch (Exception $e) {
         if (self::shouldRethrowException()) {
             throw $e;
         }
         $debugTrace = $e->getTraceAsString();
         Piwik_ExitWithMessage($e->getMessage(), $debugTrace, true);
     }
 }
Beispiel #6
0
 /**
  * The current session will be authenticated using this token_auth.
  * It will overwrite the previous Auth object.
  *
  * @param string $tokenAuth
  * @return void
  */
 private static function forceReloadAuthUsingTokenAuth($tokenAuth)
 {
     /**
      * Triggered when authenticating an API request, but only if the **token_auth**
      * query parameter is found in the request.
      *
      * Plugins that provide authentication capabilities should subscribe to this event
      * and make sure the global authentication object (the object returned by `StaticContainer::get('Piwik\Auth')`)
      * is setup to use `$token_auth` when its `authenticate()` method is executed.
      *
      * @param string $token_auth The value of the **token_auth** query parameter.
      */
     Piwik::postEvent('API.Request.authenticate', array($tokenAuth));
     Access::getInstance()->reloadAccess();
     SettingsServer::raiseMemoryLimitIfNecessary();
 }
 /**
  * Get system information
  */
 public static function getSystemInformation()
 {
     global $piwik_minimumPHPVersion;
     $minimumMemoryLimit = Config::getInstance()->General['minimum_memory_limit'];
     $infos = array();
     $infos['general_infos'] = array();
     $directoriesToCheck = array();
     if (!DbHelper::isInstalled()) {
         // at install, need /config to be writable (so we can create config.ini.php)
         $directoriesToCheck[] = '/config/';
     }
     $directoriesToCheck = array_merge($directoriesToCheck, array('/tmp/', '/tmp/assets/', '/tmp/cache/', '/tmp/latest/', '/tmp/logs/', '/tmp/sessions/', '/tmp/tcpdf/', '/tmp/templates_c/'));
     $infos['directories'] = Filechecks::checkDirectoriesWritable($directoriesToCheck);
     $infos['can_auto_update'] = Filechecks::canAutoUpdate();
     self::initServerFilesForSecurity();
     $infos['phpVersion_minimum'] = $piwik_minimumPHPVersion;
     $infos['phpVersion'] = PHP_VERSION;
     $infos['phpVersion_ok'] = version_compare($piwik_minimumPHPVersion, $infos['phpVersion']) === -1;
     // critical errors
     $extensions = @get_loaded_extensions();
     $needed_extensions = array('zlib', 'SPL', 'iconv', 'Reflection');
     $infos['needed_extensions'] = $needed_extensions;
     $infos['missing_extensions'] = array();
     foreach ($needed_extensions as $needed_extension) {
         if (!in_array($needed_extension, $extensions)) {
             $infos['missing_extensions'][] = $needed_extension;
         }
     }
     $infos['pdo_ok'] = false;
     if (in_array('PDO', $extensions)) {
         $infos['pdo_ok'] = true;
     }
     $infos['adapters'] = Adapter::getAdapters();
     $needed_functions = array('debug_backtrace', 'create_function', 'eval', 'gzcompress', 'gzuncompress', 'pack');
     $infos['needed_functions'] = $needed_functions;
     $infos['missing_functions'] = array();
     foreach ($needed_functions as $needed_function) {
         if (!self::functionExists($needed_function)) {
             $infos['missing_functions'][] = $needed_function;
         }
     }
     // warnings
     $desired_extensions = array('json', 'libxml', 'dom', 'SimpleXML');
     $infos['desired_extensions'] = $desired_extensions;
     $infos['missing_desired_extensions'] = array();
     foreach ($desired_extensions as $desired_extension) {
         if (!in_array($desired_extension, $extensions)) {
             $infos['missing_desired_extensions'][] = $desired_extension;
         }
     }
     $desired_functions = array('set_time_limit', 'mail', 'parse_ini_file', 'glob');
     $infos['desired_functions'] = $desired_functions;
     $infos['missing_desired_functions'] = array();
     foreach ($desired_functions as $desired_function) {
         if (!self::functionExists($desired_function)) {
             $infos['missing_desired_functions'][] = $desired_function;
         }
     }
     $infos['openurl'] = Http::getTransportMethod();
     $infos['gd_ok'] = SettingsServer::isGdExtensionEnabled();
     $infos['hasMbstring'] = false;
     $infos['multibyte_ok'] = true;
     if (function_exists('mb_internal_encoding')) {
         $infos['hasMbstring'] = true;
         if ((int) ini_get('mbstring.func_overload') != 0) {
             $infos['multibyte_ok'] = false;
         }
     }
     $serverSoftware = isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : '';
     $infos['serverVersion'] = addslashes($serverSoftware);
     $infos['serverOs'] = @php_uname();
     $infos['serverTime'] = date('H:i:s');
     $infos['registerGlobals_ok'] = ini_get('register_globals') == 0;
     $infos['memoryMinimum'] = $minimumMemoryLimit;
     $infos['memory_ok'] = true;
     $infos['memoryCurrent'] = '';
     $raised = SettingsServer::raiseMemoryLimitIfNecessary();
     if (($memoryValue = SettingsServer::getMemoryLimitValue()) > 0) {
         $infos['memoryCurrent'] = $memoryValue . 'M';
         $infos['memory_ok'] = $memoryValue >= $minimumMemoryLimit;
     }
     $infos['isWindows'] = SettingsServer::isWindows();
     $integrityInfo = Filechecks::getFileIntegrityInformation();
     $infos['integrity'] = $integrityInfo[0];
     $infos['integrityErrorMessages'] = array();
     if (isset($integrityInfo[1])) {
         if ($infos['integrity'] == false) {
             $infos['integrityErrorMessages'][] = Piwik::translate('General_FileIntegrityWarningExplanation');
         }
         $infos['integrityErrorMessages'] = array_merge($infos['integrityErrorMessages'], array_slice($integrityInfo, 1));
     }
     $infos['timezone'] = SettingsServer::isTimezoneSupportEnabled();
     $infos['tracker_status'] = Common::getRequestVar('trackerStatus', 0, 'int');
     $infos['protocol'] = ProxyHeaders::getProtocolInformation();
     if (!\Piwik\ProxyHttp::isHttps() && $infos['protocol'] !== null) {
         $infos['general_infos']['assume_secure_protocol'] = '1';
     }
     if (count($headers = ProxyHeaders::getProxyClientHeaders()) > 0) {
         $infos['general_infos']['proxy_client_headers'] = $headers;
     }
     if (count($headers = ProxyHeaders::getProxyHostHeaders()) > 0) {
         $infos['general_infos']['proxy_host_headers'] = $headers;
     }
     // check if filesystem is NFS, if it is file based sessions won't work properly
     $infos['is_nfs'] = Filesystem::checkIfFileSystemIsNFS();
     $infos = self::enrichSystemChecks($infos);
     return $infos;
 }