示例#1
0
 private function render_cli_error($heading, array $messages, $traces = [])
 {
     $cli = new Cli();
     $cli->error(sprintf('<underline><bold>%s</bold></underline>', $heading));
     foreach ($messages as $label => $message) {
         $cli->error(sprintf('%s : <bold>%s</bold>', $label, $message));
     }
     if ($traces) {
         $cli->br()->error('<underline><bold>Backtrace</bold></underline>');
         $i = 1;
         foreach ($traces as $error) {
             $line = isset($error['line']) ? $error['line'] : 'Unknown';
             if (isset($error['file'])) {
                 $console->out(' ' . $i . ') ' . str_replace(FCPATH, './', $error['file']) . ':' . $line);
             } else {
                 $i--;
             }
             $func = '';
             if (isset($error['class'], $error['type'])) {
                 $func .= $error['class'] . $error['type'];
             }
             $func .= $error['function'];
             $console->error('    ' . $func . '()');
             $i++;
         }
     }
 }
示例#2
0
 /**
  * Runs the CMF installer
  */
 public function install()
 {
     if (strtolower(\Cli::prompt('Install CMF now? WARNING: This will reset the contents of your app folder!', array('y', 'n'))) !== 'y') {
         return;
     }
     // Site title etc
     Installer::initialSetup();
     // Database
     if (strtolower(\Cli::prompt('Create database now?', array('y', 'n'))) === 'y') {
         $result = Installer::createDatabase();
         if (isset($result['error'])) {
             \Cli::error('There was an error creating the database: ' . $result['error']);
             exit;
         }
     }
     // This stuff relies on the database being set up
     if (Project::databaseExists()) {
         // Sync models
         \Cli::write("");
         // Just a spacer!
         Project::sync('default', 'app', true, true);
         // Super user
         $hasSuper = Project::hasSuperUser();
         if (!$hasSuper || strtolower(\Cli::prompt('Create super user now?', array('y', 'n'))) === 'y') {
             if (!$hasSuper) {
                 \Cli::write("\nCreating a super user...");
             }
             Project::createSuperUser();
         }
         // Check some DB settings are in place
         Project::ensureMinimumSettings();
     }
 }
 public function monitor($file, $channel)
 {
     if (false === ($fp = @fopen($file, "r"))) {
         Cli::error("Failed to open {$file}");
     } else {
         Cli::out("Monitoring file: {$file}");
     }
     while (1) {
         if (-1 === fseek($fp, 0, SEEK_END) or !($pos = ftell($fp))) {
             goto retry;
         }
         if ($this->lastPosition === null or $this->lastPosition > $pos) {
             $this->lastPosition = $pos;
             goto retry;
         }
         if ($this->lastPosition < $pos) {
             fseek($fp, $this->lastPosition - $pos, SEEK_CUR);
             if (false === ($content = fread($fp, $pos - $this->lastPosition))) {
                 goto retry;
             }
             try {
                 $this->client->send($content, $channel);
             } catch (\Exception $ex) {
                 Cli::error($ex->getMessage());
             }
             $this->lastPosition = $pos;
         }
         retry:
         usleep(200000);
     }
 }
 public function foursquare_venue($venue_id, $cycles = 25)
 {
     if ($this->spider->updateFoursquareVenue($venue_id, $cycles)) {
         \Cli::write('Scan finished.');
     } else {
         \Cli::error('No region found / Invalid region id');
     }
 }
 private function main()
 {
     \Cli::write(sprintf('Fuel %s - PHP %s (%s) (%s) [%s]', \Fuel::VERSION, phpversion(), php_sapi_name(), self::build_date(), PHP_OS));
     // Loop until they break it
     while (TRUE) {
         if (\Cli::$readline_support) {
             readline_completion_function(array(__CLASS__, 'tab_complete'));
         }
         if (!($__line = rtrim(trim(trim(\Cli::input('>>> ')), PHP_EOL), ';'))) {
             continue;
         }
         if ($__line == 'quit') {
             break;
         }
         // Add this line to history
         //$this->history[] = array_slice($this->history, 0, -99) + array($line);
         if (\Cli::$readline_support) {
             readline_add_history($__line);
         }
         if (self::is_immediate($__line)) {
             $__line = "return ({$__line})";
         }
         ob_start();
         // Unset the previous line and execute the new one
         $random_ret = \Str::random();
         try {
             $ret = eval("unset(\$__line); {$__line};");
         } catch (\Exception $e) {
             $ret = $random_ret;
             $__line = $e->getMessage();
         }
         // Error was returned
         if ($ret === $random_ret) {
             \Cli::error('Parse Error - ' . $__line);
             \Cli::beep();
         }
         if (ob_get_length() == 0) {
             if (is_bool($ret)) {
                 echo $ret ? 'true' : 'false';
             } elseif (is_string($ret)) {
                 echo addcslashes($ret, "....ÿ");
             } elseif (!is_null($ret)) {
                 var_export($ret);
             }
         }
         unset($ret);
         $out = ob_get_contents();
         ob_end_clean();
         if (strlen($out) > 0 && substr($out, -1) != PHP_EOL) {
             $out .= PHP_EOL;
         }
         echo $out;
         unset($out);
     }
 }
