示例#1
0
文件: Cli.php 项目: ngchie/system
 /**
  * method to set the options from the command line
  * 
  * @return boolean true on success, else false
  */
 protected function setOptions()
 {
     try {
         $input = array('r|R|receive' => 'Receive files and process them into database', 'p|P|process' => 'Process files into database', 'c|C|calc|calculate' => 'Calculate lines in database', 'a|A|aggregate' => 'Aggregate lines for billrun', 'g|G|generate' => 'Generate xml and csv files of specific billrun', 'e|E|respond' => 'Respond to files that were processed', 'l|L|alert' => 'Process and detect alerts', 'h|H|help' => 'Displays usage information.', 'type-s' => 'Process: Ild type to use', 'stamp-s' => 'Process: Stamp to use for this run', 'path-s' => 'Process: Path of the process file', 'export-path-s' => 'Respond: The path To export files', 'workspace-s' => 'The path to the workspace directory', 'parser-s' => 'Process: Parser type (default fixed)', 'backup' => 'Process: Backup path after the file processed (default ./backup)', 'page-s' => 'the  page to aggregate', 'size-s' => 'the size of the page to aggregate', 'environment-s' => 'Environment of the running command', 'env-s' => 'Environment of the running command', 'fetchonly' => 'Only fetch data from remote or db instead of doing complete action');
         $this->options = new Zend_Console_Getopt($input);
         $this->options->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         $this->addOutput($e->getMessage() . "\n\n" . $e->getUsageMessage());
         return false;
     }
     return true;
 }
示例#2
0
 public function routeStartup(Zend_Controller_Request_Abstract $request)
 {
     try {
         $opts = new Zend_Console_Getopt(array('controller|c=s' => 'Name of the controller to open', 'action|a=s' => 'The command line action to execute', 'cityId|ci=i' => 'City id to get trend data for', 'startDate|sd=s' => 'Start date for the price trends', 'endDate|ed=s' => 'End date for the price trends', 'hours|h=i' => 'How many hours to simulate for'));
         $opts->parse();
         $args = $opts->getRemainingArgs();
         if (!isset($opts->action)) {
             throw new Zend_Console_Getopt_Exception('Action parameter missing');
         }
         $cliAction = $opts->action;
         $cliController = $opts->controller;
         $paramters = array();
         $optArray = $opts->toArray();
         for ($i = 0; $i < count($optArray); $i += 2) {
             $paramters[$optArray[$i]] = $optArray[$i + 1];
         }
     } catch (Zend_Console_Getopt_Exception $e) {
         echo $opts->getUsageMessage();
         exit;
     }
     // set the request as a CLI request
     $request = new Zend_Controller_Request_Simple($cliAction, $cliController, 'cli');
     foreach ($paramters as $key => $paramVal) {
         $request->setParam($key, $paramVal);
     }
     foreach ($args as $argument) {
         $request->setParam($argument, true);
     }
     $response = new Zend_Controller_Response_Cli();
     $front = Zend_Controller_Front::getInstance();
     $front->setRequest($request)->setResponse($response);
 }
