Copyright 2003-2016 Horde LLC (http://www.horde.org/) See the enclosed file COPYING for license information (LGPL). If you did not receive this file, see http://www.horde.org/licenses/lgpl21.
Author: Chuck Hagenbuch (chuck@horde.org)
Author: Jan Schneider (jan@horde.org)
Example #1
0
 /**
  * The main entry point for the application.
  *
  * @param array $parameters A list of named configuration parameters.
  * <pre>
  * 'parser'   - (array)     Parser configuration parameters.
  *   'class'  - (string)    The class name of the parser to use.
  * 'output'   - (Horde_Cli) The output handler.
  * </pre>
  */
 public static function main(array $parameters = array())
 {
     $modular = self::_prepareModular($parameters);
     if (empty($parameters['output'])) {
         if (!class_exists('Horde_Cli')) {
             throw new Horde_Kolab_Cli_Exception('The Horde_Cli package seems to be missing (Class Horde_Cli is missing)!');
         }
         $cli = Horde_Cli::init();
     } else {
         $cli = $parameters['output'];
     }
     $parser = $modular->createParser();
     list($options, $arguments) = $parser->parseArgs();
     if (count($arguments) == 0) {
         $parser->printHelp();
     } else {
         try {
             if (!empty($options['config'])) {
                 if (!file_exists($options['config'])) {
                     throw new Horde_Kolab_Cli_Exception(sprintf('The specified config file %s does not exist!', $options['config']));
                 }
                 global $conf;
                 include $options['config'];
                 foreach ($conf as $key => $value) {
                     $options->ensureValue($key, $value);
                 }
             }
             if (empty($options['host'])) {
                 $options['host'] = 'localhost';
             }
             if (empty($options['driver'])) {
                 $options['driver'] = 'horde';
             }
             $world = array();
             foreach ($modular->getModules() as $module) {
                 $modular->getProvider()->getModule($module)->handleArguments($options, $arguments, $world);
             }
             if (!empty($options['timed']) && class_exists('Horde_Support_Timer')) {
                 $timer = new Horde_Support_Timer();
                 $timer->push();
             } else {
                 $timer = false;
             }
             $modular->getProvider()->getModule(Horde_String::ucfirst($arguments[0]))->run($cli, $options, $arguments, $world);
             if (!empty($options['timed'])) {
                 if ($timer) {
                     $cli->message(floor($timer->pop() * 1000) . ' ms');
                 } else {
                     $cli->message('The class Horde_Support_Timer seems to be missing!');
                 }
             }
         } catch (Horde_Cli_Modular_Exception $e) {
             $parser->printHelp();
         }
     }
 }
Example #2
0
 public function pear($text)
 {
     if (!$this->_verbose) {
         return;
     }
     $this->_cli->message('-------------------------------------------------', $this->_getType('cli.message'));
     $this->_cli->message('PEAR output START', $this->_getType('cli.message'));
     $this->_cli->message('-------------------------------------------------', $this->_getType('cli.message'));
     $this->_cli->writeln($text);
     $this->_cli->message('-------------------------------------------------', $this->_getType('cli.message'));
     $this->_cli->message('PEAR output END', $this->_getType('cli.message'));
     $this->_cli->message('-------------------------------------------------', $this->_getType('cli.message'));
 }
Example #3
0
File: Cli.php Project: horde/horde
 /**
  * Formats an event to be written by the handler.
  *
  * @param array $event  Log event.
  *
  * @return string  Formatted line.
  */
 public function format($event)
 {
     $flag = '[' . str_pad($event['levelName'], 7, ' ', STR_PAD_BOTH) . '] ';
     switch ($event['level']) {
         case Horde_Log::EMERG:
         case Horde_Log::ALERT:
         case Horde_Log::CRIT:
         case Horde_Log::ERR:
             $type_message = $this->_cli->red($flag);
             break;
         case Horde_Log::WARN:
         case Horde_Log::NOTICE:
             $type_message = $this->_cli->yellow($flag);
             break;
         case Horde_Log::INFO:
         case Horde_Log::DEBUG:
             $type_message = $this->_cli->blue($flag);
             break;
         default:
             $type_message = $flag;
     }
     return $type_message . $event['message'];
 }
Example #4
0
 /**
  * Run the module.
  *
  * @param Horde_Cli $cli       The CLI handler.
  * @param mixed     $options   An array of options.
  * @param mixed     $arguments An array of arguments.
  * @param array     &$world    A list of initialized dependencies.
  *
  * @return NULL
  */
 public function run($cli, $options, $arguments, &$world)
 {
     if (!isset($arguments[1])) {
         $action = 'display';
     } else {
         $action = $arguments[1];
     }
     switch ($action) {
         case 'display':
             $folders = $world['storage']->getList()->getQuery()->listByType('h-ledger');
             foreach ($folders as $folder) {
                 $cli->writeln($folder);
             }
             break;
             break;
         case 'import':
             $ledger = new Horde_Kolab_Cli_Data_Ledger();
             $ledger->importFile($arguments[3]);
             $data = $world['storage']->getData($arguments[2], 'h-ledger');
             $object = array('type' => 'h-ledger');
             foreach ($ledger->asXml() as $entry) {
                 $object['xml'] = $entry;
                 $data->create($object);
             }
             break;
         default:
             $cli->message(sprintf(Horde_Kolab_Cli_Translation::t('Action %s not supported!'), $action), 'cli.error');
             break;
     }
 }
Example #5
0
/**
 * Horde installer script.
 *
 * Copyright 2013 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (GPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/gpl.html.
 *
 * @author    Michael Slusarz <*****@*****.**>
 * @category  Horde
 * @copyright 2013 Horde LLC
 * @license   http://www.fsf.org/copyleft/gpl.html GPL
 */
require 'vendor/autoload.php';
require 'lib/HordeInstaller.php';
$c = new Horde_Cli();
$c->writeln($c->bold('----------------------'));
$c->writeln($c->bold('Horde installer script'));
$c->writeln($c->bold('----------------------'));
$argv = new Horde_Argv_Parser();
$argv->addOption('-i', '--install-dir', array('action' => 'store', 'dest' => 'horde_dir', 'help' => 'Horde install directory'));
$argv->addOption('-l', '--log', array('action' => 'store', 'dest' => 'log', 'help' => 'Log filename'));
list($values, ) = $argv->parseArgs();
$version = phpversion();
if (version_compare($version, '5.3.0') === -1) {
    $c->fatal('You need at least PHP version 5.3.0 to run Horde.');
}
$c->writeln();
$c->message('PHP version: ' . $version, 'cli.message');
exec('which pear', $pear_output);
if (empty($pear_output)) {
Example #6
0
File: Cli.php Project: horde/horde
 /**
  * Write a message to the log.
  *
  * @param array $event  Log event.
  *
  * @return boolean  True.
  * @throws Horde_Log_Exception
  */
 public function write($event)
 {
     $this->_cli->writeln($this->_formatter->format($event));
     return true;
 }
Example #7
0
#!/usr/bin/env php
<?php 
/**
 * This script will check the user table and create any mail directories on the
 * system for any new users. A cron job can be set up to run this periodically.
 */
require_once __DIR__ . '/../lib/Application.php';
$vilma = Horde_Registry::appInit('vilma', array('authentication' => 'none'));
// Make sure no one runs this from the web.
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.
Horde_Cli::init();
foreach ($vilma->driver->getAllUsers() as $domain => $users) {
    foreach ($users as $user) {
        /* Check for user's home dir. */
        if (!file_exists($user['user_home_dir'])) {
            /* Try to make the user_home_dir, if false skip. */
            if (!mkdir($user['user_home_dir'])) {
                continue;
            }
        }
        /* Check for the domain's dir. */
        $domain_dir = $user['user_home_dir'] . '/' . $domain;
        if (!file_exists($domain_dir)) {
            /* Try to make the user_home_dir, if false skip. */
            if (!mkdir($domain_dir)) {
                continue;
            }
Example #8
0
 /**
  * Run the module.
  *
  * @param Horde_Cli $cli       The CLI handler.
  * @param mixed     $options   An array of options.
  * @param mixed     $arguments An array of arguments.
  * @param array     &$world    A list of initialized dependencies.
  *
  * @return NULL
  */
 public function run($cli, $options, $arguments, &$world)
 {
     if (!isset($arguments[1])) {
         $action = 'read';
     } else {
         $action = $arguments[1];
     }
     switch ($action) {
         case 'read':
             $parser = $world['format']->create('Xml', $arguments[2]);
             if (empty($arguments[4])) {
                 if (file_exists($arguments[3])) {
                     $contents = file_get_contents($arguments[3]);
                     $data = $parser->load($contents);
                     $id = $arguments[3];
                 } else {
                     $cli->message(sprintf(Horde_Kolab_Cli_Translation::t('%s is no local file!'), $arguments[3]), 'cli.error');
                 }
             } else {
                 $ks_data = $world['storage']->getData($arguments[3]);
                 $part = $ks_data->fetchPart($arguments[4], $arguments[5]);
                 rewind($part);
                 $xml = quoted_printable_decode(stream_get_contents($part));
                 $data = $parser->load($xml);
                 $id = $arguments[3] . ':' . $arguments[4] . '[' . $arguments[5] . ']';
             }
             if (class_exists('Horde_Yaml')) {
                 $this->_formatOutput($cli, $id, Horde_Yaml::dump($data));
             } else {
                 $this->_formatOutput($cli, $id, print_r($data, true));
             }
             break;
         default:
             $cli->message(sprintf(Horde_Kolab_Cli_Translation::t('Action %s not supported!'), $action), 'cli.error');
             break;
     }
 }
Example #9
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;
 }
Example #10
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;
 }
Example #11
0
 /**
  * Constructor.
  *
  * @param ReflectionMethod $method  The PHP method to introspect.
  */
 public function __construct(ReflectionFunction $method)
 {
     $this->_cli = Horde_Cli::init();
     parent::__construct($method);
 }
Example #12
0
#!/usr/bin/env php
<?php 
/**
 * @package Cli
 */
require 'Horde/Cli.php';
$cli = new Horde_Cli();
/* Explicit colors */
$cli->writeln($cli->red('Red'));
$cli->writeln($cli->yellow('Yellow'));
$cli->writeln($cli->green('Green'));
$cli->writeln($cli->blue('Blue'));
$cli->writeln();
/* These messages are automatically colorized based on the message type. */
$cli->message('test', 'cli.error');
$cli->message('test', 'cli.warning');
$cli->message('test', 'cli.success');
$cli->message('test', 'cli.message');
Example #13
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;
 }
Example #14
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);
    }
