public static function install($package = null) { // Make sure something is set if ($package === null) { static::help(); return; } $version = \Cli::option('version', 'master'); // Check to see if this package is already installed if (is_dir(PKGPATH . $package)) { throw new \FuelException('Package "' . $package . '" is already installed.'); return; } $request_url = static::$_api_url . 'cells/show.json?name=' . urlencode($package); $response = json_decode(@file_get_contents($request_url), true); if (!$response) { throw new \FuelException('No response from the API. Perhaps check your internet connection?'); } if (empty($response['cell'])) { throw new \FuelException('Could not find the cell "' . $package . '".'); } $cell = $response['cell']; // Now, lets get this package // If it is git and (they have git installed (TODO) and they havent asked for a zip) if ($cell['repository_type'] == 'git' and !\Cli::option('via-zip')) { \Cli::write('Downloading package: ' . $package); static::_clone_package_repo($cell['repository_url'], $package, $version); } else { \Cli::write('Downloading package: ' . $package); static::_download_package_zip($zip_url, $package, $version); } }
/** * Detects and returns the current URI based on a number of different server * variables. * * @return string */ public static function uri() { if (static::$detected_uri !== null) { return static::$detected_uri; } if (\Fuel::$is_cli) { if ($uri = \Cli::option('uri') !== null) { static::$detected_uri = $uri; } else { static::$detected_uri = \Cli::option(1); } return static::$detected_uri; } // We want to use PATH_INFO if we can. if (!empty($_SERVER['PATH_INFO'])) { $uri = $_SERVER['PATH_INFO']; } elseif (!empty($_SERVER['ORIG_PATH_INFO']) and ($path = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['ORIG_PATH_INFO'])) != '') { $uri = $path; } else { // Fall back to parsing the REQUEST URI if (isset($_SERVER['REQUEST_URI'])) { $uri = $_SERVER['REQUEST_URI']; } else { throw new \FuelException('Unable to detect the URI.'); } // Remove the base URL from the URI $base_url = parse_url(\Config::get('base_url'), PHP_URL_PATH); if ($uri != '' and strncmp($uri, $base_url, strlen($base_url)) === 0) { $uri = substr($uri, strlen($base_url)); } // If we are using an index file (not mod_rewrite) then remove it $index_file = \Config::get('index_file'); if ($index_file and strncmp($uri, $index_file, strlen($index_file)) === 0) { $uri = substr($uri, strlen($index_file)); } // When index.php? is used and the config is set wrong, lets just // be nice and help them out. if ($index_file and strncmp($uri, '?/', 2) === 0) { $uri = substr($uri, 1); } // Lets split the URI up in case it contains a ?. This would // indicate the server requires 'index.php?' and that mod_rewrite // is not being used. preg_match('#(.*?)\\?(.*)#i', $uri, $matches); // If there are matches then lets set set everything correctly if (!empty($matches)) { $uri = $matches[1]; $_SERVER['QUERY_STRING'] = $matches[2]; parse_str($matches[2], $_GET); } } // Strip the defined url suffix from the uri if needed if (strpos($uri, '.') !== false) { static::$detected_ext = preg_replace('#(.*)\\.#', '', $uri); $uri = substr($uri, 0, -(strlen(static::$detected_ext) + 1)); } // Do some final clean up of the uri static::$detected_uri = \Security::clean_uri($uri, true); return static::$detected_uri; }
public static function run($task, $args) { // Just call and run() or did they have a specific method in mind? list($task, $method)=array_pad(explode(':', $task), 2, 'run'); $task = ucfirst(strtolower($task)); if ( ! $file = \Fuel::find_file('tasks', $task)) { throw new \Exception('Well that didnt work...'); return; } require $file; $task = '\\Fuel\\Tasks\\'.$task; $new_task = new $task; // The help option hs been called, so call help instead if (\Cli::option('help') && is_callable(array($new_task, 'help'))) { $method = 'help'; } if ($return = call_user_func_array(array($new_task, $method), $args)) { \Cli::write($return); } }
public static function install($package = null) { // Make sure something is set if ($package === null) { static::help(); return; } $config = \Config::load('package'); $version = \Cli::option('version', 'master'); // Check to see if this package is already installed if (is_dir(PKGPATH . $package)) { throw new Exception('Package "' . $package . '" is already installed.'); return; } foreach ($config['sources'] as $source) { $packages = array('fuel-' . $package, $package); foreach ($packages as $package) { $zip_url = 'http://' . rtrim($source, '/') . '/' . $package . '/zipball/' . $version; if ($fp = @fopen($zip_url, 'r')) { // We don't actually need this, just checking the file is there fclose($fp); // Now, lets get this package // If a direct download is requested, or git is unavailable, download it! if (\Cli::option('direct') or static::_use_git() === false) { static::_download_package_zip($zip_url, $package, $version); exit; } else { static::_clone_package_repo($source, $package, $version); exit; } } } } throw new Exception('Could not find package "' . $package . '".'); }
public static function run() { \Config::load('migrations', true); $current_version = \Config::get('migrations.version'); // -v or --version $version = \Cli::option('v', \Cli::option('version')); // version is used as a flag, so show it if ($version === true) { \Cli::write('Currently on migration: ' . $current_version . '.', 'green'); return; } else { if (!is_null($version) and $version == $current_version) { throw new \Oil\Exception('Migration: ' . $version . ' already in use.'); return; } } $run = false; // Specific version if (is_numeric($version) and $version >= 0) { if (\Migrate::version($version) === false) { throw new \Oil\Exception('Migration ' . $version . ' could not be found.'); } else { static::_update_version($version); \Cli::write('Migrated to version: ' . $version . '.', 'green'); } } else { if (($result = \Migrate::latest()) === false) { throw new \Oil\Exception("Could not migrate to latest version, still using {$current_version}."); } else { static::_update_version($result); \Cli::write('Migrated to latest version: ' . $result . '.', 'green'); } } }
/** * Show help. * * Usage (from command line): * * php oil refine simple2orm */ public static function run() { // fetch the commandline options $run_migration = \Cli::option('migrate', \Cli::option('m', false)); $run_validation = $run_migration ? true : \Cli::option('validate', \Cli::option('v', false)); // if no run options are present, show the help if (!$run_migration and !$run_validation) { return static::help(); } // step 1: run validation $validated = true; if ($run_validation) { $validated = static::run_validation(); } // step 2: run migration if ($run_migration) { if ($validated) { $migrated = static::run_migration(); if ($migrated) { \Cli::write('Migration succesfully finished', 'light_green'); } else { \Cli::write("\n" . 'Migration failed. Skipping the remainder of the migration. Please correct the errors and run again.', 'light_red'); } } else { \Cli::write("\n" . 'Validation failed. Skipping the actual migration. Please correct the errors.', 'light_red'); } } }
public static function detect() { if (static::$detected_uri !== null) { return static::$detected_uri; } if (\Fuel::$is_cli) { if ($uri = \Cli::option('uri') !== null) { static::$detected_uri = $uri; } else { static::$detected_uri = \Cli::option(1); } return static::$detected_uri; } // We want to use PATH_INFO if we can. if (!empty($_SERVER['PATH_INFO'])) { $uri = $_SERVER['PATH_INFO']; } elseif (!empty($_SERVER['ORIG_PATH_INFO']) and ($path = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['ORIG_PATH_INFO'])) != '') { $uri = $path; } else { // Fall back to parsing the REQUEST URI if (isset($_SERVER['REQUEST_URI'])) { // Some servers require 'index.php?' as the index page // if we are using mod_rewrite or the server does not require // the question mark, then parse the url. if (\Config::get('index_file') != 'index.php?') { $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); } else { $uri = $_SERVER['REQUEST_URI']; } } else { throw new \Fuel_Exception('Unable to detect the URI.'); } // Remove the base URL from the URI $base_url = parse_url(\Config::get('base_url'), PHP_URL_PATH); if ($uri != '' and strncmp($uri, $base_url, strlen($base_url)) === 0) { $uri = substr($uri, strlen($base_url)); } // If we are using an index file (not mod_rewrite) then remove it $index_file = \Config::get('index_file'); if ($index_file and strncmp($uri, $index_file, strlen($index_file)) === 0) { $uri = substr($uri, strlen($index_file)); } // Lets split the URI up in case it containes a ?. This would // indecate the server requires 'index.php?' and that mod_rewrite // is not being used. preg_match('#(.*?)\\?(.*)#i', $uri, $matches); // If there are matches then lets set set everything correctly if (!empty($matches)) { $uri = $matches[1]; $_SERVER['QUERY_STRING'] = $matches[2]; parse_str($matches[2], $_GET); } } // Strip the defined url suffix from the uri if needed $ext = \Config::get('url_suffix'); strrchr($uri, '.') === $ext and $uri = substr($uri, 0, -strlen($ext)); // Do some final clean up of the uri static::$detected_uri = str_replace(array('//', '../'), '/', $uri); return static::$detected_uri; }
public static function run($task, $args) { // Make sure something is set if ($task === null or $task === 'help') { static::help(); return; } // Just call and run() or did they have a specific method in mind? list($task, $method) = array_pad(explode(':', $task), 2, 'run'); $task = ucfirst(strtolower($task)); // Find the task if (!($file = \Fuel::find_file('tasks', $task))) { throw new Exception(sprintf('Task "%s" does not exist.', $task)); return; } require $file; $task = '\\Fuel\\Tasks\\' . $task; $new_task = new $task(); // The help option hs been called, so call help instead if (\Cli::option('help') && is_callable(array($new_task, 'help'))) { $method = 'help'; } if ($return = call_user_func_array(array($new_task, $method), $args)) { \Cli::write($return); } }
/** * Listen to a queue * * @param mixed $queue */ public function run($queue = 'default', $connector = null) { $worker = \Worker::forge($queue, $connector); // Register shutdown function to catch exit // \Event::register('shutdown', $this->shutdown); $interval = \Cli::option('interval', \Cli::option('i', 5)); $worker->listen($interval); }
public static function run($task, $args = array()) { $task = strtolower($task); // Make sure something is set if (empty($task) or $task === 'help') { static::help(); return; } $module = false; list($module, $task) = array_pad(explode('::', $task), 2, null); if ($task === null) { $task = $module; $module = false; } if ($module) { try { \Module::load($module); $path = \Module::exists($module); \Finder::instance()->add_path($path); } catch (\FuelException $e) { throw new Exception(sprintf('Module "%s" does not exist.', $module)); } } // Just call and run() or did they have a specific method in mind? list($task, $method) = array_pad(explode(':', $task), 2, 'run'); // Find the task if (!($file = \Finder::search('tasks', $task))) { $files = \Finder::instance()->list_files('tasks'); $possibilities = array(); foreach ($files as $file) { $possible_task = pathinfo($file, \PATHINFO_FILENAME); $difference = levenshtein($possible_task, $task); $possibilities[$difference] = $possible_task; } ksort($possibilities); if ($possibilities and current($possibilities) <= 5) { throw new Exception(sprintf('Task "%s" does not exist. Did you mean "%s"?', $task, current($possibilities))); } else { throw new Exception(sprintf('Task "%s" does not exist.', $task)); } return; } require_once $file; $task = '\\Fuel\\Tasks\\' . ucfirst($task); $new_task = new $task(); // The help option has been called, so call help instead if ((\Cli::option('help') or $method == 'help') and is_callable(array($new_task, 'help'))) { $method = 'help'; } else { // if the task has an init method, call it now is_callable($task . '::_init') and $task::_init(); } if ($return = call_fuel_func_array(array($new_task, $method), $args)) { \Cli::write($return); } }
public static function original_uri() { if (static::$uri !== null) { return static::$uri; } if (\Fuel::$is_cli) { if ($uri = \Cli::option('uri') !== null) { static::$uri = $uri; } else { static::$uri = \Cli::option(1); } return static::$uri; } // We want to use PATH_INFO if we can. if (!empty($_SERVER['PATH_INFO'])) { $uri = $_SERVER['PATH_INFO']; } elseif (!empty($_SERVER['ORIG_PATH_INFO']) and ($path = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['ORIG_PATH_INFO'])) != '') { $uri = $path; } else { // Fall back to parsing the REQUEST URI if (isset($_SERVER['REQUEST_URI'])) { $uri = urldecode($_SERVER['REQUEST_URI']); } else { throw new \FuelException('CMF was unable to detect the URI.'); } // Remove the base URL from the URI $base_url = parse_url(\Config::get('base_url'), PHP_URL_PATH); if ($uri != '' and strncmp($uri, $base_url, strlen($base_url)) === 0) { $uri = substr($uri, strlen($base_url)); } // If we are using an index file (not mod_rewrite) then remove it $index_file = \Config::get('index_file'); if ($index_file and strncmp($uri, $index_file, strlen($index_file)) === 0) { $uri = substr($uri, strlen($index_file)); } // When index.php? is used and the config is set wrong, lets just // be nice and help them out. if ($index_file and strncmp($uri, '?/', 2) === 0) { $uri = substr($uri, 1); } // Lets split the URI up in case it contains a ?. This would // indicate the server requires 'index.php?' and that mod_rewrite // is not being used. preg_match('#(.*?)\\?(.*)#i', $uri, $matches); // If there are matches then lets set set everything correctly if (!empty($matches)) { $uri = $matches[1]; $_SERVER['QUERY_STRING'] = $matches[2]; parse_str($matches[2], $_GET); } } // Deal with any trailing dots $uri = '/' . trim(rtrim($uri, '.'), '/'); return static::$uri = $uri; }
/** * Forge * * @param array Fields mainly * @param string Subfolder (or admin "theme") where views are held * @return mixed */ public static function forge($args, $subfolder) { $data = array(); $subfolder = trim($subfolder, '/'); if (!is_dir(PKGPATH . 'oil/views/' . static::$view_subdir . $subfolder)) { throw new Exception('The subfolder for admin templates does not exist or is spelled wrong: ' . $subfolder . ' '); } // Go through all arguments after the first and make them into field arrays $data['fields'] = array(); foreach (array_slice($args, 1) as $arg) { // Parse the argument for each field in a pattern of name:type[constraint] preg_match(static::$fields_regex, $arg, $matches); $data['fields'][] = array('name' => \Str::lower($matches[1]), 'type' => isset($matches[2]) ? $matches[2] : 'string', 'constraint' => isset($matches[4]) ? $matches[4] : null); } $name = array_shift($args); // Replace / with _ and classify the rest. DO NOT singularize $controller_name = \Inflector::classify(static::$controller_prefix . str_replace(DS, '_', $name), false); // Replace / with _ and classify the rest. Singularize $model_name = \Inflector::classify(static::$model_prefix . str_replace(DS, '_', $name)); // Either foo or folder/foo $view_path = $controller_path = str_replace(array('_', '-'), DS, \Str::lower($controller_name)); // Models are always singular, tough! $model_path = str_replace(array('_', '-'), DS, \Str::lower($model_name)); // uri's have forward slashes, DS is a backslash on Windows $uri = str_replace(DS, '/', $controller_path); $data['include_timestamps'] = !\Cli::option('no-timestamp', false); // If a folder is used, the entity is the last part $name_parts = explode(DS, $name); $data['singular_name'] = \Inflector::singularize(end($name_parts)); $data['plural_name'] = \Inflector::pluralize($data['singular_name']); $data['table'] = \Inflector::tableize($model_name); $data['controller_parent'] = static::$controller_parent; /** Generate the Migration **/ $migration_args = $args; array_unshift($migration_args, 'create_' . \Inflector::pluralize(\Str::lower($name))); Generate::migration($migration_args, false); // Merge some other data in $data = array_merge(compact(array('controller_name', 'model_name', 'model_path', 'view_path', 'uri')), $data); /** Generate the Model **/ $model = \View::forge(static::$view_subdir . $subfolder . '/model', $data); Generate::create(APPPATH . 'classes/model/' . $model_path . '.php', $model, 'model'); /** Generate the Controller **/ $controller = \View::forge(static::$view_subdir . $subfolder . '/controller', $data); $controller->actions = array(array('name' => 'index', 'params' => '', 'code' => \View::forge(static::$view_subdir . $subfolder . '/actions/index', $data)), array('name' => 'view', 'params' => '$id = null', 'code' => \View::forge(static::$view_subdir . $subfolder . '/actions/view', $data)), array('name' => 'create', 'params' => '$id = null', 'code' => \View::forge(static::$view_subdir . $subfolder . '/actions/create', $data)), array('name' => 'edit', 'params' => '$id = null', 'code' => \View::forge(static::$view_subdir . $subfolder . '/actions/edit', $data)), array('name' => 'delete', 'params' => '$id = null', 'code' => \View::forge(static::$view_subdir . $subfolder . '/actions/delete', $data))); Generate::create(APPPATH . 'classes/controller/' . $controller_path . '.php', $controller, 'controller'); // Create each of the views foreach (array('index', 'view', 'create', 'edit', '_form') as $view) { Generate::create(APPPATH . 'views/' . $controller_path . '/' . $view . '.php', \View::forge(static::$view_subdir . $subfolder . '/views/actions/' . $view, $data), 'view'); } // Add the default template if it doesnt exist if (!file_exists($app_template = APPPATH . 'views/template.php')) { Generate::create($app_template, file_get_contents(PKGPATH . 'oil/views/' . static::$view_subdir . $subfolder . '/views/template.php'), 'view'); } Generate::build(); }
public static function run() { $version = \Cli::option('v', \Cli::option('version')); if ($version > 0) { \Migrate::version($version); } else { \Migrate::current(); } }
/** * Send command with runtime option: * php oil refine autho --install * php oil refine autho --help * php oil refine autho --test * * @static * @access public * @return void */ public static function run() { $install = \Cli::option('i', \Cli::option('install')); $help = \Cli::option('h', \Cli::option('help')); $test = \Cli::option('t', \Cli::option('test')); switch (true) { case null !== $install: static::install($install); break; case null !== $test: static::test(); break; case null !== $help: default: static::help(); break; } }
public static function create($subjects, $fields) { $field_str = ''; $defined_columns = array(); foreach ($fields as $field) { $name = array_shift($field); $field_opts = array(); foreach ($field as $option => $val) { if ($val === true) { $field_opts[] = "'{$option}' => true"; } else { if (is_int($val)) { $field_opts[] = "'{$option}' => {$val}"; } else { $field_opts[] = "'{$option}' => '{$val}'"; } } } $field_opts = implode(', ', $field_opts); $field_str .= "\t\t\t'{$name}' => array({$field_opts})," . PHP_EOL; $defined_columns[$name] = true; } // ID Field $field_str = "\t\t\t'id' => array('constraint' => 11, 'type' => 'int', 'auto_increment' => true)," . PHP_EOL . $field_str; if (!\Cli::option('no-timestamps', false)) { if (!isset($defined_columns['created_at'])) { $field_str .= "\t\t\t'created_at' => array('constraint' => 11, 'type' => 'int')," . PHP_EOL; } if (!isset($definied_columns['updated_at'])) { $field_str .= "\t\t\t'updated_at' => array('constraint' => 11, 'type' => 'int'),"; } } $up = <<<UP \t\t\\DBUtil::create_table('{$subjects[1]}', array( {$field_str} \t\t), array('id')); UP; $down = <<<DOWN \t\t\\DBUtil::drop_table('{$subjects[1]}'); DOWN; return array($up, $down); }
/** * Queue job * * @param mixed $id Supplier id * @param string $method Method to run * @param integer $delay * @param integer $ttr Time limit * @return null */ public function execute($id, $method, $delay = 0, $ttr = 300) { // Cast id is_numeric($id) and $id = (int) $id; // Job data $data = array('id' => $id, 'cached' => (bool) \Cli::option('cached', \Cli::option('c', false)), 'force' => (bool) \Cli::option('force', \Cli::option('f', false)), 'method' => $method); // Execute job immediately $execute = (bool) \Cli::option('execute', \Cli::option('e', false)); // Use Queue if available (greater performance) if (\Package::loaded('queue')) { // Create queue data if ($execute) { // Initialize logger $logger = clone \Log::instance(); // Get original handler $handler = $logger->popHandler(); $handler->pushProcessor(new \Monolog\Processor\PsrLogMessageProcessor()); $logger->pushHandler($handler); // Console handler $handler = new \Monolog\Handler\ConsoleHandler(\Monolog\Logger::NOTICE); $formatter = new \Monolog\Formatter\LineFormatter("%message% - %context%" . PHP_EOL, "Y-m-d H:i:s"); $handler->setFormatter($formatter); $logger->pushHandler($handler); // Add other handlers to logger through Event trigger \Event::instance('queue')->trigger('logger', $logger); $queue = array('supplier', array('driver' => 'direct', 'logger' => $logger)); } else { $queue = 'supplier'; } $options = array('delay' => $delay, 'ttr' => $ttr); // Push job and data to queue \Queue::push($queue, 'Indigo\\Erp\\Stock\\Job_Supplier', $data, $options); } else { try { $job = new Job_Supplier(); return $job->execute(null, $data); } catch (\Exception $e) { // TODO: process exceptions } } }
/** * 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); }
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 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 static function run($task, $args) { // Make sure something is set if ($task === null or $task === 'help') { static::help(); return; } // Just call and run() or did they have a specific method in mind? list($task, $method) = array_pad(explode(':', $task), 2, 'run'); $task = ucfirst(strtolower($task)); // Find the task if (!($file = \Fuel::find_file('tasks', $task))) { $files = \Fuel::list_files('tasks'); $possibilities = array(); foreach ($files as $file) { $possible_task = pathinfo($file, \PATHINFO_FILENAME); $difference = levenshtein($possible_task, $task); $possibilities[$difference] = $possible_task; } ksort($possibilities); if ($possibilities and current($possibilities) <= 5) { throw new Exception(sprintf('Task "%s" does not exist. Did you mean "%s"?', strtolower($task), current($possibilities))); } else { throw new Exception(sprintf('Task "%s" does not exist.', strtolower($task))); } return; } require $file; $task = '\\Fuel\\Tasks\\' . $task; $new_task = new $task(); // The help option hs been called, so call help instead if (\Cli::option('help') && is_callable(array($new_task, 'help'))) { $method = 'help'; } if ($return = call_user_func_array(array($new_task, $method), $args)) { \Cli::write($return); } }
public static function create($filepath, $contents, $type = 'file') { $directory = dirname($filepath); is_dir($directory) or static::$create_folders[] = $directory; // Check if a file exists then work out how to react if (file_exists($filepath)) { // Don't override a file if (\Cli::option('s', \Cli::option('skip')) === true) { // Don't bother trying to make this, carry on camping return; } // If we aren't skipping it, tell em to use -f if (\Cli::option('f', \Cli::option('force')) === null) { throw new Exception($filepath . ' already exists, use -f or --force to override.'); exit; } } static::$create_files[] = array('path' => $filepath, 'contents' => $contents, 'type' => $type); }
<?php echo '<?php'; ?> class <?php echo \Config::get('controller_prefix', 'Controller_') . $controller_name; ?> extends <?php echo \Cli::option('extends', $controller_parent) . "\n"; ?> { <?php foreach ($actions as $action) { ?> public function action_<?php echo $action['name']; ?> (<?php echo $action['params']; ?> ) { <?php echo $action['code'] . "\n"; ?> } <?php }
/** * Construct the argument list * * @param string $table name of the database table we need to create the list for * @return array */ protected static function arguments($table) { // get the list of columns from the table try { $columns = \DB::list_columns(trim($table), null, \Cli::option('db', null)); } catch (\Exception $e) { \Cli::write($e->getMessage(), 'red'); exit; } // construct the arguments list, starting with the table name $arguments = array($table); // set some switches $include_timestamps = false; $timestamp_is_int = true; // process the columns found foreach ($columns as $column) { // do we have a data_type defined? If not, use the generic type isset($column['data_type']) or $column['data_type'] = $column['type']; // skip the 'id' column, it will be added automatically if ($column['name'] == 'id') { continue; } // detect timestamp columns if (in_array($column['name'], array('created_at', 'updated_at'))) { $include_timestamps = true; $timestamp_is_int = $column['data_type'] == 'int'; continue; } // do we need to add constraints? $constraint = ''; foreach (array('length', 'character_maximum_length', 'display') as $idx) { // check if we have such a column, and filter out some default values if (isset($column[$idx]) and !in_array($column[$idx], array('65535', '4294967295'))) { $constraint = '[' . $column[$idx] . ']'; break; } } // if it's an enum column, list the available options if (in_array($column['data_type'], array('set', 'enum'))) { $constraint = '[' . implode(',', $column['options']) . ']'; } // store the column in the argument list $arguments[] = $column['name'] . ':' . $column['data_type'] . $constraint; } // set the switches for the code generation \Cli::set_option('no-timestamp', $include_timestamps === false); \Cli::set_option('mysql-timestamp', $timestamp_is_int === false); // return the generated argument list return $arguments; }
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()}"`; } }
public function __construct($args = null) { self::$absolute_execute = \Cli::option('absolute_execute', false); self::$charset = \Config::get('db.default.charset') ?: 'utf8'; }
private static function _find_migration_number() { $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'); } } $files = new \GlobIterator($base_path . 'migrations/*_*.php'); try { $migrations = array(); foreach ($files as $file) { $migrations[] = $file->getPathname(); } sort($migrations); list($last) = explode('_', basename(end($migrations))); } catch (\LogicException $e) { throw new Exception("Unable to read existing migrations. Path does not exist, or you may have an 'open_basedir' defined"); } return str_pad($last + 1, 3, '0', STR_PAD_LEFT); }
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(); } }
/** * migrates item down to the given version * * @param string * @param string */ protected static function _down($name, $type) { // -v or --version $version = \Cli::option('v', \Cli::option('version', null)); // if version has a value, make sure only 1 item was passed if ($version and static::$default + static::$module_count + static::$package_count > 1) { \Cli::write('Migration: version only accepts 1 item.'); return; } $migrations = \Migrate::down($version, $name, $type); if ($migrations) { \Cli::write('Reverted migrations for ' . $type . ':' . $name . ':', 'green'); foreach ($migrations as $migration) { \Cli::write('- ' . $migration); } } else { // there is no 'down'... \Cli::write('There are no migrations installed to revert for ' . $type . ':' . $name . '.'); } }
/** * Detects and returns the current URI based on a number of different server * variables. * * @return string */ public static function uri() { if (static::$detected_uri !== null) { return static::$detected_uri; } if (\Fuel::$is_cli) { if ($uri = \Cli::option('uri') !== null) { static::$detected_uri = $uri; } else { static::$detected_uri = \Cli::option(1); } return static::$detected_uri; } // We want to use PATH_INFO if we can. if (!empty($_SERVER['PATH_INFO'])) { $uri = $_SERVER['PATH_INFO']; } elseif (!empty($_SERVER['ORIG_PATH_INFO']) and ($path = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['ORIG_PATH_INFO'])) != '') { $uri = $path; } else { // Fall back to parsing the REQUEST URI if (isset($_SERVER['REQUEST_URI'])) { $uri = strpos($_SERVER['SCRIPT_NAME'], $_SERVER['REQUEST_URI']) !== 0 ? $_SERVER['REQUEST_URI'] : ''; } else { throw new \FuelException('Unable to detect the URI.'); } // Remove the base URL from the URI $base_url = parse_url(\Config::get('base_url'), PHP_URL_PATH); if ($uri != '' and strncmp($uri, $base_url, strlen($base_url)) === 0) { $uri = substr($uri, strlen($base_url) - 1); } // If we are using an index file (not mod_rewrite) then remove it $index_file = \Config::get('index_file'); if ($index_file and strncmp($uri, $index_file, strlen($index_file)) === 0) { $uri = substr($uri, strlen($index_file)); } // When index.php? is used and the config is set wrong, lets just // be nice and help them out. if ($index_file and strncmp($uri, '?/', 2) === 0) { $uri = substr($uri, 1); } // decode the uri, and put any + back (does not mean a space in the url path) $uri = str_replace("\r", '+', urldecode(str_replace('+', "\r", $uri))); // Lets split the URI up in case it contains a ?. This would // indicate the server requires 'index.php?' and that mod_rewrite // is not being used. preg_match('#(.*?)\\?(.*)#i', $uri, $matches); // If there are matches then lets set set everything correctly if (!empty($matches)) { $uri = $matches[1]; // only reconstruct $_GET if we didn't have a query string if (empty($_SERVER['QUERY_STRING'])) { $_SERVER['QUERY_STRING'] = $matches[2]; parse_str($matches[2], $_GET); $_GET = \Security::clean($_GET); } } } // Deal with any trailing dots $uri = rtrim($uri, '.'); // Do we have a URI and does it not end on a slash? if ($uri and substr($uri, -1) !== '/') { // Strip the defined url suffix from the uri if needed $ext = strrchr($uri, '.'); $path = $ext === false ? $uri : substr($uri, 0, -strlen($ext)); // Did we detect something that looks like an extension? if (!empty($ext)) { // if it has a slash in it, it's a URI segment with a dot in it if (strpos($ext, '/') === false) { static::$detected_ext = ltrim($ext, '.'); if (\Config::get('routing.strip_extension', true)) { $uri = $path; } } } } // Do some final clean up of the uri static::$detected_uri = \Security::clean_uri($uri, true); return static::$detected_uri; }
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; } }