示例#3
0
 /**
  * handler for command line scripts
  * 
  * @return boolean
  */
 public function handle()
 {
     try {
         $opts = new Zend_Console_Getopt(array('help|h' => 'Display this help Message', 'verbose|v' => 'Output messages', 'config|c=s' => 'Path to config.inc.php file', 'setconfig' => 'Update config. To specify the key and value, append \' -- configKey="your_key" configValue="your config value"\'
                      Examples:
                        setup.php --setconfig -- configkey=sample1 configvalue=value11
                        setup.php --setconfig -- configkey=sample2 configvalue=arrayKey1:Value1,arrayKey2:value2', 'check_requirements' => 'Check if all requirements are met to install and run tine20', 'create_admin' => 'Create new admin user (or reactivate if already exists)', 'install-s' => 'Install applications [All] or comma separated list;' . ' To specify the login name and login password of the admin user that is created during installation, append \' -- adminLoginName="admin" adminPassword="******"\'' . ' To add imap or smtp settings, append (for example) \' -- imap="host:mail.example.org,port:143,dbmail_host:localhost" smtp="ssl:tls"\'', 'update-s' => 'Update applications [All] or comma separated list', 'uninstall-s' => 'Uninstall application [All] or comma separated list', 'list-s' => 'List installed applications', 'sync_accounts_from_ldap' => 'Import user and groups from ldap', 'egw14import' => 'Import user and groups from egw14
                      Examples: 
                       setup.php --egw14import egwdbhost egwdbuser egwdbpass egwdbname latin1
                       setup.php --egw14import egwdbhost egwdbuser egwdbpass egwdbname utf8'));
         $opts->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         echo "Invalid usage: {$e->getMessage()}\n\n";
         echo $e->getUsageMessage();
         exit;
     }
     if (count($opts->toArray()) === 0 || $opts->h || empty($opts->install) && empty($opts->update) && empty($opts->uninstall) && empty($opts->list) && empty($opts->sync_accounts_from_ldap) && empty($opts->egw14import) && empty($opts->check_requirements) && empty($opts->create_admin) && empty($opts->setconfig)) {
         echo $opts->getUsageMessage();
         exit;
     }
     if ($opts->config) {
         // add path to config.inc.php to include path
         $path = strstr($opts->config, 'config.inc.php') !== false ? dirname($opts->config) : $opts->config;
         set_include_path($path . PATH_SEPARATOR . get_include_path());
     }
     Setup_Core::initFramework();
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Is cli request. method: ' . (isset($opts->mode) ? $opts->mode : 'EMPTY'));
     }
     $setupServer = new Setup_Frontend_Cli();
     #$setupServer->authenticate($opts->username, $opts->password);
     return $setupServer->handle($opts);
 }
 /**
  * Main Entry Point
  * */
 public function run()
 {
     //deal with command line argument
     try {
         $opts = new Zend_Console_Getopt(array('discover|d' => 'special Twitter search for PHP around Ottawa (not saved)'));
         $opts->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         echo $e->getUsageMessage();
         exit;
     }
     // if special argument is received
     if (isset($opts->d)) {
         $this->fetchTwitterSpecial($opts->getRemainingArgs());
     } else {
         $this->fetchBlogs();
         $this->fetchTwitter();
         // clear all cache
         $cacheConfig = $this->application->getBootstrap()->getOption('cache');
         if ($cacheConfig['enabled']) {
             $cache = Zend_Cache::factory('Page', 'File', array(), $cacheConfig['backend']);
             echo PHP_EOL . '->clearing cache' . PHP_EOL;
             $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
         }
     }
 }
示例#5
0
 public function index()
 {
     try {
         $opts = new Zend_Console_Getopt(array('help|h' => 'Displays usage information', 'profiling|p' => 'Turn on Magento\'s profiler', 'database|d' => 'Turn on profiling of db queries'));
         $opts->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         $this->out('I do apologise! ' . $e->getMessage(), "red");
         echo "\n" . str_replace("magentleman", "magentleman console", $e->getUsageMessage()) . "\n";
         exit;
     }
     // Help action
     if (isset($opts->help)) {
         $this->out("It's terribly simple to use me:", "green");
         echo "\n";
         echo str_replace("magentleman", "magentleman console", $opts->getUsageMessage());
         echo "\n";
         exit;
     }
     if (isset($opts->profiling)) {
         $this->profiling = true;
     }
     if (isset($opts->database)) {
         $this->database = true;
     }
     $this->clear();
     $this->out("");
     $this->out(" " . $this->greeting, "green");
     $this->out(" To get help using this console, visit our website at http://www.qipcreative.com/magentleman\n", "yellow");
     $this->startConsole();
 }
示例#6
0
 public function init()
 {
     // Define some CLI options
     $getopt = new Zend_Console_Getopt(array('withdata|w' => 'Load database with sample data', 'env|e-s' => 'Application environment for which to create database (defaults to development)', 'help|h' => 'Help -- usage message'));
     try {
         $getopt->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         // Bad options passed: report usage
         echo $e->getUsageMessage();
         return false;
     }
     // Initialize Zend_Application
     $application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
     // Initialize and retrieve DB resource
     $bootstrap = $application->getBootstrap();
     $bootstrap->bootstrap('db');
     $dbAdapter = $bootstrap->getResource('db');
     // let the user know whats going on (we are actually creating a
     // database here)
     if ('testing' != APPLICATION_ENV) {
         echo 'Writing Database Guestbook in (control-c to cancel): ' . PHP_EOL;
         for ($x = 5; $x > 0; $x--) {
             echo $x . "\r";
             sleep(1);
         }
     }
     vd(1);
 }
示例#7
0
 /**
  * Parses the configuration options and populates the data store.
  *
  * @param bool $force if true; forces parsing independently of the _parsed property.
  *
  * @return void
  */
 public function parse($force = false)
 {
     if ($this->_parsed === true && !$force) {
         return $this;
     }
     $this->_parsed = false;
     try {
         parent::parse();
     } catch (Zend_Exception $e) {
         $name = basename($_SERVER['SCRIPT_NAME'], '.php');
         echo $name . ': ' . $e->getMessage() . PHP_EOL;
         echo 'Try: \'' . $name . ' --help\' for more information.' . PHP_EOL;
         exit(22);
     }
     if ($this->getHelp()) {
         DocBlox_Core_Application::renderVersion();
         echo $this->getUsageMessage();
         exit(0);
     }
     // prevent the loading of configuration files by specifying 'none'.
     if (strtolower($this->getConfig()) == 'none') {
         return;
     }
     if ($this->getConfig()) {
         // when the configuration parameter is provided; merge that with the basic config
         DocBlox_Core_Abstract::config()->merge(new Zend_Config_Xml($this->getConfig()));
     } elseif (is_readable('docblox.xml')) {
         // when the configuration is not provided; check for the presence of a configuration file in the current directory
         // and merge that
         DocBlox_Core_Abstract::config()->merge(new Zend_Config_Xml('docblox.xml'));
     } elseif (is_readable('docblox.dist.xml')) {
         // when no docblox.xml is provided; check for a dist.xml file. Yes, compared to, for example, PHPUnit the xml
         // and dist is reversed; this is done on purpose so IDEs have an easier time on it.
         DocBlox_Core_Abstract::config()->merge(new Zend_Config_Xml('docblox.dist.xml'));
     }
     $this->prePopulate();
     // the parse method does not have a hook point to invoke the setter methods; thus we iterate through the options and
     // invoke the setters. If no setter exists the __call method will handle this.
     // We have explicitly kept this intact (as the __call's set does nothing special) to enable subclasses to override
     // the __call and receive the benefits.
     foreach ($this->getOptions() as $value) {
         $method_name = '';
         // loop through all aliases to check whether a real method was overridden
         foreach ($this->_rules[$value]['alias'] as $alias) {
             $method_name = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $alias)));
             if (method_exists($this, $method_name)) {
                 // found one! execute it and continue to the next
                 $this->{$method_name}($this->getOption($value));
                 continue 2;
             }
         }
         if ($method_name == '') {
             throw new Exception('Unable to find a name for the setter for argument ' . $value);
         }
         // no overridden methods found; just invoke the default name to trigger the __call method
         $this->{$method_name}($this->getOption($value));
     }
 }
示例#8
0
 /**
  * Prepare options & aguments
  *
  * @return void
  */
 protected final function _parseParams()
 {
     $this->_parseArguments();
     $aOptions = $this->_parseOptions();
     try {
         $this->_oGetopt = new Zend_Console_Getopt($aOptions);
         $this->_oGetopt->parse();
     } catch (Zend_Console_Getopt_Exception $oException) {
         echo $oException->getUsageMessage();
         exit;
     }
 }
