Run migration

@museDescription  Runs pending migrations according to options provided

@return  void
510462
public function run()
	{
		// Direction, up or down
		$direction = 'up';
		if ($this->arguments->getOpt('d'))
		{
			if ($this->arguments->getOpt('d') == 'up' || $this->arguments->getOpt('d') == 'down')
			{
				$direction = $this->arguments->getOpt('d');
			}
			else
			{
				$this->output->error('Error: Direction must be one of "up" or "down"');
			}
		}

		// Overriding default document root?
		$directory = null;
		if ($this->arguments->getOpt('r'))
		{
			if (is_dir($this->arguments->getOpt('r')) && is_readable($this->arguments->getOpt('r')))
			{
				$directory = rtrim($this->arguments->getOpt('r'), DS);
			}
			else
			{
				$this->output->error('Error: Provided directory is not valid');
			}
		}

		// Migrating a super group
		$alternativeDatabase = null;
		if ($this->arguments->getOpt('group'))
		{
			$cname = $this->arguments->getOpt('group');
			$group = \Hubzero\User\Group::getInstance($cname);
			if ($group && $group->isSuperGroup())
			{
				// Get group config
				$groupsConfig = \Component::params('com_groups');

				// Path to group folder
				$directory  = PATH_APP . DS . trim($groupsConfig->get('uploadpath', '/site/groups'), DS);
				$directory .= DS . $group->get('gidNumber');

				// make sure we have migrations dir
				if (!is_dir($directory . DS . 'migrations') || !is_readable($directory . DS . 'migrations'))
				{
					$this->output->error('Error: Migrations directory does not exist.');
				}

				// Get group database
				$alternativeDatabase = \Hubzero\User\Group\Helper::getDBO(array(), $group->get('cn'));

				// make sure we have a group db
				if ($alternativeDatabase->getErrorNum() > 0)
				{
					$this->output->error('Error: Could not connect to Group Database.');
				}
			}
			else
			{
				$this->output->error('Error: Provided group is not valid');
			}
		}

		// Forcing update
		$force = false;
		if ($this->arguments->getOpt('force'))
		{
			if (!$this->arguments->getOpt('e') && !$this->arguments->getOpt('file'))
			{
				$this->output->error('Error: You cannot specify the "force" option without specifying a specific extention or file');
			}
			else
			{
				$force = true;
			}
		}

		// Logging only - record migration
		$logOnly = false;
		if ($this->arguments->getOpt('m'))
		{
			if (!$this->arguments->getOpt('e') && !$this->arguments->getOpt('file'))
			{
				$this->output->error('Error: You cannot specify the "Log only (-m)" option without specifying a specific extention or file');
			}
			else
			{
				$logOnly = true;
			}
		}

		// Ignore dates
		$listAll = false;
		if ($this->arguments->getOpt('a') || $this->arguments->getOpt('i'))
		{
			$listAll = true;
		}

		// Specific extension
		$extension = null;
		if ($this->arguments->getOpt('e'))
		{
			if (!preg_match('/^com_[[:alnum:]]+$|^mod_[[:alnum:]]+$|^plg_[[:alnum:]]+_[[:alnum:]]+$|^core$/i', $this->arguments->getOpt('e')))
			{
				$this->output->error('Error: extension should match the pattern of com_*, mod_*, plg_*_*, or core');
			}
			else
			{
				$extension = $this->arguments->getOpt('e');
			}
		}

		// Specific file
		$file = null;
		if ($this->arguments->getOpt('file'))
		{
			if (!preg_match('/^Migration[0-9]{14}[[:alnum:]]+\.php$/', $this->arguments->getOpt('file')))
			{
				$this->output->error('Error: Provided filename does not appear to be valid');
			}
			else
			{
				$file = $this->arguments->getOpt('file');

				// Also force "ignore dates mode", as that's somewhat implied by giving a specific filename
				$listAll = true;
			}
		}

		// Dryrun
		$dryrun = true;
		if ($this->arguments->getOpt('f'))
		{
			$dryrun = false;
		}

		// Email results
		$email = false;
		if ($this->arguments->getOpt('email'))
		{
			if (!preg_match('/^[a-zA-Z0-9\.\_\-]+@[a-zA-Z0-9\.]+\.[a-zA-Z]{2,4}$/', $this->arguments->getOpt('email')))
			{
				$this->output->error('Error: ' . $this->arguments->getOpt('email') . ' does not appear to be a valid email address');
			}
			else
			{
				$email = $this->arguments->getOpt('email');
			}
		}

		// Create migration object
		$migration = new \Hubzero\Content\Migration($directory, $alternativeDatabase);

		// Search vendor directories?
		if ($this->arguments->getOpt('vendor'))
		{
			$vendorPath = PATH_APP . DS . 'vendor';

			if (is_dir($vendorPath))
			{
				foreach (scandir($vendorPath) as $namespace)
				{
					if ($namespace != '.' && $namespace != '..' && is_dir($vendorPath . DS . $namespace))
					{
						foreach (scandir($vendorPath . DS . $namespace) as $package)
						{
							if ($package != '.' && $package != '..' && is_dir($vendorPath . DS . $namespace . DS . $package))
							{
								$migrationPath = $vendorPath . DS . $namespace . DS . $package . DS . 'src';
								if (is_dir($migrationPath . DS . 'migrations'))
								{
									$migration->addSearchPath($migrationPath);
								}
							}
						}
					}
				}
			}
		}

		// Make sure we got a migration object
		if ($migration === false)
		{
			$this->output->error('Error: failed to instantiate new migration object.');
		}

		if ($this->output->isInteractive())
		{
			// Register callback function for adding lines interactively
			$output   = $this->output;
			$callback = function($message, $type=null) use ($output)
			{
				$output->addLine($message, $type);
			};
			$migration->registerCallback('message', $callback);

			// Add progress callback as well
			$progress = $this->output->getProgressOutput();
			$migration->registerCallback('progress', $progress);
		}

		// Find migration files
		if ($migration->find($extension, $file) === false)
		{
			// Find failed, do nothing
			if (count($migration->get('log')) > 0)
			{
				$this->output->addLinesFromArray($migration->get('log'));
			}
			$this->output->error('Migration find failed! See log messages for details.');
		}
		else // no errors during 'find', so continue
		{
			// Run migration itself
			if (!$result = $migration->migrate($direction, $force, $dryrun, $listAll, $logOnly))
			{
				if (count($migration->get('log')) > 0)
				{
					$this->output->addLinesFromArray($migration->get('log'));
				}
				$this->output->error('Migration failed! See log messages for details.');
			}
			else
			{
				if (!$this->output->isInteractive())
				{
					if ($this->output->getMode() == 'minimal')
					{
						if (count($migration->get('log')) > 0)
						{
							$missed   = array();
							$pending  = array();
							$complete = array();
							foreach ($migration->get('log') as $log)
							{
								if (preg_match('/would run up\(\) (.*?)(Migration[0-9]{14}[[:alnum:]_]*\.php)/i', $log['message'], $matches))
								{
									$pending[] = $matches[1] . $matches[2];
								}
								if (preg_match('/completed up\(\) in (.*?)(Migration[0-9]{14}[[:alnum:]_]*\.php)/i', $log['message'], $matches)
								 || preg_match('/would ignore up\(\) (.*?)(Migration[0-9]{14}[[:alnum:]_]*\.php)/i', $log['message'], $matches))
								{
									$complete[] = $matches[1] . $matches[2];
								}
								if (preg_match('/migration up\(\) in (.*?)(Migration[0-9]{14}[[:alnum:]_]*\.php) has not been run/i', $log['message'], $matches))
								{
									$missed[] = $matches[1] . $matches[2];
								}
							}

							if (count($pending) > 0)
							{
								$this->output->addLine(array('pending'  => $pending));
							}
							if (count($missed) > 0)
							{
								$this->output->addLine(array('missed'   => $missed));
							}
							if (count($complete) > 0)
							{
								$this->output->addLine(array('complete' => $complete));
							}
						}
					}
					else
					{
						$this->output->addLinesFromArray($migration->get('log'));
					}
				}

				// Final success message
				if ($this->output->getMode() != 'minimal')
				{
					$this->output->addLine('Success: ' . ucfirst($direction) . ' migration complete!', 'success');
				}
			}
		}

		// Email results if requested (only do so if there's something to report)
		if ($email && count($migration->get('affectedFiles')) > 0)
		{
			$this->output->addLine("Emailing results to: {$email}");

			$headers = "From: Migrations <automator@" . php_uname("n") . ">";
			$subject = "Migration output - " . php_uname("n") . " [" . date("d-M-Y H:i:s") . "]";

			$message = "";
			foreach ($migration->get('log') as $line)
			{
				$message .= $line['message'] . "\n";
			}

			// Send the message
			if (!mail($email, $subject, $message, $headers))
			{
				$this->output->addLine("Error: failed to send message!", 'warning');
			}
		}
		elseif ($email)
		{
			$this->output->addLine('Ignoring email as no files were affected in this run.', 'info');
		}
	}