示例#6
0
 public function add($keyword)
 {
     if (!$keyword) {
         \Cli::error('Please provide keyword');
         return;
     }
     if (!\Collection\Keyword::addKeywordToDB($keyword)) {
         \Cli::error('Keyword already exists');
         return;
     }
     \Cli::write('Keyword added.');
 }
示例#7
0
 /**
  * {@inheritdocs}
  */
 protected function write(array $record)
 {
     if (\Fuel::$is_cli) {
         $colors = \Arr::get($this->levels, $record['level'], array('white', null));
         list($fg, $bg) = $colors;
         $message = \Cli::color((string) $record['formatted'], $fg, $bg);
         if ($level >= 300) {
             \Cli::error($message);
         } else {
             \Cli::write($message);
         }
     }
 }
示例#8
0
 public static function getQueuedItems($source, $frequency = 'hourly', $limit = 100, $region_id = false)
 {
     $query = \DB::select()->from(self::$_table_name);
     $query->join('tracking_cycle');
     $query->on('tracking_cycle.object_id', '=', 'tracking_log.object_id');
     $query->join('singleton');
     $query->on('tracking_log.object_id', '=', 'singleton.id');
     $query->where('tracking_log.success', 1);
     $query->where('tracking_log.is_latest', 1);
     $query->where('tracking_cycle.frequency', $frequency);
     $query->where('tracking_log.source', $source);
     if ($region_id) {
         $query->join('venue');
         $query->on('venue.id', '=', 'singleton.id');
         $query->where('venue.region_id', $region_id);
     }
     switch ($frequency) {
         case 'quaterday':
             $query->where('tracking_log.created_at', '<=', \DB::expr('DATE_SUB(NOW(),INTERVAL 6 HOUR)'));
             break;
         case 'hourly':
             $query->where('tracking_log.created_at', '<=', \DB::expr('DATE_SUB(NOW(),INTERVAL 1 HOUR)'));
             break;
         case 'daily':
             $query->where('tracking_log.created_at', '<=', \DB::expr('DATE_SUB(NOW(),INTERVAL 1 DAY)'));
             break;
         case 'weekly':
             $query->where('tracking_log.created_at', '<=', \DB::expr('DATE_SUB(NOW(),INTERVAL 7 DAY)'));
             break;
         case 'monthly':
             $query->where('tracking_log.created_at', '<=', \DB::expr('DATE_SUB(NOW(),INTERVAL 1 MONTH)'));
             break;
         default:
             \Cli::error('Failure: Invalid frequency type');
             return;
     }
     if (0) {
         $query->join('venue_record');
         $query->on('venue_record.id', '=', 'singleton.id');
         $query->order_by('venue_record.checkin', 'desc');
     } else {
         $query->order_by('tracking_log.created_at', 'asc');
     }
     $query->limit($limit);
     $tracking_logs = $query->execute();
     // echo \DB::last_query();
     //  exit;
     return $tracking_logs;
 }
示例#9
0
 public function error($errno, $error, $file, $line)
 {
     $msg = $error . "({$errno})" . $file . " ({$line}).";
     IS_CLI and Cli::error($msg);
     switch ($errno) {
         case E_NOTICE:
         case E_USER_NOTICE:
         case E_DEPRECATED:
             break;
         default:
             if (c('app.debug') === true) {
                 require __DIR__ . '/view/debug.php';
                 exit;
             } else {
                 class_exists('Log') && Log::write($msg, $this->errorType($errno));
                 die(view(c('view.bug')));
             }
     }
 }
示例#10
0
 public function mysql()
 {
     $db = \DbConfig::get_params();
     $dbname = $db['dbname'];
     $scheme_sql = 'CREATE DATABASE IF NOT EXISTS `' . $dbname . '`;';
     $scheme_sql .= 'DROP TABLE IF EXISTS `comment`;';
     $scheme_sql .= 'DROP TABLE IF EXISTS `post`;';
     $scheme_sql .= file_get_contents(APPPATH . '../../schema/php_dev.sql');
     foreach (explode(';', $scheme_sql) as $sql) {
         if (preg_match('/^\\n$/u', $sql)) {
             continue;
         }
         $result = \DB::query($sql)->execute();
         if ($result) {
             \Cli::write(\Cli::color($sql, 'green'));
         } else {
             \Cli::error(\Cli::color($sql, 'red'));
         }
     }
 }
示例#11
0
 public function updateVenuesService()
 {
     while (1) {
         if ($this->spider->getCurrentRateLimit() == 0) {
             // wait for 15min if we hit the rate limit
             $message = 'Warning: Rate limit hit! Script will pause for 15mins.';
             \Cli::error($message);
             $this->spider->emailReport($message);
             \Cli::wait(1800);
         }
         $success = $this->spider->updateVenues();
         if (!$success) {
             $message = 'Warning: Probably hit the rate limit. Foursquare headers incorrect at the moment! Script will pause for 15mins.';
             \Cli::error($message);
             $this->spider->emailReport($message);
             \Cli::wait(1800);
         } else {
             \Cli::wait(5, true);
         }
     }
 }