示例#9
0
 public function __construct(Zend_Console_Getopt $getopt)
 {
     $this->_getopt = $getopt;
     $getopt->parse();
     if ($getopt->{$this->getModuleKey()}) {
         $this->setModuleName(HCLI_Controller_Util::decode($getopt->{$this->getModuleKey()}));
     }
     if ($getopt->{$this->getControllerKey()}) {
         $this->setControllerName(HCLI_Controller_Util::decode($getopt->{$this->getControllerKey()}));
     }
     if ($getopt->{$this->getActionKey()}) {
         $this->setActionName($getopt->{$this->getActionKey()});
     }
 }
示例#10
0
 public function parse()
 {
     // get actionname from arguments
     if (count($this->_arguments) == 0) {
         return;
     }
     // action name will be a free floating string
     $actionName = array_shift($this->_arguments);
     // check to make sure that the action exists
     if (!($actionContext = $this->_buildManifest->getContext('action', $actionName)) instanceof Zend_Build_Manifest_Context) {
         require_once 'Zend/Tool/Cli/Context/Exception.php';
         throw new Zend_Tool_Cli_Context_Exception('No action context by name ' . $actionName . ' was found in the manifest.');
     }
     $getoptRules = array();
     // get the attributes from this action context
     $actionContextAttrs = $actionContext->getAttributes();
     foreach ($actionContextAttrs as $actionContextAttr) {
         if (isset($actionContextAttr['attributes']['getopt'])) {
             $getoptRules[$actionContextAttr['attributes']['getopt']] = $actionContextAttr['usage'];
         }
     }
     // parse those options out of the arguments array
     $getopt = new Zend_Console_Getopt($getoptRules, $this->_arguments, array('parseAll' => false));
     $getopt->parse();
     // put remaining args into local property
     $this->_arguments = $getopt->getRemainingArgs();
     // get class name
     $actionClassName = $actionContext->getClassName();
     // load appropriate file
     try {
         Zend_Loader::loadClass($actionClassName);
     } catch (Zend_Loader_Exception $e) {
         echo 'couldnt load ' . $actionClassName . PHP_EOL;
     }
     // get actual object for class name
     $this->_action = new $actionClassName();
     // make sure its somewhat sane (implements proper interface)
     if (!$this->_action instanceof Zend_Build_Action_Abstract) {
         echo 'does not implement Zend_Build_Action_Abstract ' . PHP_EOL;
     }
     $parameters = array();
     foreach ($getopt->getOptions() as $getoptParsedOption) {
         $parameters[$getoptParsedOption] = $getopt->getOption($getoptParsedOption);
     }
     $this->_action->setParameters($parameters);
     $this->_action->validate();
     $this->setExecutable();
     return;
     // everything succeeded
 }
示例#11
0
文件: Cli.php 项目: GemsTracker/MUtil
 /**
  * Processes a request and sets its controller and action.  If
  * no route was possible, an exception is thrown.
  *
  * @param  \Zend_Controller_Request_Abstract
  * @throws \Zend_Controller_Router_Exception
  * @return \Zend_Controller_Request_Abstract|boolean
  */
 public function route(\Zend_Controller_Request_Abstract $request)
 {
     $options = array('help|h' => 'Show this help', 'org|o=i' => 'The user organization number', 'pwd|p=s' => 'User password', 'user|u=s' => 'The user name');
     $getopt = new \Zend_Console_Getopt($options);
     try {
         $getopt->parse();
     } catch (\Zend_Console_Getopt_Exception $e) {
         echo $this->_expandMessage($e);
         exit;
     }
     if ($getopt->getOption('h')) {
         // $getopt->s
         echo $this->_expandMessage($getopt);
         exit;
     }
     if ($request instanceof \MUtil_Controller_Request_Cli) {
         $request->setUserLogin($getopt->getOption('u'), $getopt->getOption('o'), $getopt->getOption('p'));
     }
     $arguments = $getopt->getRemainingArgs();
     if ($arguments) {
         $controller = array_shift($arguments);
         $action = array_shift($arguments);
         if (!$action) {
             $action = 'index';
         }
         if (preg_match('/^\\w+(-\\w+)*$/', $controller) && preg_match('/^\\w+(-\\w+)*$/', $action)) {
             $request->setControllerName($controller);
             $request->setActionName($action);
             $params[$request->getControllerKey()] = $controller;
             $params[$request->getActionKey()] = $action;
             foreach ($arguments as $arg) {
                 if (\MUtil_String::contains($arg, '=')) {
                     list($name, $value) = explode('=', $arg, 2);
                 } else {
                     $name = $arg;
                     $value = '';
                 }
                 $params[$name] = $value;
             }
             $request->setParams($params);
             return $request;
         }
         echo "Invalid command: {$controller}/{$action}.\n", exit;
     }
     echo "No command given.\n\n";
     echo $this->_expandMessage($getopt), exit;
 }
示例#12
0
 public function parse()
 {
     try {
         $getopt = new Zend_Console_Getopt($this->_globalGetoptRules(), $this->_arguments, array('parseAll' => false));
         $getopt->parse();
     } catch (Exception $e) {
         die($e->getMessage());
     }
     if (in_array('help', $getopt->getOptions())) {
         $this->setShortCircuited(true);
         $this->_displayHelp();
         return;
     }
     $this->setExecutable();
     // check if global switches are supported
     return;
 }
