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); }
protected function buildErrors() { if ($this->hasErrors()) { echo implode("\n", $this->getErrors()); echo $this->opts->getUsageMessage(); } }
/** * 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); }
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(); }
private function configure() { $zend_console = new Zend_Console_Getopt(array('create|c' => 'Create database configureation', 'adapter|a=w' => 'Database adapter (mysql)', 'host|h=w' => 'Default to localhost', 'username|u=w' => 'Username to connect to database', 'password|p=w' => 'Password to connect to database', 'database|d=w' => 'Database Name', 'port|o-i' => '(optional) Port for connecting to database', 'socket|s-w' => '(optional) Location for database socket'), $this->argv); try { echo $a = $zend_console->getOption('a'); echo $h = $zend_console->getOption('h'); // Load all sections from an existing config file, while skipping the extends. $config = new Zend_Config_Ini(SMCONFIG_DIRECTORY . DIRECTORY_SEPARATOR . 'database.ini', null, array('skipExtends' => true, 'allowModifications' => true)); // Modify values $config->database->doctrine_adapter = $zend_console->getOption('a'); $config->database->params->host = $zend_console->getOption('h'); $config->database->params->username = $zend_console->getOption('u'); $config->database->params->password = $zend_console->getOption('p'); $config->database->params->dbname = $zend_console->getOption('d'); $config->database->params->port = $zend_console->getOption('h'); $config->database->params->socket = $zend_console->getOption('h'); // Write the config file $writer = new Zend_Config_Writer_Ini(array('config' => $config, 'filename' => 'config.ini')); $writer->write(); //*/ } catch (Zend_Console_Getopt_Exception $e) { fwrite(STDOUT, "Connection Failed\n"); echo $e->getUsageMessage(); exit; } }
/** * 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); } } }
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); }
public function route(Zend_Controller_Request_Abstract $dispatcher) { try { $getopt = new Zend_Console_Getopt(array('verbose|v' => 'Print verbose output', 'file|f=s' => 'File to upload')); $getopt->parse; $arguments = $getopt->getRemainingArgs(); } catch (Zend_Console_Getopt_Exception $e) { echo $e->getUsageMessage(); exit; } if ($arguments) { $command = array_shift($arguments); $action = array_shift($arguments); if (!preg_match('~\\W~', $command)) { $dispatcher->setControllerName($command); $dispatcher->setActionName($action); $dispatcher->setParams($arguments); if (isset($getopt->v)) { $dispatcher->setParam('verbose', true); } if (isset($getopt->f)) { $dispatcher->setParam('file', $getopt->f); } return $dispatcher; } echo "Invalid command.\n", exit; } echo "No command given.\n", exit; }
/** * * @param Zend_Controller_Request_Abstract $dispatcher * @return Zend_Controller_Request_Abstract */ public function route(Zend_Controller_Request_Abstract $dispatcher) { $getopt = new Zend_Console_Getopt(array()); $arguments = $getopt->getRemainingArgs(); $controller = null; $action = null; $params = array(); if ($arguments) { foreach ($arguments as $index => $command) { if (preg_match('/([a-z0-9]+)=([a-z0-9]+)/i', trim($command), $match)) { switch ($match[1]) { case 'controller': $controller = $match[2]; break; case 'action': $action = $match[2]; break; default: $params[$match[1]] = $match[2]; } } } $action = empty($action) ? 'index' : $action; $controller = empty($controller) ? 'index' : $controller; $dispatcher->setControllerName($controller); $dispatcher->setActionName($action); $dispatcher->setParams($params); return $dispatcher; } echo "Invalid command.\n"; echo "No command given.\n", exit; }
/** * import employee data from csv file * * @param Zend_Console_Getopt $opts * @return integer */ public function importEmployee($opts) { $args = $opts->getRemainingArgs(); array_push($args, 'definition=' . 'hr_employee_import_csv'); if ($opts->d) { array_push($args, '--dry'); } if ($opts->v) { array_push($args, '--verbose'); } $opts->setArguments($args); $result = $this->_import($opts); if (empty($result)) { return 2; } foreach ($result as $filename => $importResult) { $importedEmployee = $this->_getImportedEmployees($importResult); foreach ($importedEmployee as $employee) { $this->_sanitizeEmployee($opts, $employee); $currentEmployee = $this->_getCurrentEmployee($employee); if ($currentEmployee) { $employee = $this->_updateImportedEmployee($opts, $employee, $currentEmployee); } else { $employee = $this->_createImportedEmployee($opts, $employee); } if ($opts->v) { print_r($employee->toArray()); } if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($employee->toArray(), TRUE)); } } } return 0; }
public function route(Zend_Controller_Request_Abstract $dispatcher) { $getopt = new Zend_Console_Getopt(array()); $arguments = $getopt->getRemainingArgs(); $controller = ""; $action = ""; $params = array(); if ($arguments) { foreach ($arguments as $index => $command) { $details = explode("=", $command); if ($details[0] == "controller") { $controller = $details[1]; } else { if ($details[0] == "action") { $action = $details[1]; } else { $params[$details[0]] = $details[1]; } } } if ($action == "" || $controller == "") { die("\n\t\t\t\t\t\tMissing Controller and Action Arguments\n\t\t\t\t\t\t==\n\t\t\t\t\t\tYou should have:\n\t\t\t\t\t\tphp script.php controller=[controllername] action=[action] token=[token]\n\t\t\t\t\t\t"); } $dispatcher->setModuleName('cronjob'); $dispatcher->setControllerName($controller); $dispatcher->setActionName($action); $dispatcher->setParams($params); return $dispatcher; } echo "Invalid command.\n", exit; echo "No command given.\n", exit; }
public function route(Zend_Controller_Request_Abstract $dispatcher) { $getopt = new Zend_Console_Getopt(array()); $arguments = $getopt->getRemainingArgs(); $controller = 'index'; $action = 'index'; if ($arguments) { $controller = array_shift($arguments); if ($arguments) { $action = array_shift($arguments); $pattern_valid_action = '~^\\w+[\\-\\w\\d]+$~'; if (false == preg_match($pattern_valid_action, $action)) { echo "Invalid action {$action}.\n", exit; } if ($arguments) { foreach ($arguments as $arg) { $parameter = explode('=', $arg, 2); if (false == isset($parameter[1])) { $parameter[1] = true; } $dispatcher->setParam($parameter[0], $parameter[1]); unset($parameter); } } } } $dispatcher->setControllerName($controller)->setActionName($action); return $dispatcher; }
function __construct($process_classes_folder) { $this->Logger = \Logger::getLogger('JobLauncher'); $processes = @glob("{$process_classes_folder}/class.*Process.php"); $options = array(); if (count($processes) > 0) { foreach ($processes as $process) { $filename = basename($process); $directory = dirname($process); if (!file_exists($directory . "/" . $filename)) { throw new \Exception(sprintf("File %s does not exist.", $directory . "/" . $filename)); } include_once $directory . "/" . $filename; preg_match("/class.(.*)Process.php/s", $filename, $tmp); $process_name = $tmp[1]; if (class_exists("{$process_name}Process")) { $reflect = new \ReflectionClass("{$process_name}Process"); if ($reflect) { if ($reflect->implementsInterface('Scalr\\System\\Pcntl\\ProcessInterface')) { $options[$process_name] = $reflect->getProperty("ProcessDescription")->getValue($reflect->newInstance()); } else { throw new \Exception("Class '{$process_name}Process' doesn't implement 'ProcessInterface'.", E_ERROR); } } else { throw new \Exception("Cannot use ReflectionAPI for class '{$process_name}Process'", E_ERROR); } } else { throw new \Exception("'{$process}' does not contain definition for '{$process_name}Process'", E_ERROR); } } } else { throw new \Exception(_("No job classes found in {$process_classes_folder}"), E_ERROR); } $options["help"] = "Print this help"; $options["piddir=s"] = "PID directory"; $Getopt = new \Zend_Console_Getopt($options); try { $opts = $Getopt->getOptions(); } catch (\Zend_Console_Getopt_Exception $e) { print "{$e->getMessage()}\n\n"; die($Getopt->getUsageMessage()); } if (in_array("help", $opts) || count($opts) == 0 || !$options[$opts[0]]) { print $Getopt->getUsageMessage(); exit; } else { $this->ProcessName = $opts[0]; /* if (in_array("piddir", $opts)) { $piddir = trim($Getopt->getOption("piddir")); if (substr($piddir, 0, 1) != '/') { //$this->PIDDir = realpath($process_classes_folder . "/" . $piddir); } else { //$this->PIDDir = $piddir; } } */ } }
/** * call handle cli function with params * * @param array $_params */ protected function _cliHelper($command, $_params) { $opts = new Zend_Console_Getopt(array($command => $command)); $opts->setArguments($_params); ob_start(); $this->_cli->handle($opts, false); $out = ob_get_clean(); return $out; }
/** * Get option value * * @param string $key * @param mixed $default * * @return mixed|null */ public static function getOption($key, $default = null) { if (!static::$_getopt instanceof \Zend_Console_Getopt) { return $default; } $value = static::$_getopt->getOption($key); if (is_null($value)) { return $default; } return $value; }
/** * import from egroupware * * @param Zend_Console_Getopt $_opts */ public function importegw14($_opts) { //$args = $_opts->getRemainingArgs(); list($host, $username, $password, $dbname, $charset) = $_opts->getRemainingArgs(); $egwDb = Zend_Db::factory('PDO_MYSQL', array('host' => $host, 'username' => $username, 'password' => $password, 'dbname' => $dbname)); $egwDb->query("SET NAMES {$charset}"); $writer = new Zend_Log_Writer_Stream('php://output'); $logger = new Zend_Log($writer); $config = new Zend_Config(array('egwServerTimezone' => 'UTC', 'setPersonalCalendarGrants' => TRUE, 'forcePersonalCalendarGrants' => FALSE)); $importer = new Calendar_Setup_Import_Egw14($egwDb, $config, $logger); $importer->import(); }
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 }
/** * exports calendars as ICS * * @param Zend_Console_Getopt $_opts */ public function exportICS($_opts) { Tinebase_Core::set('HOSTNAME', 'localhost'); $opts = $_opts->getRemainingArgs(); $container_id = $opts[0]; $filter = new Calendar_Model_EventFilter(array(array('field' => 'container_id', 'operator' => 'equals', 'value' => $container_id))); $result = Calendar_Controller_MSEventFacade::getInstance()->search($filter, null, false, false, 'get'); if ($result->count() == 0) { throw new Tinebase_Exception('this calendar does not contain any records.'); } $converter = Calendar_Convert_Event_VCalendar_Factory::factory("generic"); $result = $converter->fromTine20RecordSet($result); print $result->serialize(); }
/** * import helper */ protected function _doImport($checkOutput = TRUE) { $opts = new Zend_Console_Getopt(array('verbose|v' => 'Output messages', 'dry|d' => "Dry run - don't change anything")); $filename = dirname(__FILE__) . '/files/employee.csv'; $args = array($filename, 'feast_calendar_id=' . $this->_getFeastCalendar()->getId(), 'working_time_model_id=' . $this->_getWorkingTime()->getId(), 'vacation_days=30'); $opts->setArguments($args); ob_start(); $result = $this->_cli->importEmployee($opts); $out = ob_get_clean(); $this->assertEquals(0, $result, 'import failed: ' . $out); if ($checkOutput) { $this->assertContains("Imported 2 records.", $out); } }
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()}); } }
public function route(Zend_Controller_Request_Abstract $dispatcher) { $getopt = new Zend_Console_Getopt(array()); $getopt->addRules(array('controller|c=s' => 'Controller Name', 'action|a=s' => 'Controller Action', 'from|f=s' => 'From yyyy-mm-dd', 'to|t=s' => 'To yyyy-mm-dd')); $arguments = $getopt->getRemainingArgs(); if ($getopt->getOption('controller') && $getopt->getOption('action')) { $dispatcher->setControllerName($getopt->getOption('controller')); $dispatcher->setActionName($getopt->getOption('action')); $dispatcher->setParams(array('from' => $getopt->getOption('from'), 'to' => $getopt->getOption('to'))); return $dispatcher; } }
/** * Creates the new project * @throws Exception */ public function createProject() { $force = !!$this->console->getOption('force'); $realAppPath = realpath($this->appPath) . DIRECTORY_SEPARATOR; $realLibraryPath = realpath(dirname(__FILE__) . '/../') . DIRECTORY_SEPARATOR; $libraryPath = 'Library/'; while (!file_exists($this->appPath . $libraryPath) && strpos($realAppPath, $realLibraryPath) === 0) { $libraryPath = '../' . $libraryPath; } foreach ($this->projectFiles as $projectFile => $projectFileValue) { if (is_int($projectFile)) { $projectFile = $projectFileValue; $projectFileValue = array(); } if (file_exists($this->appPath . $projectFile) && !$force) { throw new Exception('Project file "' . $projectFile . '" already exists failure.'); } if (substr($projectFile, -1) === '/') { if (!file_exists($this->appPath . $projectFile)) { mkdir($this->appPath . $projectFile, 0777, !empty($projectFileValue['recursive'])); } if (isset($projectFileValue['chmod'])) { $old = umask(0); chmod($this->appPath . $projectFile, $projectFileValue['chmod']); umask($old); } } else { $fileContent = isset($projectFileValue['content']) ? $projectFileValue['content'] : ''; $fileContent = str_replace(array('%app%', '%appPath%', '%libraryPath%'), array($this->app, $this->appPath, $libraryPath), $fileContent); file_put_contents($this->appPath . $projectFile, $fileContent); } } }
/** * method to sync the options received from cli with the possible options * if options is mandatory and not received return false * * @param type $possibleOptions * * @return mixed array of options if all mandatory options received, else false */ public function getInstanceOptions($possibleOptions = null) { if (is_null($possibleOptions)) { $possibleOptions = array('type' => false, 'stamp' => false, 'path' => "./", 'parser' => 'fixed'); } $options = array(); //Retrive the command line properties // foreach($this->options->getRemainingArgs() as $cmdLineArg) { // $seperatedCmdStr = !strpos('=',$cmdLineArg) ? split("=", $cmdLineArg) : split(" ", $cmdLineArg); // $inLineOpt = isset($seperatedCmdStr[1]) ? $seperatedCmdStr[1] : true; // foreach (array_reverse(split("\.", $seperatedCmdStr[0])) as $field) { // $inLineOpt = array( $field => $inLineOpt); // } // $options['cmd_opts'] = array_merge_recursive( (isset($options['cmd_opts']) ? $options['cmd_opts'] : array() ), $inLineOpt ); // } foreach ($possibleOptions as $key => $defVal) { $options[$key] = $this->options->getOption($key); if (is_null($options[$key])) { if (!$defVal) { $this->addOutput("Error: No {$key} selected"); return false; } else { if (true !== $defVal) { $options[$key] = $defVal; } else { unset($options[$key]); } } } } return $options; }
public function compileSchema() { if (!$this->opts->getOption('dest')) { throw new RuntimeException("Specify destination folder (--dest PATH)"); } if (!$this->opts->getOption('schema')) { throw new RuntimeException("Specify path to XML Schema file (--schema PATH)"); } $schema = $this->opts->getOption('schema'); if (!file_exists($schema)) { throw new RuntimeException("Schema file " . $schema . " is not found"); } $dest = $this->opts->getOption('dest'); $this->legko->compileSchema($schema, $dest); $this->println("Bindings successfully generated in " . realpath($dest)); }
/** * Takes the config from config.inc.php and creates an account with the associated lines * @param Zend_Console_Getopt $_opts */ public function take_config($_opts) { // resolve arguments $args = $this->_parseArgs($_opts, array()); $type = in_array('shared', $args['other']) ? 'shared' : 'private'; if (@isset(Tinebase_Core::getConfig()->sipgate)) { $conf = Tinebase_Core::getConfig()->sipgate; if (@isset($conf->api_username) && @isset($conf->api_password)) { echo 'Validate configuration from config.inc.php...' . PHP_EOL; $accountData = array('data' => array('accounttype' => @isset($conf->api_url) && $conf->api_url != 'https://samurai.sipgate.net/RPC2' ? 'team' : 'plus', 'description' => 'Created by update', 'username' => $conf->api_username, 'password' => $conf->api_password, 'type' => $type)); if (Sipgate_Controller_Account::getInstance()->validateAccount($accountData)) { echo 'Data from config.inc.php could be validated, creating account...' . PHP_EOL; try { $account = Sipgate_Controller_Account::getInstance()->create(new Sipgate_Model_Account($accountData['data'])); } catch (Tinebase_Exception_Duplicate $e) { echo 'An account with this credentials exists already! Did you use this script twice?' . PHP_EOL; die; } if ($account) { echo 'Account created. Trying to synchronize the lines..' . PHP_EOL; if (Sipgate_Controller_Line::getInstance()->syncAccount($account->getId())) { $opts = new Zend_Console_Getopt('abp:'); $args = array('initial', 'verbose'); if ($type == 'shared') { $args[] = 'shared'; } $opts->setArguments($args); echo 'Lines have been synchronized. Now syncing connections from the last two months, day per day. This could take some time.' . PHP_EOL; $this->sync_connections($opts); echo 'Connections has been synchronized. Now assign users to the line(s) to allow them to use the line(s)' . PHP_EOL; echo 'READY!' . PHP_EOL; } else { echo 'The lines for the account could not be created!' . PHP_EOL; } } else { echo 'The account could not be created!' . PHP_EOL; } } else { echo 'The credentials found in config.inc.php could not be validated!' . PHP_EOL; } } else { echo 'No username or password could be found in config.php.inc!' . PHP_EOL; } } else { echo 'No sipgate config could be found in config.php.inc!' . PHP_EOL; } }
/** * 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; }
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; }
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())); }
/** * Method build and show error message * * @return \Extlib\Cli\CliAbstract */ protected function buildErrors() { if ($this->hasErrors()) { echo implode(PHP_EOL, $this->getErrors()); echo PHP_EOL, $this->opts->getUsageMessage(); } return $this; }
/** * Get option value by name * * @param string $sName * @return string */ protected final function _getOption($sName) { $sOption = $this->_oGetopt->getOption($sName); if (is_null($sOption) && !is_null($this->_aExpectedOptions[$sName]['default'])) { $sOption = $this->_aExpectedOptions[$sName]['default']; } return $sOption; }