isPhpCliMode() public static method

Returns true if PHP was invoked from command-line interface (shell)
public static isPhpCliMode ( ) : boolean
return boolean true if PHP invoked as a CGI or from CLI
Exemplo n.º 1
0
 public static function handleException(Exception $exception)
 {
     if (Common::isPhpCliMode()) {
         self::dieWithCliError($exception);
     }
     self::dieWithHtmlErrorPage($exception);
 }
Exemplo n.º 2
0
 public function findPhpBinary()
 {
     if (defined('PHP_BINARY')) {
         if ($this->isValidPhpType(PHP_BINARY)) {
             return PHP_BINARY . ' -q';
         }
         if ($this->isHhvmBinary(PHP_BINARY)) {
             return PHP_BINARY . ' --php';
         }
     }
     $bin = '';
     if (!empty($_SERVER['_']) && Common::isPhpCliMode()) {
         $bin = $this->getPhpCommandIfValid($_SERVER['_']);
     }
     if (empty($bin) && !empty($_SERVER['argv'][0]) && Common::isPhpCliMode()) {
         $bin = $this->getPhpCommandIfValid($_SERVER['argv'][0]);
     }
     if (!$this->isValidPhpType($bin)) {
         $bin = shell_exec('which php');
     }
     if (!$this->isValidPhpType($bin)) {
         $bin = shell_exec('which php5');
     }
     if (!$this->isValidPhpType($bin)) {
         return false;
     }
     $bin = trim($bin);
     if (!$this->isValidPhpVersion($bin)) {
         return false;
     }
     $bin .= ' -q';
     return $bin;
 }
Exemplo n.º 3
0
 /**
  * Constructor.
  * 
  * @param string|null $name The name of the command, eg, `'generate:api'`.
  */
 public function __construct($name = null)
 {
     if (!Common::isPhpCliMode()) {
         throw new \RuntimeException('Only executable in CLI mode');
     }
     parent::__construct($name);
 }
 /**
  * @param string $namespace
  * @param bool $singleInstance
  */
 public function __construct($namespace = 'Default', $singleInstance = false)
 {
     if (Common::isPhpCliMode()) {
         self::$_readable = true;
         return;
     }
     parent::__construct($namespace, $singleInstance);
 }
Exemplo n.º 5
0
 /**
  * Display the message in a nice red font with a nice icon
  * ... and dies
  *
  * @param string $message
  */
 public static function exitWithErrorMessage($message)
 {
     if (!Common::isPhpCliMode()) {
         @header('Content-Type: text/html; charset=utf-8');
     }
     $output = "<style>a{color:red;}</style>\n" . "<div style='color:red;font-family:Georgia;font-size:120%'>" . "<p><img src='plugins/Morpheus/images/error_medium.png' style='vertical-align:middle; float:left;padding:20 20 20 20' />" . $message . "</p></div>";
     print $output;
     exit;
 }
Exemplo n.º 6
0
 public function shouldRun(Tracker $tracker)
 {
     if (Common::isPhpCliMode()) {
         // don't run scheduled tasks in CLI mode from Tracker, this is the case
         // where we bulk load logs & don't want to lose time with tasks
         return false;
     }
     return $tracker->shouldRecordStatistics();
 }
 public function __invoke(array $record)
 {
     if (Common::isPhpCliMode()) {
         return $record;
     }
     if (empty($this->currentRequestKey)) {
         $this->currentRequestKey = substr(Common::generateUniqId(), 0, 5);
     }
     $record['extra']['request_id'] = $this->currentRequestKey;
     return $record;
 }
Exemplo n.º 8
0
 public static function formatScreenMessage(&$message, $level, $tag, $datetime, $log)
 {
     if ($message instanceof \Exception) {
         if (!Common::isPhpCliMode()) {
             @header('Content-Type: text/html; charset=utf-8');
         }
         $outputFormat = strtolower(Common::getRequestVar('format', 'html', 'string'));
         $response = new ResponseBuilder($outputFormat);
         $message = $response->getResponseException(new \Exception($message->getMessage()));
     }
 }