Example #15
0
 /**
  * Run the module.
  *
  * @param Horde_Cli $cli       The CLI handler.
  * @param mixed     $options   An array of options.
  * @param mixed     $arguments An array of arguments.
  * @param array     &$world    A list of initialized dependencies.
  *
  * @return NULL
  */
 public function run($cli, $options, $arguments, &$world)
 {
     if (!isset($arguments[1])) {
         $action = 'info';
     } else {
         $action = $arguments[1];
     }
     if (!isset($arguments[2])) {
         $folder_name = 'INBOX';
     } else {
         $folder_name = $arguments[2];
     }
     switch ($action) {
         case 'info':
             break;
         case 'synchronize':
             $world['storage']->getData($folder_name, $arguments[3])->synchronize();
             break;
         case 'stamp':
             $cli->writeln((string) $world['storage']->getData($folder_name)->getStamp());
             break;
         case 'complete':
             $data = $world['storage']->getData($folder_name);
             $complete = $data->fetchComplete($arguments[3]);
             $cli->writeln($complete[1]->toString(array('headers' => $complete[0])));
             break;
         case 'part':
             $data = $world['storage']->getData($folder_name);
             $part = $data->fetchPart($arguments[3], $arguments[4]);
             rewind($part);
             $cli->writeln(quoted_printable_decode(stream_get_contents($part)));
             break;
         case 'fetch':
             $data = $world['storage']->getData($folder_name, $arguments[3]);
             $objects = $data->fetch(explode(',', $arguments[4]));
             foreach ($objects as $uid => $message) {
                 $this->_yamlOutput($cli, $uid, $message);
             }
             break;
         case 'ids':
             $data = $world['storage']->getData($folder_name, $arguments[3]);
             foreach ($data->getObjectIds() as $id) {
                 $cli->writeln((string) $id);
             }
             break;
         case 'objects':
             $data = $world['storage']->getData($folder_name, $arguments[3]);
             foreach ($data->getObjects() as $id => $object) {
                 $this->_yamlOutput($cli, $id, $object);
             }
             break;
         case 'backendobjects':
             $data = $world['storage']->getData($folder_name, $arguments[3]);
             foreach ($data->getObjectsByBackendId() as $id => $object) {
                 $this->_yamlOutput($cli, $id, $object);
             }
             break;
         case 'object':
             $data = $world['storage']->getData($folder_name, $arguments[3]);
             $object = $data->getObject($arguments[4]);
             $this->_yamlOutput($cli, $arguments[4], $object);
             break;
         case 'backendobject':
             $data = $world['storage']->getData($folder_name, $arguments[3]);
             $object = $data->getObjectByBackendId($arguments[4]);
             $this->_yamlOutput($cli, $arguments[4], $object);
             break;
         case 'create':
             $data = $world['storage']->getData($folder_name, $arguments[3]);
             switch (Horde_String::lower($arguments[4])) {
                 case 'yaml':
                     if (class_exists('Horde_Yaml')) {
                         $object = Horde_Yaml::loadFile($arguments[5]);
                     } else {
                         throw new Horde_Kolab_Cli_Exception('The Horde_Yaml package is missing!');
                     }
             }
             $data->create($object);
             $cli->writeln($object['uid']);
             break;
         case 'move':
             $data = $world['storage']->getData($folder_name, $arguments[3]);
             $objects = $data->move($arguments[4], $arguments[5]);
             break;
         case 'delete':
             $data = $world['storage']->getData($folder_name, $arguments[3]);
             $objects = $data->delete(explode(',', $arguments[4]));
             break;
         case 'deleteall':
             $world['storage']->getData($folder_name, $arguments[3])->deleteAll();
             break;
         case 'deleteuids':
             $data = $world['storage']->getData($folder_name, $arguments[3]);
             $objects = $data->deleteBackendIds(explode(',', $arguments[4]));
             break;
         case 'backendid':
             $data = $world['storage']->getData($folder_name, $arguments[3]);
             $cli->writeln((string) $data->getBackendId($arguments[4]));
             break;
         default:
             $cli->message(sprintf(Horde_Kolab_Cli_Translation::t('Action %s not supported!'), $action), 'cli.error');
             break;
     }
 }