示例#13
0
文件: Cli.php 项目: sirprize/xzend
 public function __construct()
 {
     $flags = array('--' . $this->getActionKey(), '-a', '--' . $this->getControllerKey(), '-c', '--' . $this->getModuleKey(), '-m');
     $argv = array($_SERVER['argv'][0]);
     foreach ($_SERVER['argv'] as $key => $value) {
         if (in_array($value, $flags)) {
             $argv[] = $value;
             $argv[] = $_SERVER['argv'][$key + 1];
         }
     }
     require_once 'Zend/Console/Getopt.php';
     $getopt = new Zend_Console_Getopt($this->_getGetoptRules(), $argv);
     $getopt->parse();
     $this->setModuleName($getopt->getOption($this->getModuleKey()));
     $this->setControllerName($getopt->getOption($this->getControllerKey()));
     $this->setActionName($getopt->getOption($this->getActionKey()));
 }
function main()
{
    prepareEnvironment();
    try {
        $opts = new Zend_Console_Getopt(array('create application|a=s' => 'create application option with required string parameter', 'help' => 'help option with no required parameter'));
        $opts->parse();
    } catch (Zend_Console_Getopt_Exception $e) {
        echo $e->getUsageMessage();
        exit;
    }
    if ($applicationName = $opts->getOption('a')) {
        echo create(APPLICATION, array($applicationName));
        exit;
    }
    echo "UNEXPECTED ERROR: missing argument. Type tn -help to see parameters \n";
    exit;
}
示例#15
0
文件: Cli.php 项目: kandy/system
 /**
  * Constructor 
  * @param Zend_Console_Getopt $getopt
  */
 public function __construct(Zend_Console_Getopt $getopt)
 {
     $this->_getopt = $getopt;
     try {
         $getopt->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         echo $e->getUsageMessage();
         exit(-1);
     }
     if ($getopt->{$this->getModuleKey()}) {
         $this->setModuleName($getopt->{$this->getModuleKey()});
     }
     if ($getopt->{$this->getControllerKey()}) {
         $this->setControllerName($getopt->{$this->getControllerKey()});
     }
     if ($getopt->{$this->getActionKey()}) {
         $this->setActionName($getopt->{$this->getActionKey()});
     }
 }
示例#16
0
function main()
{
    prepareEnvironment();
    try {
        $opts = new Zend_Console_Getopt(array('create application|a=s' => 'create application option with required string parameter', 'help' => 'help option with no required parameter'));
        $opts->parse();
    } catch (Zend_Console_Getopt_Exception $e) {
        echo $e->getUsageMessage();
        exit;
    }
    if ($applicationName = $opts->getOption('a')) {
        create(APPLICATION, array($applicationName));
        exit;
    }
    if ($opts->getOption('h')) {
        echo $e->getUsageMessage();
        exit;
    }
}
示例#17
0
 /**
  * Parses the configuration options and populates the data store.
  *
  * @param bool $force if true; forces parsing independently of the _parsed property.
  *
  * @return void
  */
 public function parse($force = false)
 {
     if ($this->_parsed === true && !$force) {
         return $this;
     }
     $this->_parsed = false;
     try {
         parent::parse();
     } catch (Zend_Exception $e) {
         $name = basename($_SERVER['SCRIPT_NAME'], '.php');
         echo $name . ': ' . $e->getMessage() . PHP_EOL;
         echo 'Try: \'' . $name . ' --help\' for more information.' . PHP_EOL;
         exit(22);
     }
     if ($this->getHelp()) {
         DocBlox_Core_Application::renderVersion();
         echo $this->getUsageMessage();
         exit(0);
     }
     $this->prePopulate();
     // the parse method does not have a hook point to invoke the setter methods; thus we iterate through the options and
     // invoke the setters. If no setter exists the __call method will handle this.
     // We have explicitly kept this intact (as the __call's set does nothing special) to enable subclasses to override
     // the __call and receive the benefits.
     foreach ($this->getOptions() as $value) {
         $method_name = '';
         // loop through all aliases to check whether a real method was overridden
         foreach ($this->_rules[$value]['alias'] as $alias) {
             $method_name = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $alias)));
             if (method_exists($this, $method_name)) {
                 // found one! execute it and continue to the next
                 $this->{$method_name}($this->getOption($value));
                 continue 2;
             }
         }
         if ($method_name == '') {
             throw new Exception('Unable to find a name for the setter for argument ' . $value);
         }
         // no overridden methods found; just invoke the default name to trigger the __call method
         $this->{$method_name}($this->getOption($value));
     }
 }