示例#12
0
 /**
  * Called by: php oil r movescaffoldtomodule
  * Moves scaffold files to module.
  */
 public function run($args = NULL)
 {
     /* We handle here options:
      *  * scaffold alias s: name of the scaffold to move
      *  * module alias m: module to move the scaffold into
      *  * force alias f: do we override existing files ?
      */
     $scaffold = \Cli::option('scaffold', \Cli::option('s'));
     $module = \Cli::option('module', \Cli::option('m'));
     static::$force = \Cli::option('force', \Cli::option('f', false));
     // Checking if the scaffold and module options are
     // defined
     if (is_null($scaffold) || is_null($module)) {
         \Cli::error('Some parameters are missing.');
         \Cli::error('Ex: php oil r moveScaffoldToModule' . ' -scaffold=category -module=blog');
         return;
     }
     $module_path = \Module::exists($module);
     // Is the module found ?
     if ($module_path == null) {
         \Cli::error('The specified module doesn\'t exists!');
         return;
     }
     // Now processing each scaffold file / folders
     foreach (static::$files_to_move as $item) {
         $path = str_replace('(:scaffold)', $scaffold, $item['path']);
         if (file_exists(APPPATH . $path)) {
             /*
              * As each file type must be processed
              * differently, a different method is called
              * depending on the type. For instance, if
              * the file type is controller, we will call
              * the process_controller method.
              */
             static::{'process_' . $item['type']}($path, $module, $module_path);
         }
     }
     // Processing migration as it is a special cases.
     static::process_migration($scaffold, $module, $module_path);
 }
示例#13
0
 public function run($fonts = null)
 {
     if (\Cli::option('help', \Cli::option('h', false)) or empty($fonts)) {
         empty($fonts) and \Cli::error(\Cli::color('No font given.', 'red'));
         return static::help();
     }
     $pdf = new \TCPDF();
     $type = \Cli::option('type', \Cli::option('t', ''));
     $enc = \Cli::option('enc', \Cli::option('e', ''));
     $flags = \Cli::option('flags', \Cli::option('f', 32));
     $outpath = \Cli::option('outpath', \Cli::option('o', K_PATH_FONTS));
     $platid = \Cli::option('platid', \Cli::option('p', 3));
     $encid = \Cli::option('encid', \Cli::option('n', 1));
     $addcbbox = \Cli::option('addcbbox', \Cli::option('b', false));
     $link = \Cli::option('link', \Cli::option('l', false));
     $path = \Cli::option('path', \Cli::option('p'));
     if (!is_null($path) and !\Str::ends_with($path, DS)) {
         $path .= DS;
     }
     $fonts = explode(',', $fonts);
     foreach ($fonts as $font) {
         if (strpos($font, DS) === false and !is_null($path)) {
             $font = $path . $font;
         }
         $fontfile = realpath($font);
         $fontname = \TCPDF_FONTS::addTTFfont($fontfile, $type, $enc, $flags, $outpath, $platid, $encid, $addcbbox, $link);
         if ($fontname == false) {
             $errors = true;
             \Cli::error(\Cli::color($font . ' cannot be added.', 'red'));
         } else {
             \Cli::write(\Cli::color($font . ' added.', 'green'));
         }
     }
     if (!empty($errors)) {
         \Cli::error(\Cli::color('Process finished with errors.', 'red'));
     } else {
         \Cli::write(\Cli::color('Process successfully finished.', 'green'));
     }
 }