Example #16
0
File: List.php Project: horde/horde
 /**
  * Run the module.
  *
  * @param Horde_Cli $cli       The CLI handler.
  * @param mixed     $options   An array of options.
  * @param mixed     $arguments An array of arguments.
  * @param array     &$world    A list of initialized dependencies.
  *
  * @return NULL
  */
 public function run($cli, $options, $arguments, &$world)
 {
     if (!isset($arguments[1])) {
         $action = 'folders';
     } else {
         $action = $arguments[1];
     }
     switch ($action) {
         case 'folders':
             $folders = $world['storage']->getList()->listFolders();
             foreach ($folders as $folder) {
                 $cli->writeln($folder);
             }
             break;
         case 'types':
             $types = $world['storage']->getList()->getQuery()->listTypes();
             if (!empty($types)) {
                 $pad = max(array_map('strlen', array_keys($types))) + 2;
                 foreach ($types as $folder => $type) {
                     $cli->writeln(Horde_String::pad($folder . ':', $pad) . $type);
                 }
             }
             break;
         case 'type':
             if (!isset($arguments[2])) {
                 throw new Horde_Kolab_Cli_Exception('You must provide a TYPE argument!');
             }
             $type = $arguments[2];
             $folders = $world['storage']->getList()->getQuery()->listByType($type);
             foreach ($folders as $folder) {
                 $cli->writeln($folder);
             }
             break;
         case 'owners':
             $owners = $world['storage']->getList()->getQuery()->listOwners();
             if (!empty($owners)) {
                 $pad = max(array_map('strlen', array_keys($owners))) + 2;
                 foreach ($owners as $folder => $owner) {
                     $cli->writeln(Horde_String::pad($folder . ':', $pad) . $owner);
                 }
             }
             break;
         case 'defaults':
             $defaults = $world['storage']->getList()->getQuery()->listDefaults();
             if (!empty($defaults)) {
                 foreach ($defaults as $owner => $folders) {
                     $cli->writeln('User "' . $owner . '":');
                     $cli->writeln();
                     foreach ($folders as $type => $folder) {
                         $cli->writeln('  ' . Horde_String::pad($type . ':', 14) . $folder);
                     }
                     $cli->writeln();
                 }
             }
             break;
         case 'aclsupport':
             if ($world['storage']->getList()->getQuery(Horde_Kolab_Storage_List::QUERY_ACL)->hasAclSupport()) {
                 echo "The remote server supports ACL.\n";
             } else {
                 echo "The remote server does not support ACL.\n";
             }
             break;
         case 'namespaces':
             $cli->writeln((string) $world['storage']->getList()->getNamespace());
             break;
         case 'sync':
             $folders = $world['storage']->getList()->synchronize();
             break;
         default:
             $cli->message(sprintf(Horde_Kolab_Cli_Translation::t('Action %s not supported!'), $action), 'cli.error');
             break;
     }
 }