示例#18
0
文件: Cli.php 项目: henvic/MediaLab
 public function route(Zend_Controller_Request_Abstract $dispatcher)
 {
     try {
         $opts = new Zend_Console_Getopt(array('help|h' => 'prints this usage information', 'action|a=s' => 'action name (default: index)', 'controller|c=s' => 'controller name  (default: index)', 'verbose|v' => 'explain what is being done'));
         $opts->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         echo $e->getMessage() . "\n\n" . $e->getUsageMessage();
         exit(1);
     }
     if ($opts->getOption("help")) {
         echo $opts->getUsageMessage();
         exit;
     }
     if (!$opts->getOption("action")) {
         $opts->setOption("action", "index");
     }
     if (!$opts->getOption("controller")) {
         $opts->setOption("controller", "index");
     }
     $dispatcher->setControllerName($opts->getOption("controller"))->setActionName($opts->getOption("action"));
 }
 /**
  * (non-PHPdoc)
  * @see Tinebase_Server_Interface::handle()
  */
 public function handle(\Zend\Http\Request $request = null, $body = null)
 {
     try {
         $opts = new Zend_Console_Getopt(array('help|h' => 'Display this help Message', 'verbose|v' => 'Output messages', 'config|c=s' => 'Path to config.inc.php file', 'setconfig' => 'Update config. To specify the key and value, append \' -- configkey="your_key" configValue="your config value"\'
                      Examples:
                        setup.php --setconfig -- configkey=sample1 configvalue=value11
                        setup.php --setconfig -- configkey=sample2 configvalue=arrayKey1:Value1,arrayKey2:value2
                       ', 'getconfig' => 'Get Config value for a specify the key \' -- configkey="your_key"\'', 'check_requirements' => 'Check if all requirements are met to install and run tine20', 'create_admin' => 'Create new admin user (or reactivate if already exists)', 'install-s' => 'Install applications [All] or comma separated list;' . ' To specify the login name and login password of the admin user that is created during installation, append \' -- adminLoginName="admin" adminPassword="******"\'' . ' To add imap or smtp settings, append (for example) \' -- imap="host:mail.example.org,port:143,dbmail_host:localhost" smtp="ssl:tls"\'', 'update-s' => 'Update applications [All] or comma separated list', 'uninstall-s' => 'Uninstall application [All] or comma separated list', 'list-s' => 'List installed applications', 'sync_accounts_from_ldap' => 'Import user and groups from ldap', 'dbmailldap' => 'Only usable with sync_accounts_from_ldap. Fetches dbmail email user data from LDAP.', 'onlyusers' => 'Only usable with sync_accounts_from_ldap. Fetches only users and no groups from LDAP.', 'syncdeletedusers' => 'Only usable with sync_accounts_from_ldap. Removes users from Tine 2.0 DB that no longer exist in LDAP', 'syncaccountstatus' => 'Only usable with sync_accounts_from_ldap. Synchronizes current account status from LDAP', 'syncontactphoto' => 'Only usable with sync_accounts_from_ldap. Always syncs contact photo from ldap', 'sync_passwords_from_ldap' => 'Synchronize user passwords from ldap', 'egw14import' => 'Import user and groups from egw14
                      Examples: 
                       setup.php --egw14import /path/to/config.ini', 'reset_demodata' => 'reinstall applications and install Demodata (Needs Admin user)', 'updateAllImportExportDefinitions' => 'update ImportExport definitions for all applications', 'backup' => 'backup config and data
                      Examples:
                        setup.php --backup -- config=1 db=1 files=1 backupDir=/backup/tine20 noTimestamp=1', 'restore' => 'restore config and data
                      Examples:
                        setup.php --restore -- config=1 db=1 files=1 backupDir=/backup/tine20'));
         $opts->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         echo "Invalid usage: {$e->getMessage()}\n\n";
         echo $e->getUsageMessage();
         exit;
     }
     if (count($opts->toArray()) === 0 || $opts->h || empty($opts->install) && empty($opts->update) && empty($opts->uninstall) && empty($opts->list) && empty($opts->sync_accounts_from_ldap) && empty($opts->sync_passwords_from_ldap) && empty($opts->egw14import) && empty($opts->check_requirements) && empty($opts->reset_demodata) && empty($opts->updateAllImportExportDefinitions) && empty($opts->create_admin) && empty($opts->setconfig) && empty($opts->backup) && empty($opts->restore) && empty($opts->getconfig)) {
         echo $opts->getUsageMessage();
         exit;
     }
     if ($opts->config) {
         // add path to config.inc.php to include path
         $path = strstr($opts->config, 'config.inc.php') !== false ? dirname($opts->config) : $opts->config;
         set_include_path($path . PATH_SEPARATOR . get_include_path());
     }
     Setup_Core::initFramework();
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Is cli request. method: ' . $this->getRequestMethod());
     }
     $setupServer = new Setup_Frontend_Cli();
     #$setupServer->authenticate($opts->username, $opts->password);
     return $setupServer->handle($opts);
 }
示例#20
0
 /**
  * Delete a partner
  *
  * This is the delete action method. It allows you to delete a partner.
  *
  * @return void
  */
 public function deleteAction()
 {
     $this->_helper->viewRenderer->setViewSuffix('txt');
     // The options we are accepting for deleting
     $options = new Zend_Console_Getopt(array('email|e=s' => 'Username/Email of the partner.'));
     try {
         $options->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         $this->view->message = $e->getUsageMessage();
         return;
     }
     if ($options->email == '') {
         echo $options->getUsageMessage();
         exit;
     }
     $partner_email = strtolower($options->email);
     $model = new Default_Model_Partner();
     $tempPartners = $model->getAll();
     $partner_id = null;
     foreach ($tempPartners as $key => $value) {
         if ($partner_email == $value['email']) {
             $partner_id = $value['hash'];
             break;
         }
     }
     if (!$partner_id) {
         $this->view->message = 'Could not delete partner: ' . $partner_email . '. Could not find match.' . PHP_EOL;
         return;
     }
     try {
         $model->delete($partner_id);
         $this->view->message = 'Successfully deleted partner: ' . $partner_email . PHP_EOL;
     } catch (RuntimeException $e) {
         $this->view->message = 'Error deleting partner: ' . $partner_email . '. ' . $e->getMessage() . PHP_EOL;
     }
 }
示例#21
0
 public function parseCommandLine()
 {
     try {
         $opts = new Zend_Console_Getopt(array('development|d' => 'development mode', 'verbose|v' => 'verbose output', 'json|j' => 'JSON output'));
         $opts->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         echo $e->getUsageMessage();
         exit;
     }
     if ($opts->getOption('d')) {
         $this->_environment = 'development';
     }
     $args = $opts->getRemainingArgs();
     if (count($args) < 1) {
         $args = array('help');
     }
     $this->_controller = array_shift($args);
     if (count($args) < 1) {
         $args = array('help');
     }
     $this->_action = array_shift($args);
     $this->_arguments = $args;
     return $this;
 }
<?php

// scripts/load.sqlite.php
/**
* Script for creating and loading database
*/
// Initialize the application path and autoloading
defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../core/application'));
set_include_path(implode(PATH_SEPARATOR, array(APPLICATION_PATH . '/../library', get_include_path())));
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
// Define some CLI options
$getopt = new Zend_Console_Getopt(array('withbuffer|b' => 'Load database with buffer data', 'withdata|w' => 'Load database with sample data', 'withdevs|d' => 'Load database with dev settings', 'env|e-s' => 'Application environment for which to create database (defaults to development)', 'help|h' => 'Help -- usage message'));
try {
    $getopt->parse();
} catch (Zend_Console_Getopt_Exception $e) {
    // Bad options passed: report usage
    echo $e->getUsageMessage();
    return false;
}
// If help requested, report usage message
if ($getopt->getOption('h')) {
    echo $getopt->getUsageMessage();
    return true;
}
// Initialize values based on presence or absence of CLI options
$withData = $getopt->getOption('w');
$withBuffer = $getopt->getOption('b');
$withDevs = $getopt->getOption('d');
$env = $getopt->getOption('e');
defined('APPLICATION_ENV') || define('APPLICATION_ENV', null === $env ? 'development' : $env);
示例#23
0
文件: init.php 项目: knatorski/SMS
<?php

defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../application'));
define('CMD', true);
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(realpath(APPLICATION_PATH . '/../library'), get_include_path())));
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
$optsConfig = array_merge($optsConfig, array('app_env=s' => 'Parametr jest wymaganay i może przyjmować jedynie nazwy sekcji obecnych w pliku configuracyjnym application/configs/application.ini'));
//$args = $_SERVER['argv'];
//var_dump($optsConfig);
try {
    $opts = new Zend_Console_Getopt($optsConfig);
    $opts->setOptions(array('ignoreCase' => true, 'dashDash' => false));
    $opts->parse();
} catch (Zend_Console_Getopt_Exception $e) {
    echo "\n\n" . $e->getMessage() . "\n\n" . $e->getUsageMessage() . "\n\n";
    exit;
}
if (isset($opts->h)) {
    echo "\n\n" . $opts->getUsageMessage() . "\n\n";
    exit;
}
if (isset($opts->app_env)) {
    defined('APPLICATION_ENV') || define('APPLICATION_ENV', $opts->app_env);
} else {
    echo "\n\nParametr app_env jest wymagany!";
    echo "\n\n" . $opts->getUsageMessage() . "\n\n";
    exit;
}
/** Zend_Application */
示例#24
0
/**
 * Do general setup for a CLI script
 * @param array $pa_additional_parameters Additional command line parameters. You don't have to add
 * --log/-l for the log file and --log-level/-d for the Zend_Log log level. They're always set up automatically
 * @return Zend_Console_Getopt
 */
