Returns an array of commands required to either install or fix audit database objects.
@param ActiveRecord $model
@param string $direction
@return array
@throws InvalidConfigException
424335
public function getDbCommands($model = null, $direction = 'up')
    {
        if ($model === null) {
            $auditTableName = 'audits.logged_actions';
            $changesetTableName = 'audits.changesets';
        } else {
            if (($behavior = $this->getBehavior($model)) === null) {
                throw new InvalidConfigException('Attach the TrackableBehavior to the ' . $model::className()
                    . ' model.');
            }
            $auditTableName = $behavior->auditTableName;
            $changesetTableName = $behavior->changesetTableName;
        }
        if (($pos=strpos($auditTableName, '.')) !== false) {
            $auditSchema = substr($auditTableName, 0, $pos);
            $auditTableName = substr($auditTableName, $pos + 1);
        } else {
            $auditSchema = 'public';
        }
        if (($pos=strpos($changesetTableName, '.')) !== false) {
            if (substr($changesetTableName, 0, $pos) !== $auditSchema) {
                throw new InvalidCallException('Meta and audit tables cannot be in different schemas.');
            }
            $changesetTableName = substr($changesetTableName, $pos + 1);
        }

        $commands = [];

        if ($direction == 'up') {
            // don't drop schema and operator, since other objects could be left there
            $schemaTemplate = $this->schemaTemplate($auditSchema);
            if (!$schemaTemplate['exists']) {
                $commands[] = $this->db->createCommand($schemaTemplate[$direction]);
            }
            $actionTypeTemplate = $this->actionTypeTemplate($auditSchema);
            if (!$actionTypeTemplate['exists']) {
                $commands[] = $this->db->createCommand($actionTypeTemplate[$direction]);
            }
        }

        $tableTemplates = $this->tableTemplate($auditTableName, $changesetTableName, $auditSchema);
        $queryBuilder = $this->db->getQueryBuilder();
        foreach ($tableTemplates as $tableTemplate) {
            if ($tableTemplate['exists']) {
                continue;
            }
            if ($direction == 'down') {
                $commands[] = $this->db->createCommand($queryBuilder->dropTable($tableTemplate['name']));
                continue;
            }
            $query = $queryBuilder->createTable($tableTemplate['name'], $tableTemplate['columns']);
            $commands[] = $this->db->createCommand($query);
            foreach ($tableTemplate['indexes'] as $columns => $type) {
                if (is_numeric($columns)) {
                    $columns = $type;
                    $type = null;
                }
                if ($type === null) {
                    $query = "CREATE INDEX ON {$tableTemplate['name']} ($columns)";
                } else {
                    $query = "CREATE INDEX ON {$tableTemplate['name']} $type";
                }
                $commands[] = $this->db->createCommand($query);
            }
        }

        $procTemplate = $this->procTemplate($auditTableName, $changesetTableName, $auditSchema);
        if (!$procTemplate['exists']) {
            foreach ($procTemplate[$direction] as $query) {
                $commands[] = $this->db->createCommand($query);
            }
        }

        if ($model !== null) {
            $triggerTemplate = $this->triggerTemplate($model->getTableSchema()->fullName, $auditSchema);
            if (!$triggerTemplate['exists']) {
                foreach ($triggerTemplate[$direction] as $query) {
                    $commands[] = $this->db->createCommand($query);
                }
            }
        }

        return $direction == 'down' ? array_reverse($commands) : $commands;
    }
256475
public function getLdapUserRequiredAttributes($direction = LDAP_USER_PROV_DIRECTION_ALL, $ldap_context = NULL) {

    $attributes_map = array();
    $required_attributes = array();
    if ($this->drupalAcctProvisionServer) {
      $prov_events = $this->ldapContextToProvEvents($ldap_context);
      $attributes_map = $this->getSynchMappings($direction, $prov_events);
      $required_attributes = array();
      foreach ($attributes_map as $detail) {
        if (count(array_intersect($prov_events, $detail['prov_events']))) {
          // Add the attribute to our array.
          if ($detail['ldap_attr']) {
            ldap_servers_token_extract_attributes($required_attributes,  $detail['ldap_attr']);
          }
        }
      }
    }
    return $required_attributes;
  }
