Пример #1
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();
     }
 }
Пример #2
0
 /**
  * Install registries table
  *
  * @static
  * @access  protected
  * @return  void
  */
 public static function generate($table_name = null)
 {
     $table_name or $table_name = \Config::get('hybrid.tables.registry', 'options');
     $class_name = \Inflector::classify($table_name, true);
     if ('y' === \Cli::prompt("Would you like to install `registry.{$table_name}` table?", array('y', 'n'))) {
         Generate::migration(array('create_' . $table_name, 'name:string[255]', 'value:longtext'));
         Generate::$create_files = array();
     }
 }
Пример #3
0
 public static function run()
 {
     // Prompt the user with menu options
     $option = \Cli::prompt('What would you like to do?', array('work', 'listen', 'help'));
     switch ($option) {
         case 'work':
             return static::work();
             break;
         case 'listen':
             return static::listen();
             break;
         case 'help':
             return static::help();
             break;
         default:
             return static::help();
             break;
     }
 }
 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');
     }
 }
Пример #5
0
 /**
  * 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');
 }
Пример #6
0
 public static function module($args)
 {
     if (!($module_name = strtolower(array_shift($args)))) {
         throw new Exception('No module name has been provided.');
     }
     if ($path = \Module::exists($module_name)) {
         throw new Exception('A module named ' . $module_name . ' already exists at ' . $path);
     }
     $module_paths = \Config::get('module_paths');
     $base = reset($module_paths);
     if (count($module_paths) > 1) {
         \Cli::write('Your app has multiple module paths defined. Please choose the appropriate path from the list below', 'yellow', 'blue');
         $options = array();
         foreach ($module_paths as $key => $path) {
             $idx = $key + 1;
             \Cli::write('[' . $idx . '] ' . $path);
             $options[] = $idx;
         }
         $path_idx = \Cli::prompt('Please choose the desired module path', $options);
         $base = $module_paths[$path_idx - 1];
     }
     $module_path = $base . $module_name . DS;
     static::$create_folders[] = $module_path;
     static::$create_folders[] = $module_path . 'classes/';
     if (($folders = \Cli::option('folders')) !== true) {
         $folders = explode(',', $folders);
         foreach ($folders as $folder) {
             static::$create_folders[] = $module_path . $folder;
         }
     }
     static::$create_folders && static::build();
 }
Пример #7
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());
         }
     }
 }
Пример #8
0
 /**
  * Confirm database connection setting
  */
 private static function confirm()
 {
     while (true) {
         $options = array();
         /**
          * entered values
          */
         $i = 1;
         foreach (static::$config as $k => &$v) {
             if ($k != 'driver') {
                 $display = $k === 'password' ? str_pad('', strlen($v), '*') : $v;
                 $options[$i] = $i . '. ' . $k . ':' . $display;
                 $i++;
             }
         }
         $options['y'] = 'y. OK.';
         $options['c'] = 'c. Cancel.';
         \Cli::write("\nConfirm", 'green');
         \Cli::write(implode("\n", $options));
         $index = \Cli::prompt('Enter a number, "y" or "c".' . "\n", array_flip($options));
         switch ($index) {
             case 'y':
                 return;
             case 'c':
                 \Cli::write('Good bye!!', 'green');
                 exit;
             default:
                 static::prompt($index);
                 break;
         }
     }
 }
Пример #9
0
 /**
  * Execute all available migration
  *
  * @static
  * @access  protected
  * @return  void
  */
 protected static function execute()
 {
     if (empty(static::$queries)) {
         \Cli::write("Nothing to generate", "red");
     } elseif ('y' === \Cli::prompt("Confirm Generate Model and Migration?", array('y', 'n'))) {
         foreach (static::$queries as $data) {
             Generate::model($data);
             Generate::$create_files = array();
         }
     }
 }
Пример #10
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;
    }
Пример #11
0
 /**
  * generate the module
  * 
  * @param string $module_name the module name is StudlyCaps as PSR-1 specified.
  */
 public static function module($args)
 {
     $module_name = array_shift($args);
     $module_name = str_replace(' ', '', $module_name);
     if ($path = \Module::exists(strtolower($module_name))) {
         throw new Exception('A module named ' . $module_name . ' already exists at ' . $path);
         exit;
     }
     $module_paths = \Config::get('module_paths');
     $base = reset($module_paths);
     if (count($module_paths) > 1) {
         \Cli::write('Your app has multiple module paths defined. Please choose the appropriate path from the list below', 'yellow', 'blue');
         $options = array();
         foreach ($module_paths as $key => $path) {
             $idx = $key + 1;
             \Cli::write('[' . $idx . '] ' . $path);
             $options[] = $idx;
         }
         $path_idx = \Cli::prompt('Please choose the desired module path', $options);
         $base = $module_paths[$path_idx - 1];
     }
     $module_path = $base . strtolower($module_name) . DS;
     static::$create_folders[] = $module_path;
     static::$create_folders[] = $module_path . 'classes/controller/admin';
     static::$create_folders[] = $module_path . 'classes/model';
     static::$create_folders[] = $module_path . 'config';
     $languages = \Config::get('locales');
     if (is_array($languages) && !empty($languages)) {
         foreach ($languages as $key => $item) {
             static::$create_folders[] = $module_path . 'lang/' . $key;
         }
     } else {
         static::$create_folders[] = $module_path . 'lang/en';
     }
     unset($item, $key, $languages);
     static::$create_folders[] = $module_path . 'views/admin/templates/index';
     static::$create_folders[] = $module_path . 'views/front/templates/index';
     // create _module.php file
     static::createModuleFile($module_path, $module_name);
     // create [module name]admin.php file for define permissions
     static::createAdminFile($module_path, $module_name);
     // create config file
     static::createConfig($module_path, $module_name);
     // create language files
     static::createLangFiles($module_path, $module_name);
     // create controllers
     static::createControllers($module_path, $module_name);
     // create views
     static::createViews($module_path, $module_name);
     $result = static::build();
     if (isset($result) && $result === true) {
         \Cli::write('Completed create folders.');
     }
     unset($result);
 }
Пример #12
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);
 }
Пример #13
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');
 }