예제 #1
0
 /**
  * Progress one or more command-line options. 
  *
  *     // Create a controller "controller_home" and a action named "action_index"
  *     // stored in path: APPPATH.'/classes/controller/home.php'
  *     kohana controller home index
  *
  *     // Create a model named user.php
  *     // stored in path: APPPATH.'/classes/model/auth/user.php'
  *     kohana model auth_user
  *
  */
 public function action_index()
 {
     // Instance terminal
     $terminal = new Terminal();
     // Init terminal
     $terminal->init();
 }
예제 #2
0
 public function testAliasesHasAndAddWorks()
 {
     $term = new Terminal();
     $this->assertFalse($term->hasAlias("foo"));
     $command = new ShellCommand("foo");
     $term->addAlias("foo", $command);
     $this->assertTrue($term->hasAlias("foo"));
 }
예제 #3
0
파일: ListCommand.php 프로젝트: Rhoban/deps
 public function run(array $arguments)
 {
     Terminal::info("Installed packages:\n");
     foreach ($this->deps->getPackages() as $package) {
         Terminal::bold('* ' . $package->getName() . "\n");
     }
 }
 /**
  * Renders process queue page
  * @param $service_id
  */
 public function getTerminal($terminal_id)
 {
     if (!TerminalUser::isCurrentUserAssignedToTerminal($terminal_id)) {
         return Redirect::back();
     }
     return View::make('process-queue.process-queue')->with('body', 'processq')->with('terminal_id', $terminal_id)->with('service_id', Terminal::serviceId($terminal_id))->with('terminal_name', Terminal::name($terminal_id))->with('business_id', Business::getBusinessIdByTerminalId($terminal_id))->with('business_name', Business::getBusinessNameByTerminalId($terminal_id));
 }
예제 #5
0
 public function run(array $arguments)
 {
     Terminal::info("Installed packages:\n");
     foreach ($this->deps->getPackages() as $package) {
         $this->printStatus($package);
     }
 }
예제 #6
0
 /**
  * Format a string containing `<styles>`...`</>` sequences
  *
  * @param  string $in
  * @param  string[] $stack
  * @return string
  */
 public static function format($in, &$stack)
 {
     $offset = 0;
     $length = strlen($in);
     $formatted = '';
     do {
         $p = strcspn($in, '<', $offset);
         $formatted .= substr($in, $offset, $p);
         $offset += $p + 1;
         if ($offset >= $length) {
             break;
         }
         $e = strcspn($in, '>', $offset);
         $token = substr($in, $offset, $e);
         if ('' === $token) {
             $e = strpos($in, '</>', $offset) - $offset;
             $formatted .= substr($in, $offset + 1, $e - 1);
             $e += 2;
         } else {
             if ('/' === $token[0]) {
                 $formatted .= array_pop($stack);
             } else {
                 if (strlen($token) !== strspn($token, 'abcdefghijklmnopqrstuvwxyz0123456789-,@')) {
                     $formatted .= substr($in, $offset - 1, $e + 1 + 1);
                 } else {
                     list($set, $unset) = Terminal::transition($token);
                     $formatted .= $set;
                     $stack[] = $unset;
                 }
             }
         }
         $offset += $e + 1;
     } while ($offset < $length);
     return $formatted;
 }
예제 #7
0
 public function generate($filename, $extends = NULL)
 {
     // Progress controller file
     $files = explode('/', $filename);
     $files_count = count($files);
     // Progress controller directory
     $model = array('Model');
     $directory = NULL;
     if ($files_count > 1) {
         // progress controller name
         for ($i = 0; $i < $files_count; $i++) {
             $model[] = $this->_format_name($files[$i]);
             if ($i != $files_count - 1) {
                 $directory .= $files[$i] . DIRECTORY_SEPARATOR;
             }
         }
         $filename = $files[$files_count - 1];
     } else {
         $model[] = $this->_format_name($filename);
     }
     // Set the name of controller file
     $model = implode('_', $model);
     // Set controller extends
     if ($extends) {
         $parent = strtolower($extends);
         switch ($parent) {
             case 'orm':
                 $parent = strtoupper($parent);
             default:
                 $parent = ucfirst($parent);
         }
         $extends = $parent;
     } else {
         $extends = 'Model';
     }
     // Set the name of the controller path
     $directory = $this->config->apppath . Terminal::MODELPATH . $directory;
     if (!is_dir($directory)) {
         // Create the yearly directory
         mkdir($directory, 0777, TRUE);
         // Set permissions (must be manually set to fix umask issues)
         chmod($directory, 0777);
     }
     // Set the name of the log file
     $filename = $directory . $filename . EXT;
     if (!file_exists($filename)) {
         // Create the controller file
         file_put_contents($filename, Kohana::FILE_SECURITY . PHP_EOL);
         // Allow anyone to write to controller files
         chmod($filename, 0666);
         // Continute to write
         file_put_contents($filename, PHP_EOL . 'class ' . ucfirst($model) . ' extends ' . $extends . ' {', FILE_APPEND);
         file_put_contents($filename, PHP_EOL . PHP_EOL . '}' . PHP_EOL . PHP_EOL, FILE_APPEND);
         $result = Terminal::color('create', 'green');
     } else {
         $result = Terminal::color('exist', 'blue');
     }
     $result = '    ' . $result . '  ' . Kohana::debug_path($filename);
     echo $result . PHP_EOL;
 }
