/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Category::find(); // Подзапрос для получения количества статей в категориях и возможности сортировки по этому параметру $subQuery = Post::find()->select('category_id, count(id) as post_count')->groupBy('category_id'); $query->leftJoin(['postsNum' => $subQuery], 'postsNum.category_id = id'); $query->select('{{%category}}.*, postsNum.post_count'); $dataProvider = new ActiveDataProvider(['query' => $query]); /** * Setup your sorting attributes * Note: This is setup before the $this->load($params) * statement below */ $dataProvider->setSort(['attributes' => ['id', 'parent_id', 'name', 'url', 'category_art', 'add_method', 'postCount' => ['asc' => ['postsNum.post_count' => SORT_ASC], 'desc' => ['postsNum.post_count' => SORT_DESC], 'label' => 'Order Name']]]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } // filter by order amount $query->andFilterWhere(['postsNum.post_count' => $this->postCount]); $query->andFilterWhere(['id' => $this->id, 'parent_id' => $this->parent_id, 'post_num' => $this->post_num, 'category_art' => $this->category_art]); $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'url', $this->url])->andFilterWhere(['like', 'icon', $this->icon])->andFilterWhere(['like', 'description', $this->description])->andFilterWhere(['like', 'meta_title', $this->meta_title])->andFilterWhere(['like', 'meta_descr', $this->meta_descr])->andFilterWhere(['like', 'meta_keywords', $this->meta_keywords])->andFilterWhere(['like', 'post_sort', $this->post_sort])->andFilterWhere(['like', 'short_view', $this->short_view])->andFilterWhere(['like', 'full_view', $this->full_view])->andFilterWhere(['like', 'header', $this->header])->andFilterWhere(['like', 'footer', $this->footer])->andFilterWhere(['like', 'header', $this->add_method]); return $dataProvider; }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Post::find(); $query->with('category'); $dataProvider = new ActiveDataProvider(['query' => $query, 'sort' => ['defaultOrder' => ['date' => SORT_DESC]]]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'author_id' => $this->author_id, 'date' => $this->date, 'category_id' => $this->category_id, 'edit_date' => $this->edit_date, 'edit_user' => $this->edit_user, 'allow_comm' => $this->allow_comm, 'allow_main' => $this->allow_main, 'allow_catlink' => $this->allow_catlink, 'allow_similar' => $this->allow_similar, 'allow_rate' => $this->allow_rate, 'approve' => $this->approve, 'fixed' => $this->fixed, 'category_art' => $this->category_art, 'inm' => $this->inm, 'not_in_related' => $this->not_in_related]); $query->andFilterWhere(['like', 'short', $this->short])->andFilterWhere(['like', 'full', $this->full])->andFilterWhere(['like', 'title', $this->title])->andFilterWhere(['like', 'meta_title', $this->meta_title])->andFilterWhere(['like', 'meta_descr', $this->meta_descr])->andFilterWhere(['like', 'meta_keywords', $this->meta_keywords])->andFilterWhere(['like', 'url', $this->url])->andFilterWhere(['like', 'edit_reason', $this->edit_reason]); return $dataProvider; }
/** * @inheritdoc */ public function run() { // Получаем список из numPosts постов отсортированных по количеству просмотров $posts = Post::find()->where(['!=', 'category_art', '1'])->andWhere(['approve' => '1'])->orderBy(['views' => SORT_DESC])->limit($this->numPosts)->all(); // Если listType не соответствует списку возможных типов из массива _listTypes, присваиваем ему значение по умолчанию if (!in_array($this->listType, $this->_listTypes)) { $this->listType = $this->_defaultListType; } $populars = []; // Пробегаемся по выбранным numPosts постам foreach ($posts as $post) { // Проверяем соответствует ли заголовок статьи максимальной длине (maxTitle). Если нет, укорачиваем его $linkTitle = strlen($post['title']) <= $this->maxTitle ? $post['title'] : $this->cutTitle($post['title']); // Формируем ссылку $link = Html::a($linkTitle, $post->link); // Если популярные статьи нужно выводить в виде тизеров if ($this->tizerStyle) { $postHtml = $post->full; preg_match('/(img|src)=("|\')[^"\'>]+/i', $postHtml, $media); $src = preg_replace('/(img|src)("|\'|="|=\')(.*)/i', "\$3", $media[0]); if (!$src) { $src = '/bw15/images/post_no_image.jpg'; } $image = Html::tag('div', Html::img($src, ['width' => $this->imageWidth]), ['class' => $this->listClass . '_image']); $link = Html::tag('div', $link, ['class' => $this->listClass . '_link']); $populars[] = Html::tag('div', $image . $link, ['class' => $this->listClass . '_item']); } else { // Иначе добавляем в итоговый массив только ссылку на статью $populars[] = $link; } } // Определяем тип списка и вызываем соответствующий метод Html-хелпера для создания списка $list = $this->listType; $result = ''; if (!empty($populars)) { $result = Html::$list($populars, ['encode' => false, 'class' => $this->listClass]); } // Если необходимо, заворачиваем список в контейнер div if ($this->container) { $result = Html::tag('div', $result, ['class' => $this->containerClass ? $this->containerClass : 'container_' . $this->listClass]); } return $result; }
public function actionDo($test = 1, $count = 1) { $posts = Post::find()->where(['approve' => Post::NOT_APPROVED])->andWhere(['between', 'id', 2858, 3211])->limit($count)->orderBy(['id' => SORT_DESC])->all(); echo "========= Found " . count($posts) . " articles =========\n\n"; foreach ($posts as $post) { echo "\n---------------- {$post->id} -------------------.\n"; /** @var Post $post */ $text = $post->full; $text = str_ireplace('skincaremask', 'beauty-women', $text); $matches_count = 0; $matchesFlag = false; $pattern = '/\\[link=([0-9]{1,3})\\]/si'; preg_match_all($pattern, $text, $matches); if ($matches[0]) { foreach ($matches[0] as $key => $full) { $oldId = $matches[1][$key]; $newId = $oldId + 2857; $text = str_ireplace('[link=' . $oldId . ']', '[link=' . $newId . ']', $text); echo "== Replaced {$oldId} with {$newId}\n"; $matches_count++; $matchesFlag = true; } } echo "{$post->id}: matches {$matches_count}.\n"; if ($matchesFlag) { /* Save */ $post->full = $text; /*if($post->save()) { echo "!!! Saved ID: {$post->id}"; if ($test) { echo "********** ID: {$post->id}. Matches: {$matches_count}. TEXT: {$text}\n\n"; } } else { echo json_encode($post->getErrors())."\n"; }*/ } else { echo "**** Matches not found!!! ID: {$post->id}. Matches: {$matches_count}.\n"; } } }
public static function getSiteSummary() { $today_begin = date("Y-m-d") . " 00:00:00"; $today_end = date("Y-m-d") . " 23:59:59"; $yesterday_begin = date("Y-m-d 00:00:00", time() - 86400); $yesterday_end = date("Y-m-d 23:59:59", time() - 86400); // Статьи $summary['postsCount'] = Post::find()->count(); $summary['postsToday'] = Post::find()->where(['between', 'date', $today_begin, $today_end])->count(); $summary['postsYesterday'] = Post::find()->where(['between', 'date', $yesterday_begin, $yesterday_end])->count(); // Пользователи $summary['usersCount'] = User::find()->count(); $summary['usersToday'] = User::find()->where(['between', 'created_at', strtotime($today_begin), strtotime($today_end)])->count(); $summary['usersYesterday'] = User::find()->where(['between', 'created_at', strtotime($yesterday_begin), strtotime($yesterday_end)])->count(); // Комментарии $summary['commentsCount'] = Comment::find()->count(); $summary['commentsToday'] = Comment::find()->where(['between', 'date', $today_begin, $today_end])->count(); $summary['commentsYesterday'] = Comment::find()->where(['between', 'date', $yesterday_begin, $yesterday_end])->count(); // Ошибки $summary['errorsCount'] = Log::find()->count(); $summary['errorsToday'] = Log::find()->where(['between', 'log_time', strtotime($today_begin), strtotime($today_end)])->count(); $summary['errorsYesterday'] = Log::find()->where(['between', 'log_time', strtotime($yesterday_begin), strtotime($yesterday_end)])->count(); return $summary; }
/** * Заменяет конструкцию вида [link=<id_статьи>]<текст>[/link] на ссылку на статью с данным ID * * @param $post */ protected function replaceLinks($post) { // Поиск ссылок на другие страницы сайта preg_match_all("@\\[link=([0-9]{1,5})\\](.*?)\\[/link\\]@", $post->full, $matches); // $matches[1] - ID страниц // $matches[0] - Полное совпадение // $matches[2] - Текст ссылки if (!empty($matches[1])) { $posts = Post::find()->where(['approve' => Post::APPROVED])->andWhere(['in', 'id', $matches[1]])->all(); $links = []; foreach ($posts as $p) { $links[$p->id] = $p->link; } foreach ($matches[1] as $key => $linkId) { if (array_key_exists($linkId, $links)) { $linkText = $matches[2][$key]; $link = '<a href="' . $links[$linkId] . '">' . $linkText . '</a>'; $post->full = str_replace($matches[0][$key], $link, $post->full); } else { $post->full = str_replace($matches[0][$key], $matches[2][$key], $post->full); } } } }
/** * Возвращает набор похожих статей для данной статьи, если они разрешены * * @return array|null|\yii\db\ActiveRecord[] */ public function getSimilarPosts() { // Если для данной статьи похожие запрещены, возвращаем null if (!$this->allow_similar) { return null; } $similarPosts = Post::find()->where("MATCH(short, full, title, meta_title) AGAINST('{$this->title}')")->andWhere(['approve' => static::APPROVED])->andWhere('id != ' . $this->id)->andWhere(['not_in_related' => 0])->andWhere(['category_art' => 0])->limit(5)->all(); return $similarPosts; }
/** * Генерация XML карты сайта * * @return string */ public function generateSitemap() { $xml_map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"; // Главная страница $xml_map .= "\n\t\t<url>\n\t\t\t<loc>" . Yii::$app->params['frontendBaseUrl'] . "</loc>\n\t\t\t<lastmod>" . date("Y-m-d") . "</lastmod>\n\t\t\t<changefreq>daily</changefreq>\n\t\t\t<priority>1.0</priority>\n\t\t</url>"; // Категории $categories = GlobalHelper::getCategories(); foreach ($categories as $mass) { $id = $mass['id']; $xml_name = GlobalHelper::getCategoryUrlById($id); $xml_date = date("Y-m-d"); $xml_map .= "\n\t\t<url>\n\t\t\t<loc>" . Yii::$app->params['frontendBaseUrl'] . $xml_name . "/</loc>\n\t\t\t<lastmod>" . $xml_date . "</lastmod>\n\t\t\t<changefreq>daily</changefreq>\n\t\t\t<priority>0.8</priority>\n\t\t</url>"; } // Статьи $posts = Post::find()->where(['approve' => '1'])->andWhere(['<=', 'date', date('Y-m-d')])->andWhere(['!=', 'category_art', 1])->orderBy('date')->all(); //var_dump($posts); foreach ($posts as $post) { $xml_map .= "\n\t\t<url>\n\t\t\t<loc>" . $post->absoluteLink . "</loc>\n\t\t\t<lastmod>" . date("Y-m-d", strtotime($post->date)) . "</lastmod>\n\t\t\t<changefreq>weekly</changefreq>\n\t\t\t<priority>0.6</priority>\n\t\t</url>"; } $xml_map .= "\n</urlset>"; return $xml_map; }