示例#14
0
function checkEnvVars()
{
    $ret_php = -1;
    $output_php = array();
    $ret_arc = -1;
    $output_arc = array();
    exec("php -v", $output_php, $ret_php);
    exec("arc help", $output_arc, $ret_arc);
    if ($ret_arc === 0 && $ret_php === 0) {
        return true;
    } else {
        if ($ret_arc) {
            Cli::error("Could not add Arcanist to the enviromnment");
            echo concatString($output_arc) . PHP_EOL;
        }
        if ($ret_php) {
            Cli::error("Could not add PHP to the environment");
            echo concatString($output_php) . PHP_EOL;
        }
        return false;
    }
}
 public function up()
 {
     //populate the system roles if they don't exist
     if (\DBUtil::table_exists('roles')) {
         if (\DB::count_records('roles') == 0) {
             $roles = array(\Access::ROLE_ADMIN => 'Admin', \Access::ROLE_DEVELOPER => 'Developer', \Access::ROLE_EDITOR => 'Editor', \Access::ROLE_PENDING => 'Pending', \Access::ROLE_STANDARD => 'Standard', \Access::ROLE_SILVER => 'Silver', \Access::ROLE_GOLD => 'Gold', \Access::ROLE_DUMMY => 'Dummy');
             foreach ($roles as $id => $role) {
                 \DB::insert('roles')->set(array('id' => $id, 'name' => strtolower($role), 'Description' => $role))->execute();
             }
             \Cli::write("\nPopulated roles.");
         }
     }
     //create default admin user if we have no users
     if (\DBUtil::table_exists('users')) {
         if (\DB::count_records('users') == 0) {
             //create the admin user
             $data = array('username' => \Cli::prompt("Please enter an admin username"), 'email' => \Cli::prompt("Please enter an admin email"), 'password' => \Cli::prompt("Please enter an admin password"));
             try {
                 $user = new \Warden\Model_User($data);
                 if (\Config::get('warden.confirmable.in_use') === true) {
                     $user->is_confirmed = true;
                 }
                 \Access::set_roles(array(\Access::ROLE_STANDARD, \Access::ROLE_ADMIN), $user);
                 //this will assign the roles and save the user
                 \Cli::write("\nCreated admin user.");
                 \Cli::write(\Cli::color("\nUsername : {$user->username}", 'blue'));
                 \Cli::write(\Cli::color("\nEmail    : {$user->email}", 'blue'));
             } catch (\Exception $e) {
                 \Cli::error("\n:( Failed to create admin user because: " . $e->getMessage());
             }
         }
     }
     //create the blog table if it doesnt exist
     if (!\DBUtil::table_exists('blogs')) {
         \DBUtil::create_table('blogs', array('id' => array('constraint' => 11, 'type' => 'int', 'unsigned' => true, 'auto_increment' => true), 'user_id' => array('constraint' => 11, 'type' => 'int', 'unsigned' => true), 'title' => array('constraint' => 255, 'type' => 'varchar'), 'post' => array('type' => 'text'), 'publish_flag' => array('constraint' => 11, 'type' => 'int', 'default' => 0, 'unsigned' => true), 'public_flag' => array('constraint' => 11, 'type' => 'int', 'default' => 0, 'unsigned' => true), 'created_at' => array('type' => 'timestamp', 'default' => \DB::expr('CURRENT_TIMESTAMP')), 'updated_at' => array('type' => 'timestamp')), array('id'), true, 'InnoDB');
         \DBUtil::create_index('blogs', 'user_id', 'user_id');
     }
 }
示例#16
0
include_once './library/Runner.php';
include_once './Cli.php';
$cli = new Cli();
$options = array('siteUrl' => 'http://www.zalora.sg', 'crawlerAdapterName' => 'Fgc', 'parserAdapterName' => 'Xpath', 'processorName' => 'Zalora_Price');
try {
    $runner = new Runner($options);
    $notInIntervalUrls = array();
    while ($runner->getPlanner()->plannerQueueHasMore()) {
        $currenUrl = $runner->getPlanner()->getNext();
        $data = $runner->getCrawler()->getAdapter()->getHtmlData($currenUrl);
        $urls = $runner->getParser()->getAdapter()->getUrls($data);
        $runner->getPlanner()->addUrls($urls);
        if (!$runner->getProcessor()->is_price_interval($data, 20, 2000)) {
            $notInIntervalUrls[] = $currenUrl;
            $cli->info("Price of this item not in providing interval: {$currenUrl}");
        }
        if ($runner->getPlanner()->processedListSize() % 10 == 0) {
            $cli->info("Processed List Size {$runner->getPlanner()->processedListSize()}");
            $cli->info("Planner Queue Size {$runner->getPlanner()->plannerQueueSize()}");
            $notInIntervalUrlsCount = count($notInIntervalUrls);
            $cli->info("Not in interval url count  {$notInIntervalUrlsCount}");
        }
        $runner->getPlanner()->moveToProcessed($currenUrl);
    }
    $cli->info('Results:');
    foreach ($notInIntervalUrls as $url) {
        $cli->info($url);
    }
} catch (Exception $e) {
    $cli->error("Error: {$e->getMessage()}");
}
示例#17
0
 public static function init($args)
 {
     // Remove flag options from the main argument list
     for ($i = 0; $i < count($args); $i++) {
         if (strpos($args[$i], '-') === 0) {
             unset($args[$i]);
         }
     }
     try {
         if (!isset($args[1])) {
             if (\Cli::option('v', \Cli::option('version'))) {
                 \Cli::write('Fuel: ' . \Fuel::VERSION);
                 return;
             }
             static::help();
             return;
         }
         switch ($args[1]) {
             case 'g':
             case 'generate':
                 $action = isset($args[2]) ? $args[2] : 'help';
                 $subfolder = 'default';
                 if (is_int(strpos($action, 'scaffold/'))) {
                     $subfolder = str_replace('scaffold/', '', $action);
                     $action = 'scaffold';
                 }
                 switch ($action) {
                     case 'controller':
                     case 'model':
                     case 'views':
                     case 'migration':
                         call_user_func('Oil\\Generate::' . $action, array_slice($args, 3));
                         break;
                     case 'scaffold':
                         call_user_func('Oil\\Scaffold::generate', array_slice($args, 3), $subfolder);
                         break;
                     default:
                         Generate::help();
                 }
                 break;
             case 'c':
             case 'console':
                 new Console();
             case 'r':
             case 'refine':
                 // Developers of third-party tasks may not be displaying PHP errors. Report any error and quit
                 set_error_handler(function ($errno, $errstr, $errfile, $errline) {
                     \Cli::error("Error: {$errstr} in {$errfile} on {$errline}");
                     \Cli::beep();
                     exit;
                 });
                 $task = isset($args[2]) ? $args[2] : null;
                 call_user_func('Oil\\Refine::run', $task, array_slice($args, 3));
                 break;
             case 'p':
             case 'package':
                 $action = isset($args[2]) ? $args[2] : 'help';
                 switch ($action) {
                     case 'install':
                     case 'uninstall':
                         call_user_func_array('Oil\\Package::' . $action, array_slice($args, 3));
                         break;
                     default:
                         Package::help();
                 }
                 break;
             case 't':
             case 'test':
                 // Suppressing this because if the file does not exist... well thats a bad thing and we can't really check
                 // I know that supressing errors is bad, but if you're going to complain: shut up. - Phil
                 @(include_once 'PHPUnit/Autoload.php');
                 // Attempt to load PHUnit.  If it fails, we are done.
                 if (!class_exists('PHPUnit_Framework_TestCase')) {
                     throw new Exception('PHPUnit does not appear to be installed.' . PHP_EOL . PHP_EOL . "\tPlease visit http://phpunit.de and install.");
                 }
                 // CD to the root of Fuel and call up phpunit with a path to our config
                 $command = 'cd ' . DOCROOT . '; phpunit -c "' . COREPATH . 'phpunit.xml"';
                 // Respect the group option
                 \Cli::option('group') and $command .= ' --group ' . \Cli::option('group');
                 // Respect the coverage-html option
                 \Cli::option('coverage-html') and $command .= ' --coverage-html ' . \Cli::option('coverage-html');
                 passthru($command);
                 break;
             default:
                 static::help();
         }
     } catch (Exception $e) {
         \Cli::error('Error: ' . $e->getMessage());
         \Cli::beep();
     }
 }
