/** * @param ActiveRecord $model * @param array $actions Custom actions array in the form of * ```php * 'name' => function() { * * } * ``` * @param bool $addDefaultActions If true default actions will be added * @return \yii\web\Response * @throws BadRequestHttpException */ protected function getCreateUpdateResponse($model, $actions = [], $addDefaultActions = true) { $defaultActions = [AdminHtml::ACTION_SAVE_AND_STAY => function () use($model) { /** @var Controller | CrudControllerTrait $this */ return $this->redirect(['update', 'id' => $model->getPrimaryKey()]); }, AdminHtml::ACTION_SAVE_AND_CREATE => function () use($model) { /** @var Controller | CrudControllerTrait $this */ if ($url = Url::previous($this->createUrlParam)) { Url::remember(null, $this->createUrlParam); return $this->redirect($url); } return $this->redirect(['create']); }, AdminHtml::ACTION_SAVE_AND_LEAVE => function () use($model) { /** @var Controller | CrudControllerTrait $this */ if ($url = \Yii::$app->request->get('return')) { return $this->redirect($url); } if ($url = Url::previous($this->indexUrlParam)) { Url::remember(null, $this->indexUrlParam); return $this->redirect($url); } return $this->redirect(['index']); }]; if ($addDefaultActions) { $actions = array_merge($defaultActions, $actions); } $actionName = \Yii::$app->request->post(AdminHtml::ACTION_BUTTON_NAME, AdminHtml::ACTION_SAVE_AND_LEAVE); if (isset($actions[$actionName])) { return call_user_func($actions[$actionName]); } else { throw new BadRequestHttpException('Unknown action: ' . $actionName); } }
/** * @param integer $type * @param \yii\db\ActiveRecord $object */ public function run($type, $object) { $pkey = $object->primaryKey(); $pkey = $pkey[0]; $data = ['table' => $object->tableName(true), 'model_id' => $object->getPrimaryKey(), 'type' => $type, 'date' => date('Y-m-d H:i:s', time())]; switch ($type) { case self::EVT_INSERT: $data['field_name'] = $pkey; $this->saveField($data); break; case self::EVT_UPDATE: foreach ($this->updatedFields as $updatedFieldKey => $updatedFieldValue) { $data['field_name'] = $updatedFieldKey; $data['old_value'] = $updatedFieldValue; $data['new_value'] = $object->{$updatedFieldKey}; $this->saveField($data); } break; case self::EVT_DELETE: $data['field_name'] = $pkey; $this->saveField($data); break; case self::EVT_UPDATE_PK: $data['field_name'] = $pkey; $data['old_value'] = $object->getOldPrimaryKey(); $data['new_value'] = $object->{$pkey}; $this->saveField($data); break; } }
/** * @param $direction string * @param $model ActiveRecord * @return array */ protected function getUrl($direction, ActiveRecord $model) { $url = !empty($this->url) ? $this->url : ['order']; $url['direction'] = $direction; $url['attribute'] = $this->attribute; $url['id'] = $model->getPrimaryKey(); return $url; }
public function run() { $buttons = []; $translations = $this->model->translations; foreach ($translations as $translationModel) { /** @var ActiveRecord | TranslatableInterface $translationModel */ // if ($translationModel->equals($this->model)) continue; $lang = $translationModel->language; $buttons[$lang] = Html::a($lang, ['update', 'id' => $translationModel->getPrimaryKey()], ['class' => 'btn btn-xs' . ($this->model->language == $lang ? ' btn-primary' : ' btn-default'), 'data-pjax' => '0']); } $unsupportedLanguages = array_diff(Yii::$app->acceptedLanguages, array_keys($buttons)); foreach ($unsupportedLanguages as $lang) { $buttons[$lang] = Html::a($lang, ['create', 'language' => $lang, 'sourceId' => $this->model->getPrimaryKey()], ['class' => 'btn btn-danger btn-xs', 'data-pjax' => '0']); } ksort($buttons); return implode(' ', $buttons); }
/** * @param ActiveRecord $activeRecord * @param $attribute * @param null $extension * * @return string */ public function getFilenameFor($activeRecord, $attribute, $extension = null) { $path = Inflector::camel2id((new \ReflectionClass($activeRecord))->getShortName()); $basename = implode('-', $activeRecord->getPrimaryKey(true)) . '-' . $attribute; if ($extension) { $basename .= '.' . $extension; } return $path . DIRECTORY_SEPARATOR . $basename; }
/** Render widget */ public function run() { if ($this->apiRoute === null) { throw new Exception('$apiRoute must be set.', 500); } $images = array(); foreach ($this->behavior->getImages() as $image) { $images[] = array('id' => $image->id, 'rank' => $image->rank, 'name' => (string) $image->name, 'description' => (string) $image->description, 'preview' => $image->getUrl('preview')); } $baseUrl = [$this->apiRoute, 'type' => $this->behavior->type, 'behaviorName' => $this->behaviorName, 'galleryId' => $this->model->getPrimaryKey()]; $opts = array('hasName' => $this->behavior->hasName ? true : false, 'hasDesc' => $this->behavior->hasDescription ? true : false, 'uploadUrl' => Url::to($baseUrl + ['action' => 'ajaxUpload']), 'deleteUrl' => Url::to($baseUrl + ['action' => 'delete']), 'updateUrl' => Url::to($baseUrl + ['action' => 'changeData']), 'arrangeUrl' => Url::to($baseUrl + ['action' => 'order']), 'nameLabel' => Yii::t('bupy7/gallery/manager/core', 'Name'), 'descriptionLabel' => Yii::t('bupy7/gallery/manager/core', 'Description'), 'photos' => $images); $opts = Json::encode($opts); $view = $this->getView(); GalleryManagerAsset::register($view); $view->registerJs("\$('#{$this->id}').galleryManager({$opts});"); $this->options['id'] = $this->id; $this->options['class'] = 'gallery-manager'; return $this->render('manager'); }
/** * Initialize widget with default options. * * @throws \yii\base\InvalidConfigException */ public function initDefaults() { $this->voteUrl = isset($this->voteUrl) ?: Yii::$app->getUrlManager()->createUrl(['vote/default/vote']); $this->targetId = isset($this->targetId) ?: $this->model->getPrimaryKey(); if (!isset($this->aggregateModel)) { $this->aggregateModel = $this->isBehaviorIncluded() ? $this->model->getVoteAggregate($this->entity) : VoteAggregate::findOne(['entity' => $this->getModule()->encodeEntity($this->entity), 'target_id' => $this->targetId]); } if (!isset($this->userValue)) { $this->userValue = $this->isBehaviorIncluded() ? $this->model->getUserValue($this->entity) : null; } }
/** * Append to operation internal handler * @param bool $append * @throws Exception */ protected function insertIntoInternal($append) { $this->checkNode(false); $this->owner->setAttribute($this->parentAttribute, $this->node->getPrimaryKey()); if ($this->sortable !== false) { if ($append) { $this->owner->moveLast(); } else { $this->owner->moveFirst(); } } }
/** Render widget */ public function run() { if ($this->apiRoute === null) { throw new Exception('$apiRoute must be set.', 500); } $images = array(); foreach ($this->behavior->getImages($this->sort) as $image) { $images[] = array('id' => $image->id, 'rank' => $image->rank, 'preview' => $image->getUrl('preview')); } $baseUrl = [$this->apiRoute, 'type' => $this->behavior->type, 'behaviorName' => $this->behaviorName, 'galleryId' => $this->model->getPrimaryKey()]; $opts = array('uploadUrl' => Url::to($baseUrl + ['action' => 'ajaxUpload']), 'deleteUrl' => Url::to($baseUrl + ['action' => 'delete']), 'updateUrl' => Url::to($baseUrl + ['action' => 'changeData']), 'arrangeUrl' => Url::to($baseUrl + ['action' => 'order']), 'photos' => $images, 'prepend' => $this->prepend); $opts = Json::encode($opts); $view = $this->getView(); GalleryManagerAsset::register($view); $view->registerJs("(function(){\$('#{$this->id}').galleryManager({$opts});})();", \yii\web\View::POS_READY); $this->options['id'] = $this->id; $this->options['class'] = 'gallery-manager'; if ($this->view) { return $this->render($this->view); } return $this->render('galleryManager'); }
/** * Loads a specific translation model * * @param string $language the language to return * * @return null|\yii\db\ActiveQuery|static */ private function getNewTranslation($language) { $translation = null; /** @var \yii\db\ActiveQuery $relation */ $relation = $this->owner->getRelation($this->relation); /** @var ActiveRecord $class */ $class = $relation->modelClass; //if ($translation === null) { $translation = new $class(); $translation->{key($relation->link)} = $this->owner->getPrimaryKey(); $translation->{$this->languageAttribute} = $language; //} return $translation; }
/** * Deletes this notification */ public function delete(\humhub\modules\user\models\User $user = null) { $condition = []; $condition['class'] = $this->className(); if ($user !== null) { $condition['user_id'] = $user->id; } if ($this->originator !== null) { $condition['originator_user_id'] = $this->originator->id; } if ($this->source !== null) { $condition['source_pk'] = $this->source->getPrimaryKey(); $condition['source_class'] = $this->source->className(); } Notification::deleteAll($condition); }
/** * Creates an activity * * @throws \yii\base\Exception */ public function create() { if ($this->moduleId == "") { throw new \yii\base\InvalidConfigException("No moduleId given!"); } if (!$this->source instanceof \yii\db\ActiveRecord) { throw new \yii\base\InvalidConfigException("Invalid source object given!"); } $model = new Activity(); $model->class = $this->className(); $model->module = $this->moduleId; $model->content->visibility = $this->visibility; $model->object_model = $this->source->className(); $model->object_id = $this->source->getPrimaryKey(); // Automatically determine content container if ($this->container == null) { if ($this->source instanceof ContentActiveRecord || $this->source instanceof ContentAddonActiveRecord) { $this->container = $this->source->content->container; // Take visibility from Content/Addon $model->content->visibility = $this->source->content->visibility; } elseif ($this->source instanceof ContentContainerActiveRecord) { $this->container = $this->source; } else { throw new \yii\base\InvalidConfigException("Could not determine content container for activity!"); } } $model->content->container = $this->container; // Automatically determine originator - if not set if ($this->originator !== null) { $model->content->user_id = $this->originator->id; } elseif ($this->source instanceof ContentActiveRecord) { $model->content->user_id = $this->source->content->user_id; } elseif ($this->source instanceof ContentAddonActiveRecord) { $model->content->user_id = $this->source->created_by; } else { throw new \yii\base\InvalidConfigException("Could not determine originator for activity!"); } if (!$model->validate() || !$model->save()) { throw new \yii\base\Exception("Could not save activity!" . $model->getErrors()); } }
/** * @param $position * @return bool * @throws \yii\db\Exception */ public function insertTo($position) { if ($this->getValue() == $position) { return true; } // 59 -> 56 = 58 57 56 // 56 -> 59 = 57 58 59 $start = $this->getValue(); $end = $position; if ($start == null || $start == 0) { $this->setInsertSort(); $this->owner->save(); return true; } $direction = $start > $end ? static::DirectionDown : static::DirectionUp; $query = $this->getQuery(); $query->andWhere(['between', $this->attributeName, min($start, $end), max($start, $end)]); $query->getSortBehavior()->sort(); /** * @var ISortableActiveRecord[]|ActiveRecord[] $items */ $items = $query->all(); $transaction = $this->owner->getDb()->beginTransaction(); try { foreach ($items as $index => $item) { if ($item->getPrimaryKey() == $this->owner->getPrimaryKey()) { $item->getSortBehavior()->setSort($position); $item->save(); } else { $item->getSortBehavior()->setSort($item->getSortBehavior()->getValue() + ($direction == static::DirectionDown ? 1 : -1)); $item->save(); } } /* @TODO сделать фикс позиций, что бы не перескакивало и не было дублей */ $transaction->commit(); } catch (\Exception $ex) { $transaction->rollBack(); return false; } return true; }
/** * Save related model * * @param array $translations * * @since 2.0.0 * @throws NotFoundHttpException */ private function saveTranslations($translations = []) { /** @var ActiveRecord $owner */ /** @var ActiveRecord $translation */ foreach ($this->availableLanguages as $language) { if (!isset($translations[$language])) { $translation = new $this->translateClassName(); $translation->{$this->languageField} = $language; $translation->{$this->translateForeignKey} = $this->owner->getPrimaryKey(); } else { $translation = $translations[$language]; } foreach ($this->attributes as $attribute) { $value = $this->getTranslateAttribute($attribute, $language); if ($value !== null) { $translation->{$attribute} = $value; } } $translation->save(); } }
public function run() { return ModalIFrame::widget(['modalOptions' => ['header' => Yii::t('gromver.platform', 'Item Versions Manager - "{title}" (ID:{id})', ['title' => $this->model->title, 'id' => $this->model->getPrimaryKey()]), 'size' => Modal::SIZE_LARGE], 'buttonContent' => Html::a('<i class="glyphicon glyphicon-hdd"></i> ' . Yii::t('gromver.platform', 'Versions'), ['/grom/version/default/item', 'item_id' => $this->model->getPrimaryKey(), 'item_class' => $this->model->className()], ['class' => 'btn btn-default btn-sm'])]); }
/** * @param SyncService $service * @param ActiveRecord $model * @param array $data * * @return bool * @throws Exception */ 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; }
/** * @param \yii\db\ActiveRecord $model * @param \yii\db\ActiveRecord $relatedModel * @param \yii\db\ActiveQuery $relation * @return array array with three arrays: create, search and index routes */ public static function getRelationRoutes($model, $relatedModel, $relation) { if (($route = Yii::$app->crudModelsMap[$relatedModel::className()]) === null) { return [null, null, null]; } $allowCreate = Yii::$app->user->can($relatedModel::className() . '.create'); if ($allowCreate && $model->isNewRecord && $relation->multiple) { foreach ($relation->link as $left => $right) { if (!$relatedModel->getTableSchema()->getColumn($left)->allowNull) { $allowCreate = false; break; } } } if (!$allowCreate) { $createRoute = null; } else { $createRoute = [$route . '/update']; if ($relation->multiple) { $createRoute['hide'] = implode(',', array_keys($relation->link)); $scope = $relatedModel->formName(); $primaryKey = $model->getPrimaryKey(true); foreach ($relation->link as $left => $right) { if (!isset($primaryKey[$right])) { continue; } $createRoute[$scope][$left] = $primaryKey[$right]; } } } $parts = explode('\\', $relatedModel::className()); $relatedModelClass = array_pop($parts); $relatedSearchModelClass = implode('\\', $parts) . '\\search\\' . $relatedModelClass; $searchRoute = !class_exists($relatedSearchModelClass) ? null : [$route . '/relation', 'per-page' => 10, 'relation' => $relation->inverseOf, 'id' => Action::exportKey($model->getPrimaryKey()), 'multiple' => $relation->multiple ? 'true' : 'false']; $indexRoute = [$route . '/index']; return [$createRoute, $searchRoute, $indexRoute]; }
/** * @param \yii\db\ActiveRecord $model */ public function addDirtyModel($model) { // --- debug - start ------------------------------------------------------ // make sure there's always only one instance referencing a DB record $dsn = $model->getDb()->dsn; $table = $model->tableName(); $pk = $model->getPrimaryKey(); $modelId = "{$dsn}:{$table}:{$pk}"; if (array_key_exists($modelId, $this->_dirtyModelsInfo)) { $storedModel = $this->_dirtyModelsInfo[$modelId]; if ($storedModel !== $model) { throw new \yii\base\NotSupportedException("Can't handle two instances for tabel '{$table}', id '{$pk}' (dsn '{$dsn}')."); } } $this->_dirtyModelsInfo[$modelId] = $model; // --- debug - end -------------------------------------------------------- $this->_dirtyModels->attach($model); }
/** * @return string */ public function getAttributeName() { return $this->owner->fieldPrefix . strval($this->attributeModel->getPrimaryKey()); }
/** * Converts a model's (composite) primary key to string. * @param ActiveRecord $model model * @return string serialized primary key * @internal */ private function serializeKey(&$model) { return serialize($model->getPrimaryKey()); }
/** * @param string $modelClass * @param ActiveRecord $model * @param ActionSearch $searchModel * @param array $tablesMap * @return SqlDataProvider */ private static function getKeysDataprovider($modelClass, $model, $searchModel, $tablesMap) { /** @var \yii\db\ActiveRecord $staticModel */ $staticModel = new $modelClass(); /** @var TrackableBehavior $behavior */ $behavior = $staticModel->getBehavior('trackable'); $conditions = ['AND', 'a.statement_only = FALSE', ['IN', '(a.relation_id::regclass)', array_keys($tablesMap['related'])]]; $params = []; if ($model !== null) { $conditions[] = "a.row_data @> (:key)::jsonb"; $params[':key'] = json_encode($model->getPrimaryKey(true)); } if ($searchModel !== null) { list($conditions, $params) = $searchModel->getConditions($conditions, $params, $tablesMap['all']); } $subQuery = (new Query())->select(['key_type' => new Expression("'c'"), 'id' => 'a.changeset_id', 'action_date' => 'MAX(a.action_date)'])->from($behavior->auditTableName . ' a')->where($conditions)->andWhere("key_type = 'c'")->groupBy('changeset_id')->union((new Query())->select(['key_type' => new Expression("'t'"), 'id' => 'a.transaction_id', 'action_date' => 'MAX(a.action_date)'])->from($behavior->auditTableName . ' a')->where($conditions)->andWhere("key_type = 't'")->groupBy('transaction_id'), true)->union((new Query())->select(['key_type' => new Expression("'a'"), 'id' => 'a.action_id', 'action_date' => 'a.action_date'])->from($behavior->auditTableName . ' a')->where($conditions)->andWhere("key_type = 'a'"), true); $query = (new Query())->select(['key_type', 'id'])->from(['a' => $subQuery]); $query->addParams($params); $countQuery = clone $query; $countQuery->select(['COUNT(DISTINCT ROW(a.key_type, a.id))']); $countQuery->groupBy([]); $command = $query->orderBy('a.action_date DESC')->createCommand($staticModel->getDb()); return new SqlDataProvider(['sql' => $command->getSql(), 'params' => $command->params, 'totalCount' => $countQuery->scalar($staticModel->getDb()), 'pagination' => ['pageSize' => 20], 'key' => function ($model) { return $model['key_type'] . $model['id']; }]); }
/** * Returns all files belongs to a given HActiveRecord Object. * @todo Add chaching * * @param HActiveRecord $object * @return Array of File instances */ public static function getFilesOfObject(\yii\db\ActiveRecord $object) { return self::findAll(array('object_id' => $object->getPrimaryKey(), 'object_model' => $object->className())); }
/** * Creates a login history entry. * * @param ActiveRecord $account account instance. * @param boolean $success whether login was successful. */ protected function createHistoryEntry(ActiveRecord $account, $success) { $dataContract = Module::getInstance()->getDataContract(); $dataContract->createLoginHistory(['accountId' => $account->getPrimaryKey(), 'success' => $success, 'numFailedAttempts' => $success ? 0 : $dataContract->getAccountNumFailedLoginAttempts($account)]); }
/** * Destroys the relationship between two models. * * The model with the foreign key of the relationship will be deleted if `$delete` is true. * Otherwise, the foreign key will be set null and the model will be saved without validation. * * @param string $name the case sensitive name of the relationship. * @param ActiveRecord $model the model to be unlinked from the current one. * @param boolean $delete whether to delete the model that contains the foreign key. * If false, the model's foreign key will be set null and saved. * If true, the model containing the foreign key will be deleted. * @throws InvalidCallException if the models cannot be unlinked */ public function unlink($name, $model, $delete = false) { $relation = $this->getRelation($name); if ($relation->via !== null) { if (is_array($relation->via)) { /** @var ActiveRelation $viaRelation */ list($viaName, $viaRelation) = $relation->via; $viaClass = $viaRelation->modelClass; unset($this->_related[$viaName]); } else { $viaRelation = $relation->via; $viaTable = reset($relation->via->from); } $columns = []; foreach ($viaRelation->link as $a => $b) { $columns[$a] = $this->{$b}; } foreach ($relation->link as $a => $b) { $columns[$b] = $model->{$a}; } if (is_array($relation->via)) { /** @var $viaClass ActiveRecord */ if ($delete) { $viaClass::deleteAll($columns); } else { $nulls = []; foreach (array_keys($columns) as $a) { $nulls[$a] = null; } $viaClass::updateAll($nulls, $columns); } } else { /** @var $viaTable string */ $command = static::getDb()->createCommand(); if ($delete) { $command->delete($viaTable, $columns)->execute(); } else { $nulls = []; foreach (array_keys($columns) as $a) { $nulls[$a] = null; } $command->update($viaTable, $nulls, $columns)->execute(); } } } else { $p1 = $model->isPrimaryKey(array_keys($relation->link)); $p2 = $this->isPrimaryKey(array_values($relation->link)); if ($p1 && $p2 || $p2) { foreach ($relation->link as $a => $b) { $model->{$a} = null; } $delete ? $model->delete() : $model->save(false); } elseif ($p1) { foreach ($relation->link as $b) { $this->{$b} = null; } $delete ? $this->delete() : $this->save(false); } else { throw new InvalidCallException('Unable to unlink models: the link does not involve any primary key.'); } } if (!$relation->multiple) { unset($this->_related[$name]); } elseif (isset($this->_related[$name])) { /** @var ActiveRecord $b */ foreach ($this->_related[$name] as $a => $b) { if ($model->getPrimaryKey() == $b->getPrimaryKey()) { unset($this->_related[$name][$a]); } } } }
public static function getBs(ActiveRecord $a) { /** * @var $class ActiveRecord */ $class = static::bClass(); $classPk = $class::primaryKey()[0]; $pivId = static::bIdAttr(); $r = $class::find()->leftJoin(static::tableName() . ' p', "{{{$classPk}}}={{p}}.{{{$pivId}}}")->where([static::aIdAttr() => $a->getPrimaryKey()]); $r->multiple = true; if (static::bOrderAttr() !== false) { $r->orderBy(static::bOrderAttr()); } return $r; }
/** * Attaches a given list of files to an record (HActiveRecord). * This is used when uploading files before the record is created yet. * * @param \yii\db\ActiveRecord $object is a HActiveRecord * @param string $files is a comma seperated list of newly uploaded file guids */ public static function attachPrecreated($object, $files) { if (!$object instanceof \yii\db\ActiveRecord) { throw new Exception('Invalid object given - require instance of \\yii\\db\\ActiveRecord!'); } // Attach Files foreach (explode(",", $files) as $fileGuid) { $file = self::findOne(['guid' => trim($fileGuid)]); if ($file != null && $file->object_model == "") { $file->object_model = $object->className(); $file->object_id = $object->getPrimaryKey(); if (!$file->save()) { throw new Exception("Could not save precreated file!"); } } } }
/** * Returns a value indicating whether the given active record is the same as the current one. * The comparison is made by comparing the table names and the primary key values of the two active records. * If one of the records [[isNewRecord|is new]] they are also considered not equal. * @param ActiveRecord $record record to compare to * @return boolean whether the two active records refer to the same row in the same database table. */ public function equals($record) { if ($this->isNewRecord || $record->isNewRecord) { return false; } return $this->tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey(); }
public function run() { return \gromver\widgets\ModalIFrame::widget(['options' => $this->options, 'label' => '<i class="glyphicon glyphicon-hdd"></i> ' . Yii::t('gromver.platform', 'Versions'), 'url' => ['/grom/version/backend/default/item', 'item_id' => $this->model->getPrimaryKey(), 'item_class' => $this->model->className()]]); }
/** * Creates a password history entry. * * @param Account $account model instance. */ public function createHistoryEntry(ActiveRecord $account) { Module::getInstance()->getDataContract()->createPasswordHistory(['accountId' => $account->getPrimaryKey(), 'password' => $account->password]); }
/** * Called after successful {@link performTransition()} execution. * @param \yii\db\ActiveRecord $model */ public function afterTransition($model) { $id = $this->exportKey($model->getPrimaryKey(true)); $response = Yii::$app->getResponse(); $response->setStatusCode(201); $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true)); }