876138
public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('alias', 50)->unique();
            $table->date('birthday_at');
            $table->enum('gender', ['male', 'female'])->nullable();

            $table->string('city', 50);
            $table->string('profession', 50);
            $table->string('hobbies');
            $table->text('about');

            $table->string('homepage', 100);
            $table->string('skype', 50);
            $table->string('facebook', 50);
            $table->string('twitter', 50);

            $table->string('main_character', 20);
            $table->string('main_guild', 50);
            $table->string('favorite_race', 20);
            $table->string('favorite_class', 20);
            $table->string('favorite_spec', 20);
            $table->string('favorite_instance', 50);
            $table->string('favorite_battleground', 50);
        });
    }
941924
public function up()
    {

        Schema::create('character_infos', function (Blueprint $table) {

            $table->bigInteger('character_id')->primary();

            $table->string('name');
            $table->text('description')->nullable();
            $table->bigInteger('corporation_id');
            $table->bigInteger('alliance_id')->nullable();
            $table->string('birthday');
            $table->string('gender');
            $table->integer('race_id');
            $table->integer('bloodline_id');
            $table->integer('ancenstry_id')->nullable();
            $table->float('security_status')->nullable();
            $table->integer('faction_id')->nullable();

            $table->timestamps();

        });
    }
1340998
public function up()
    {
        Schema::create($this->prefixCmsTable('users'), function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->string('password');
            $table->text('permissions')->nullable();
            $table->timestamp('last_login')->nullable();
            $table->string('first_name')->nullable();
            $table->string('last_name')->nullable();
            $table->boolean('is_superadmin')->default(false);
            $table->nullableTimestamps();

            $table->unique('email');
        });

        Schema::create($this->prefixCmsTable('activations'), function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('code');
            $table->boolean('completed')->default(0);
            $table->timestamp('completed_at')->nullable();
            $table->nullableTimestamps();

            $table->foreign('user_id', 'fk_' . $this->prefixCmsTable('activations_users1'))
                  ->references('id')->on($this->prefixCmsTable('users'))
                  ->onDelete('cascade');
        });

        Schema::create($this->prefixCmsTable('persistences'), function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('code');
            $table->nullableTimestamps();

            $table->unique('code');

            $table->foreign('user_id', 'fk_' . $this->prefixCmsTable('persistences_users1'))
                  ->references('id')->on($this->prefixCmsTable('users'))
                  ->onDelete('cascade');
        });

        Schema::create($this->prefixCmsTable('reminders'), function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('code');
            $table->boolean('completed')->default(0);
            $table->timestamp('completed_at')->nullable();
            $table->nullableTimestamps();

            $table->foreign('user_id', 'fk_' . $this->prefixCmsTable('reminders_users1'))
                  ->references('id')->on($this->prefixCmsTable('users'))
                  ->onDelete('cascade');
        });

        Schema::create($this->prefixCmsTable('roles'), function (Blueprint $table) {
            $table->increments('id');
            $table->string('slug');
            $table->string('name');
            $table->text('permissions')->nullable();
            $table->nullableTimestamps();

            $table->unique('slug');
        });

        Schema::create($this->prefixCmsTable('role_users'), function (Blueprint $table) {
            $table->integer('user_id')->unsigned();
            $table->integer('role_id')->unsigned();
            $table->nullableTimestamps();

            $table->primary(['user_id', 'role_id']);

            $table->foreign('user_id', 'fk_' . $this->prefixCmsTable('role_users_users1'))
                  ->references('id')->on($this->prefixCmsTable('users'))
                  ->onDelete('cascade');

            $table->foreign('role_id', 'fk_' . $this->prefixCmsTable('role_users_roles1'))
                  ->references('id')->on($this->prefixCmsTable('roles'))
                  ->onDelete('cascade');
        });

        Schema::create($this->prefixCmsTable('throttle'), function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->nullable();
            $table->string('type');
            $table->string('ip')->nullable();
            $table->nullableTimestamps();

            $table->index('user_id');

            $table->foreign('user_id', 'fk_' . $this->prefixCmsTable('throttle_users1'))
                  ->references('id')->on($this->prefixCmsTable('users'))
                  ->onDelete('cascade');
        });
    }