示例#18
0
 public static function init($args)
 {
     // Remove flag options from the main argument list
     $args = self::_clear_args($args);
     try {
         if (!isset($args[1])) {
             if (\Cli::option('v', \Cli::option('version'))) {
                 \Cli::write('Fuel: ' . \Fuel::VERSION);
                 return;
             }
             static::help();
             return;
         }
         switch ($args[1]) {
             case 'g':
             case 'generate':
                 $action = isset($args[2]) ? $args[2] : 'help';
                 $subfolder = 'orm';
                 if (is_int(strpos($action, '/'))) {
                     list($action, $subfolder) = explode('/', $action);
                 }
                 switch ($action) {
                     case 'config':
                     case 'controller':
                     case 'model':
                     case 'migration':
                         call_user_func('Oil\\Generate::' . $action, array_slice($args, 3));
                         break;
                     case 'views':
                         call_user_func('Oil\\Generate::views', array_slice($args, 3), $subfolder);
                         break;
                     case 'admin':
                         call_user_func('Oil\\Generate_Admin::forge', array_slice($args, 3), $subfolder);
                         break;
                     case 'scaffold':
                         call_user_func('Oil\\Generate_Scaffold::forge', array_slice($args, 3), $subfolder);
                         break;
                     default:
                         Generate::help();
                 }
                 break;
             case 'c':
             case 'console':
                 new Console();
             case 'r':
             case 'refine':
                 // Developers of third-party tasks may not be displaying PHP errors. Report any error and quit
                 set_error_handler(function ($errno, $errstr, $errfile, $errline) {
                     if (!error_reporting()) {
                         return;
                     }
                     // If the error was supressed with an @ then we ignore it!
                     \Cli::error("Error: {$errstr} in {$errfile} on {$errline}");
                     \Cli::beep();
                     exit;
                 });
                 $task = isset($args[2]) ? $args[2] : null;
                 call_user_func('Oil\\Refine::run', $task, array_slice($args, 3));
                 break;
             case 'cell':
             case 'cells':
                 $action = isset($args[2]) ? $args[2] : 'help';
                 switch ($action) {
                     case 'list':
                         call_user_func('Oil\\Cell::all');
                         break;
                     case 'search':
                     case 'install':
                     case 'upgrade':
                     case 'uninstall':
                         call_user_func_array('Oil\\Cell::' . $action, array_slice($args, 3));
                         break;
                     case 'info':
                     case 'details':
                         call_user_func_array('Oil\\Cell::info', array_slice($args, 3));
                         break;
                     default:
                         Cell::help();
                 }
                 break;
             case 't':
             case 'test':
                 // Suppressing this because if the file does not exist... well thats a bad thing and we can't really check
                 // I know that supressing errors is bad, but if you're going to complain: shut up. - Phil
                 @(include_once 'PHPUnit/Autoload.php');
                 // Attempt to load PHUnit.  If it fails, we are done.
                 if (!class_exists('PHPUnit_Framework_TestCase')) {
                     throw new Exception('PHPUnit does not appear to be installed.' . PHP_EOL . PHP_EOL . "\tPlease visit http://phpunit.de and install.");
                 }
                 // CD to the root of Fuel and call up phpunit with a path to our config
                 $command = 'cd ' . DOCROOT . '; phpunit -c "' . COREPATH . 'phpunit.xml"';
                 // Respect the group option
                 \Cli::option('group') and $command .= ' --group ' . \Cli::option('group');
                 // Respect the coverage-html option
                 \Cli::option('coverage-html') and $command .= ' --coverage-html ' . \Cli::option('coverage-html');
                 \Cli::write('Tests Running...This may take a few moments.', 'green');
                 foreach (explode(';', $command) as $c) {
                     passthru($c);
                 }
                 break;
             default:
                 static::help();
         }
     } catch (Exception $e) {
         \Cli::error('Error: ' . $e->getMessage());
         \Cli::beep();
         \Cli::option('speak') and `say --voice="Trinoids" "{$e->getMessage()}"`;
     }
 }