1223439
public function orderBy($column, $direction = 'asc')
	{
		if( !isset($this->valid_columns[$column]) )
		{
			throw new InvalidArgumentException("Column '{$column}' not used");
		}

		$this->orders[] = [$this->valid_columns[$column], $direction];
		return $this;
	}
1233746
protected function getRelations($model)
    {
        $methods = get_class_methods($model);
        if (!$methods) {
            return [];
        }
        foreach ($methods as $method) {
            if (Str::startsWith($method, 'get') && Str::endsWith($method, 'Attribute') && $method !== 'getAttribute') {
                $name = Str::snake(substr($method, 3, -9));
                if (!empty($name)) {
                    $this->setProperty($name, null, true, null);
                }
            } elseif (Str::startsWith($method, 'set') && Str::endsWith($method, 'Attribute') && $method !== 'setAttribute') {
                $name = Str::snake(substr($method, 3, -9));
                if (!empty($name)) {
                    $this->setProperty($name, null, null, true);
                }
            } elseif (Str::startsWith($method, 'scope') && $method !== 'scopeQuery') {
                $name = Str::camel(substr($method, 5));
                if (!empty($name)) {
                    $reflection = new \ReflectionMethod($model, $method);
                    $args       = $this->getParameters($reflection);
                    array_shift($args);
                    $this->setMethod($name, '\Illuminate\Database\Query\Builder|\\' . $reflection->class, $args);
                }
            } elseif (!method_exists('Illuminate\Database\Eloquent\Model', $method) && !Str::startsWith($method, 'get')) {
                $reflection = new ReflectionMethod($model, $method);
                $file       = new SplFileObject($reflection->getFileName());
                $file->seek($reflection->getStartLine() - 1);
                $code       = '';
                while ($file->key() < $reflection->getEndLine()) {
                    $code .= $file->current();
                    $file->next();
                }
                $code  = trim(preg_replace('/\s\s+/', '', $code));
                $begin = strpos($code, 'function(');
                $code  = substr($code, $begin, strrpos($code, '}') - $begin + 1);

                foreach (array('hasOne', 'belongsTo') as $relation) {
                    $search = '$this->' . $relation . '(';
                    if ($pos    = stripos($code, $search)) {
                        $relationObj = $model->$method();
                        if ($relationObj instanceof Relation) {
                            $relatedModel = '\\' . get_class($relationObj->getRelated());

                            $relations = ['hasManyThrough', 'belongsToMany', 'hasMany', 'morphMany', 'morphToMany'];
                            if (in_array($relation, $relations)) {
                                $this->setProperty($method, $this->getCollectionClass($relatedModel) . '|' . $relatedModel . '[]', true, null);
                            } elseif ($relation === "morphTo") {
                                $this->setProperty($method, '\Illuminate\Database\Eloquent\Model|\Eloquent', true, null);
                            } else {
                                $this->setProperty($method, $relatedModel, true, null);
                            }
                        }
                    }
                }
            }
        }
        return $this->properties;
    }
760097
public static function getModelColumns(string $model = '', string $connectionManager = 'default'): array
    {
        $result = $columns = [];

        if (empty($model)) {
            return $result;
        }

        // making sure that model is in table naming conventions.
        $model = Inflector::tableize($model);

        try {
            $connection = ConnectionManager::get($connectionManager);
            $schema = $connection->getSchemaCollection();
            $table = $schema->describe($model);
            $columns = $table->columns();
        } catch (MissingDatasourceConfigException $e) {
            return $result;
        } catch (Exception $e) {
            return $result;
        }

        // A table with no columns?
        if (empty($columns)) {
            return $result;
        }

        foreach ($columns as $column) {
            $result[$column] = $column;
        }

        return $result;
    }