198155
public function up() {
        Schema::create('languages', function (Blueprint $table) {
            $table->increments('id');
            $table->char('slug', 2)->unique();
            $table->string('title', 30);
            $table->tinyInteger('rank')->unsigned()->default(1);
            $table->boolean('active')->default(1);

            $table->index('active');
            $table->index('rank');
        });
    }
1256439
public function up()
    {
        if (Schema::hasTable('languages')) {
            return;
        }

        Schema::create('languages', function (Blueprint $table) {

            $table->string('iso_code', 2)->primary();

            $table->string('title');
            $table->string('title_localized');
            $table->boolean('is_fallback')->default(false)->index();

            $table->softDeletes();
            $table->timestamps();
        });
    }
506205
public function up()
    {
        Schema::create('settings', function (Blueprint $table) {

            $table->increments('id');
            $table->string('module_name', 30);
            $table->enum('action', ['setting', 'xfield', 'creat', 'edit'])->default('setting');
            $table->string('section', 20)->default('main');
            $table->string('fieldset', 20)->default('general');
            $table->string('name', 30);
            $table->string('type', 20)->default('string');
            $table->string('value');
            $table->text('params')->nullable(); // multiline or json, or dinamic values
            $table->text('class')->length(255)->nullable();
            $table->text('html_flags')->length(500)->nullable();
            $table->string('title', 125)->nullable();
            $table->text('descr')->length(500)->nullable();

            // If need to monitor an additional field. I.e.: create and delete him.
            $table->boolean('as_xfield')->nullable();

            $table->index('action');
            $table->index('module_name');
            $table->unique(['name', 'module_name']);
            // $table->foreign('module_id', DB::getTablePrefix() . 'settings_module_id_fk')->references('id')->on('modules')
            $table->foreign('module_name')->references('name')->on('modules')
                  ->onDelete('cascade')->onUpdate('cascade');

            $table->timestamps();
        });
    }