function caSetupCLIScript($pa_additional_parameters)
{
    require_once __CA_LIB_DIR__ . "/core/Zend/Console/Getopt.php";
    require_once __CA_LIB_DIR__ . "/core/Zend/Log.php";
    require_once __CA_LIB_DIR__ . "/core/Zend/Log/Writer/Stream.php";
    require_once __CA_LIB_DIR__ . "/core/Zend/Log/Writer/Syslog.php";
    require_once __CA_LIB_DIR__ . "/core/Zend/Log/Formatter/Simple.php";
    $va_available_cli_opts = array_merge(array("log|l-s" => "Path to log file. If omitted, we log into the system log. Note that we don't log DEBUG messages into the system log, even when the log level is set to DEBUG.", "log-level|d-s" => "Log level"), $pa_additional_parameters);
    try {
        $o_opts = new Zend_Console_Getopt($va_available_cli_opts);
        $o_opts->parse();
    } catch (Exception $e) {
        die("Invalid command line options: " . $e->getMessage() . PHP_EOL);
    }
    // set up logging
    $o_writer = null;
    if ($vs_log = $o_opts->getOption('log')) {
        // log to file
        try {
            $o_writer = new Zend_Log_Writer_Stream($vs_log);
            $o_writer->setFormatter(new Zend_Log_Formatter_Simple('%timestamp% %priorityName%: %message%' . PHP_EOL));
        } catch (Zend_Log_Exception $e) {
            // error while opening the file (usually permissions)
            $o_writer = null;
            print CLIUtils::textWithColor("Couldn't open log file. Now logging via system log.", "bold_red") . PHP_EOL . PHP_EOL;
        }
    }
    // default: log everything to syslog
    if (!$o_writer) {
        $o_writer = new Zend_Log_Writer_Syslog(array('application' => 'CollectiveAccess CLI', 'facility' => LOG_USER));
        // no need for timespamps in syslog ... the syslog itsself provides that
        $o_writer->setFormatter(new Zend_Log_Formatter_Simple('%priorityName%: %message%' . PHP_EOL));
    }
    // was a loglevel set via command line? -> add filter to Zend logger, otherwise use WARN
    $vs_level = $o_opts->getOption('log-level');
    switch ($vs_level) {
        case 'ERR':
            $o_filter = new Zend_Log_Filter_Priority(Zend_Log::ERR);
            break;
        case 'DEBUG':
            $o_filter = new Zend_Log_Filter_Priority(Zend_Log::DEBUG);
            break;
        case 'INFO':
            $o_filter = new Zend_Log_Filter_Priority(Zend_Log::INFO);
            break;
        case 'WARN':
        default:
            $o_filter = new Zend_Log_Filter_Priority(Zend_Log::WARN);
            break;
    }
    // set up global logger. can be used by importing 'global $g_logger' anywhere, but it's recommended to use the caCLILog() helper instead
    global $g_logger;
    $g_logger = new Zend_Log($o_writer);
    $g_logger->setTimestampFormat('D Y-m-d H:i:s');
    $g_logger->addFilter($o_filter);
    return $o_opts;
}
示例#25
0
<?php