660679
public function apply($query, $column, $direction = 'asc')
    {
        $direction = $direction === 'desc' ? 'desc' : 'asc';

        $modelTable = $query->getModel()->getTable();
        $modelKey   = $query->getModel()->getKeyName();

        $query->orderBy("{$modelTable}.{$modelKey}", $direction);

        return $query;
    }
1133400
public function getModelCallbacks(Model $model, $scope = '*') {
        $callbacks = array();
        $models = Configure::read('Admin.modelCallbacks');

        if (isset($models[$model->qualifiedName])) {
            foreach ($models[$model->qualifiedName] as $method => $options) {
                if (is_string($options)) {
                    $options = array('title' => $options, 'access' => 'update', 'scope' => '*');
                } else {
                    $options = $options += array('access' => 'update', 'scope' => '*');
                }

                if ($options['scope'] !== $scope) {
                    continue;
                }

                if ($this->hasAccess($model->qualifiedName, $options['access'])) {
                    $callbacks[$method] = __d('admin', $options['title'], $model->singularName);
                }
            }
        }

        return $callbacks;
    }
315321
protected function normalizeJoins($model, $first = null, $second = null)
    {
        if (is_string($model)) {
            /** @var  Models $model */
            $model = new $model;
        }

        if (!$model instanceof Models) {
            throw new \InvalidArgumentException(sprintf(
                'Expected 1 parameter of %s to be string or %s instance, %s given.',
                __FUNCTION__,
                static::class,
                gettype($model)
            ));
        }

        if (null === $first) {
            $first = $this->primary();
        }

        if (null === $second) {
            $second = $this->table().'_'.$model->primary();
        }

        return [$model, $this->table().'.'.$first, $model->table().'.'.$second];
    }
1042350
protected function createSyncModel( SyncService $service, ActiveRecord $model, array $data = array() ) {

        $syncModel             = new SyncModel();
        $syncModel->attributes = [
            'model_id'          => $model->getPrimaryKey(),
            'service_name'      => $service->getName(),
            'service_id_author' => $data['service_id_author'],
            'service_id_post'   => $data['service_id_post'],
            'time_created'      => ! empty( $data['time_created'] ) ? $data['time_created'] : time(),
        ];

        $flag = $syncModel->save();

        if ( $syncModel->hasErrors() ) {
            throw new InvalidConfigException( Yii::t( 'SyncSocial', 'Wrong sync model configuration for SyncSocial extension' ) );
        }

        return $flag;
    }
1276735
protected function findRecord($model, $attributes = [])
    {
        $this->getModelRecord($model);
        $conditions = [];
        $bind       = [];
        foreach ($attributes as $key => $value) {
            if ($value === null) {
                $conditions[] = "$key IS NULL";
            } else {
                $conditions[] = "$key = :$key:";
                $bind[$key] = $value;
            }
        }
        $query = implode(' AND ', $conditions);
        $this->debugSection('Query', $query);
        return call_user_func_array([$model, 'findFirst'], [
            [
                'conditions' => $query,
                'bind'       => $bind,
            ]
        ]);
    }
1081644
private function executeMigration(
        array $migrationsToExecute,
        string $direction,
        MigratorConfiguration $migratorConfiguration
    ) : array {
        $dryRun = $migratorConfiguration->isDryRun();

        $connection = $this->configuration->getConnection();

        $allOrNothing = $migratorConfiguration->isAllOrNothing();

        if ($allOrNothing) {
            $connection->beginTransaction();
        }

        try {
            $this->configuration->dispatchMigrationEvent(Events::onMigrationsMigrating, $direction, $dryRun);

            $sql  = [];
            $time = 0;

            foreach ($migrationsToExecute as $version) {
                $versionExecutionResult = $version->execute($direction, $migratorConfiguration);

                // capture the to Schema for the migration so we have the ability to use
                // it as the from Schema for the next migration when we are running a dry run
                // $toSchema may be null in the case of skipped migrations
                if (! $versionExecutionResult->isSkipped()) {
                    $migratorConfiguration->setFromSchema($versionExecutionResult->getToSchema());
                }

                $sql[$version->getVersion()] = $versionExecutionResult->getSql();
                $time                       += $versionExecutionResult->getTime();
            }

            $this->configuration->dispatchMigrationEvent(Events::onMigrationsMigrated, $direction, $dryRun);
        } catch (Throwable $e) {
            if ($allOrNothing) {
                $connection->rollBack();
            }

            throw $e;
        }

        if ($allOrNothing) {
            $connection->commit();
        }

        return $sql;
    }
