private static function getConfig() { if (\Yii::$app->cache->exists('configuration') && !\Yii::$app->request->get('disableConfigCache')) { return \Yii::$app->cache->get('configuration'); } if (!self::$configuration) { self::$configuration = ArrayHelper::map(Configuration::find()->select(['key', 'value'])->asArray()->all(), 'key', 'value'); \Yii::$app->cache->set('configuration', self::$configuration, 600); } return self::$configuration; }
public function actionIndex() { $todayStart = strtotime(date('Y-m-d')); $newsViews = NewsViews::find()->select("SUM(`views`)")->where(['date' => $todayStart])->scalar(); if (!$newsViews) { $newsViews = 0; } $todayViewedNews = NewsViews::find()->select('newsID')->where(['date' => $todayStart])->orderBy('views DESC')->asArray()->all(); $popularFiveToday = $popularToday = $todayPopularNews = []; if ($todayViewedNews) { $popularFiveToday = ArrayHelper::getColumn(array_slice($todayViewedNews, 0, 5), 'newsID'); } $sViews = NewsViews::find()->select(['title' => 'date', 'views' => 'COUNT(`views`)'])->groupBy('date')->limit(30)->asArray()->all(); array_walk($sViews, function (&$item, $key) { $item['title'] = \Yii::$app->formatter->asDate($item['title']); }); return $this->render('index', ['monthlyViews' => $sViews, 'todayViewedNewsCount' => count($todayViewedNews), 'lastNews' => new ActiveDataProvider(['query' => News::find(), 'pagination' => ['pageSize' => 5], 'sort' => ['defaultOrder' => ['publishDate' => SORT_DESC]]]), 'popularToday' => new ActiveDataProvider(['query' => News::find()->select(['news.*', 'todayViews' => 'newsViews.views'])->where(['in', 'id', $popularFiveToday])->with('todayViews')->joinWith('todayViews')->orderBy(['todayViews' => SORT_DESC]), 'pagination' => ['pageSize' => 5], 'sort' => false]), 'lastAuth' => new ActiveDataProvider(['query' => Authorization::find()->with('user'), 'pagination' => ['pageSize' => 5], 'sort' => ['defaultOrder' => ['date' => SORT_DESC]]]), 'newsCount' => News::find()->where("publishDate >= '{$todayStart}'")->count(), 'newsViews' => $newsViews, 'commentsCount' => Comment::find()->where("date >= '{$todayStart}'")->count()]); }
public function getPossibleNews($count, $outcludeIDs = []) { $categoryPossibleNews = ArrayHelper::getColumn(News::find()->select('id')->andWhere(['categoryID' => $this->id])->asArray()->all(), 'id'); $randomNewsCount = ($c = count($categoryPossibleNews)) && $c > $count ? $count * 2 : $c; $randomNews = $randomNewsCount <= 1 ? [0] : array_rand($categoryPossibleNews, $randomNewsCount > $c ? $c : $randomNewsCount); $randomNewsIDs = []; if (!is_array($randomNews)) { $randomNews = [$randomNews]; } foreach ($randomNews as $key) { $randomNewsIDs[] = $categoryPossibleNews[$key]; } if (!empty($outcludeIDs)) { if (!is_array($outcludeIDs)) { $outcludeIDs = [$outcludeIDs]; } $randomNewsIDs = array_diff($randomNewsIDs, $outcludeIDs); } return News::find()->andWhere(['in', 'id', $randomNewsIDs])->with('category')->limit($count)->all(); }
public function setAnswers($answers) { $answersForms = []; $currentAnswersKeys = ArrayHelper::getColumn($this->answers, 'id'); \Yii::trace('Have ' . count($answers) . ' answers'); foreach (array_diff($currentAnswersKeys, ArrayHelper::getColumn($answers, 'id')) as $deletedAnswer) { if ($desiredAnswer = $this->getAnswer($deletedAnswer)) { $this->deleteAnswer($desiredAnswer); } } foreach ($answers as $key => $answer) { if (array_key_exists('id', $answer) && ($answerID = $answer['id'])) { $answersForms[] = new QuizAnswerForm(['order' => $key, 'text' => $answer['text'], 'id' => $answerID]); unset($answers[$key]); } } foreach ($answers as $key => $answer) { $answersForms[] = new QuizAnswerForm(['order' => $key, 'text' => $answer['text']]); } $this->answers = $answersForms; }
public function save() { if (!$this->validate()) { return false; } $model = new Menu(); if (!empty($this->id)) { $model = Menu::findOne($this->id); } $model->setAttributes(['name' => $this->name, 'alias' => $this->alias]); $isNew = $model->isNewRecord; if ($model->save(false)) { $this->id = $model->id; if (!$isNew) { $oldItems = MenuItem::find()->where(['menuID' => $this->id])->all(); $existedMenus = ArrayHelper::getColumn($oldItems, 'id'); $newItems = ArrayHelper::getColumn($this->items, 'id'); if ($needToRemoveItems = array_diff($existedMenus, $newItems)) { \Yii::trace($needToRemoveItems); foreach ($oldItems as $item) { if (in_array($item->id, $needToRemoveItems)) { $item->delete(); } } } } foreach ($this->items as $order => $menuItem) { if (!$menuItem->menuID) { $menuItem->menuID = $this->id; } if (!$menuItem->order) { $menuItem->order = $order; } $menuItem->save(); } } return !empty($this->id); }
public function getCategories() { $categories = Category::find()->where(['deleted' => 0])->all(); return ArrayHelper::map($categories, 'id', 'title'); }
<?php echo Html::a(FontAwesome::i('arrow-left') . Html::tag('small', 'Назад'), ['/quiz/default/index'], ['class' => 'btn btn-app']); ?> <?php echo Html::a(FontAwesome::i('pencil') . Html::tag('small', 'Редактировать'), ['/quiz/edit/' . $quiz->id], ['class' => 'btn btn-app']); ?> </div> <div class="panel-body"> <div class="col-xs-6"> <?php echo ChartJs::widget(['type' => 'pie', 'data' => ['datasets' => [['data' => ArrayHelper::toPercents(array_values(ArrayHelper::getColumn($quiz->answersWithCount, 'count'))), 'label' => 'Результаты опроса', 'backgroundColor' => $colors]], 'labels' => array_values(ArrayHelper::getColumn($quiz->answersWithCount, 'text'))]]); ?> </div> <div class="col-xs-6"> <?php echo ChartJs::widget(['type' => 'bar', 'data' => ['datasets' => [['data' => array_values(ArrayHelper::getColumn($quiz->answersWithCount, 'count')), 'label' => 'Результаты опроса', 'backgroundColor' => $colors]], 'labels' => array_values(ArrayHelper::getColumn($quiz->answersWithCount, 'text'))], 'options' => []]); ?> </div> <div class="col-xs-12"> <hr> <h3>Ответы по дням</h3> <?php $graphs = []; foreach ($quiz->answers as $key => $answer) { $graphs[] = ['balloonText' => '[[title]]: <b>[[value]]</b>', 'fillAlphas' => true, 'id' => 'Graph' . $key, 'title' => $answer->text, 'type' => 'column', 'valueField' => 'answer' . $answer->id]; } echo \speixoto\amcharts\Widget::widget(['width' => 'auto', 'height' => '600px', 'chartConfiguration' => ['colors' => $colors, 'type' => 'serial', 'dataProvider' => $quiz->answersByDayForChart, 'categoryField' => 'date', 'startDuration' => 1, 'chartScrollbar' => ['enabled' => true], 'chartCursor' => ['enabled' => true], 'trendLines' => [], 'guides' => [], 'valueAxes' => [['stackType' => 'regular', 'id' => 'values']], 'categoryAxis' => ['gridPosition' => 'start', 'autoGridCount' => false], 'legend' => ['enabled' => true, 'useGraphSettings' => true], 'gridAboveGraphs' => true, 'graphs' => $graphs]]); ?> </div> </div> </div>
public function actionNews($id, $ignoreLink = false) { $news = News::find()->andWhere(['id' => filter_var($id, FILTER_SANITIZE_NUMBER_INT)])->with('author')->one(); if (!$news) { throw new NotFoundHttpException(); } if ($news->fullLink != \Yii::$app->request->url && !$ignoreLink) { return $this->redirect($news->fullLink, 301); } if (\Yii::$app->request->isAjax) { \Yii::$app->response->format = 'json'; switch (\Yii::$app->request->post('action')) { case 'voteComment': $commentID = \Yii::$app->request->post('commentID'); $comment = Comment::findOne($commentID); if (!$comment) { throw new NotFoundHttpException("Комментарий с идентификатором {$commentID} не найден!"); } $isGood = \Yii::$app->request->post('isGood') == 'true'; if (!empty($comment->myVote) && $comment->myVote->operation == ($isGood ? CommentVote::OPERATION_GOOD : CommentVote::OPERATION_BAD)) { return ['result' => $comment->rating]; } $comment->vote($isGood); $comment = Comment::findOne($commentID); return ['result' => $comment->rating]; break; } } if ($date = \Yii::$app->request->headers->get('If-Modified-Since', 0)) { if ($date = strtotime($date) && ($date >= $news->updated || $date >= $news->publishDate)) { header('HTTP/1.1 304 Not Modified'); die; } } \Yii::$app->response->headers->add('Last-Modified', gmdate('D, d M Y H:i:s', $news->updated ? $news->updated : $news->publishDate) . ' GMT'); if (!preg_match('/(googlebot|google.com\\/bot|yandex(\\w+|)bot|yandex\\.com\\/bots)/im', \Yii::$app->request->userAgent)) { (new Query())->createCommand(\Yii::$app->db)->setSql("UPDATE `news` SET `hits` = `hits` + 1 WHERE `id` = '{$news->id}'")->execute(); NewsViews::addView($news->id); } $commentForm = new CommentForm(); if (\Yii::$app->request->post('CommentForm')) { $commentForm->load(\Yii::$app->request->post()); $commentForm->news = $news; if ($commentForm->save()) { \Yii::$app->session->setFlash('saved', 'Комментарий успешно добавлен!' . ($news->moderatedComments == 1 ? ' Он будет опубликован после проверки модератором.' : '')); $commentForm = new CommentForm(); } } if (!empty($news->category)) { if (!empty($news->category->parentCategory)) { $this->getView()->params['breadcrumbs'][] = ['label' => $news->category->parentCategory->title, 'url' => yii\helpers\Url::toRoute(['/' . $news->category->parentCategory->fullLink], true)]; } $this->getView()->params['breadcrumbs'][] = ['label' => $news->category->title, 'url' => yii\helpers\Url::toRoute(['/' . $news->category->fullLink], true)]; } $today = strtotime(date('Y-m-d')); $interestNews = []; if ($news->category->showPopular) { $interestNews = NewsViews::find()->select('newsID')->where(['date' => $today])->andWhere(['not in', 'newsID', $news->id])->orderBy('views DESC')->limit(5)->asArray()->all(); if (empty($interestNews)) { $interestNews = NewsViews::find()->select('newsID')->where(['date' => $today - 86400])->andWhere(['not in', 'newsID', $news->id])->orderBy('views DESC')->limit(5)->asArray()->all(); } $interestNews = News::find()->andWhere(['in', 'id', ArrayHelper::getColumn($interestNews, 'newsID')])->andWhere(['not in', 'categoryID', '49'])->with('category')->limit(3)->all(); } return $this->render('article', ['article' => $news, 'interest' => $interestNews, 'commentForm' => $commentForm, 'categoryNews' => $news->category->showSimilar ? $news->category->getPossibleNews(3, [$news->id]) : []]); }
<?php use backend\helpers\ArrayHelper; use backend\models\Category; use backend\models\News; use kartik\form\ActiveForm; use kartik\select2\Select2; use yii\web\JsExpression; $form = ActiveForm::begin(['type' => ActiveForm::TYPE_HORIZONTAL, 'id' => 'edit-theme-form', 'options' => ['data-pjax' => true]]); echo $form->field($model, 'name'), $form->field($model, 'categories')->widget(Select2::className(), ['options' => ['multiple' => true], 'data' => !$model->isNew ? ArrayHelper::map(Category::find()->select('id, title')->where(['deleted' => 0])->andWhere(['in', 'id', $model->categories])->asArray()->all(), 'id', 'title') : [], 'pluginOptions' => ['ajax' => ['url' => '/categories/get-list', 'data-type' => 'json', 'data' => new JsExpression("function(params){ return {q:params.term} }")]]]), $form->field($model, 'articles')->widget(Select2::className(), ['options' => ['multiple' => true], 'data' => !$model->isNew ? ArrayHelper::map(News::find()->select('id, title')->where(['deleted' => 0])->andWhere(['in', 'id', $model->articles])->asArray()->all(), 'id', 'title') : [], 'pluginOptions' => ['ajax' => ['url' => '/news/get-list', 'data-type' => 'json', 'data' => new JsExpression('function(params){ var data = {q:params.term}, categories = $("#mainthemeform-categories").val(); if(categories !== null && categories.length > 0){ data.excludedCategories = categories;} return data; }')]]]), $form->field($model, 'color')->dropDownList($model->getColors()), $form->field($model, 'titleWords', ['inputOptions' => ['format' => 'number']]), $form->field($model, 'textWords', ['inputOptions' => ['format' => 'number']]), $form->field($model, 'enabled')->checkbox([], false), \yii\bootstrap\Html::tag('div', \yii\bootstrap\Html::button('Сохранить', ['class' => 'btn btn-success btn-lg', 'type' => 'submit']), ['class' => 'text-center']); $form->end();
<div class="panel panel-default"> <div class="panel-heading"> <?php echo Html::button(FA::i('save') . Html::tag('small', 'Сохранить'), ['class' => 'btn btn-app saveBtn']); ?> </div> <div class="panel-body"> <div class="col-xs-10 col-xs-offset-1"> <?php $form = ActiveForm::begin(['type' => ActiveForm::TYPE_HORIZONTAL, 'id' => 'edit-systemparams-form', 'options' => ['data-pjax' => true]]); foreach ($model->items as $key => $item) { $defaultInputOptions = ['name' => 'ConfigurationFieldModel[' . $key . '][clearValue]', 'id' => 'configurationfieldmodel-' . $key . '-clearValue']; $field = $form->field($item, 'clearValue', ['inputOptions' => $defaultInputOptions + ['labelSpan' => 5]])->label($item->getKeyDescription()); switch ($item->getFormat()) { case 'categories': $field->widget(\kartik\select2\Select2::className(), ['options' => array_merge($defaultInputOptions, ['multiple' => true]), 'data' => $item->clearValue ? ArrayHelper::map(Category::find()->select('id, title')->where(['deleted' => 0])->andWhere(['in', 'id', $item->clearValue])->asArray()->all(), 'id', 'title') : [], 'pluginOptions' => ['ajax' => ['url' => '/categories/get-list', 'data-type' => 'json', 'data' => new JsExpression("function(params){ return {q:params.term} }")]]]); break; case 'textarea': $field->textarea(); break; case 'number': $field->inputOptions = array_merge($defaultInputOptions, ['type' => 'number']); break; } echo $field, $form->field($item, 'id', ['options' => ['style' => 'display: none'], 'inputOptions' => ['name' => 'ConfigurationFieldModel[' . $key . '][id]']])->label(false); } echo Html::tag('div', Html::button('Сохранить', ['type' => 'submit', 'class' => 'btn btn-success']), ['class' => 'text-center']); $form->end(); ?> </div> </div>