public function actionSend() { $siteSummary = GlobalHelper::getSiteSummary(); $summaryInfo = '<h3>Отчет за ' . date('d.m.Y') . '</h3>'; $summaryInfo .= '<hr>'; $summaryInfo .= '<h4>Статьи</h4>'; $summaryInfo .= 'Всего: ' . $siteSummary['postsCount'] . '<br>'; $summaryInfo .= 'Сегодня: ' . $siteSummary['postsToday'] . '<br>'; $summaryInfo .= 'Вчера: ' . $siteSummary['postsYesterday'] . '<br>'; $summaryInfo .= '<hr>'; $summaryInfo .= '<h4>Пользователи</h4>'; $summaryInfo .= 'Всего: ' . $siteSummary['usersCount'] . '<br>'; $summaryInfo .= 'Сегодня: ' . $siteSummary['usersToday'] . '<br>'; $summaryInfo .= 'Вчера: ' . $siteSummary['usersYesterday'] . '<br>'; $summaryInfo .= '<hr>'; $summaryInfo .= '<h4>Комментарии</h4>'; $summaryInfo .= 'Всего: ' . $siteSummary['commentsCount'] . '<br>'; $summaryInfo .= 'Сегодня: ' . $siteSummary['commentsToday'] . '<br>'; $summaryInfo .= 'Вчера: ' . $siteSummary['commentsYesterday'] . '<br>'; $summaryInfo .= '<hr>'; $summaryInfo .= '<h4>Ошибки</h4>'; $summaryInfo .= 'Всего: ' . $siteSummary['errorsCount'] . '<br>'; $summaryInfo .= 'Сегодня: ' . $siteSummary['errorsToday'] . '<br>'; $summaryInfo .= 'Вчера: ' . $siteSummary['errorsYesterday'] . '<br>'; Yii::$app->mailer->compose()->setFrom(Yii::$app->params['supportEmail'])->setTo(Yii::$app->params['feedbackEmail'])->setSubject('Отчет за ' . date('d.m.Y'))->setHtmlBody($summaryInfo)->send(); return 0; }
protected function renderPageButton($label, $page, $class, $disabled, $active) { $options = ['class' => $class === '' ? null : $class]; if ($active) { Html::addCssClass($options, $this->activePageCssClass); } if ($disabled) { Html::addCssClass($options, $this->disabledPageCssClass); return Html::tag('li', Html::tag('span', $label), $options); } $linkOptions = $this->linkOptions; $linkOptions['data-page'] = $page; $url = ''; if ($this->cat) { $url .= '/' . GlobalHelper::getCategoryUrlById($this->cat[0]); } if (array_key_exists('date', Yii::$app->params)) { $url .= '/' . Yii::$app->params['date']; } if ($page != 0) { $url .= '/page/' . ($page + 1); } $url .= '/'; return Html::tag('li', Html::a($label, $url, $linkOptions), $options); }
public function getData() { $data = GlobalHelper::getMetrikaData(['preset' => 'tech_platforms', 'dimensions' => 'ym:s:browser']); $colors = $this->colorPalette(); $i = 0; $browsers = []; foreach ($data->data as $browser) { if (empty($colors)) { $colors = $this->colorPalette(); } $browserData['value'] = $browser->metrics[0]; $browserData['label'] = $browser->dimensions[0]->name; $browserData['color'] = array_shift($colors); $browserData['highlight'] = $this->lightenColor($browserData['color']); $browsers[] = $browserData; //$browsers[] = json_encode($browserData); $i++; } //$browsers = implode(',', $browsers); return $browsers; }
<h1><?php echo Html::encode($this->title); ?> </h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?php echo Html::a('Добавить статью', ['create'], ['class' => 'btn btn-success']); ?> </p> <?php echo GridView::widget(['dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => ['id', 'date', 'title', ['attribute' => 'category_id', 'filter' => GlobalHelper::getCategoriesFilter(), 'format' => 'raw', 'value' => function ($model, $key, $index, $column) { $value = $model->categoryName; $html = Html::tag('span', Html::encode($value), ['class' => 'label label-blue']); return $value === null ? $column->grid->emptyCell : $html; }], ['filter' => Post::getStatusesArray(), 'attribute' => 'approve', 'format' => 'raw', 'value' => function ($model, $key, $index, $column) { /** @var Post $model */ /** @var \yii\grid\DataColumn $column */ $value = $model->{$column->attribute}; switch ($value) { case Post::APPROVED: $class = 'success'; break; case Post::NOT_APPROVED: $class = 'warning'; break; default:
/** * Получение информации о статьях, пользователях, комментариях и ошибках из базы данных * @return mixed */ public function getSummary() { return GlobalHelper::getSiteSummary(); }
/** * Дополнение для общего лунного календаря и всех статей из данной категории * * @param object $post Объект класса Post (статья) */ public static function fullMoonCalendar($post) { if ($post->id == 1758) { $currentYear = date('Y'); $currentMonth = date('n'); $calendarYear = $currentMonth == 12 ? ++$currentYear : $currentYear; $moonCal = '<h2 align="center">Лунный календарь на ' . $calendarYear . ' год по месяцам</h2><br /> <table width="100%" class="moon_calendar_table"> <tr>'; for ($d = 1; $d <= 12; $d++) { if ($currentMonth == 12 && $d == 12) { $mLink = AppData::getMoonCalLinks($currentYear, $d); $moonCal .= '<td><a href="' . $mLink . '">Лунный календарь на ' . GlobalHelper::rusMonth($d) . ' ' . $currentYear . ' года</a></td>'; } else { $mLink = AppData::getMoonCalLinks($calendarYear, $d); $moonCal .= '<td><a href="' . $mLink . '">Лунный календарь на ' . GlobalHelper::rusMonth($d) . ' ' . $calendarYear . ' года</a></td>'; } if ($d % 2 == 0) { $moonCal .= '</tr><tr>'; } } $moonCal .= '</tr></table><br />'; $post->title = str_replace("YEAR", $calendarYear, $post->title); $post->full = str_replace("[YEAR]", $calendarYear, $post->full); $post->full = str_replace("[MOON-MONTH]", $moonCal, $post->full); } }
/** @var \yii\data\Pagination $pages */ use app\components\MyLinkPager; use common\components\helpers\GlobalHelper; if ($pages->page > 0 || array_key_exists('category', Yii::$app->params)) { $this->title = Yii::$app->params['site']['shortTitle']; } else { $this->title = Yii::$app->params['site']['title']; } // Если не первая страница, добавляем в начало <title> if ($pages->page > 0) { $this->title = 'Страница ' . ($pages->page + 1) . '. ' . $this->title; } // Если задана категория, добавляем в начало <title> имя категории if (array_key_exists('category', Yii::$app->params)) { $catName = GlobalHelper::getCategories()[Yii::$app->params['category'][0]]['name']; $this->title = $catName . ' - ' . $this->title; } // Если задана дата if (array_key_exists('date', Yii::$app->params)) { $this->title = 'Статьи за ' . Yii::$app->params['date'] . ' - ' . $this->title; } ?> <?php // Если заданы подкатегории, которые выводятся на первых страницах категорий, выводим их перед анонсами статей if ($subCategories) { echo $subCategories; } foreach ($posts as $post) {
/** * Рендерит статью, получая ее по ID * * Если необходимо, вставляет дополнительные материалы: дополнения, рекламу и т.д. * * @return string * @throws NotFoundHttpException * @throws \Exception */ public function actionFull() { // Определяем Id // Если это статья-категория, берем из params, иначе из request->get $postId = array_key_exists('category_art', Yii::$app->params) ? Yii::$app->params['category_art'] : Yii::$app->request->get('id'); $post = Post::findOne(['id' => $postId, 'approve' => Post::APPROVED]); if (is_null($post)) { throw new NotFoundHttpException('Статьи с данным адресом на сайте не существует. Проверьте правильно ли вы скопировали или ввели адрес в адресную строку. Если вы перешли на эту страницу по ссылке с данного сайта, сообщите пожалуйста о неработающей ссылке нам с помощью обратной связи.'); } // Записываем id текущей категории в виде массива в глобальный параметр Yii::$app->params['category'] = [$post->category_id]; $model = ''; // Добавление комментариев if (!Yii::$app->user->isGuest) { $model = new CommentForm(); // Значение для hidden user_id $model->user_id = Yii::$app->user->identity->getId(); $model->post_id = $post->id; if ($model->load(Yii::$app->request->post())) { if ($id = $model->addComment()) { Yii::$app->session->setFlash('comment-success', $id); return $this->refresh(); } else { Yii::$app->session->setFlash('comment-error'); } } } // Поиск и замена ссылок на другие страницы сайта (ссылки в формате [link=<id_статьи>]<текст_ссылки>[/link]) $this->replaceLinks($post); // Применение дополнительных методов для обработки полного текста статей if ($m = GlobalHelper::getCategories()[$post->category_id]['add_method']) { $methodName = 'full' . ucfirst($m); if (method_exists('app\\components\\PostAdditions', $methodName)) { PostAdditions::$methodName($post); } } // Социальные кнопки $post->full .= SocialButtonsWidget::widget(); // Вставка рекламных материалов $this->insertAdvert($post); // Обновление количества просмотров статьи $post->updateCounters(['views' => 1]); // Если статья-категория, используем представление full_cat.php, иначе full.php $viewFile = array_key_exists('category_art', Yii::$app->params) ? 'full_cat' : 'full'; return $this->render($viewFile, ['post' => $post, 'model' => $model]); }
<?php /* @var $this yii\web\View */ use common\components\helpers\GlobalHelper; ?> <?php $allCategories = GlobalHelper::getCategories(); foreach ($categories as $categoryId) { // Получаем Url категории по ее ID $cat = GlobalHelper::getCategoryUrlById($categoryId); $link = '/' . $cat . '/'; ?> <div id="content-item"> <div id="content-item-top" class="content-item-blue black_link"><span>Подраздел</span> <a href="<?php echo $link; ?> "><?php echo $allCategories[$categoryId]['name']; ?> </a></div> <div id="content-item-content"> <div id="content-small-10" class="img120"> <?php echo $allCategories[$categoryId]['description']; ?> </div> <div class="clear"></div> </div> </div> <?php
<?php /* @var $this yii\web\View */ /* @var $user common\models\ar\User */ use common\components\helpers\GlobalHelper; ?> <div class="user_avatar"> <img src="<?php echo $user->avatar; ?> " width="150"> </div> <div class="user_registered"><strong>Регистрация:</strong> <?php echo GlobalHelper::dateFormat($user->created_at); ?> </div> <div class="user_lastvisit"><strong>Последний визит:</strong> <?php echo GlobalHelper::dateFormat(($lv = $user->profile->last_visit) ? $lv : $user->last_login_at); ?> </div>
/** * Создает уменьшенную копию изображения * * @param string $sourceFilePath * @param string $thumbImagePath * @return bool */ public function createThumb($sourceFilePath, $thumbImagePath) { // Если значение 'max_pixel_side' не равно 'width' или 'height', прерываем процесс if (!in_array($this->max_pixel_side, ['width', 'height'])) { $this->_result[] = 'Невозможно создать уменьшенную копию изображения. Не определена сторона для уменьшения'; return false; } $img = Image::getImagine()->open($sourceFilePath); $size = $img->getSize(); // Если размер выбранной стороны изображения больше заданного, создаем уменьшенную копию $side = 'get' . GlobalHelper::ucfirst($this->max_pixel_side); if ($size->{$side}() > $this->max_pixel) { $ratio = $size->getWidth() / $size->getHeight(); if ($this->max_pixel_side == 'width') { $width = $this->max_pixel; $height = round($width / $ratio); } elseif ($this->max_pixel_side == 'height') { $height = $this->max_pixel; $width = round($height * $ratio); } if ($img->resize(new Box($width, $height))->save($thumbImagePath)) { // Если отмечена галочка "Добавлять водяной знак" if ($this->watermark) { $watermarkImagePath = Yii::getAlias($this->_baseUploadPathAlias) . $this->_watermarkFileName; if ($this->putWatermark($thumbImagePath, $watermarkImagePath)) { $this->_result[] = 'Водяной знак наложен'; } } return true; } } }
public function getFrontendLink() { $cat = GlobalHelper::getCategoryUrlById($this->category_id); return substr(\Yii::$app->params['frontendBaseUrl'], 0, -1) . \Yii::$app->urlManagerFrontend->createUrl(['post/full', 'cat' => $cat, 'id' => $this->id, 'alt' => $this->url]); }
<?php /* @var $this yii\web\View */ use yii\helpers\Html; use common\components\helpers\GlobalHelper; $controls = ''; if (!$noControls) { $controls = Html::tag('div', '<i class="fa fa-angle-double-left fa-lg"></i>', ['class' => 'calendar_control', 'id' => 'calendar-prev']); $controls .= Html::tag('div', '<i class="fa fa-angle-double-right fa-lg"></i>', ['class' => 'calendar_control', 'id' => 'calendar-next']); } list($year, $month) = explode('-', $date); $daysInMonth = date('t', strtotime($date)); $dateOut = GlobalHelper::ucfirst(GlobalHelper::rusMonth($month)) . ' ' . $year; if (!empty($posts)) { $dateOut = Html::a($dateOut, '/' . $year . '/' . $month . '/'); } $calendar = '<div class="calendar_nowmonth">' . $dateOut . '</div> <table class="calendar_table"> <tr> <th class="weekday">Пн</th> <th class="weekday">Вт</th> <th class="weekday">Ср</th> <th class="weekday">Чт</th> <th class="weekday">Пт</th> <th class="weekday">Сб</th> <th class="weekday">Вс</th> </tr><tr>'; for ($i = 1; $i <= $daysInMonth; $i++) { $day = sprintf('%02d', $i); $dayOfWeek = date('w', strtotime("{$year}-{$month}-{$day}")); if (!$dayOfWeek) {
<div style="margin-bottom: 15px;"> <?php echo Html::activeDropDownList($model, 'birthYear', GlobalHelper::getYearsList(), ['class' => 'form-select', 'style' => 'width:90px;']); ?> <?php echo Html::activeDropDownList($model, 'birthMonth', GlobalHelper::getMonthsList(), ['class' => 'form-select', 'style' => 'width:130px;']); ?> <?php echo Html::activeDropDownList($model, 'birthDay', GlobalHelper::getDaysList(), ['class' => 'form-select', 'style' => 'width:80px;']); ?> </div> <label class="control-label">Место жительства (Страна/Город)</label> <div style="margin-bottom: 15px;"> <?php echo Html::activeDropDownList($model, 'country', GlobalHelper::getCountriesList(), ['class' => 'form-select', 'style' => 'width:150px;']); ?> <?php echo Html::activeTextInput($model, 'city', ['class' => 'form-select', 'style' => 'width:200px;']); ?> </div> <?php if ($img = $model->avatar) { echo '<div style="display: inline;"><img src="/uploads/fotos/' . $img . '" style="width:80px;"></div>'; } ?> <?php echo $form->field($model, 'image')->fileInput(); ?>
// убираем теги $fullText = strip_tags($post->full); // вычисляем позиции первого вхождения для всех слов фразы foreach ($searchWords as $searchWord) { $pos[$searchWord] = mb_stripos($fullText, $searchWord); } // берем позицию вхождения первого слова из поисковой разы $start = $pos[$searchWords[0]]; // проходимся циклом по символам строки с полным текстом статьи, начиная от позиции вхождения слова // из поисковой фразы. Проход производим в обратном порядке. Останавливаемся, когда найдем точку. // Начиная с этой позиции и возьмем подстроку с выдержкой для вывода подсвеченного слова из поисковой фразы. $symbol = ''; $i = 1; while ($symbol != '.') { $position = $start - $i; $symbol = GlobalHelper::utf8char($fullText, $position); $i++; } $full = mb_substr($fullText, $position + 1, 200); // подсвечиваем слова из поисковой фразы $full = preg_replace($patterns, $replace, $full); // формируем блок для вывода $full = '<div style="border-radius: 5px; border: 1px #eee solid; padding: 10px; margin: 7px; background-color: #f5f5f5;"><strong style="display: block;">Выдержка из полного текста статьи:</strong>' . $full . ' ...</div>'; } ?> <div id="content-item"> <div id="content-item-top" class="content-item-pink"><a href="<?php echo $post->link; ?> "><?php echo $title;
private function replace($string) { // Год $string = str_replace('[year]', $this->year, $string); // Img Alt $string = str_replace('[alt]', $this->replace($this->alt), $string); // Месяцы if (preg_match('@\\[month_([a-z]{1})\\]@si', $string)) { $string = preg_replace_callback('@\\[month_([a-z]{1})\\]@si', function ($matches) { return GlobalHelper::rusMonth((int) $this->month, $matches[1]); }, $string); } if (preg_match('@\\[engmonth_([a-z]{1})\\]@si', $string)) { $string = preg_replace_callback('@\\[engmonth_([a-z]{1})\\]@si', function ($matches) { return GlobalHelper::engMonth((int) $this->month, $matches[1]); }, $string); } // Знаки if (preg_match('@\\[znak_([a-z]{1})\\]@si', $string)) { $string = preg_replace_callback('@\\[znak_([a-z]{1})\\]@si', function ($matches) { return GlobalHelper::rusZodiac((int) $this->znak, $matches[1]); }, $string); } if (preg_match('@\\[engznak_([a-z]{1})\\]@si', $string)) { $string = preg_replace_callback('@\\[engznak_([a-z]{1})\\]@si', function ($matches) { return mb_strtolower(GlobalHelper::translit(GlobalHelper::rusZodiac((int) $this->znak, $matches[1]))); }, $string); } return $string; }
" data-reply-user-id="<?php echo $comment['user']['id']; ?> " data-reply-user-name="<?php echo $comment['user']['username']; ?> " class="comm-reply-link">Ответить</a></div> <div class="clear"></div> </div> <div class="comment-foto"><img src="<?php echo GlobalHelper::avatarSrc($comment['user']); ?> "></div> <div class="comment-body"> <div class="comment-text"><?php echo nl2br(Html::encode(GlobalHelper::br2nl($comment['text']))); ?> </div> </div> <div class="clear"></div> <div class="comment-info"> <div class="comment-id">#<?php echo $comment['id']; ?> (<a href="#comment-<?php echo $comment['id']; ?> " class="comment-link" title="Ссылка на комментарий">Ссылка</a>)</div> <div class="comment-date"><strong>Добавлен:</strong> <?php echo $comment['date']; ?>
<?php /* @var $this yii\web\View */ /* @var $post common\models\ar\Post */ use yii\helpers\Html; use app\components\widgets\SimilarPostsWidget; use common\components\helpers\GlobalHelper; use app\components\widgets\CommentsWidget; use app\components\widgets\RatingWidget; use app\components\widgets\FavoriteWidget; foreach (GlobalHelper::getCategoryBreadcrumb(Yii::$app->params['category'][0]) as $cBreadcrumb) { $this->params['breadcrumbs'][] = ['label' => Html::a($cBreadcrumb['label'], $cBreadcrumb['link']), 'encode' => false]; } $this->params['breadcrumbs'][] = $post->title; // Проверяем, добавлены ли мета-тэги и включаем их в код страницы if ($post->meta_keywords) { $this->registerMetaTag(['name' => 'keywords', 'content' => $post->meta_keywords], 'keywords'); } if ($post->meta_descr) { $this->registerMetaTag(['name' => 'description', 'content' => $post->meta_descr], 'description'); } if ($post->meta_title) { $this->title = $post->meta_title; } else { $this->title = $post->title; } // Добавляем canonical $this->registerLinkTag(['rel' => 'canonical', 'href' => $post->absoluteLink]); ?> <div id="post-id"><?php echo $post->id;
?> <?php echo $form->field($model, 'meta_title')->textInput(['maxlength' => true]); ?> <?php echo $form->field($model, 'meta_descr')->textInput(['maxlength' => true]); ?> <?php echo $form->field($model, 'meta_keywords')->textInput(['maxlength' => true]); ?> <?php echo $form->field($model, 'category_id')->dropDownList(\common\components\helpers\GlobalHelper::getCategoriesFilter()); ?> <?php echo $form->field($model, 'url')->textInput(['maxlength' => true]); ?> <?php echo $form->field($model, 'short')->widget(TinyMCE::className(), ['clientOptions' => ['plugin_upload_post_id' => $model->id ? $model->id : 0, 'plugin_upload_r_id' => $model->id ? null : $r_id, 'plugin_upload_area' => $model->id ? 'editpost' : 'addpost']]); ?> <?php echo $form->field($model, 'full')->widget(TinyMCE::className(), ['clientOptions' => ['height' => 800, 'plugin_upload_post_id' => $model->id ? $model->id : 0, 'plugin_upload_r_id' => $model->id ? null : $r_id, 'plugin_upload_area' => $model->id ? 'editpost' : 'addpost']]); ?> <?php
$this->params['breadcrumbs'][] = $this->title; ?> <div class="category-index"> <h1><?php echo Html::encode($this->title); ?> </h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?php echo Html::a('Create Category', ['create'], ['class' => 'btn btn-success']); ?> </p> <?php echo GridView::widget(['dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [['attribute' => 'id', 'options' => ['style' => 'width: 65px; max-width: 65px;'], 'contentOptions' => ['style' => 'width: 65px; max-width: 65px;']], ['attribute' => 'parent_id', 'options' => ['style' => 'width: 75px; max-width: 75px;'], 'contentOptions' => ['style' => 'width: 75px; max-width: 75px;']], ['attribute' => 'name', 'options' => ['style' => 'min-width: 300px;'], 'contentOptions' => ['style' => 'min-width: 300px;']], ['attribute' => 'url', 'format' => 'raw', 'value' => function ($model, $key, $index, $column) { $value = $model->url; $html = Html::tag('span', Html::encode($value), ['class' => 'label label-blue']); return $value === null ? $column->grid->emptyCell : $html; }], 'category_art', 'add_method', 'postCount', ['class' => BwActionColumn::className(), 'buttons' => ['link' => function ($url, $model) { $customurl = Yii::$app->params['frontendBaseUrl'] . GlobalHelper::getCategoryUrlById($model->id) . '/'; return \yii\helpers\Html::a('<span class="glyphicon glyphicon-link"></span>', $customurl, ['title' => 'Открыть статью', 'target' => '_blank']); }], 'template' => '{view} {update} {delete} {link}']]]); ?> </div>
/** * CallBack метод для oAuth авторизации через внешние сервисы * * @param $client * @throws BadRequestHttpException * @throws \yii\base\Exception * @throws \yii\db\Exception */ public function onAuthSuccess($client) { $attributes = $client->getUserAttributes(); // VK if ($client instanceof \yii\authclient\clients\VKontakte) { $auth_params = $client->getAccessToken()->getParams(); $email = ArrayHelper::getValue($auth_params, 'email', ''); // Аватарка из VK да ПОБОЛЬШЕ!!! $vk_data_response = $client->api('users.get', 'POST', ['uids' => $attributes['id'], 'fields' => 'photo_max_orig']); if ($vk_data_response = ArrayHelper::getValue($vk_data_response, 'response', false)) { $vk_data = array_shift($vk_data_response); } $userInfo['source_id'] = $attributes['id']; $userInfo['username'] = $attributes['screen_name'] ? $attributes['screen_name'] : GlobalHelper::usernameFromEmail($attributes['email']); $userInfo['email'] = $attributes['email']; $userInfo['name'] = $attributes['first_name']; $userInfo['surname'] = $attributes['last_name']; $userInfo['birth_date'] = date('Y-m-d', strtotime($attributes['bdate'])); $userInfo['sex'] = $attributes['sex'] == 2 ? 'm' : 'f'; } // YANDEX if ($client instanceof \yii\authclient\clients\YandexOAuth) { $userInfo['source_id'] = $attributes['id']; $userInfo['username'] = $attributes['login'] ? $attributes['login'] : GlobalHelper::usernameFromEmail($attributes['emails'][0]); $userInfo['email'] = $attributes['emails'][0]; $userInfo['name'] = $attributes['first_name']; $userInfo['surname'] = $attributes['last_name']; $userInfo['birth_date'] = $attributes['birthday']; $userInfo['sex'] = $attributes['sex'] == 'male' ? 'm' : 'f'; } // FACEBOOK if ($client instanceof \yii\authclient\clients\Facebook) { //var_dump($attributes); die(); $userInfo['source_id'] = $attributes['id']; $userInfo['username'] = GlobalHelper::usernameFromEmail($attributes['email']); $userInfo['email'] = $attributes['email']; $userInfo['name'] = $attributes['name']; $userInfo['surname'] = ''; $userInfo['birth_date'] = ''; $userInfo['sex'] = ''; } // GOOGLE if ($client instanceof \yii\authclient\clients\GoogleOAuth) { //var_dump($attributes); die(); $userInfo['source_id'] = $attributes['id']; $userInfo['username'] = GlobalHelper::usernameFromEmail($attributes['emails'][0]["value"]); $userInfo['email'] = $attributes['emails'][0]["value"]; $userInfo['name'] = $attributes['name']["givenName"]; $userInfo['surname'] = $attributes['name']["familyName"]; $userInfo['birth_date'] = ''; $userInfo['sex'] = $attributes['gender'] == 'male' ? 'm' : 'f'; } // MAIL.RU if ($client instanceof \frontend\components\auth\Mailru) { //var_dump($attributes[0]); die(); $userInfo['source_id'] = $attributes['id']; $userInfo['username'] = GlobalHelper::usernameFromEmail($attributes[0]['email']); $userInfo['email'] = $attributes[0]["email"]; $userInfo['name'] = $attributes[0]["first_name"]; $userInfo['surname'] = $attributes[0]["last_name"]; $userInfo['birth_date'] = date('Y-m-d', strtotime($attributes[0]["birthday"])); $userInfo['sex'] = $attributes[0]["sex"] == 0 ? 'm' : 'f'; } /*// ODNOKLASSNIKI if($client instanceof \frontend\components\auth\Odnoklassniki) { var_dump($attributes); die(); $userInfo['source_id'] = $attributes['uid']; $userInfo['username'] = GlobalHelper::usernameFromEmail($attributes[0]['email']); if($attributes['has_email']) $userInfo['email'] = $attributes[0]["email"]; $userInfo['name'] = $attributes["first_name"]; $userInfo['surname'] = $attributes["last_name"]; $userInfo['birth_date'] = $attributes["birthday"]; $userInfo['sex'] = ($attributes["gender"] == 'male') ? 'm' : 'f'; }*/ if (!isset($userInfo['email']) || empty($userInfo['email'])) { throw new BadRequestHttpException('Не удалось получить email адрес'); } /* @var $auth Auth */ $auth = Auth::find()->where(['source' => $client->getId(), 'source_id' => $attributes['id']])->one(); if (Yii::$app->user->isGuest) { if ($auth) { // авторизация $user = $auth->user; Yii::$app->user->login($user); Yii::$app->session->setFlash('success', 'Вход произведен. Теперь вы можете использовать все дополнительные возможности сайта.'); } else { // регистрация if (isset($userInfo['email']) && User::find()->where(['email' => $userInfo['email']])->exists()) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Пользователь с электронной почтой как в <strong>{client} (" . $userInfo['email'] . ")</strong> уже существует, но не связан с этим аккаунтом. Вероятно, вы уже регистрировались на нашем сайте с помощью другой социальной сети, к которой привязан email <strong>" . $userInfo['email'] . "</strong>, или с использованием классического способа регистрации.\n Для входа на сайт используйте тот сервис, который вы использовали в первый раз. Если это невозможно, перейдите <a href='/site/request-password-reset'>на эту страницу</a> и пройдите процедуру восстановления доступа, указав email <strong>" . $userInfo['email'] . "</strong>. На этот адрес будет отправлено письмо с дальнейшими действиями. После восстановления доступа вы сможете привязать\n к своему аккаунту любую из социальных сетей и далее входить на сайт в один клик.", ['client' => $client->getTitle()])]); } else { $password = Yii::$app->security->generateRandomString(6); $user = new User(['username' => $userInfo['username'], 'email' => $userInfo['email'], 'password' => $password]); $user->generateAuthKey(); $user->generatePasswordResetToken(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $profile = new UserProfile(); $profile->user_id = $user->id; $profile->name = $userInfo['name']; $profile->surname = $userInfo['surname']; $profile->birth_date = $userInfo['birth_date']; if (isset($userInfo['sex'])) { $profile->sex = $userInfo['sex']; } $profile->save(); $auth = new Auth(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $userInfo['source_id']]); if ($auth->save()) { $transaction->commit(); Yii::$app->session->setFlash('success', 'Вход на сайт произведен. Для вас была автоматически создана учетная запись. Информация о ней отправлена на ваш email (<strong>(' . $userInfo['email'] . ')</strong>). В дальнейшем вы можете входить на сайт как с помощью {client}, так и с помощью своего логина и пароля.'); Yii::$app->user->login($user); } else { print_r($auth->getErrors()); } } else { print_r($user->getErrors()); } } } } else { // Пользователь уже зарегистрирован if ($auth->user_id != Yii::$app->user->getId()) { // Если аккаунт привязан к другому пользователю Yii::$app->session->setFlash('error', 'Данный аккаунт ' . $client->getTitle() . ' привязан к учетной записи другого пользователя сайта. Привязать аккаунт к двум учетным записям невозможно.'); } else { Yii::$app->session->setFlash('info', 'Данный аккаунт ' . $client->getTitle() . ' уже привязан к вашей учетной записи.'); } if (!$auth) { // добавляем внешний сервис аутентификации $auth = new Auth(['user_id' => Yii::$app->user->id, 'source' => $client->getId(), 'source_id' => $attributes['id']]); $auth->save(); } } }