/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
require_once __DIR__ . '/bootstrap.php';
use Magento\Framework\Test\Utility\Files;
use Magento\Tools\Dependency\ServiceLocator;
try {
    $console = new \Zend_Console_Getopt(['directory|d=s' => 'Path to base directory for parsing']);
    $console->parse();
    $directory = $console->getOption('directory') ?: BP;
    Files::setInstance(new \Magento\Framework\Test\Utility\Files($directory));
    $filesForParse = Files::init()->getComposerFiles('code', false);
    ServiceLocator::getCircularDependenciesReportBuilder()->build(['parse' => ['files_for_parse' => $filesForParse], 'write' => ['report_filename' => 'modules-circular-dependencies.csv']]);
    fwrite(STDOUT, PHP_EOL . 'Report successfully processed.' . PHP_EOL);
} catch (\Zend_Console_Getopt_Exception $e) {
    fwrite(STDERR, $e->getUsageMessage() . PHP_EOL);
    exit(1);
} catch (\Exception $e) {
    fwrite(STDERR, 'Please, check passed path. Dependencies report generator failed: ' . $e->getMessage() . PHP_EOL);
    exit(1);
}
 public static function getOpts()
 {
     try {
         $autoloader = Zend_Loader_Autoloader::getInstance();
         $opts = new Zend_Console_Getopt(array('help|h' => 'Displays usage information.', 'overwrite|o' => 'Overwrite any existing config files.', 'preserve|p' => 'Keep any existing config files.', 'no-db|n' => 'Turn off database install.', 'reinstall|r' => 'Force a fresh install of this Airtime Version', 'webonly|w' => 'Install only web files'));
         $opts->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         print $e->getMessage() . PHP_EOL;
         AirtimeInstall::printUsage($opts);
         return NULL;
     }
     return $opts;
 }