Exemplo n.º 9
0
 /**
  * @param $path
  * @param bool $startInstaller
  * @throws \Exception
  */
 private function checkConfigFileExists($path, $startInstaller = false)
 {
     if (is_readable($path)) {
         return;
     }
     $message = $this->translator->translate('General_ExceptionConfigurationFileNotFound', array($path));
     if (Common::isPhpCliMode()) {
         $message .= "\n" . $this->translator->translate('General_ExceptionConfigurationFileNotFound2', array($path, get_current_user()));
     }
     $exception = new \Exception($message);
     if ($startInstaller) {
         /**
          * Triggered when the configuration file cannot be found or read, which usually
          * means Piwik is not installed yet.
          *
          * This event can be used to start the installation process or to display a custom error message.
          *
          * @param \Exception $exception The exception that was thrown by `Config::getInstance()`.
          */
         Piwik::postEvent('Config.NoConfigurationFile', array($exception), $pending = true);
     } else {
         throw $exception;
     }
 }
Exemplo n.º 10
0
 /**
  * Gets the error message to output when a tracking request fails.
  *
  * @param Exception $e
  * @return string
  */
 protected function getMessageFromException($e)
 {
     // Note: duplicated from FormDatabaseSetup.isAccessDenied
     // Avoid leaking the username/db name when access denied
     if ($e->getCode() == 1044 || $e->getCode() == 42000) {
         return "Error while connecting to the Piwik database - please check your credentials in config/config.ini.php file";
     }
     if (Common::isPhpCliMode()) {
         return $e->getMessage() . "\n" . $e->getTraceAsString();
     }
     return $e->getMessage();
 }
Exemplo n.º 11
0
 protected function runUpdaterAndExit()
 {
     $updater = new Updater();
     $componentsWithUpdateFile = CoreUpdater::getComponentUpdates($updater);
     if (empty($componentsWithUpdateFile)) {
         Piwik::redirectToModule('CoreHome');
     }
     SettingsServer::setMaxExecutionTime(0);
     $cli = Common::isPhpCliMode() ? '_cli' : '';
     $welcomeTemplate = '@CoreUpdater/runUpdaterAndExit_welcome' . $cli;
     $doneTemplate = '@CoreUpdater/runUpdaterAndExit_done' . $cli;
     $viewWelcome = new View($welcomeTemplate);
     $viewDone = new View($doneTemplate);
     if (Common::isPhpCliMode()) {
         $this->doWelcomeUpdates($viewWelcome, $componentsWithUpdateFile);
         $output = $viewWelcome->render();
         if (!$this->coreError && Piwik::getModule() == 'CoreUpdater') {
             $this->doExecuteUpdates($viewDone, $updater, $componentsWithUpdateFile);
             $output .= $viewDone->render();
         }
         return $output;
     } else {
         if (Common::getRequestVar('updateCorePlugins', 0, 'integer') == 1) {
             $this->warningMessages = array();
             $this->doExecuteUpdates($viewDone, $updater, $componentsWithUpdateFile);
             $this->redirectToDashboardWhenNoError($updater);
             return $viewDone->render();
         } else {
             $viewWelcome->queries = $updater->getSqlQueriesToExecute();
             $viewWelcome->isMajor = $updater->hasMajorDbUpdate();
             $this->doWelcomeUpdates($viewWelcome, $componentsWithUpdateFile);
             return $viewWelcome->render();
         }
     }
     exit;
 }
Exemplo n.º 12
0
 /**
  * Executes a data purge, deleting log data and report data using the current config
  * options. Echo's the result of getDatabaseSize after purging.
  */
 public function executeDataPurge()
 {
     Piwik::checkUserHasSuperUserAccess();
     $this->checkTokenInUrl();
     // if the request isn't a POST, redirect to index
     if ($_SERVER["REQUEST_METHOD"] != "POST" && !Common::isPhpCliMode()) {
         $this->redirectToIndex('PrivacyManager', 'privacySettings');
         return;
     }
     $settings = PrivacyManager::getPurgeDataSettings();
     if ($settings['delete_logs_enable']) {
         $logDataPurger = LogDataPurger::make($settings);
         $logDataPurger->purgeData();
     }
     if ($settings['delete_reports_enable']) {
         $reportsPurger = ReportsPurger::make($settings, PrivacyManager::getAllMetricsToKeep());
         $reportsPurger->purgeData(true);
     }
 }
