public static function init($args) { try { if (!isset($args[1])) { static::help(); return; } switch ($args[1]) { case 'g': case 'generate': switch ($args[2]) { case 'controller': case 'model': case 'view': case 'views': case 'migration': call_user_func('Oil\\Generate::' . $args[2], array_slice($args, 3)); break; case 'scaffold': call_user_func('Oil\\Scaffold::generate', array_slice($args, 3)); break; default: Generate::help(); } break; case 'c': case 'console': new Console(); case 'r': case 'refine': $task = isset($args[2]) ? $args[2] : null; call_user_func('Oil\\Refine::run', $task, array_slice($args, 3)); break; case 'p': case 'package': switch ($args[2]) { case 'install': case 'uninstall': call_user_func_array('Oil\\Package::' . $args[2], array_slice($args, 3)); break; default: Package::help(); } break; case '-v': case '--version': \Cli::write('Fuel: ' . \Fuel::VERSION); break; case 'test': \Fuel::add_package('octane'); call_user_func('\\Fuel\\Octane\\Tests::run_' . $args[2], array_slice($args, 3)); break; default: static::help(); } } catch (Exception $e) { \Cli::write(\Cli::color('Error: ' . $e->getMessage(), 'light_red')); \Cli::beep(); } }
public static function show_php_error(\Exception $e) { $data['type'] = get_class($e); $data['severity'] = $e->getCode(); $data['message'] = $e->getMessage(); $data['filepath'] = $e->getFile(); $data['error_line'] = $e->getLine(); $data['backtrace'] = $e->getTrace(); $data['severity'] = !isset(static::$levels[$data['severity']]) ? $data['severity'] : static::$levels[$data['severity']]; if (\Fuel::$is_cli) { \Cli::write(\Cli::color($data['severity'] . ' - ' . $data['message'] . ' in ' . \Fuel::clean_path($data['filepath']) . ' on line ' . $data['error_line'], 'red')); return; } $debug_lines = array(); foreach ($data['backtrace'] as $key => $trace) { if (!isset($trace['file'])) { unset($data['backtrace'][$key]); } elseif ($trace['file'] == COREPATH . 'classes/error.php') { unset($data['backtrace'][$key]); } } $debug_lines = array('file' => $data['filepath'], 'line' => $data['error_line']); $data['severity'] = !isset(static::$levels[$data['severity']]) ? $data['severity'] : static::$levels[$data['severity']]; $data['debug_lines'] = \Debug::file_lines($debug_lines['file'], $debug_lines['line']); $data['filepath'] = \Fuel::clean_path($debug_lines['file']); $data['filepath'] = str_replace("\\", "/", $data['filepath']); $data['error_line'] = $debug_lines['line']; echo \View::factory('errors' . DS . 'php_error', $data); }
/** * Run the credential importer * * @param string $json_file The JSON file that contains a list of the APIs and their credentials */ public static function run($json_file = null) { if (empty($json_file) || file_exists($json_file) === false) { exit('You must specify a valid JSON file that contains your credentials.' . PHP_EOL); } if (($json = json_decode(file_get_contents($json_file), true)) === null) { exit('The JSON file does not contain valid JSON text.' . PHP_EOL); } // Find the API version to use for importing the keys $version = 'V1'; if (!empty($json[0]['version'])) { if (is_int($json[0]['version']) && \Module::exists('V' . $json[0]['version'])) { \Module::load('V' . $json[0]['version']); $version = 'V' . $json[0]['version']; } else { \Module::load($version); } array_shift($json); } else { \Module::load($version); } $error = false; foreach ($json as $entry) { // We need these keys for each entry. if (!array_key_exists('api', $entry) || !array_key_exists('credentials', $entry)) { echo \Cli::color('The JSON data is in the wrong format. Skipping.' . PHP_EOL, 'yellow'); $error = true; continue; } if (!is_string($entry['api'])) { echo \Cli::color('The API name must be a string. Skipping.' . PHP_EOL, 'yellow'); $error = true; continue; } // Make sure that we have credentials to add to the DB. if (empty($entry['credentials']) || !is_array($entry['credentials'])) { echo \Cli::color('The array of credentials for ' . $entry['api'] . ' is empty. Skipping.' . PHP_EOL, 'yellow'); $error = true; continue; } $response = call_user_func('\\' . $version . '\\Keyring::set_credentials', $entry['credentials'], $entry['api']); // Show and log the result if ($response === true) { $success_text = 'Successfully imported the credentials for API: ' . $entry['api']; echo \Cli::color($success_text . PHP_EOL, 'green'); \Log::logger('INFO', 'CLI:ADD_CREDENTIALS', $success_text, __METHOD__, array('api' => $entry['api'])); } else { $error_text = 'Failed to import the credentials for API: ' . $entry['api']; echo \Cli::color('Warning: ' . $error_text . PHP_EOL, 'red'); $error = true; \Log::logger('ERROR', 'CLI:ADD_CREDENTIALS', $error_text, __METHOD__, array('api' => $entry['api'])); } } // Display the summary. if ($error === true) { echo \Cli::color(PHP_EOL . 'Some credentials were not added to the database. See the error log for more details.' . PHP_EOL, 'red'); } else { echo \Cli::color(PHP_EOL . 'All credentials were successfully added to the database.' . PHP_EOL, 'green'); } }
public static function search($name) { $request_url = static::$_api_url . 'cells/search.json?name=' . urlencode($name); $response = json_decode(file_get_contents($request_url), true); if (empty($response['cells'])) { throw new \FuelException('No cells were found with this name.'); } foreach ($response['cells'] as $cell) { \Cli::write(\Cli::color($cell['name'], 'yellow') . ' ' . \Cli::color($cell['current_version'], 'white') . ' - ' . $cell['summary']); } }
/** * {@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); } } }
private function main() { echo sprintf('Fuel %s - PHP %s (%s) (%s) [%s]', \Fuel::VERSION, phpversion(), php_sapi_name(), self::build_date(), PHP_OS) . PHP_EOL; // Loop until they break it while (TRUE) { echo ">>> "; if (!($__line = rtrim(trim(trim(fgets(STDIN)), PHP_EOL), ';'))) { continue; } if ($__line == 'quit') { break; } if (self::is_immediate($__line)) { $__line = "return ({$__line})"; } ob_start(); // Unset the previous line and execute the new one $ret = eval("unset(\$__line); {$__line};"); // Error was returned if ($ret === false) { \Cli::write(\Cli::color('Parse Error - ' . $__line, 'light_red')); \Cli::beep(); } if (ob_get_length() == 0) { if (is_bool($ret)) { echo $ret ? "true" : "false"; } else { if (is_string($ret)) { echo addcslashes($ret, "....ÿ"); } else { if (!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); } }
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')); } } }
public static function run() { $writable_paths = array( APPPATH . 'cache', APPPATH . 'logs', APPPATH . 'tmp' ); foreach ($writable_paths as $path) { if (@chmod($path, 0777)) { \Cli::write("\t" . \Cli::color('Made writable: ' . $path, 'green')); } else { \Cli::write("\t" . \Cli::color('Failed to make writable: ' . $path, 'red')); } } }
public static function run() { // -v or --version $version = \Cli::option('v', \Cli::option('version')); $run = false; // Spoecific version if ($version > 0) { if (\Migrate::version($version) === false) { \Cli::write(\Cli::color('Already on migration: ' . $version . '.', 'light_red')); } else { static::_update_version($result); \Cli::write(\Cli::color('Migrated to version: ' . $version . '.', 'green')); } } else { if (($result = \Migrate::latest()) === false) { \Cli::write(\Cli::color('Already on latest migration.', 'light_red')); } else { static::_update_version($result); \Cli::write(\Cli::color('Migrated to latest version: ' . $result . '.', 'green')); } } }
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')); } }
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'); } }
/** * clear the sessions table * php oil r session:clear */ public static function clear() { // load session config \Config::load('session', true); // prompt the user to confirm they want to clear the table. $iamsure = \Cli::prompt('Are you sure you want to clear the sessions table?', array('y', 'n')); // if they are sure, then let's drop it if ($iamsure === 'y') { \DBUtil::truncate_table(\Config::get('session.db.table')); return \Cli::color('Session database table successfully truncated.', 'green'); } // if we made it to here, than that means the user said no. return \Cli::color('Session database table was not cleared.', 'red'); }
/** * Shows an error. It will stop script execution if the error code is not * in the errors.continue_on whitelist. * * @param Exception $e the exception to show * @return void */ public static function show_php_error(\Exception $e) { $fatal = (bool) (!in_array($e->getCode(), \Config::get('errors.continue_on'))); $data = static::prepare_exception($e, $fatal); if ($fatal) { ob_end_clean(); } else { static::$non_fatal_cache[] = $data; } if (\Fuel::$is_cli) { \Cli::write(\Cli::color($data['severity'] . ' - ' . $data['message'] . ' in ' . \Fuel::clean_path($data['filepath']) . ' on line ' . $data['error_line'], 'red')); return; } if ($fatal) { $data['non_fatal'] = static::$non_fatal_cache; exit(\View::factory('errors' . DS . 'php_fatal_error', $data, false)); } echo \View::factory('errors' . DS . 'php_error', $data, false); }
public static function task($args, $build = true) { if (!($name = \Str::lower(array_shift($args)))) { throw new Exception('No task name was provided.'); } if (empty($args)) { \Cli::write("\tNo tasks actions have been provided, the TASK will only create default task.", 'red'); } $args or $args = array('index'); // Uppercase each part of the class name and remove hyphens $class_name = \Inflector::classify($name, false); $filename = trim(str_replace(array('_', '-'), DS, $name), DS); $base_path = APPPATH; if ($module = \Cli::option('module')) { if (!($base_path = \Module::exists($module))) { throw new Exception('Module ' . $module . ' was not found within any of the defined module paths'); } } $filepath = $base_path . 'tasks' . DS . $filename . '.php'; $action_str = ''; foreach ($args as $action) { $task_path = '\\' . \Inflector::humanize($name) . '\\' . \Inflector::humanize($action); if (!ctype_alpha($action[0])) { throw new Exception('An action does not start with alphabet character. ABORTING'); } $action_str .= ' /** * This method gets ran when a valid method name is not used in the command. * * Usage (from command line): * * php oil r ' . $name . ':' . $action . ' "arguments" * * @return string */ public function ' . $action . '($args = NULL) { echo "\\n==========================================="; echo "\\nRunning task [' . \Inflector::humanize($name) . ':' . \Inflector::humanize($action) . ']"; echo "\\n-------------------------------------------\\n\\n"; /*************************** Put in TASK DETAILS HERE **************************/ }' . PHP_EOL; $message = \Cli::color("\t\tPreparing task method [", 'green'); $message .= \Cli::color(\Inflector::humanize($action), 'cyan'); $message .= \Cli::color("]", 'green'); \Cli::write($message); } // Default RUN task action $action = 'run'; $default_action_str = ' /** * This method gets ran when a valid method name is not used in the command. * * Usage (from command line): * * php oil r ' . $name . ' * * @return string */ public function run($args = NULL) { echo "\\n==========================================="; echo "\\nRunning DEFAULT task [' . \Inflector::humanize($name) . ':' . \Inflector::humanize($action) . ']"; echo "\\n-------------------------------------------\\n\\n"; /*************************** Put in TASK DETAILS HERE **************************/ }' . PHP_EOL; // Build Controller $task_class = <<<CONTROLLER <?php namespace Fuel\\Tasks; class {$class_name} { {$default_action_str} {$action_str} } /* End of file tasks/{$name}.php */ CONTROLLER; // Write controller static::create($filepath, $task_class, 'tasks'); $build and static::build(); }
/** * Shows an error. It will stop script execution if the error code is not * in the errors.continue_on whitelist. * * @param Exception $e the exception to show * @return void */ public static function show_php_error(\Exception $e) { $fatal = (bool) (!in_array($e->getCode(), \Config::get('errors.continue_on', array()))); $data = static::prepare_exception($e, $fatal); if ($fatal) { $data['contents'] = ob_get_contents(); while (ob_get_level() > 0) { ob_end_clean(); } ob_start(\Config::get('ob_callback', null)); } else { static::$non_fatal_cache[] = $data; } if (\Fuel::$is_cli) { \Cli::write(\Cli::color($data['severity'] . ' - ' . $data['message'] . ' in ' . \Fuel::clean_path($data['filepath']) . ' on line ' . $data['error_line'], 'red')); return; } if ($fatal) { if (!headers_sent()) { $protocol = \Input::server('SERVER_PROTOCOL') ? \Input::server('SERVER_PROTOCOL') : 'HTTP/1.1'; header($protocol . ' 500 Internal Server Error'); } $data['non_fatal'] = static::$non_fatal_cache; try { exit(\View::forge('errors' . DS . 'php_fatal_error', $data, false)); } catch (\FuelException $view_exception) { exit($data['severity'] . ' - ' . $data['message'] . ' in ' . \Fuel::clean_path($data['filepath']) . ' on line ' . $data['error_line']); } } try { echo \View::forge('errors' . DS . 'php_error', $data, false); } catch (\FuelException $e) { echo $e->getMessage() . '<br />'; } }
/** * An example method that is here just to show the various uses of tasks. * * Usage (from command line): * * php oil r robots:protect * * @return string */ public static function protect() { $eye = \Cli::color("*", 'green'); return \Cli::color("\n\t\t\t\t\t\"PROTECT ALL HUMANS\"\n\t\t\t _____ /\n\t\t\t /_____\\", 'blue') . "\n" . \Cli::color("\t\t\t ____[\\", 'blue') . $eye . \Cli::color('---', 'blue') . $eye . \Cli::color('/]____', 'blue') . "\n" . \Cli::color("\t\t\t /\\ #\\ \\_____/ /# /\\\n\t\t\t / \\# \\_.---._/ #/ \\\n\t\t\t / /|\\ | | /|\\ \\\n\t\t\t/___/ | | | | | | \\___\\\n\t\t\t| | | | |---| | | | |\n\t\t\t|__| \\_| |_#_| |_/ |__|\n\t\t\t//\\\\ <\\ _//^\\\\_ /> //\\\\\n\t\t\t\\||/ |\\//// \\\\\\\\/| \\||/\n\t\t\t | | | |\n\t\t\t |---| |---|\n\t\t\t |---| |---|\n\t\t\t | | | |\n\t\t\t |___| |___|\n\t\t\t / \\ / \\\n\t\t\t |_____| |_____|\n\t\t\t |HHHHH| |HHHHH|", 'blue'); }
private function _alter_or_return_fields($name, array $fields, $new) { if (!$new) { if (\Cli::option('R', false) || \Cli::option('remove', false)) { \DBUtil::drop_fields('users', array_keys($fields)); \Cli::write(\Cli::color("{$name} fields removed successfully", 'green')); } else { \DBUtil::add_fields('users', $fields); \Cli::write(\Cli::color("{$name} fields added successfully", 'green')); } } else { return $fields; } }
public function uninstall($package) { $package_folder = PKGPATH . $package; // Check to see if this package is already installed if ( ! is_dir($package_folder)) { \Cli::write(\Cli::color('Package "' . $package . '" is not installed.', 'red')); return; } \Cli::write('Uninstalling package "' . $package . '"'); \File::delete_dir($package_folder); }
public static function output_message($message, $message_level = true) { $color = static::get_message_color($message_level); return $color ? Cli::color($message, $color) : $message; }