예제 #8
0
파일: Tap.php 프로젝트: samsonasik/kahlan
 /**
  * Callback called before any specs processing.
  *
  * @param array $params The suite params array.
  */
 public function start($params)
 {
     $this->_header = false;
     parent::start($params);
     $this->write("\n");
     $this->write("# Building report it can take some time, please be patient");
 }
예제 #9
0
파일: InfoCommand.php 프로젝트: Rhoban/deps
 public function run(array $arguments)
 {
     $json = $this->deps->nearestJson();
     $package = new Package(dirname($json));
     $porcelain = count($arguments) && $arguments[0] == 'porcelain';
     if (!$porcelain) {
         Terminal::info("From {$json}\n\n");
         Terminal::bold("* project name: " . $package->getName() . "\n");
     }
     $dependencies = $package->getDependencies();
     if ($porcelain) {
         echo implode(':', $dependencies) . "\n";
     } else {
         if ($dependencies) {
             Terminal::bold("* dependencies:\n");
             foreach ($dependencies as $dep) {
                 echo "  - {$dep} ";
                 if ($this->deps->hasPackage($dep)) {
                     Terminal::success("(installed)");
                 } else {
                     Terminal::warning("(not installed)");
                 }
                 echo "\n";
             }
         } else {
             Terminal::bold("* no dependencies\n");
         }
     }
 }
예제 #10
0
 public function dispenseDone()
 {
     $terminal_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
     $product = isset($_GET['p']) ? floatval($_GET['p']) : 0;
     if ($terminal_id > 0 && $product > 0) {
         error_log('Receieved DISPENSE_DONE value ' . $product . ' event from terminal ' . $terminal_id);
         Terminal::addEvent($terminal_id, 2, $product);
     } else {
         error_log('method called without params.');
     }
 }
예제 #11
0
 public function __construct(\lib\Webos $webos, \lib\Authorization $auth, $cmdText, Terminal $terminal)
 {
     $cmdText = trim($cmdText);
     $this->cmdText = $cmdText;
     $this->terminal = $terminal;
     $arrayCmd = explode(' ', $cmdText);
     $this->cmd = $arrayCmd[0];
     if (preg_match('#^".+"$#', $this->cmd)) {
         $this->cmd = preg_replace('#^"(.+)"$#', '$1', $this->cmd);
     }
     unset($arrayCmd[0]);
     $args = implode(' ', $arrayCmd);
     $this->arguments = new CmdArguments($webos);
     $this->arguments->setArguments($args);
     $path = null;
     if (preg_match('#^[\\.~]?/#', $this->cmd)) {
         if ($webos->managers()->get('File')->exists($this->terminal->getAbsoluteLocation($this->cmd))) {
             $file = $webos->managers()->get('File')->get($this->terminal->getAbsoluteLocation($this->cmd));
             if (!$file->isDir() && in_array($file->extension(), $this->extensions)) {
                 $path = $file->path();
             }
         }
     }
     foreach ($this->directories as $dir) {
         $dirContents = $webos->managers()->get('File')->get($dir)->contents();
         foreach ($dirContents as $file) {
             if (!$file->isDir() && in_array($file->extension(), $this->extensions)) {
                 if ($file->filename() == $this->cmd || $file->basename() == $this->cmd) {
                     $path = $file;
                 }
             }
         }
     }
     if (empty($path)) {
         throw new \InvalidArgumentException('"' . $this->cmd . '" : commande introuvable');
     }
     //On appelle le constructeur du parent.
     parent::__construct($webos, $auth, $path);
 }