Example #17
0
 * 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);
$ical = new Horde_Icalendar();
if (!$ical->parseVCalendar($data)) {
    $cli->fatal('iCalendar parsing failed.');
Example #18
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;
 }
Example #19
0
 /**
  * The main entry point for the application.
  *
  * @param array $parameters A list of named configuration parameters.
  */
 public static function main(array $parameters = array())
 {
     $parser = new Horde_Argv_Parser(array('usage' => '%prog [OPTIONS] [SOURCE://ID]'));
     $parser->addOptions(array(new Horde_Argv_Option('-c', '--config', array('action' => 'store', 'help' => Horde_Push_Translation::t('Path to the configuration file.'))), new Horde_Argv_Option('-S', '--summary', array('action' => 'store', 'help' => Horde_Push_Translation::t('A summary replacing the value provided by the source.'))), new Horde_Argv_Option('-R', '--recipients', array('action' => 'store', 'help' => Horde_Push_Translation::t('A comma delimited list of recipients.'))), new Horde_Argv_Option('-T', '--tags', array('action' => 'store', 'help' => Horde_Push_Translation::t('A comma delimited list of tags.'))), new Horde_Argv_Option('-L', '--links', array('action' => 'store', 'help' => Horde_Push_Translation::t('A comma delimited list of links.'))), new Horde_Argv_Option('-p', '--pretend', array('action' => 'store_true', 'help' => Horde_Push_Translation::t('Do not push the content but display what would be done.')))));
     list($options, $arguments) = $parser->parseArgs();
     global $conf;
     if (isset($options['config'])) {
         if (!file_exists($options['config'])) {
             throw new Horde_Push_Exception(sprintf('The specified config file %s does not exist!', $options['config']));
         }
         include $options['config'];
     } else {
         $conf = array('recipients' => array('mock'));
     }
     if (empty($arguments)) {
         $arguments = explode(' ', trim(file_get_contents('php://stdin')));
     }
     $push_factory = new Horde_Push_Factory_Push();
     $pushes = $push_factory->create($arguments, $options, $conf);
     $fail = false;
     foreach ($pushes as $push) {
         if (isset($options['summary'])) {
             $push->setSummary($options['summary']);
         }
         if (isset($options['tags'])) {
             foreach (explode(',', $options['tags']) as $tag) {
                 $push->addTag($tag);
             }
         }
         if (isset($options['links'])) {
             foreach (explode(',', $options['links']) as $reference) {
                 $push->addReference($reference);
             }
         }
         $recipient_factory = new Horde_Push_Factory_Recipients();
         $recipients = $recipient_factory->create($options, $conf);
         foreach ($recipients as $recipient) {
             $push->addRecipient($recipient);
         }
         $results = $push->push(array('pretend' => !empty($options['pretend'])));
         $cli = Horde_Cli::init();
         foreach ($results as $result) {
             if ($result instanceof Exception) {
                 $cli->message($result->getMessage(), 'cli.error');
                 $fail = true;
             } else {
                 $cli->message((string) $result, 'cli.success');
             }
         }
     }
     if ($fail === true) {
         $status = 1;
     } else {
         $status = 0;
     }
     if (empty($parameters['no_exit'])) {
         exit($status);
     } else {
         return $status;
     }
 }
Example #20
0
 /**
  * Create the CLI handler.
  *
  * @return Horde_Cli The CLI handler.
  */
 public function createCli()
 {
     return Horde_Cli::init();
 }
Example #21
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;
 }