runningFromCLI() public static method

Make sure we're being called from the command line, and not via the web.
public static runningFromCLI ( ) : boolean
return boolean True if we are, false otherwise.
Ejemplo n.º 1
0
 /**
  * In the long run we might wish to use the Horde permission system
  * here. But for the first draft this would be too much as the permission
  * system would also require integration with the group system etc.
  */
 public function hasPermission($id, $user = null, $perm = null)
 {
     $global = $this->_hasPermission($this->perms, $id, $perm);
     if ($user === null) {
         try {
             $session = Horde_Kolab_Session::singleton();
             if (!empty($session->user_uid)) {
                 $user = $this->getObject($session->user_uid);
                 if (get_class($user) == $this->conf['koward']['cli_admin'] && Horde_Cli::runningFromCLI()) {
                     return true;
                 }
                 $type = $this->getType($user);
                 if (isset($this->objects[$type]['permission'])) {
                     return $this->_hasPermission($this->objects[$type]['permission'], $id, $perm);
                 }
             }
         } catch (Exception $e) {
             Horde::log($e, 'DEBUG');
         }
     }
     return $global;
 }
Ejemplo n.º 2
0
 /**
  * Returns whether the event should be considered private.
  *
  * The event's private flag can be overriden if the current user
  * is an administrator and the code is run from command line, and no
  * $user parameter was passed. This is to allow full event notifications in
  * alarm messages (agendas know the user the agenda is being prepared for).
  *
  * @param string $user  The current user. If omitted, uses the current user.
  *
  * @return boolean  Whether to consider the event as private.
  */
 public function isPrivate($user = null)
 {
     global $registry;
     $haveNullUser = false;
     if ($user === null) {
         $user = $registry->getAuth();
         $haveNullUser = true;
     }
     if (!(Horde_Cli::runningFromCLI() && $registry->isAdmin()) && $this->private && $this->creator != $user) {
         return true;
     }
     if ($registry->isAdmin() && $haveNullUser || $this->hasPermission(Horde_Perms::READ, $user)) {
         return false;
     }
     return true;
 }
Ejemplo n.º 3
0
    /**
     * Aborts with a fatal error, displaying debug information to the user.
     *
     * @param mixed $error  Either a string or an object with a getMessage()
     *                      method (e.g. PEAR_Error, Exception).
     */
    public static function fatal($error)
    {
        global $registry;
        if (is_object($error)) {
            switch (get_class($error)) {
                case 'Horde_Exception_AuthenticationFailure':
                    $auth_app = !$registry->clearAuthApp($error->application);
                    if ($auth_app && $registry->isAuthenticated(array('app' => $error->application, 'notransparent' => true))) {
                        break;
                    }
                    try {
                        Horde::log($error, 'NOTICE');
                    } catch (Exception $e) {
                    }
                    if (Horde_Cli::runningFromCLI()) {
                        $cli = new Horde_Cli();
                        $cli->fatal($error);
                    }
                    $params = array();
                    if ($registry->getAuth()) {
                        $params['app'] = $error->application;
                    }
                    switch ($error->getCode()) {
                        case Horde_Auth::REASON_MESSAGE:
                            $params['msg'] = $error->getMessage();
                            $params['reason'] = $error->getCode();
                            break;
                    }
                    $logout_url = $registry->getLogoutUrl($params);
                    /* Clear authentication here. Otherwise, there might be
                     * issues on the login page since we would otherwise need
                     * to do session token checking (which might not be
                     * available, so logout won't happen, etc...) */
                    if ($auth_app && array_key_exists('app', $params)) {
                        $registry->clearAuth();
                    }
                    $logout_url->redirect();
            }
        }
        try {
            Horde::log($error, 'EMERG');
        } catch (Exception $e) {
        }
        try {
            $cli = Horde_Cli::runningFromCLI();
        } catch (Exception $e) {
            die($e);
        }
        if ($cli) {
            $cli = new Horde_Cli();
            $cli->fatal($error);
        }
        if (!headers_sent()) {
            header('Content-type: text/html; charset=UTF-8');
        }
        echo <<<HTML
<html>
<head><title>Horde :: Fatal Error</title></head>
<body style="background:#fff; color:#000">
HTML;
        ob_start();
        try {
            $admin = isset($registry) && $registry->isAdmin();
            echo '<h1>' . Horde_Core_Translation::t("A fatal error has occurred") . '</h1>';
            if (is_object($error) && method_exists($error, 'getMessage')) {
                echo '<h3>' . htmlspecialchars($error->getMessage()) . '</h3>';
            } elseif (is_string($error)) {
                echo '<h3>' . htmlspecialchars($error) . '</h3>';
            }
            if ($admin) {
                $trace = $error instanceof Exception ? $error : debug_backtrace();
                echo '<div id="backtrace"><pre>' . strval(new Horde_Support_Backtrace($trace)) . '</pre></div>';
                if (is_object($error)) {
                    echo '<h3>' . Horde_Core_Translation::t("Details") . '</h3>';
                    echo '<h4>' . Horde_Core_Translation::t("The full error message is logged in Horde's log file, and is shown below only to administrators. Non-administrative users will not see error details.") . '</h4>';
                    ob_flush();
                    flush();
                    echo '<div id="details"><pre>' . htmlspecialchars(print_r($error, true)) . '</pre></div>';
                }
            } else {
                echo '<h3>' . Horde_Core_Translation::t("Details have been logged for the administrator.") . '</h3>';
            }
        } catch (Exception $e) {
            die($e);
        }
        ob_end_flush();
        echo '</body></html>';
        exit(1);
    }
