public static function showed(Event $event) { /** * @var $request Request */ $q = self::find(); $request = Yii::$app->request; if ($request->getIsRobot()) { return null; } $ip = Yii::$app->request->getUserIP() ? ip2long(Yii::$app->request->getUserIP()) : null; $userId = !Yii::$app->user->isGuest ? Yii::$app->user->id : null; if (!$ip) { return false; } $q->where(['and', ['or', ['=', 'ip', $ip], ['=', 'user_id', $userId]], ['=', 'event_id', $event->id]]); if (!$q->exists()) { $obj = new static(); $obj->ip = $ip; $obj->user_id = $userId; $obj->event_id = $event->id; $obj->referrer = $request->getReferrer(); return $obj->insert(false); } return false; }
/** * Clone an item. Data from $values takes precedence of data from cloned object. * * @param unknown_type $mapper * @param unknown_type $values * @param unknown_type $options */ public function saveAs($document = array(), $options = array()) { $item_data = $this->cast(); // preserve any key=>values from the original item that are not in the new document array $new_values = array_merge($document, array_diff_key($item_data, $document)); unset($new_values[$this->getItemKey()]); if ($existing = $this->pathExists($this->path)) { if ($new_values['title'] == $existing->title) { //THEY CHANGED THE TITLE SO lets unset slug and path and regenerate unset($new_values['slug']); unset($new_values['path']); } else { //Set path to something like string/string-2 $i = 2; do { $new_values['slug'] = $new_values['slug'] . '-' . $i; $new_values['path'] = $this->path . '-' . $i; if ($this->pathExists($new_values['path'])) { $i++; } else { $i = false; } } while ($i); } if ($new_values['details']['url'] == $existing->{'details.url'}) { //TODO I am not sure if we should append this as well or just alert them, I assume they would clone it to make a simliar URL so adding text to it could be annoying \Dsc\System::instance()->addMessage('Item shares a URL with another menu Item be sure to change it', 'warning'); } } $item = new static($new_values); return $item->insert(array(), $options); }
/** * * @param TypeDoc $type * @param $version */ public static function createRecord($type, $version) { /** @var SearchApiType $model */ $model = new static(); $model->version = $version; $model->name = $type->name; $model->namespace = $type->namespace; $model->shortDescription = $type->shortDescription; $model->description = $type->description; $model->since = $type->since; $model->deprecatedSince = $type->deprecatedSince; $model->deprecatedReason = $type->deprecatedReason; if ($type instanceof ClassDoc) { $model->type = 'class'; } elseif ($type instanceof InterfaceDoc) { $model->type = 'interface'; } elseif ($type instanceof TraitDoc) { $model->type = 'trait'; } $model->insert(false); if ($type->methods !== null) { foreach ($type->methods as $method) { if ($method->visibility === 'private') { continue; } SearchApiPrimitive::createRecord($model, $method, $version); } } if ($type->properties !== null) { foreach ($type->properties as $property) { if ($property->visibility === 'private') { continue; } SearchApiPrimitive::createRecord($model, $property, $version); } } if ($type instanceof ClassDoc) { foreach ($type->constants as $const) { SearchApiPrimitive::createRecord($model, $const, $version); } foreach ($type->events as $event) { SearchApiPrimitive::createRecord($model, $event, $version); } } }
/** * Приивязывает теги к элементам * @param Event| $obj Связывает данные модели в БД с тегом, зависит от класса переданной модели * @param array [string] $tags Массив с тегами, * @return int * @throws \Exception * @throws \yii\db\Exception */ public static function bind($obj, array $tags) { /** * @var \common\models\Tag[] $existsTag */ $tagsS = static::filter($tags); $tags = []; foreach ($tagsS as $tag) { $tags[mb_strtolower($tag)] = $tag; } if (empty($tags)) { return false; } $existsTag = static::find()->where(['name' => array_values($tags)])->all(); if ($obj instanceof Event) { // если тэг привязываем к событию(в будущем возможно теги будем привязывать к другим сущностям) $updatedTag = []; $rows = []; //сначала записываем существующие теги foreach ($existsTag as $ex) { $updatedTag[] = $ex->id; unset($tags[mb_strtolower($ex->name)]); $rows[] = [$ex->id, $obj->id]; } foreach ($tags as $tag) { $tagModel = new static(['name' => $tag]); $tagModel->insert(); if ($tagModel->id) { $rows[] = [$tagModel->id, $obj->id]; } } if (!empty($updatedTag)) { Yii::$app->db->createCommand('UPDATE tag SET popularity=popularity+1 WHERE id IN (' . implode(',', $updatedTag) . ')')->execute(); } return Yii::$app->db->createCommand()->batchInsert(TagEvent::tableName(), ['tag_id', 'event_id'], $rows)->execute(); } }
/** * * @param ApiType $parent * @param MethodDoc|PropertyDoc|ConstDoc|EventDoc $primitive * @param $version */ public static function createRecord($parent, $primitive, $version) { /** @var SearchApiPrimitive $model */ $model = new static(); $model->version = $version; $model->name = $primitive->name; $model->parentId = $parent->getPrimaryKey(); $model->shortDescription = $primitive->shortDescription; $model->description = $primitive->description; $model->since = $primitive->since; $model->deprecatedSince = $primitive->deprecatedSince; $model->deprecatedReason = $primitive->deprecatedReason; $model->definedBy = $primitive->definedBy; if ($primitive instanceof MethodDoc) { $model->type = 'method'; $model->visibility = $primitive->visibility; $model->isStatic = $primitive->isStatic; $model->isAbstract = $primitive->isAbstract; $model->isFinal = $primitive->isFinal; $params = []; foreach ($primitive->params as $param) { $params[] = ['name' => $param->name, 'description' => $param->description, 'isOptional' => $param->isOptional, 'defaultValue' => $param->defaultValue, 'isPassedByReference' => $param->isPassedByReference, 'typeHint' => $param->typeHint, 'types' => $param->types]; } $model->params = $params; $exceptions = []; foreach ($primitive->exceptions as $name => $description) { $exceptions[] = ['name' => $name, 'description' => $description]; } $model->exceptions = $exceptions; $model->return = $primitive->return; $model->returnTypes = $primitive->returnTypes; $model->isReturnByReference = $primitive->isReturnByReference; } elseif ($primitive instanceof PropertyDoc) { $model->type = 'property'; $model->writeOnly = $primitive->isWriteOnly; $model->readOnly = $primitive->isReadOnly; $model->types = $primitive->types; $model->defaultValue = $primitive->defaultValue; $model->setter = $primitive->setter ? $primitive->setter->name : null; $model->getter = $primitive->getter ? $primitive->getter->name : null; } elseif ($primitive instanceof ConstDoc) { $model->type = 'const'; $model->value = $primitive->value; } elseif ($primitive instanceof EventDoc) { $model->type = 'event'; $model->value = $primitive->value; } $model->insert(false, null, ['op_type' => 'create', 'parent' => $model->parentId]); }
/** * @param \nodge\eauth\ServiceBase $service * @return User * @throws ErrorException */ public static function findByEAuth($service) { if (!$service->getIsAuthenticated()) { throw new ErrorException('Авторизован.'); } /** * @var $social UserSocial * @var $socialOth UserSocial */ $email = $service->getAttribute('email'); $social = UserSocial::findOne(['service' => $service->getServiceName(), 'service_id' => "{$service->getId()}"]); if ($social) { return $social->user; } $socialOth = $email ? UserSocial::findOne(['email' => $email]) : false; $user = User::findOne(['email' => $email]); if (!$user) { if (!$socialOth) { $user = new static(['username' => $service->getAttribute('name'), 'email' => $email, 'auth_key' => Yii::$app->security->generateRandomString()]); $user->insert(false); } else { $user = $socialOth->user; } } $social = new UserSocial(['service' => $service->getServiceName(), 'service_id' => $service->getId(), 'user_id' => $user->id, 'email' => $user->email]); $social->insert(false); return $user; }
/** * Clone an item. Data from $values takes precedence of data from cloned object. * * @param unknown_type $mapper * @param unknown_type $values * @param unknown_type $options */ public function saveAs($document = array(), $options = array()) { $item_data = $this->cast(); // preserve any key=>values from the original item that are not in the new document array $new_values = array_merge($document, array_diff_key($item_data, $document)); unset($new_values[$this->getItemKey()]); $item = new static($new_values); return $item->insert(array(), $options); }
/** * Create table rows in bulk mode. * * @param array $batch and array of column-value pairs. * @return int The number of affected rows. * @throws Zend_Db_Adapter_Exception */ public static function bulkInsert(array $batch) { $table = new static(); if (1 === sizeof($batch)) { return $table->insert(array_shift($batch)); } $adapter = $table->getAdapter(); $counter = 0; $sqlBinds = []; $values = []; // // Do some voodoo here... foreach ($batch as $i => $row) { $placeholders = []; foreach ($row as $column => $value) { ++$counter; if ($adapter->supportsParameters('positional')) { $placeholders[] = '?'; $values[] = $value; } elseif ($adapter->supportsParameters('named')) { $name = ":col{$i}{$counter}"; $placeholders[] = $name; $values[$name] = $value; } else { throw new Zend_Db_Adapter_Exception(sprintf('%s doesn\'t support positional or named binding', get_class($table))); } } // // and more blacky magic over here... $sqlBinds[] = '(' . implode(',', $placeholders) . ')'; } // // extract column names... $columns = array_keys($row); // // and quoteIdentifier() them. array_walk($columns, function (&$index) use($adapter) { $index = $adapter->quoteIdentifier($index, true); }); // // Shit, shit, shit! F U ZF. $spec = $adapter->quoteIdentifier(($table->_schema ? "{$table->_schema}." : '') . $table->_name); // // Build the SQL using the placeholders... $sql = sprintf('INSERT INTO %s (%s) VALUES %s', $spec, implode(',', $columns), implode(',', $sqlBinds)); // Ready? $stmt = $adapter->prepare($sql); // // Fight! $stmt->execute($values); // // aaaaaaand voilá! return $stmt->rowCount(); }
/** * "Installs" the plugin * @return boolean success */ public static function install() { $plugin = new static(); $plugin->last_cron = 0; $plugin->insert(); }