示例#19
0
 private function _create_admin()
 {
     \Cli::beep(1);
     // get attention
     $create_admin = \Cli::prompt("\nCreate an admin user?", array('y', 'n'));
     if ($create_admin === 'y') {
         $data = array('username' => \Cli::prompt("Please enter an admin username"), 'email' => \Cli::prompt("Please enter an admin email"), 'password' => \Cli::prompt("Please enter an admin password"));
         try {
             $user = new \Model_User($data);
             if (\Config::get('warden.confirmable.in_use') === true) {
                 $user->is_confirmed = true;
             }
             $user->roles[] = new \Model_Role(array('name' => 'Admin', 'description' => 'Site admin role.'));
             $user->save();
             $roles = array();
             foreach ($user->roles as $role) {
                 $roles[] = "<id: {$role->id}, name: {$role->name}>";
             }
             \Cli::write(\Cli::color("\nUsername : {$user->username}", 'blue'));
             \Cli::write(\Cli::color("Email    : {$user->email}", 'blue'));
             \Cli::write(\Cli::color("Password : {$data['password']}", 'blue'));
             if (!empty($roles)) {
                 \Cli::write(\Cli::color('Roles	 : ' . join(', ', $roles), 'blue'));
             }
         } catch (\Exception $e) {
             \Cli::error("\n:( Failed to create admin user because: " . $e->getMessage());
         }
     }
 }
示例#20
0
 /**
  * Creates a super user
  * @return array
  */
 public static function createSuperUser($email = '*****@*****.**', $username = '******', $password = null)
 {
     // Load up the admin module and it's classes, otherwise we won't get
     // access to the admin user class
     \Module::load('admin');
     if (\Fuel::$is_cli) {
         $email = \Cli::prompt('Enter an email address', $email);
         $username = \Cli::prompt('Enter a user name', $username);
         $first = true;
         while ($first || strlen($password) > 0 && strlen($password) < 6) {
             $password = \Cli::prompt('Enter a password (leave blank to generate one)');
             if (strlen($password) > 0 && strlen($password) < 6) {
                 \Cli::error('The password must be 6 characters or more!');
             }
             $first = false;
         }
         $confirm_password = '';
         if (empty($password)) {
             // The user left the password field blank, so we are generating one
             $gen = new PWGen(3, false, false, false, false, false, false);
             $password = $confirm_password = $gen->generate() . '-' . $gen->generate() . '-' . $gen->generate();
         } else {
             // If the user entered a password, we need them to confirm it
             while ($confirm_password != $password) {
                 $confirm_password = \Cli::prompt('Confirm password');
                 if ($confirm_password != $password) {
                     \Cli::error('The passwords do not match!');
                 }
             }
         }
     }
     // Check if the user exists
     $em = \D::manager();
     $user = \Admin\Model_User::select('item')->where("item.username = '******'")->getQuery()->getResult();
     $exists = count($user) > 0;
     if ($exists) {
         $user = $user[0];
     } else {
         $user = new \Admin\Model_User();
     }
     // Populate the user
     $user->set('email', $email);
     $user->set('username', $username);
     $user->set('password', $password);
     $user->set('confirm_password', $confirm_password);
     $user->set('super_user', true);
     // Create the admin role
     $role = \CMF\Model\Role::findBy(array("name = 'admin'"))->getQuery()->getResult();
     if (count($role) == 0) {
         $role = new \CMF\Model\Role();
         $role->set('name', 'admin');
         $role->set('description', 'users of this admin site');
         $em->persist($role);
     } else {
         $role = $role[0];
     }
     $user->add('roles', $role);
     // Validate the newly created user
     if (!$user->validate()) {
         if (\Fuel::$is_cli) {
             \Cli::write('There was something wrong with the info you entered. Try again!', 'red');
             static::createSuperUser();
         } else {
             return array('errors' => $user->errors);
         }
     }
     $em->persist($user);
     $em->flush();
     \Cli::write($exists ? "\n\tExisting super user updated:" : "\n\tNew super user created:", 'light_gray');
     \Cli::write("\tusername:    "******"\n\tpassword:    "******"\n", 'light_cyan');
 }