示例#27
0
use Magento\Framework\ObjectManager\Code\Generator\Converter;
use Magento\Framework\ObjectManager\Code\Generator\Factory;
use Magento\Framework\ObjectManager\Code\Generator\Proxy;
use Magento\Framework\ObjectManager\Code\Generator\Repository;
use Magento\Framework\ObjectManager\Code\Generator\Persistor;
use Magento\Framework\Api\Code\Generator\ExtensionAttributesGenerator;
use Magento\Framework\Api\Code\Generator\ExtensionAttributesInterfaceGenerator;
use Magento\Tools\Di\Code\Scanner;
use Magento\Tools\Di\Compiler\Log\Log;
use Magento\Tools\Di\Compiler\Log\Writer;
use Magento\Tools\Di\Definition\Compressor;
use Magento\Tools\Di\Definition\Serializer\Igbinary;
use Magento\Tools\Di\Definition\Serializer\Standard;
try {
    $opt = new Zend_Console_Getopt(['serializer=w' => 'serializer function that should be used (serialize|igbinary) default: serialize', 'verbose|v' => 'output report after tool run', 'extra-classes-file=s' => 'path to file with extra proxies and factories to generate', 'generation=s' => 'absolute path to generated classes, <magento_root>/var/generation by default', 'di=s' => 'absolute path to DI definitions directory, <magento_root>/var/di by default', 'exclude-pattern=s' => 'allows to exclude Paths from compilation (default is #[\\\\/]m1[\\\\/]#i)']);
    $opt->parse();
    $generationDir = $opt->getOption('generation') ? $opt->getOption('generation') : $rootDir . '/var/generation';
    $diDir = $opt->getOption('di') ? $opt->getOption('di') : $rootDir . '/var/di';
    $testExcludePatterns = ["#^{$rootDir}/app/code/[\\w]+/[\\w]+/Test#", "#^{$rootDir}/lib/internal/[\\w]+/[\\w]+/([\\w]+/)?Test#", "#^{$rootDir}/setup/src/Magento/Setup/Test#", "#^{$rootDir}/dev/tools/Magento/Tools/[\\w]+/Test#"];
    $fileExcludePatterns = $opt->getOption('exclude-pattern') ? [$opt->getOption('exclude-pattern')] : ['#[\\\\/]M1[\\\\/]#i'];
    $fileExcludePatterns = array_merge($fileExcludePatterns, $testExcludePatterns);
    $relationsFile = $diDir . '/relations.ser';
    $pluginDefFile = $diDir . '/plugins.ser';
    $compilationDirs = [$rootDir . '/app/code', $rootDir . '/lib/internal/Magento', $rootDir . '/dev/tools/Magento/Tools'];
    /** @var Writer\WriterInterface $logWriter Writer model for success messages */
    $logWriter = $opt->getOption('v') ? new Writer\Console() : new Writer\Quiet();
    $log = new Log($logWriter, new Writer\Console());
    $serializer = $opt->getOption('serializer') == Igbinary::NAME ? new Igbinary() : new Standard();
    AutoloaderRegistry::getAutoloader()->addPsr4('Magento\\', $generationDir . '/Magento/');
    // 1 Code generation
    // 1.1 Code scan
示例#28
0
 /**
  * Delete a partner
  *
  * This is the delete action method. It allows you to delete a partner.
  *
  * @return void
  */
 public function deleteAction()
 {
     $this->_helper->viewRenderer->setViewSuffix('txt');
     // The options we are accepting for deleting
     $options = new Zend_Console_Getopt(array('email|e=s' => $this->tr->_('EMAIL_USERNAME')));
     try {
         $options->parse();
     } catch (Zend_Console_Getopt_Exception $e) {
         $this->view->message = $e->getUsageMessage();
         return;
     }
     if ($options->email == '') {
         echo $options->getUsageMessage();
         exit;
     }
     $partner_email = strtolower($options->email);
     $model = new Default_Model_Partner();
     $tempPartners = $model->getAll();
     $partner_id = null;
     foreach ($tempPartners as $key => $value) {
         if ($partner_email == $value['email']) {
             $partner_id = $value['hash'];
             break;
         }
     }
     if (!$partner_id) {
         $this->view->message = $this->tr->_('COULD_NOT_DELETE_PARTNER') . ': ' . $partner_email . '. ' . $this->tr->_('COULD_NOT_FIND_MATCH') . PHP_EOL;
         return;
     }
     try {
         $model->delete($partner_id);
         $this->view->message = $this->tr->_('SUCCESS_DELETE_PARTNER') . ': ' . $partner_email . PHP_EOL;
     } catch (RuntimeException $e) {
         $this->view->message = $this->tr->_('ERROR_DELETING_PARTNER') . ': ' . $partner_email . '. ' . $e->getMessage() . PHP_EOL;
     }
 }
示例#29
0
 public function parse()
 {
     $endpointRequest = $this->_endpoint->getRequest();
     if ($this->_workingArguments[0] == $_SERVER["SCRIPT_NAME"]) {
         array_shift($this->_workingArguments);
     }
     if (!$this->_parseGlobalPart() || count($this->_workingArguments) == 0) {
         // @todo process global options?
         return;
     }
     $actionName = array_shift($this->_workingArguments);
     // is the action name valid?
     $cliActionNameMetadatas = Zend_Tool_Rpc_Manifest_Registry::getInstance()->getMetadatas(array('type' => 'Action', 'name' => 'cliActionName'));
     foreach ($cliActionNameMetadatas as $cliActionNameMetadata) {
         if ($actionName == $cliActionNameMetadata->getValue()) {
             $action = $cliActionNameMetadata->getReference();
             break;
         }
     }
     $endpointRequest->setActionName($action->getName());
     /* @TODO Action Parameter Requirements */
     if (count($this->_workingArguments) == 0) {
         return;
     }
     if (!$this->_parseActionPart() || count($this->_workingArguments) == 0) {
         return;
     }
     $cliProviderName = array_shift($this->_workingArguments);
     $cliSpecialtyName = '_global';
     if (strstr($cliProviderName, '.')) {
         list($cliProviderName, $cliSpecialtyName) = explode('.', $cliProviderName);
     }
     $cliProviderNameMetadatas = Zend_Tool_Rpc_Manifest_Registry::getInstance()->getMetadatas(array('type' => 'Provider', 'name' => 'cliProviderName'));
     foreach ($cliProviderNameMetadatas as $cliProviderNameMetadata) {
         if ($cliProviderName == $cliProviderNameMetadata->getValue()) {
             $provider = $cliProviderNameMetadata->getReference();
             break;
         }
     }
     $endpointRequest->setProviderName($provider->getName());
     $cliSpecialtyNameMetadatas = Zend_Tool_Rpc_Manifest_Registry::getInstance()->getMetadatas(array('type' => 'Provider', 'providerName' => $provider->getName(), 'name' => 'cliSpecialtyNames'));
     foreach ($cliSpecialtyNameMetadatas as $cliSpecialtyNameMetadata) {
         if ($cliSpecialtyName == $cliSpecialtyNameMetadata->getValue()) {
             $specialtyName = $cliSpecialtyNameMetadata->getSpecialtyName();
             break;
         }
     }
     $endpointRequest->setSpecialtyName($specialtyName);
     $cliActionableMethodLongParameterMetadata = Zend_Tool_Rpc_Manifest_Registry::getInstance()->getMetadata(array('type' => 'Provider', 'providerName' => $provider->getName(), 'actionName' => $action->getName(), 'specialtyName' => $specialtyName, 'name' => 'cliActionableMethodLongParameters'));
     $cliActionableMethodShortParameterMetadata = Zend_Tool_Rpc_Manifest_Registry::getInstance()->getMetadata(array('type' => 'Provider', 'providerName' => $provider->getName(), 'actionName' => $action->getName(), 'specialtyName' => $specialtyName, 'name' => 'cliActionableMethodShortParameters'));
     $cliParameterNameShortValues = $cliActionableMethodShortParameterMetadata->getValue();
     $getoptOptions = array();
     foreach ($cliActionableMethodLongParameterMetadata->getValue() as $parameterNameLong => $cliParameterNameLong) {
         $optionConfig = $cliParameterNameLong . '|';
         $cliActionableMethodReferenceData = $cliActionableMethodLongParameterMetadata->getReference();
         if ($cliActionableMethodReferenceData['type'] == 'string' || $cliActionableMethodReferenceData['type'] == 'bool') {
             $optionConfig .= $cliParameterNameShortValues[$parameterNameLong] . ($cliActionableMethodReferenceData['optional'] ? '-' : '=') . 's';
         } elseif (in_array($cliActionableMethodReferenceData['type'], array('int', 'integer', 'float'))) {
             $optionConfig .= $cliParameterNameShortValues[$parameterNameLong] . ($cliActionableMethodReferenceData['optional'] ? '-' : '=') . 'i';
         } else {
             $optionConfig .= $cliParameterNameShortValues[$parameterNameLong] . '-s';
         }
         $getoptOptions[$optionConfig] = $cliActionableMethodReferenceData['description'] != '' ? $cliActionableMethodReferenceData['description'] : 'No description available.';
     }
     $getoptParser = new Zend_Console_Getopt($getoptOptions, $this->_workingArguments, array('parseAll' => false));
     $getoptParser->parse();
     foreach ($getoptParser->getOptions() as $option) {
         $value = $getoptParser->getOption($option);
         $endpointRequest->setProviderParameter($option, $value);
     }
     /*
     Zend_Debug::dump($getoptParser); 
     Zend_Debug::dump($endpointRequest);
     die();
     */
     $this->_workingArguments = $getoptParser->getRemainingArgs();
     return;
 }
示例#30
0
文件: GetoptTest.php 项目: travisj/zf
 /**
  * @group ZF-5345
  */
 public function testUsingDashWithoutOptionNotAsLastArgumentThrowsException()
 {
     $opts = new Zend_Console_Getopt("abp:", array("-", "file1"));
     try {
         $opts->parse();
         $this->fail();
     } catch (Exception $e) {
         $this->assertTrue($e instanceof Zend_Console_Getopt_Exception);
     }
 }