Exemplo n.º 13
0
 private function disableLoggingBasedOnConfig($logConfig)
 {
     $disableLogging = false;
     if (!empty($logConfig['log_only_when_cli']) && !Common::isPhpCliMode()) {
         $disableLogging = true;
     }
     if (!empty($logConfig['log_only_when_debug_parameter']) && !isset($_REQUEST['debug'])) {
         $disableLogging = true;
     }
     if ($disableLogging) {
         $this->currentLogLevel = self::NONE;
     }
 }
Exemplo n.º 14
0
 public function runUpdaterAndExit($doDryRun = null)
 {
     $updater = new Updater();
     $componentsWithUpdateFile = CoreUpdater::getComponentUpdates($updater);
     if (empty($componentsWithUpdateFile)) {
         throw new NoUpdatesFoundException("Everything is already up to date.");
     }
     SettingsServer::setMaxExecutionTime(0);
     $cli = Common::isPhpCliMode() ? '_cli' : '';
     $welcomeTemplate = '@CoreUpdater/runUpdaterAndExit_welcome' . $cli;
     $doneTemplate = '@CoreUpdater/runUpdaterAndExit_done' . $cli;
     $viewWelcome = new View($welcomeTemplate);
     $this->addCustomLogoInfo($viewWelcome);
     $viewDone = new View($doneTemplate);
     $this->addCustomLogoInfo($viewDone);
     $doExecuteUpdates = Common::getRequestVar('updateCorePlugins', 0, 'integer') == 1;
     if (is_null($doDryRun)) {
         $doDryRun = !$doExecuteUpdates;
     }
     if ($doDryRun) {
         $viewWelcome->queries = $updater->getSqlQueriesToExecute();
         $viewWelcome->isMajor = $updater->hasMajorDbUpdate();
         $this->doWelcomeUpdates($viewWelcome, $componentsWithUpdateFile);
         return $viewWelcome->render();
     }
     // CLI
     if (Common::isPhpCliMode()) {
         $this->doWelcomeUpdates($viewWelcome, $componentsWithUpdateFile);
         $output = $viewWelcome->render();
         // Proceed with upgrade in CLI only if user specifically asked for it, or if running console command
         $isUpdateRequested = Common::isRunningConsoleCommand() || Piwik::getModule() == 'CoreUpdater';
         if (!$this->coreError && $isUpdateRequested) {
             $this->doExecuteUpdates($viewDone, $updater, $componentsWithUpdateFile);
             $output .= $viewDone->render();
         }
         return $output;
     }
     // Web
     if ($doExecuteUpdates) {
         $this->warningMessages = array();
         $this->doExecuteUpdates($viewDone, $updater, $componentsWithUpdateFile);
         $this->redirectToDashboardWhenNoError($updater);
         return $viewDone->render();
     }
     exit;
 }
Exemplo n.º 15
0
 protected function shouldRunScheduledTasks()
 {
     // don't run scheduled tasks in CLI mode from Tracker, this is the case
     // where we bulk load logs & don't want to lose time with tasks
     return !Common::isPhpCliMode() && $this->getState() != self::STATE_LOGGING_DISABLE;
 }
Exemplo n.º 16
0
 /**
  * Sets outgoing header.
  *
  * @param string $header The header.
  * @param bool $replace Whether to replace existing or not.
  */
 public static function sendHeader($header, $replace = true)
 {
     // don't send header in CLI mode
     if (Common::isPhpCliMode()) {
         return;
     }
     if (isset($GLOBALS['PIWIK_TRACKER_LOCAL_TRACKING']) && $GLOBALS['PIWIK_TRACKER_LOCAL_TRACKING']) {
         @header($header, $replace);
     } else {
         header($header, $replace);
     }
 }