Ejemplo n.º 4
0
#!/usr/bin/env php
<?php 
/**
 * Takes a filename on the command line and parses it, displaying what it
 * finds. Intended for use in debugging the iCalendar parser's behavior with
 * problem files or for adding new features.
 *
 * @category Horde
 * @package  Icalendar
 */
require_once 'Horde/Cli.php';
require_once 'Horde/Icalendar.php';
// This only works on the command line.
if (!Horde_Cli::runningFromCLI()) {
    exit("Must be run from the command line\n");
}
// Load the CLI environment - make sure there's no time limit, init
// some variables, etc.
$cli = Horde_Cli::init();
if (empty($argv[1])) {
    $cli->fatal('No file specified on the command line.');
}
$input_file = $argv[1];
if (!file_exists($input_file)) {
    $cli->fatal($input_file . ' does not exist.');
}
if (!is_readable($input_file)) {
    $cli->fatal($input_file . ' is not readable.');
}
$cli->writeln($cli->blue('Parsing ' . $input_file . ' ...'));
$data = file_get_contents($input_file);
Ejemplo n.º 5
0
 /**
  * Application bootstrap initialization.
  * Solves chicken-and-egg problem - need a way to init Horde environment
  * from application without an active Horde_Registry object.
  *
  * Page compression will be started (if configured).
  *
  * Global variables defined:
  * <pre>
  *   - $browser: Horde_Browser object
  *   - $cli: Horde_Cli object (if 'cli' is true)
  *   - $conf: Configuration array
  *   - $injector: Horde_Injector object
  *   - $language: Language
  *   - $notification: Horde_Notification object
  *   - $page_output: Horde_PageOutput object
  *   - $prefs: Horde_Prefs object
  *   - $registry: Horde_Registry object
  *   - $session: Horde_Session object
  * </pre>
  *
  * @param string $app  The application to initialize.
  * @param array $args  Optional arguments:
  * <pre>
  *   - admin: (boolean) Require authenticated user to be an admin?
  *            DEFAULT: false
  *   - authentication: (string) The type of authentication to use:
  *     - none: Do not authenticate
  *     - fallback: Attempt to authenticate; if failure, then don't auth
  *                 (@since 2.11.0).
  *     - [DEFAULT]: Authenticate; on no auth redirect to login screen
  *   - cli: (boolean) Initialize a CLI interface. Setting this to true
  *          implicitly sets 'authentication' to 'none' and 'admin' and
  *          'nocompress' to true.
  *          DEFAULT: false
  *   - nocompress: (boolean) If set, the page will not be compressed.
  *                 DEFAULT: false
  *   - nologintasks: (boolean) If set, don't perform logintasks (never
  *                   performed if authentication is 'none').
  *                   DEFAULT: false
  *   - nonotificationinit: (boolean) If set, don't initialize the
  *                         application handlers for the notification
  *                         system (@since 2.12.0).
  *   - permission: (array) The permission required by the user to access
  *                 the page. The first element (REQUIRED) is the permission
  *                 name. The second element (OPTION; defaults to SHOW) is
  *                 the permission level.
  *   - session_cache_limiter: (string) Use this value for the session
  *                            cache limiter.
  *                            DEFAULT: Uses the value in the config.
  *   - session_control: (string) Special session control limitations:
  *     - netscape: TODO; start read/write session
  *     - none: Do not start a session
  *     - readonly: Start session readonly
  *     - [DEFAULT] - Start read/write session
  *   - test: (boolean) Is this the test script? If so, we relax several
  *           sanity checks and don't load things from the cache.
  *           DEFAULT: false
  *   - timezone: (boolean) Set the time zone?
  *               DEFAULT: false
  *   - user_admin: (boolean) Set authentication to an admin user?
  *                 DEFAULT: false
  * </pre>
  *
  * @return Horde_Registry_Application  The application object.
  * @throws Horde_Exception
  */
 public static function appInit($app, array $args = array())
 {
     if (isset($GLOBALS['registry'])) {
         return $GLOBALS['registry']->getApiInstance($app, 'application');
     }
     $args = array_merge(array('admin' => false, 'authentication' => null, 'cli' => null, 'nocompress' => false, 'nologintasks' => false, 'nonotificationinit' => false, 'permission' => false, 'session_cache_limiter' => null, 'session_control' => null, 'timezone' => false, 'user_admin' => null), $args);
     /* CLI initialization. */
     if ($args['cli']) {
         /* Make sure no one runs from the web. */
         if (!Horde_Cli::runningFromCLI()) {
             throw new Horde_Exception(Horde_Core_Translation::t("Script must be run from the command line"));
         }
         /* Load the CLI environment - make sure there's no time limit,
          * init some variables, etc. */
         $GLOBALS['cli'] = Horde_Cli::init();
         $args['nocompress'] = true;
         $args['authentication'] = 'none';
     }
     // For 'fallback' authentication, try authentication first.
     if ($args['authentication'] === 'fallback') {
         $fallback_auth = true;
         $args['authentication'] = null;
     } else {
         $fallback_auth = false;
     }
     // Registry.
     $s_ctrl = 0;
     switch ($args['session_control']) {
         case 'netscape':
             // Chicken/egg: Browser object doesn't exist yet.
             // Can't use Horde_Core_Browser since it depends on registry to be
             // configured.
             $browser = new Horde_Browser();
             if ($browser->isBrowser('mozilla')) {
                 $args['session_cache_limiter'] = 'private, must-revalidate';
             }
             break;
         case 'none':
             $s_ctrl = self::SESSION_NONE;
             break;
         case 'readonly':
             $s_ctrl = self::SESSION_READONLY;
             break;
     }
     $classname = __CLASS__;
     $registry = $GLOBALS['registry'] = new $classname($s_ctrl, $args);
     $registry->initialApp = $app;
     $appob = $registry->getApiInstance($app, 'application');
     $appob->initParams = $args;
     do {
         try {
             $registry->pushApp($app, array('check_perms' => $args['authentication'] != 'none', 'logintasks' => !$args['nologintasks'], 'notransparent' => !empty($args['notransparent'])));
             if ($args['admin'] && !$registry->isAdmin()) {
                 throw new Horde_Exception(Horde_Core_Translation::t("Not an admin"));
             }
             $e = null;
         } catch (Horde_Exception_PushApp $e) {
             if ($fallback_auth) {
                 $registry->authException = $e;
                 $registry->setAuthenticationSetting('none');
                 $args['authentication'] = 'none';
                 $fallback_auth = false;
                 continue;
             }
         }
         break;
     } while (true);
     if (!is_null($e)) {
         $appob->appInitFailure($e);
         switch ($e->getCode()) {
             case self::AUTH_FAILURE:
                 $failure = new Horde_Exception_AuthenticationFailure($e->getMessage());
                 $failure->application = $app;
                 throw $failure;
             case self::NOT_ACTIVE:
                 /* Try redirect to Horde if an app is not active. */
                 if (!$args['cli'] && $app != 'horde') {
                     $GLOBALS['notification']->push($e, 'horde.error');
                     Horde::url($registry->getInitialPage('horde'))->redirect();
                 }
                 /* Shouldn't reach here, but fall back to permission denied
                  * error if we can't even access Horde. */
                 // Fall-through
             /* Shouldn't reach here, but fall back to permission denied
              * error if we can't even access Horde. */
             // Fall-through
             case self::PERMISSION_DENIED:
                 $failure = new Horde_Exception_AuthenticationFailure($e->getMessage(), Horde_Auth::REASON_MESSAGE);
                 $failure->application = $app;
                 throw $failure;
         }
         throw $e;
     }
     if ($args['timezone']) {
         $registry->setTimeZone();
     }
     if (!$args['nocompress']) {
         $GLOBALS['page_output']->startCompression();
     }
     if ($args['user_admin']) {
         if (empty($GLOBALS['conf']['auth']['admins'])) {
             throw new Horde_Exception(Horde_Core_Translation::t("Admin authentication requested, but no admin users defined in configuration."));
         }
         $registry->setAuth(reset($GLOBALS['conf']['auth']['admins']), array(), array('no_convert' => true));
     }
     if ($args['permission']) {
         $admin_opts = array('permission' => $args['permission'][0], 'permlevel' => isset($args['permission'][1]) ? $args['permission'][1] : Horde_Perms::SHOW);
         if (!$registry->isAdmin($admin_opts)) {
             throw new Horde_Exception_PermissionDenied(Horde_Core_Translation::t("Permission denied."));
         }
     }
     return $appob;
 }