예제 #12
0
 public function run(array $arguments)
 {
     $remotes = $this->deps->getRemotes();
     $current = $remotes->getCurrent();
     Terminal::info("Remotes:\n");
     foreach ($remotes->getRemotes() as $remote => $addr) {
         if ($remote == $current) {
             Terminal::success("* {$remote} ({$addr})\n");
         } else {
             Terminal::bold("* {$remote} ({$addr})\n");
         }
     }
 }
예제 #13
0
 /**
  * Creates a new instance of a Command and returns it.
  *
  * @param Terminal $terminal
  * @param InputResult $inputResult
  * @return mixed
  * @throws CommandNotFoundException
  */
 public function create(Terminal $terminal, InputResult $inputResult)
 {
     $commandDirectories = $terminal->getCommandDirectories();
     $systemCommandDirectories = $terminal->getSystemCommandDirectories();
     $class = ucfirst($inputResult->command) . 'Command';
     foreach ($commandDirectories as $dir) {
         $file = $dir . $class . '.php';
         if (file_exists($file)) {
             require_once $file;
             return $class::createFromInput($inputResult);
         }
     }
     foreach ($systemCommandDirectories as $dir) {
         $file = $dir . $class . '.php';
         if (file_exists($file)) {
             require_once $file;
             $instance = $class::createFromInput($inputResult);
             $instance->setTerminal($terminal);
             return $instance;
         }
     }
     throw new CommandNotFoundException($inputResult->command . ': ' . \Config::get('invalidCmdMsg', 'command not found'));
 }
예제 #14
0
 public function run(array $arguments)
 {
     if ($arguments) {
         foreach ($arguments as $dep) {
             $this->deps->install($dep, false);
         }
     } else {
         foreach ($this->deps->getPackages() as $package) {
             try {
                 $dep = $package->getName();
                 $this->deps->install($dep, false);
             } catch (\Exception $error) {
                 Terminal::error($error->getMessage() . "\n");
             }
         }
     }
     return true;
 }
예제 #15
0
 /**
  * Show the form for editing the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function edit($id)
 {
     $stock = $this->stock->find($id);
     if (is_null($stock)) {
         return Redirect::route('stocks.index');
     }
     $terminals = Terminal::all();
     $arrTerminals = array();
     foreach ($terminals as $terminal) {
         $arrTerminals[$terminal->id] = $terminal->name;
     }
     $productss = Product::all();
     $arrProducts = array();
     foreach ($productss as $products) {
         $arrProducts[$products->id] = $products->title;
     }
     return View::make('stocks.edit', compact('stock'), array('terminals_selector' => $arrTerminals, 'products_selector' => $arrProducts, 'promo_type_selector' => Promo::getTypes()));
 }
예제 #16
0
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function show($id)
 {
     $terminal = Terminal::find($id);
     $terminal_config = array();
     $terminal_config['urls'] = array();
     $terminal_config['urls']['dispense'] = Config::get('jidou.hw_dispense_url');
     $terminal['config'] = $terminal_config;
     $terminal['stock'] = Stock::getStock($id);
     $terminal['timestamp'] = time();
     $max = DB::table('terminal_events')->select(DB::raw('max(id) as max'))->where('terminal_id', '=', $id)->get();
     $max = intval($max[0]->max);
     $terminal['max'] = $max;
     if (isset($_GET['_callback'])) {
         return Response::json($terminal)->setCallback($_GET['_callback']);
     } else {
         return Response::json($terminal);
     }
 }
예제 #17
0
 public function run(array $arguments)
 {
     if ($arguments) {
         foreach ($arguments as $dep) {
             $this->deps->install($dep);
         }
     } else {
         $json = $this->deps->nearestJson();
         $package = new Package(dirname($json));
         $dependencies = $package->getDependencies();
         if ($dependencies) {
             foreach ($dependencies as $dep) {
                 $this->deps->install($dep);
             }
         } else {
             Terminal::success("Nothing to do!\n");
         }
     }
     return true;
 }
예제 #18
0
 public function run(array $arguments)
 {
     $flags = "";
     if ($arguments) {
         foreach ($arguments as $dep) {
             if ($this->deps->hasPackage($dep)) {
                 $flags .= $this->cflags($this->deps->getPackage($dep));
             }
         }
     } else {
         $json = $this->deps->nearestJson();
         $package = new Package(dirname($json));
         $dependencies = $package->getDependencies();
         foreach ($dependencies as $dep) {
             if ($this->deps->hasPackage($dep)) {
                 $flags .= $this->cflags($this->deps->getPackage($dep));
             }
         }
     }
     Terminal::write($flags . "\n");
 }
예제 #19
0
파일: Debug.php 프로젝트: ansendu/ansio
 /**
  * Send print to terminal.
  */
 private static function _log($msgType, $args)
 {
     if (!Config::get('debug_mode', 0)) {
         return;
     }
     if (count($args) == 1) {
         $msg = is_scalar($args[0]) ? $args[0] : self::dump($args[0]);
     } else {
         $msg = self::dump($args);
     }
     $mt = explode(' ', microtime());
     if (self::$DEBUG_TRACE) {
         $trace = self::getTrace();
     } else {
         $trace = array();
     }
     $msg = ' ' . $msg . " mem: " . Utils::convertSize(memory_get_usage()) . "\n";
     Terminal::drawStr('[' . Daemon::$pid . '][' . date('H:i:s', $mt[1]) . '.' . sprintf('%06d', $mt[0] * 1000000) . ']', 'default');
     if ($msgType == 'debug') {
         Terminal::drawStr($msg, 'magenta');
     } else {
         if ($msgType == 'log') {
             Terminal::drawStr($msg, 'lightgray');
         } else {
             if ($msgType == 'error') {
                 Terminal::drawStr($msg, 'red');
             } else {
                 if ($msgType == 'info') {
                     Terminal::drawStr($msg, 'brown');
                 } else {
                     Terminal::drawStr($msg, 'default');
                 }
             }
         }
     }
     //echo "\n";
     !empty($trace) && Terminal::drawStr("\t" . implode(" <-- ", $trace) . "\n");
 }