609405
public function check($model)
    {
        $moderated = false;

        foreach ($model->getModerateList() as $id => $moderation) {
            $rules = explode('|', $moderation);

            foreach ($rules as $rule) {
                $action = explode(':', $rule);
                $options = isset($action[1]) ? $action[1] : null;

                $method = $action[0];
                if ($this->$method($model->$id, $options)) {
                    return $moderated = true;
                }
            }

            // No reason to keep going
            if ($moderated === true) {
                return $moderated;
            }
        }

        return $moderated;
    }
31207
public function createDataProvider($modelForm)
    {
        $query = new Query;
        $this->prepareCondition($query, $modelForm);
        $count = $query->from("audits.{$modelForm->table}")->count();
        $query = new Query;
        $this->prepareCondition($query, $modelForm);
        $columns = $this->getRelations($query, $modelForm->table);
        $columns[] = 'audit.*';

        $query->select(join(', ', $columns))->from("audits.{$modelForm->table} audit");
        $dataProvider = new \yii\data\ActiveDataProvider([
            'query' => $query,
            'totalCount' => $count,
            'sort' => [
                'attributes' => ['operation_date'],
            ],
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);
        return $dataProvider;
    }
324080
public function handleImageRules($model, $rules)
    {

        // If the model is an image, the rules were passed in by NestedModels
        // and are good to go
        if (is_a($model, Image::class)) {
            return $rules;
        }

        // Otherwise, remove any image rules because this is a non-Image and
        // these rules will get applied by NestedModels
        return array_where($rules, function ($val, $key) {
            return !starts_with($key, 'images.');
        });
    }
1133841
protected function getCleanLog(Model $Model)
	{
		$ds = $Model->getDataSource();
		$queries = array();

		if (method_exists($ds, 'getLog')) {
			$log = $ds->getLog(false, false);
			$diff = Set::diff($log['log'], $this->cachedQueries);

			$this->cachedQueries = $log['log'];

			foreach ($diff as $entry) {
				if (empty($entry['affected'])) {
					continue;
				}

				$queries[] = $entry['query'];
			}
		}

		return $queries;
	}
1233565
private function eventQuery(string $direction)
    {
        return DB::table('dates')
            ->select(['d_gid as id', 'd_year as year', 'd_fact AS fact', 'd_type AS type'])
            ->where('d_file', '=', $this->tree->id())
            ->where('d_gid', '<>', 'HEAD')
            ->whereIn('d_fact', $this->getCommonFacts())
            ->where('d_julianday1', '<>', 0)
            ->orderBy('d_julianday1', $direction)
            ->orderBy('d_type')
            ->first();
    }
628502
protected static function getModelsForRelation($model, $relationKey)
    {
        if (!method_exists($model, $relationKey)) {
            throw new Exception(
                    'Relation "' . $relationKey . '" does not exist in model',
                    static::ERROR_SCOPE | static::ERROR_UNKNOWN_ID,
                    BaseResponse::HTTP_INTERNAL_SERVER_ERROR
                );
        }
        $relationModels = $model->{$relationKey};
        if (is_null($relationModels)) {
            return null;
        }

        if (! $relationModels instanceof Collection) {
            return [ $relationModels ];
        }

        return $relationModels;
    }