134188
public function up()
    {
        // We need a better way of handling data migrations...
        $system = app(System::class);
        $prefix = $system->getTablePrefix();
        DB::update("INSERT INTO {$prefix}schedules (name, message, scheduled_at, created_at, updated_at) SELECT name, message, scheduled_at, created_at, updated_at FROM {$prefix}incidents WHERE scheduled_at IS NOT NULL");

        DB::table('incidents')->whereNotNull('scheduled_at')->delete();

        Schema::table('incidents', function (Blueprint $table) {
            $table->dropColumn('scheduled_at');
        });
    }
1094182
public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('uuid', 36)->unique();
            $table->string('username', 120)->unique();
            $table->string('email_address', 120)->unique();
            $table->string('password', 36);
            $table->string('password_token', 120);
            $table->tinyInteger('status')->default(1)->comment('1 = Active, 2 = Inactive');
            $table->tinyInteger('is_vissible')->default(1)->comment('1 = Visible, 2 = Disable');
            $table->dateTime('last_seen');
            $table->rememberToken();
            $table->timestamps();
            $table->charset = 'utf8';
            $table->collation = 'utf8_general_ci';
        });
    }
578981
public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->uuid('id')->primary('id');
            $table->uuid('user_id')->index();
            $table->string('text', 64)->index('text');
            $table->timestamps();

            $table->unique(['user_id', 'text']);

            $table->foreign('user_id')->references('id')->on('users');
        });

    }