예제 #20
0
 public function generate($filename)
 {
     // Progress controller file
     $files = explode('/', $filename);
     $files_count = count($files);
     // Progress controller directory
     $directory = NULL;
     if ($files_count > 1) {
         // progress controller name
         for ($i = 0; $i < $files_count; $i++) {
             if ($i != $files_count - 1) {
                 $directory .= $files[$i] . DIRECTORY_SEPARATOR;
             }
         }
         $filename = $files[$files_count - 1];
     }
     // Set the name of the controller path
     $directory = $this->config->apppath . Terminal::VIEWPATH . $directory;
     if (!is_dir($directory)) {
         // Create the yearly directory
         mkdir($directory, 0777, TRUE);
         // Set permissions (must be manually set to fix umask issues)
         chmod($directory, 0777);
     }
     // Set the name of the log file
     $filename = $directory . $filename . EXT;
     if (!file_exists($filename)) {
         // Create the controller file
         file_put_contents($filename, Kohana::FILE_SECURITY . PHP_EOL);
         // Allow anyone to write to controller files
         chmod($filename, 0666);
         $result = Terminal::color('create', 'green');
     } else {
         $result = Terminal::color('exist', 'blue');
     }
     $result = '    ' . $result . '  ' . Kohana::debug_path($filename);
     echo $result . PHP_EOL;
 }
예제 #21
0
파일: Daemon.php 프로젝트: ansendu/ansio
 public static function init()
 {
     Daemon::$eventBase = event_base_new();
     $args = $_SERVER['argv'];
     if (!isset($args[1]) || !isset($args[2])) {
         Terminal::drawStr('usage: php xxx.php sArea (start|stop|restart|reload|status)' . "\n");
         exit(-1);
     }
     // todo run multi app in one daemon.
     $sArea = $args[1];
     $command = $args[2];
     $appName = Config::get('socket_server_class', null, true);
     Daemon::$runName = $appName;
     $runAppInstance = array($appName => $appName);
     if ($command == 'start') {
         // fork later
         self::$pid = posix_getpid();
         Debug::log('start');
         foreach ($runAppInstance as $appName) {
             $obj = new $appName();
         }
         while (!Daemon::$breakEventLoop) {
             event_base_loop(daemon::$eventBase, EVLOOP_ONCE);
             // 清空本次写状态数组
             gc_collect_cycles();
             //daemon::debug('<== evet_base_loop() ending');
         }
     } elseif ($command == 'stop') {
         // cat pid, stop
     } elseif ($command == 'status') {
         // cat pid, show status
     } elseif ($command == 'restart') {
         //self::stop();
         //self::start();
     }
 }