示例#21
0
 private static function print_exception(\Exception $ex)
 {
     \Cli::error('Uncaught exception ' . get_class($ex) . ': ' . $ex->getMessage());
     \Cli::error('Callstack: ');
     \Cli::error($ex->getTraceAsString());
     \Cli::beep();
     \Cli::option('speak') and `say --voice="Trinoids" "{$ex->getMessage()}"`;
     if (($previous = $ex->getPrevious()) != null) {
         \Cli::error('');
         \Cli::error('Previous exception: ');
         static::print_exception($previous);
     }
 }
示例#22
0
 /**
  * Sets up the database with the provided details and saves the config.
  * @return array
  */
 public static function createDatabase($host = 'localhost', $username = '******', $password = '******', $database = null)
 {
     // Get user input if we're in the CLI
     if (\Fuel::$is_cli) {
         $host = \Cli::prompt('DB Host', $host);
         $username = \Cli::prompt('Root DB User', $username);
         $password = \Cli::prompt('Root DB Password', $password);
     }
     // Connect to the MySQL instance
     $con = @mysql_connect($host, $username, $password) or $db_error = mysql_error();
     if (!$con) {
         return array('error' => 'Could not make connection. ' . $db_error);
     }
     // Get database name
     if (\Fuel::$is_cli) {
         $exists = true;
         $overwrite = false;
         while (empty($database)) {
             $database = \Cli::prompt('DB Name', \Config::get('db.doctrine2.cache_namespace', null));
             if (empty($database)) {
                 \Cli::error('You must enter a database name!');
             }
         }
         $exists = mysql_num_rows(mysql_query("SHOW DATABASES LIKE '" . $database . "'", $con)) > 0;
         while ($exists && !$overwrite) {
             $overwrite = \Cli::prompt("The database '{$database}' already exists. Would you still like to use this?", array('y', 'n')) == 'y';
             if (!$overwrite) {
                 $database = null;
                 while (empty($database)) {
                     $database = \Cli::prompt('Enter an alternate DB name', \Config::get('db.doctrine2.cache_namespace', null));
                     if (empty($database)) {
                         \Cli::error('You must enter a database name!');
                     }
                 }
             }
             $exists = mysql_num_rows(mysql_query("SHOW DATABASES LIKE '" . $database . "'", $con)) > 0;
         }
     }
     // Try and create the database
     if (mysql_query("CREATE DATABASE IF NOT EXISTS " . $database, $con)) {
         mysql_close($con);
     } else {
         mysql_close($con);
         return array('error' => 'Error creating database: ' . mysql_error());
     }
     // Set the config
     $development = static::setDBConfig($host, $username, $password, $database);
     $production = static::setDBConfig($host, $username, $password, $database, 'production');
     return array('success' => true, 'config' => $development && $production);
 }
示例#23
0
 * Register all the error/shutdown handlers
 */