Exemplo n.º 17
0
 protected static function isRequestAuthorizedToArchive()
 {
     return !self::$archivingDisabledByTests && (Rules::isBrowserTriggerEnabled() || Common::isPhpCliMode() || Piwik::isUserIsSuperUser() && SettingsServer::isArchivePhpTriggered());
 }
Exemplo n.º 18
0
// first AJAX call by browser
$displayNotes = $start == 0;
// try getting the pecl location provider
$provider = new Pecl();
if (!$provider->isAvailable()) {
    if ($displayNotes) {
        Log::info("[note] The GeoIP PECL extension is not installed.");
    }
    $provider = null;
} else {
    $workingOrError = $provider->isWorking();
    if ($workingOrError !== true) {
        if ($displayNotes) {
            Log::info("[note] The GeoIP PECL extension is broken: {$workingOrError}");
        }
        if (Common::isPhpCliMode()) {
            Log::info("[note] Make sure your command line PHP is configured to use the PECL extension.");
        }
        $provider = null;
    }
}
// use php api if pecl extension cannot be used
if (is_null($provider)) {
    if ($displayNotes) {
        Log::info("[note] Falling back to PHP API. This may become too slow for you. If so, you can read this link on how to install the PECL extension: http://piwik.org/faq/how-to/#faq_164");
    }
    $provider = new Php();
    if (!$provider->isAvailable()) {
        if ($displayNotes) {
            Log::info("[note] The GeoIP PHP API is not available. This means you do not have a GeoIP location database in your ./misc directory. The database must be named either GeoIP.dat or GeoIPCity.dat based on the type of database it is.");
        }
Exemplo n.º 19
0
 private static function redirectToUrlNoExit($url)
 {
     if (UrlHelper::isLookLikeUrl($url) || strpos($url, 'index.php') === 0) {
         Common::sendResponseCode(302);
         Common::sendHeader("Location: {$url}");
     } else {
         echo "Invalid URL to redirect to.";
     }
     if (Common::isPhpCliMode()) {
         throw new Exception("If you were using a browser, Piwik would redirect you to this URL: {$url} \n\n");
     }
 }
Exemplo n.º 20
0
 /**
  * Returns the URL to this Piwik instance, eg. **http://demo.piwik.org/** or **http://example.org/piwik/**.
  *
  * @return string
  * @api
  */
 public static function getPiwikUrl()
 {
     // Only set in tests
     if (self::$piwikUrlCache !== null) {
         return self::$piwikUrlCache;
     }
     $key = 'piwikUrl';
     $url = Option::get($key);
     if (Common::isPhpCliMode() || SettingsServer::isArchivePhpTriggered() || defined('PIWIK_MODE_ARCHIVE')) {
         return $url;
     }
     $currentUrl = Common::sanitizeInputValue(Url::getCurrentUrlWithoutFileName());
     if (empty($url) || $currentUrl != $url) {
         if (strlen($currentUrl) >= strlen('http://a/')) {
             Option::set($key, $currentUrl, $autoLoad = true);
         }
         $url = $currentUrl;
     }
     return $url;
 }
Exemplo n.º 21
0
 protected function handleSSLRedirection()
 {
     if (!Common::isPhpCliMode() && Config::getInstance()->General['force_ssl'] == 1 && !ProxyHttp::isHttps() && !(Common::getRequestVar('module', '') == 'CoreAdminHome' && Common::getRequestVar('action', '') == 'optOut')) {
         $url = Url::getCurrentUrl();
         $url = str_replace("http://", "https://", $url);
         Url::redirectToUrl($url);
     }
 }
Exemplo n.º 22
0
 /**
  * Redirects the user to the specified URL.
  *
  * @param string $url
  * @api
  */
 public static function redirectToUrl($url)
 {
     // Close the session manually.
     // We should not have to call this because it was registered via register_shutdown_function,
     // but it is not always called fast enough
     Session::close();
     if (UrlHelper::isLookLikeUrl($url) || strpos($url, 'index.php') === 0) {
         @header("Location: {$url}");
     } else {
         echo "Invalid URL to redirect to.";
     }
     if (Common::isPhpCliMode()) {
         throw new Exception("If you were using a browser, Piwik would redirect you to this URL: {$url} \n\n");
     }
     exit;
 }
Exemplo n.º 23
0
 protected function handleSSLRedirection()
 {
     // Specifically disable for the opt out iframe
     if (Piwik::getModule() == 'CoreAdminHome' && Piwik::getAction() == 'optOut') {
         return;
     }
     // Disable Https for VisitorGenerator
     if (Piwik::getModule() == 'VisitorGenerator') {
         return;
     }
     if (Common::isPhpCliMode()) {
         return;
     }
     // Only enable this feature after Piwik is already installed
     if (!SettingsPiwik::isPiwikInstalled()) {
         return;
     }
     // proceed only when force_ssl = 1
     if (!SettingsPiwik::isHttpsForced()) {
         return;
     }
     Url::redirectToHttps();
 }
Exemplo n.º 24
0
 /**
  * Executes a data purge, deleting log data and report data using the current config
  * options. Echo's the result of getDatabaseSize after purging.
  */
 public function executeDataPurge()
 {
     $this->checkDataPurgeAdminSettingsIsEnabled();
     Piwik::checkUserHasSuperUserAccess();
     $this->checkTokenInUrl();
     // if the request isn't a POST, redirect to index
     if ($_SERVER["REQUEST_METHOD"] != "POST" && !Common::isPhpCliMode()) {
         $this->redirectToIndex('PrivacyManager', 'privacySettings');
         return;
     }
     $settings = PrivacyManager::getPurgeDataSettings();
     if ($settings['delete_logs_enable']) {
         /** @var LogDataPurger $logDataPurger */
         $logDataPurger = StaticContainer::get('Piwik\\Plugins\\PrivacyManager\\LogDataPurger');
         $logDataPurger->purgeData($settings['delete_logs_older_than']);
     }
     if ($settings['delete_reports_enable']) {
         $reportsPurger = ReportsPurger::make($settings, PrivacyManager::getAllMetricsToKeep());
         $reportsPurger->purgeData(true);
     }
 }
Exemplo n.º 25
0
 /**
  * Sets outgoing header.
  *
  * @param string $header The header.
  * @param bool $replace Whether to replace existing or not.
  */
 public static function sendHeader($header, $replace = true)
 {
     // don't send header in CLI mode
     if (!Common::isPhpCliMode() and !headers_sent()) {
         header($header, $replace);
     }
 }
Exemplo n.º 26
0
 /**
  * @param $level
  * @param $tag
  * @param $datetime
  * @param $message
  * @return string
  */
 private function getMessageFormattedScreen($level, $tag, $datetime, $message)
 {
     static $currentRequestKey;
     if (empty($currentRequestKey)) {
         $currentRequestKey = substr(Common::generateUniqId(), 0, 5);
     }
     if (is_string($message)) {
         if (!defined('PIWIK_TEST_MODE')) {
             $message = '[' . $currentRequestKey . '] ' . $message;
         }
         $message = $this->formatMessage($level, $tag, $datetime, $message);
         if (!Common::isPhpCliMode()) {
             $message = Common::sanitizeInputValue($message);
             $message = '<pre>' . $message . '</pre>';
         }
     } else {
         $logger = $this;
         /**
          * Triggered when trying to log an object to the screen. Plugins can use
          * this event to convert objects to strings before they are logged.
          *
          * The result of this callback can be HTML so no sanitization is done on the result.
          * This means **YOU MUST SANITIZE THE MESSAGE YOURSELF** if you use this event.
          *
          * **Example**
          *
          *     public function formatScreenMessage(&$message, $level, $tag, $datetime, $logger) {
          *         if ($message instanceof MyCustomDebugInfo) {
          *             $message = Common::sanitizeInputValue($message->formatForScreen());
          *         }
          *     }
          *
          * @param mixed &$message The object that is being logged. Event handlers should
          *                        check if the object is of a certain type and if it is,
          *                        set `$message` to the string that should be logged.
          * @param int $level The log level used with this log entry.
          * @param string $tag The current plugin that started logging (or if no plugin,
          *                    the current class).
          * @param string $datetime Datetime of the logging call.
          * @param Log $logger The Log singleton.
          */
         Piwik::postEvent(self::FORMAT_SCREEN_MESSAGE_EVENT, array(&$message, $level, $tag, $datetime, $logger));
     }
     return $message . "\n";
 }
Exemplo n.º 27
0
 /**
  * @throws \Exception
  * @return string or False if not set
  */
 protected static function getPiwikInstanceId()
 {
     // until Piwik is installed, we use hostname as instance_id
     if (!self::isPiwikInstalled() && Common::isPhpCliMode()) {
         // enterprise:install use case
         return Config::getHostname();
     }
     // config.ini.php not ready yet, instance_id will not be set
     if (!Config::getInstance()->existsLocalConfig()) {
         return false;
     }
     $instanceId = @Config::getInstance()->General['instance_id'];
     if (!empty($instanceId)) {
         return $instanceId;
     }
     // do not rewrite the path as Piwik uses the standard config.ini.php file
     return false;
 }
Exemplo n.º 28
0
 public static function isSupported()
 {
     return Common::isPhpCliMode() && !Common::isPhpCgiType();
 }
Exemplo n.º 29
0
 public function safemode($lastError = array())
 {
     $this->tryToRepairPiwik();
     if (empty($lastError)) {
         $lastError = array('message' => Common::getRequestVar('error_message', null, 'string'), 'file' => Common::getRequestVar('error_file', null, 'string'), 'line' => Common::getRequestVar('error_line', null, 'integer'));
     }
     $outputFormat = Common::getRequestVar('format', 'html', 'string');
     $outputFormat = strtolower($outputFormat);
     if (!empty($outputFormat) && 'html' !== $outputFormat) {
         $errorMessage = $lastError['message'];
         if (Piwik::isUserIsAnonymous()) {
             $errorMessage = 'A fatal error occurred.';
         }
         $response = new \Piwik\API\ResponseBuilder($outputFormat);
         $message = $response->getResponseException(new Exception($errorMessage));
         return $message;
     }
     if (Common::isPhpCliMode()) {
         // TODO: I can't find how this will ever get called / safeMode is never set for Console
         throw new Exception("Error: " . var_export($lastError, true));
     }
     $view = new View('@CorePluginsAdmin/safemode');
     $view->lastError = $lastError;
     $view->isSuperUser = Piwik::hasUserSuperUserAccess();
     $view->isAnonymousUser = Piwik::isUserIsAnonymous();
     $view->plugins = Plugin\Manager::getInstance()->loadAllPluginsAndGetTheirInfo();
     $view->deactivateNonce = Nonce::getNonce(static::DEACTIVATE_NONCE);
     $view->uninstallNonce = Nonce::getNonce(static::UNINSTALL_NONCE);
     $view->emailSuperUser = implode(',', Piwik::getAllSuperUserAccessEmailAddresses());
     $view->piwikVersion = Version::VERSION;
     $view->showVersion = !Common::getRequestVar('tests_hide_piwik_version', 0);
     $view->pluginCausesIssue = '';
     if (!empty($lastError['file'])) {
         preg_match('/piwik\\/plugins\\/(.*)\\//', $lastError['file'], $matches);
         if (!empty($matches[1])) {
             $view->pluginCausesIssue = $matches[1];
         }
     }
     return $view->render();
 }
Exemplo n.º 30
0
 /**
  * Script does run on http:// ONLY if the SU token is specified
  */
 private function initCheckCli()
 {
     if (Common::isPhpCliMode()) {
         return;
     }
     $token_auth = Common::getRequestVar('token_auth', '', 'string');
     if ($token_auth !== $this->token_auth || strlen($token_auth) != 32) {
         die('<b>You must specify the Super User token_auth as a parameter to this script, eg. <code>?token_auth=XYZ</code> if you wish to run this script through the browser. </b><br>
             However it is recommended to run it <a href="http://piwik.org/docs/setup-auto-archiving/">via cron in the command line</a>, since it can take a long time to run.<br/>
             In a shell, execute for example the following to trigger archiving on the local Piwik server:<br/>
             <code>$ /path/to/php /path/to/piwik/console core:archive --url=http://your-website.org/path/to/piwik/</code>');
     }
 }