예제 #22
0
파일: Dot.php 프로젝트: Ilyes512/kahlan
 /**
  * Callback called before any specs processing.
  *
  * @param array $params The suite params array.
  */
 public function start($params)
 {
     parent::start($params);
     $this->write("\n");
 }
예제 #23
0
 function match_code($value)
 {
     $code = parent::match_code('');
     return $value ? $code->replace(array('FAIL' => NULL)) : $code;
 }
예제 #24
0
파일: term.php 프로젝트: richardjoo/Codiad
    //////////////////////////////////////////////////////////////
    // Exit
    //////////////////////////////////////////////////////////////
    $_SESSION['term_auth'] = 'false';
    $output = '[CLOSED]';
} else {
    if (!isset($_SESSION['term_auth']) || $_SESSION['term_auth'] != 'true') {
        //////////////////////////////////////////////////////////////
        // Authentication
        //////////////////////////////////////////////////////////////
        if ($command == PASSWORD) {
            $_SESSION['term_auth'] = 'true';
            $output = '[AUTHENTICATED]';
        } else {
            $output = 'Enter Password:'******'';
        $command = explode("&&", $command);
        foreach ($command as $c) {
            $Terminal->command = $c;
            $output .= $Terminal->Process();
        }
    }
}
echo htmlentities($output);
예제 #25
0
파일: Deps.php 프로젝트: Rhoban/deps
 public function build($dep)
 {
     $this->updateEnv();
     Terminal::info("* Building {$dep}...\n");
     if ($this->hasPackage($dep)) {
         $package = $this->getPackage($dep);
         $package->build();
     } else {
         throw new \Exception("Unable to build not existing package {$dep}");
     }
 }
예제 #26
0
 private static function printHelp()
 {
     $term = new Terminal();
     echo 'phpDaemon ' . Daemon::$version . ". Made in Russia. http://phpdaemon.net\n";
     self::printUsage();
     echo "\nAlso you can use some optional parameters to override the same configuration variables:\n";
     foreach (self::$params as $name => $desc) {
         if (empty($desc)) {
             continue;
         } elseif (!is_array($desc)) {
             $term->drawParam($name, $desc);
         } else {
             $term->drawParam($name, isset($desc['desc']) ? $desc['desc'] : '', isset($desc['val']) ? $desc['val'] : '');
         }
     }
     echo "\n";
 }
예제 #27
0
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function destroy($id)
 {
     $this->terminal->find($id)->delete();
     return Redirect::route('terminals.index');
 }
 public function postRemove()
 {
     $post = json_decode(file_get_contents("php://input"));
     if (Helper::isBusinessOwner($post->business_id, Helper::userId())) {
         // PAG added permission checking
         Business::deleteBusinessByBusinessId($post->business_id);
         $branches = Branch::getBranchesByBusinessId($post->business_id);
         foreach ($branches as $count => $data) {
             $services = Service::getServicesByBranchId($data->branch_id);
             foreach ($services as $count2 => $data2) {
                 $terminals = Terminal::getTerminalsByServiceId($data2->service_id);
                 foreach ($terminals as $count3 => $data3) {
                     TerminalUser::deleteUserByTerminalId($data3['terminal_id']);
                 }
                 Terminal::deleteTerminalsByServiceId($data2->service_id);
             }
             Service::deleteServicesByBranchId($data->branch_id);
         }
         Branch::deleteBranchesByBusinessId($post->business_id);
         UserBusiness::deleteUserByBusinessId($post->business_id);
         return json_encode(array('status' => 1));
     } else {
         return json_encode(array('status' => 0, 'message' => 'You are not allowed to access this function.'));
     }
 }
예제 #29
0
 public static function init()
 {
     Daemon::initSettings();
     Daemon::$runName = basename($_SERVER['argv'][0]);
     $error = FALSE;
     $argv = $_SERVER['argv'];
     $runmode = isset($argv[1]) ? str_replace('-', '', $argv[1]) : '';
     $args = Daemon_Bootstrap::getArgs($argv);
     if (isset($args[$k = 'configfile'])) {
         Daemon::$settings[$k] = $args[$k];
     }
     if (isset(Daemon::$settings['configfile']) && !Daemon::loadConfig(Daemon::$settings['configfile'])) {
         $error = TRUE;
     }
     if (!Daemon::loadSettings($args)) {
         $error = TRUE;
     }
     if (version_compare(PHP_VERSION, '5.3.0', '>=') === 1) {
         Daemon::log('PHP >= 5.3.0 required.');
         $error = TRUE;
     }
     if (isset(Daemon::$settings['locale'])) {
         setlocale(LC_ALL, explode(',', Daemon::$settings['locale']));
     }
     if (!is_callable('posix_kill')) {
         Daemon::log('Posix not found. You should compile PHP without \'--disable-posix\'.');
         $error = TRUE;
     }
     if (!is_callable('pcntl_signal')) {
         Daemon::log('PCNTL not found. You should compile PHP with \'--enable-pcntl\'.');
         $error = TRUE;
     }
     if (!is_callable('event_base_new')) {
         Daemon::log('libevent extension not found. You have to install libevent from pecl (http://pecl.php.net/package/libevent). `svn checkout http://svn.php.net/repository/pecl/libevent pecl-libevent`.');
         $error = TRUE;
     }
     if (!is_callable('socket_create')) {
         Daemon::log('Sockets extension not found. You should compile PHP with \'--enable-sockets\'.');
         $error = TRUE;
     }
     if (!is_callable('shmop_open')) {
         Daemon::log('Shmop extension not found. You should compile PHP with \'--enable-shmop\'.');
         $error = TRUE;
     }
     if (!isset(Daemon::$settings['user'])) {
         Daemon::log('You must set \'user\' parameter.');
         $error = TRUE;
     }
     if (!isset(Daemon::$settings['path'])) {
         Daemon::log('You must set \'path\' parameter (path to your application resolver).');
         $error = TRUE;
     }
     Daemon_Bootstrap::$pidfile = realpath(Daemon::$settings['pidfile']);
     if (!Daemon_Bootstrap::$pidfile) {
         Daemon_Bootstrap::$pidfile = Daemon::$settings['pidfile'];
     }
     if (!file_exists(Daemon_Bootstrap::$pidfile)) {
         if (!touch(Daemon_Bootstrap::$pidfile)) {
             Daemon::log('Couldn\'t create pid-file \'' . Daemon_Bootstrap::$pidfile . '\'.');
             $error = TRUE;
         }
         Daemon_Bootstrap::$pid = 0;
     } elseif (!is_file(Daemon_Bootstrap::$pidfile)) {
         Daemon::log('Pid-file \'' . Daemon_Bootstrap::$pidfile . '\' must be a regular file.');
         Daemon_Bootstrap::$pid = FALSE;
         $error = TRUE;
     } elseif (!is_writable(Daemon_Bootstrap::$pidfile)) {
         Daemon::log('Pid-file \'' . Daemon_Bootstrap::$pidfile . '\' must be writable.');
         $error = TRUE;
     } elseif (!is_readable(Daemon_Bootstrap::$pidfile)) {
         Daemon::log('Pid-file \'' . Daemon_Bootstrap::$pidfile . '\' must be readable.');
         Daemon_Bootstrap::$pid = FALSE;
         $error = TRUE;
     } else {
         Daemon_Bootstrap::$pid = (int) file_get_contents(Daemon_Bootstrap::$pidfile);
     }
     if (Daemon::$settings['chroot'] !== '/') {
         if (posix_getuid() != 0) {
             Daemon::log('You must have the root privileges to change root.');
             $error = TRUE;
         }
     }
     if (!@is_file(Daemon::$pathReal)) {
         Daemon::log('Your application resolver \'' . Daemon::$settings['path'] . '\' is not available.');
         $error = TRUE;
     }
     if (isset(Daemon::$settings['group']) && is_callable('posix_getgid')) {
         if (($sg = posix_getgrnam(Daemon::$settings['group'])) === FALSE) {
             Daemon::log('Unexisting group \'' . Daemon::$settings['group'] . '\'. You have to replace config-variable \'group\' with existing group-name.');
             $error = TRUE;
         } elseif ($sg['gid'] != posix_getgid() && posix_getuid() != 0) {
             Daemon::log('You must have the root privileges to change group.');
             $error = TRUE;
         }
     }
     if (isset(Daemon::$settings['user']) && is_callable('posix_getuid')) {
         if (($su = posix_getpwnam(Daemon::$settings['user'])) === FALSE) {
             Daemon::log('Unexisting user \'' . Daemon::$settings['user'] . '\', user not found. You have to replace config-variable \'user\' with existing username.');
             $error = TRUE;
         } elseif ($su['uid'] != posix_getuid() && posix_getuid() != 0) {
             Daemon::log('You must have the root privileges to change user.');
             $error = TRUE;
         }
     }
     if (isset(Daemon::$settings['minspareworkers']) && isset(Daemon::$settings['maxspareworkers'])) {
         if (Daemon::$settings['minspareworkers'] > Daemon::$settings['maxspareworkers']) {
             Daemon::log('\'minspareworkers\' cannot be greater than \'maxspareworkers\'.');
             $error = TRUE;
         }
     }
     if (isset(Daemon::$settings['minworkers']) && isset(Daemon::$settings['maxworkers'])) {
         if (Daemon::$settings['minworkers'] > Daemon::$settings['maxworkers']) {
             Daemon::$settings['maxworkers'] = Daemon::$settings['minworkers'];
         }
     }
     if ($runmode == 'start') {
         if ($error === FALSE) {
             Daemon_Bootstrap::start();
         }
     } elseif ($runmode == 'status' or $runmode == 'fullstatus') {
         $status = Daemon_Bootstrap::$pid && posix_kill(Daemon_Bootstrap::$pid, SIGTTIN);
         echo '[STATUS] phpDaemon ' . Daemon::$version . ' is ' . ($status ? 'running' : 'NOT running') . ' (' . Daemon_Bootstrap::$pidfile . ").\n";
         if ($status && $runmode == 'fullstatus') {
             echo 'Uptime: ' . Daemon::date_period_text(filemtime(Daemon_Bootstrap::$pidfile), time()) . "\n";
             Daemon::$shm_wstate = Daemon::shmop_open(Daemon::$settings['ipcwstate'], 0, 'wstate', FALSE);
             $stat = Daemon::getStateOfWorkers();
             echo "State of workers:\n";
             echo "\tTotal: " . $stat['alive'] . "\n";
             echo "\tIdle: " . $stat['idle'] . "\n";
             echo "\tBusy: " . $stat['busy'] . "\n";
             echo "\tShutdown: " . $stat['shutdown'] . "\n";
             echo "\tPre-init: " . $stat['preinit'] . "\n";
             echo "\tWait-init: " . $stat['waitinit'] . "\n";
             echo "\tInit: " . $stat['init'] . "\n";
         }
         echo "\n";
     } elseif ($runmode == 'update') {
         if (!Daemon_Bootstrap::$pid || !posix_kill(Daemon_Bootstrap::$pid, SIGHUP)) {
             echo '[UPDATE] ERROR. It seems that phpDaemon is not running' . (Daemon_Bootstrap::$pid ? ' (PID ' . Daemon_Bootstrap::$pid . ')' : '') . ".\n";
         }
     } elseif ($runmode == 'reopenlog') {
         if (!Daemon_Bootstrap::$pid || !posix_kill(Daemon_Bootstrap::$pid, SIGUSR1)) {
             echo '[REOPEN-LOG] ERROR. It seems that phpDaemon is not running' . (Daemon_Bootstrap::$pid ? ' (PID ' . Daemon_Bootstrap::$pid . ')' : '') . ".\n";
         }
     } elseif ($runmode == 'reload') {
         if (!Daemon_Bootstrap::$pid || !posix_kill(Daemon_Bootstrap::$pid, SIGUSR2)) {
             echo '[RELOAD] ERROR. It seems that phpDaemon is not running' . (Daemon_Bootstrap::$pid ? ' (PID ' . Daemon_Bootstrap::$pid . ')' : '') . ".\n";
         }
     } elseif ($runmode == 'restart') {
         Daemon_Bootstrap::stop(2);
         Daemon_Bootstrap::start();
     } elseif ($runmode == 'hardrestart') {
         Daemon_Bootstrap::stop(3);
         Daemon_Bootstrap::start();
     } elseif ($runmode == 'configtest') {
         $term = new Terminal();
         $term->enable_color = TRUE;
         echo "\n";
         $rows = array();
         $rows[] = array('parameter' => 'PARAMETER', 'value' => 'VALUE', '_color' => '37', '_bold' => TRUE);
         foreach (Daemon::$settings as $name => &$value) {
             $row = array('parameter' => $name, 'value' => var_export($value, TRUE));
             if (isset(Daemon::$parsedSettings[$name])) {
                 $row['value'] .= ' (' . Daemon::$parsedSettings[$name] . ')';
             }
             $rows[] = $row;
         }
         $term->drawtable($rows);
         echo "\n";
     } elseif ($runmode == 'stop') {
         Daemon_Bootstrap::stop();
     } elseif ($runmode == 'hardstop') {
         echo '[HARDSTOP] Sending SIGINT to ' . Daemon_Bootstrap::$pid . '... ';
         $ok = Daemon_Bootstrap::$pid && posix_kill(Daemon_Bootstrap::$pid, SIGINT);
         echo $ok ? 'OK.' : 'ERROR. It seems that phpDaemon is not running.';
         if ($ok) {
             $i = 0;
             while ($r = posix_kill(Daemon_Bootstrap::$pid, SIGTTIN)) {
                 usleep(500000);
                 if ($i == 9) {
                     echo "\nphpDaemon master-process hasn't finished. Sending SIGKILL... ";
                     posix_kill(Daemon_Bootstrap::$pid, SIGKILL);
                     if (!posix_kill(Daemon_Bootstrap::$pid, SIGTTIN)) {
                         echo " Oh, his blood is on my hands :'(";
                     } else {
                         echo "ERROR: Process alive. Permissions?";
                     }
                     break;
                 }
                 ++$i;
             }
         }
         echo "\n";
     } elseif ($runmode == 'help') {
         echo 'phpDaemon ' . Daemon::$version . ". Made in Russia. http://phpdaemon.googlecode.com/\nusage: " . Daemon::$runName . " (start|(hard)stop|update|reload|(hard)restart|fullstatus|status|configtest|help) ...\n\n\tAlso you can use some optional parameters to override the same config variables.\n\t--pid-file='/path/to/pid-file'  -  (Pid-file)\n\t--max-requests=" . Daemon::$settings['maxrequests'] . "  -  (Maximum requests to worker before respawn)\n\t--path='" . Daemon::$settings['path'] . "'  -  (You can set a path to your application resolver)\n\t--config-file='" . Daemon::$settings['configfile'] . "'  -  (You can set a path to configuration file manually)\n\t--logging=1  -  (Logging. 1-Enable, 0-Disable)\n\t--log-storage='" . Daemon::$settings['logstorage'] . "'  -  (Log storage. This field has special syntax, but it allows simple path.)\n\t--user='******'user'] . "'  -  (You can set user of master process (aka sudo).) \n\t--group='" . Daemon::$settings['group'] . "'  -  (You can set user of master process (aka sudo).)\n\t--manual  -  (Open the manual pages.)\n\t--help  -  (This help information.)\n  \n\n";
     } else {
         if ($runmode !== '') {
             echo 'Unrecognized command: ' . $runmode . "\n";
         }
         echo 'usage: ' . Daemon::$runName . " (start|(hard)stop|update|reload|(hard)restart|fullstatus|status|configtest|help) ...\n";
         exit;
     }
 }
 /**
  * Outputs a visual list of the autocomplete candidates.
  *
  * @param array $options an array of the candidates
  *
  * @return void
  */
 private function _showAutoCompleteOptions($options)
 {
     // TAB must be pressed twice to show autocomplete options
     if (!$this->_autocompleteTabPressCount > 0) {
         $this->_autocompleteTabPressCount++;
         return;
     } else {
         $this->_autocompleteTabPressCount = 0;
     }
     $optionMaxChars = 0;
     // Get length of the longest match (for spacing)
     foreach ($options as $option) {
         if (mb_strlen($option) + 2 > $optionMaxChars) {
             $optionMaxChars = mb_strlen($option) + 2;
             // +2 spaces to pad with
         }
     }
     // Get tty width
     $ttySize = Terminal::getTtySize();
     $ttyChars = $ttySize[1];
     // Calculate number of lines required
     $linesRequired = ceil(count($options) * $optionMaxChars / $ttyChars);
     // Calculate number of items per line
     $itemsPerLine = floor($ttyChars / $optionMaxChars);
     for ($i = 0; $i < count($options); $i++) {
         if ($i % $itemsPerLine === 0) {
             echo "\n";
         }
         printf("%-" . $optionMaxChars . "s", $options[$i]);
     }
     echo "\n";
     echo $this->_prompt . $this->_buffer;
 }