Ejemplo n.º 6
0
 /**
  * Return the driver name.
  *
  * @since 2.5.0
  *
  * @return string  Lowercase driver name.
  */
 public function getDriverName()
 {
     global $conf;
     $driver = empty($conf['cache']['driver']) ? 'null' : Horde_String::lower($conf['cache']['driver']);
     switch ($driver) {
         case 'none':
             $driver = 'null';
             break;
         case 'xcache':
             if (Horde_Cli::runningFromCLI()) {
                 $driver = 'null';
             }
             break;
     }
     return $driver;
 }
Ejemplo n.º 7
0
 /**
  * Returns whether the event should be considered private.
  *
  * The event's private flag can be overriden if the current user
  * is an administrator and the code is run from command line. This
  * is to allow full event notifications in alarm messages or
  * agendas.
  *
  * @param string $user  The current user.
  *
  * @return boolean  Whether to consider the event as private.
  */
 public function isPrivate($user = null)
 {
     if ($user === null) {
         $user = $GLOBALS['registry']->getAuth();
     }
     if (!(Horde_Cli::runningFromCLI() && $GLOBALS['registry']->isAdmin()) && $this->private && $this->creator != $user) {
         return true;
     }
     if ($GLOBALS['registry']->isAdmin() || $this->hasPermission(Horde_Perms::READ, $user)) {
         return false;
     }
     return true;
 }