register_shutdown_function(function () {
    // reset the autoloader
    \Autoloader::_reset();
    // make sure we're having an output filter so we can display errors
    // occuring before the main config file is loaded
    \Config::get('security.output_filter', null) or \Config::set('security.output_filter', 'Security::htmlentities');
    try {
        // fire any app shutdown events
        \Event::instance()->trigger('shutdown', '', 'none', true);
        // fire any framework shutdown events
        \Event::instance()->trigger('fuel-shutdown', '', 'none', true);
    } catch (\Exception $e) {
        if (\Fuel::$is_cli) {
            \Cli::error("Error: " . $e->getMessage() . " in " . $e->getFile() . " on " . $e->getLine());
            \Cli::beep();
            exit(1);
        }
    }
    return \Error::shutdown_handler();
});
set_exception_handler(function (\Exception $e) {
    // reset the autoloader
    \Autoloader::_reset();
    // deal with PHP bugs #42098/#54054
    if (!class_exists('Error')) {
        include COREPATH . 'classes/error.php';
        class_alias('\\Fuel\\Core\\Error', 'Error');
        class_alias('\\Fuel\\Core\\PhpErrorException', 'PhpErrorException');
    }
示例#24
0
    public function generate_model($table_name, $db = null)
    {
        $table_class = \Inflector::classify($table_name);
        // Generate the full path for the model
        $file_path = APPPATH . 'classes' . DS . 'model' . DS;
        $file_path .= str_replace('_', '/', strtolower($table_class)) . '.php';
        if (file_exists($file_path)) {
            \Cli::error('Model already found for database table ' . $table_name);
            $answer = \Cli::prompt('Overwrite model?', array('y', 'n'));
            if ($answer == 'n') {
                \Cli::write('Existing model not overwritten.');
                return false;
            }
        }
        $columns = \DB::list_columns($table_name, null, $db);
        \Cli::write('Found ' . count($columns) . " columns for the {$table_name} database table.", 'green');
        $model_properties = array();
        foreach ($columns as $column) {
            // Process some of the column info to allow easier detection
            list($column_type, $column_unsigned) = explode(' ', $column['data_type'] . ' ');
            // Concatenated space stops an error happening when data_type has no spaces
            // A hack to detect Bool data types
            if ($column_type == 'tinyint' and $column['display'] == 1) {
                $column_type = 'bool';
            }
            // Basic Properties
            $column_properties = array('data_type' => in_array($column_type, static::$data_typing_types) ? $column_type : 'string', 'label' => \Inflector::humanize($column['name']), 'null' => $column['null']);
            $column['default'] and $column_properties['default'] = $column['default'];
            // Validation
            // TODO: Add thresholds rather than having rediculously high max values
            $column_validation = array();
            $column['null'] or $column_validation[] = 'required';
            if ($column_type == 'bool') {
                $column_validation = array('required');
            } elseif (key_exists($column_type, static::$string_max_lengths)) {
                $column_validation['max_length'] = array((int) min($column['character_maximum_length'], static::$string_max_lengths[$column_type]));
            } elseif ($column['type'] == 'int') {
                $display_max = (int) str_repeat(9, $column['display']);
                $column_validation['numeric_min'] = array((int) $column['min']);
                $column_validation['numeric_max'] = array((int) min($column['max'], $display_max));
            } elseif ($column['type'] == 'float') {
                $max = (double) (str_repeat(9, $column['numeric_precision'] - $column['numeric_scale']) . '.' . str_repeat(9, $column['numeric_scale']));
                $min = substr($column['data_type'], -8) == 'unsigned' ? 0 : $max * -1;
                $column_validation['numeric_min'] = array($min);
                $column_validation['numeric_max'] = array($max);
            }
            // Form
            $column_form = array('type' => 'text');
            if (in_array($column['name'], array('id', 'created_at', 'updated_at'))) {
                $column_form['type'] = false;
            } else {
                $column['default'] and $column_form['value'] = $column['default'];
                switch ($column_type) {
                    case 'char':
                    case 'varchar':
                    case 'tinytext':
                    case 'tinyblob':
                        isset($column_validation['max_length']) and $column_form['maxlength'] = $column_validation['max_length'][0];
                        break;
                    case 'text':
                    case 'blob':
                    case 'mediumtext':
                    case 'mediumblob':
                    case 'longtext':
                    case 'longblob':
                        $column_form['type'] = 'textarea';
                        break;
                    case 'enum':
                    case 'set':
                        $column_form['type'] = 'select';
                        $column_form['options'] = array();
                        break;
                    case 'bool':
                        $column_form['type'] = 'radio';
                        $column_form['options'] = array(1 => 'Yes', 0 => 'No');
                        break;
                    case 'decimal':
                    case 'double':
                    case 'float':
                        $column_form['step'] = floatval('0.' . str_repeat(9, $column['numeric_scale']));
                        // break is intentionally missing
                    // break is intentionally missing
                    case 'tinyint':
                    case 'smallint':
                    case 'int':
                    case 'mediumint':
                    case 'bigint':
                        $column_form['type'] = 'number';
                        isset($column_validation['numeric_min']) and $column_form['min'] = $column_validation['numeric_min'][0];
                        isset($column_validation['numeric_max']) and $column_form['max'] = $column_validation['numeric_max'][0];
                        break;
                        /* @TODO
                           case 'date':
                           case 'datetime':
                           case 'time':
                           case 'timestamp':
                               break;*/
                }
            }
            $column_properties['validation'] = $column_validation;
            $column_properties['form'] = $column_form;
            $model_properties[$column['name']] = $column_properties;
        }
        $model_properties_str = str_replace(array("\n", '  ', 'array ('), array("\n\t", "\t", 'array('), \Format::forge($model_properties)->to_php());
        $model_properties_str = preg_replace('/=>\\s+array/m', '=> array', $model_properties_str);
        $model_str = <<<MODEL
<?php
class Model_{$table_class} extends \\Orm\\Model
{
    protected static \$_table_name = '{$table_name}';
    protected static \$_properties = {$model_properties_str};
    protected static \$_observers = array(
        'Orm\\Observer_Validation' => array(
            'events' => array('before_save'),
        ),
        'Orm\\Observer_Typing' => array(
            'events' => array('before_save', 'after_save', 'after_load'),
        ),
MODEL;
        if (isset($model_properties['created_at'])) {
            $model_str .= <<<MODEL
        'Orm\\Observer_CreatedAt' => array(
            'events' => array('before_insert'),
            'mysql_timestamp' => false,
            'property' => 'created_at',
        ),
MODEL;
        }
        if (isset($model_properties['updated_at'])) {
            $model_str .= <<<MODEL
        'Orm\\Observer_UpdatedAt' => array(
            'events' => array('before_save'),
            'mysql_timestamp' => false,
            'property' => 'updated_at',
        ),
MODEL;
        }
        $model_str .= <<<MODEL
    );
}
MODEL;
        // Make sure the directory exists
        is_dir(dirname($file_path)) or mkdir(dirname($file_path), 0775, true);
        // Show people just how clever FuelPHP can be
        \File::update(dirname($file_path), basename($file_path), $model_str);
        return true;
    }
 private function _initTable()
 {
     $this->subscribers = new \swoole_table(4096);
     $this->subscribers->column('channel', \swoole_table::TYPE_STRING, 128);
     if (!$this->subscribers->create()) {
         Cli::error("Failed to call swoole_table::create().");
     }
 }