478543
public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%gr_lang}}', [
            'id' => Schema::TYPE_PK,
            'url' => Schema::TYPE_STRING . '(255) NOT NULL',
            'local' => Schema::TYPE_STRING . '(255) NOT NULL',
            'name' => Schema::TYPE_STRING . '(255) NOT NULL',
            'default' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 0',
            'date_update' => Schema::TYPE_INTEGER . ' NOT NULL',
            'date_create' => Schema::TYPE_INTEGER . ' NOT NULL',
        ], $tableOptions);

        $this->batchInsert('gr_lang', ['url', 'local', 'name', 'default', 'date_update', 'date_create'], [
            ['en', 'en-EN', 'English', 0, time(), time()],
            ['ru', 'ru-RU', 'Русский', 1, time(), time()],
        ]);
    }
369385
public function up()
    {
        Schema::create('jobs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('queue')->index();
            $table->longText('payload');
            $table->unsignedTinyInteger('attempts');
            $table->unsignedInteger('reserved_at')->nullable();
            $table->unsignedInteger('available_at');
            $table->unsignedInteger('created_at');
        });
    }
682410
public function up()
    {
        Schema::create('objects', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('image_id')->unsigned()->nullable();
            $table->json('status');
            $table->json('title');
            $table->json('slug');
            $table->json('summary');
            $table->json('body');
            $table->timestamps();
        });
    }
367368
public function up()
    {
        Schema::create('hc_resource_grab_property', function (Blueprint $table) {
            $table->increments('count');
            $table->uuid('id')->unique();
            $table->datetime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->datetime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->datetime('deleted_at')->nullable();

            $table->uuid('thumbnail_id');
            $table->uuid('resource_id');

            $table->uuid('source_id');
            $table->string('source_type');

            $table->integer('x')->nullable();
            $table->integer('y')->nullable();
            $table->double('zoom')->nullable();

            $table->foreign('resource_id')->references('id')->on('hc_resource')->onUpdate('CASCADE')->onDelete('CASCADE');
            $table->foreign('thumbnail_id')->references('id')->on('hc_resource_thumbnail')->onUpdate('CASCADE')->onDelete('CASCADE');
        });
    }
1130679
public function up()
    {
        Schema::create('crud_notify', function ($table) {
            $table->increments('id');
            $table->string('message');
            $table->integer('target_user_id');
            $table->integer('ttl')->default(0);
            $table->tinyInteger('broadcast')->default(0);
            $table->tinyInteger('delivered')->default(0);
            $table->integer('created_by');
            $table->integer('created_at');
            $table->integer('updated_at');
            $table->integer('delivered_at');
        });
    }
80385
public function up()
    {

        Schema::create('corporation_outpost_details', function (Blueprint $table) {

            $table->bigInteger('corporation_id');
            $table->bigInteger('owner_id');
            $table->bigInteger('outpost_id');
            $table->integer('system_id');
            $table->float('docking_cost_per_ship_volume');
            $table->bigInteger('office_rental_cost');
            $table->integer('type_id');
            $table->float('reprocessing_efficiency');
            $table->float('reprocessing_station_take');
            $table->bigInteger('standing_owner_id');
            $table->double('x');
            $table->double('y');
            $table->double('z');

            $table->primary(['corporation_id', 'outpost_id'], 'corporation_outpost_details_primary_key');
            $table->index('corporation_id');
            $table->index('outpost_id');
            $table->index('system_id');
            $table->index('type_id');
            $table->index('standing_owner_id');

            $table->timestamps();
        });
    }
238038
public function up()
    {
        \Schema::create('config', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->string('namespace')
                  ->default('');
            $table->string('key');
            $table->string('value');
            $table->enum('type', ['int', 'bool', 'string']);
            $table->unsignedInteger('modified_by_user_id');
            $table->timestamp('modified_at');

            $table->unique(['namespace', 'key']);
        });
    }