public function actionAutopost() { $semester = Semesters::model()->actual(); if (!$semester) { throw new CException('Нет семестра'); } $tomorrow_date = (new DateTime())->add(new DateInterval("P1D"))->format('Y-m-d'); $tomorrow_time = strtotime($tomorrow_date); if (date('N', $tomorrow_time) == 7) { throw new CException('Завтра выходной'); } $current_hour = date('G'); $week_number = ($semester->week_number + date('W', $tomorrow_time) - date('W', strtotime($semester->start_date))) % 2 ? 1 : 2; $week_day = date('N', $tomorrow_time); /** @var GroupAutopost[] $autoposts */ if (!($autoposts = GroupAutopost::model()->with(['group' => ['with' => ['schedule_elements' => ['condition' => 'week_number = :week_number AND week_day = :week_day AND semester_id = :semester_id', 'params' => [':week_number' => $week_number, ':week_day' => $week_day, ':semester_id' => $semester->id]]]]])->findAllByAttributes(['hour' => $current_hour, 'status' => GroupAutopost::STATUS_ACTIVE]))) { throw new CException('Нет групп для автопостинга'); } foreach ($autoposts as $autopost) { $replaces = CHtml::listData(GroupReplace::model()->with(['subject', 'classroom', 'teacher'])->findAllByAttributes(['group_id' => $autopost->group_id, 'date' => $tomorrow_date]), 'number', function ($model) { return array_merge($model->attributes, ['teacher' => $model->teacher, 'classroom' => $model->classroom, 'subject' => $model->subject]); }); $schedule_elements = CHtml::listData($autopost->group->schedule_elements, 'number', function ($model) { return array_merge($model->attributes, ['teacher' => $model->teacher, 'classroom' => $model->classroom, 'subject' => $model->subject]); }); $schedule = $replaces + $schedule_elements; ksort($schedule); $schedule_text = 'Расписание на завтра:' . PHP_EOL; $schedule_count = 0; /** @var $holiday Holiday */ if ($holiday = Holiday::model()->findByAttributes(['date' => $tomorrow_date])) { $schedule_text .= 'Выходной - ' . $holiday->name; } else { if ($schedule) { foreach ($schedule as $subject) { if (isset($subject['cancel']) && $subject['cancel']) { continue; } $schedule_count++; $schedule_text .= $subject['number'] . ') ' . $subject['subject']->name; if ($subject['teacher']) { $schedule_text .= ', ' . $subject['teacher']->lastname . ' ' . mb_substr($subject['teacher']->firstname, 0, 1, "UTF-8") . '.' . mb_substr($subject['teacher']->middlename, 0, 1, "UTF-8") . '.'; } if ($subject['classroom']) { $schedule_text .= ' (' . $subject['classroom']->name . ')'; } if (isset($subject['comment']) && strlen($subject['comment'])) { $schedule_text .= ' - ' . $subject['comment']; } $schedule_text .= PHP_EOL; } } if (!$schedule || $schedule_count == 0) { $schedule_text .= 'Пар нет' . PHP_EOL; } } $schedule_text .= 'Данные предоставлены проектом @studyschedule (Расписание ККЭП)'; $params = http_build_query(['owner_id' => $autopost->page_id, 'message' => $schedule_text, 'from_group' => 1, 'access_token' => $autopost->access_token]); echo "----" . $autopost->group->number . "----" . PHP_EOL; $response = file_get_contents('https://api.vk.com/method/wall.post?' . $params); if ($response) { $answer = json_decode($response, true); var_dump($answer); if (isset($answer['error'])) { $autopost->status = GroupAutopost::STATUS_DISABLE; $autopost->save(); $email = $autopost->group->owner->email; $mail = new YiiMailer("autopost", ['group' => $autopost->group]); $mail->setFrom(isset(Yii::app()->params->YiiMailer->Username) ? Yii::app()->params->YiiMailer->Username : Yii::app()->params->adminEmail, 'Система управления учебным расписанием'); $mail->setTo($email); $mail->setSubject('Ошибка автопостинга в ВКонтакте'); $mail->send(); } } else { echo 'Error when send request...'; } echo PHP_EOL; } }
public function actionAutoPost($step = 0) { if ($autopost = GroupAutopost::model()->findByAttributes(['group_id' => self::$group->id])) { //throw new CHttpException(403, 'У вашей группы уже есть автопостинг, его настройки будут доступны позже'); $delete = Yii::app()->request->getParam('delete', 0); if (!$delete) { $this->render('autopost/settings', ['group' => self::$group, 'autopost' => $autopost]); } else { $autopost->delete(); Yii::app()->user->setFlash('success', 'Автопостинг в ВК успешно отключен'); $this->redirect(['site/dashboard']); } } else { if (!in_array($step, [0, 1, 2])) { throw new CHttpException(404, 'Данный шаг отсутсвует'); } switch ($step) { case 0: $this->render('autopost/token', ['group' => self::$group]); break; case 1: $url = Yii::app()->request->getParam('access_token'); if (!$url) { Yii::app()->user->setFlash('error', 'Вы не вставили ссылку'); $this->render('autopost/token', ['group' => self::$group]); } else { parse_str(explode('#', $url)[1], $url_data); if (!isset($url_data['access_token'])) { Yii::app()->user->setFlash('error', 'Ссылка неверна'); $this->render('autopost/token', ['group' => self::$group]); } else { $access_token = $url_data['access_token']; $params = http_build_query(['access_token' => $access_token]); $answer = json_decode(file_get_contents('https://api.vk.com/method/account.getAppPermissions?' . $params), true); if (isset($answer['error'])) { Yii::app()->user->setFlash('error', 'Ключ в ссылке неверный'); $this->render('autopost/token', ['group' => self::$group]); } else { if (($answer['response'] & 262144) == 0 || ($answer['response'] & 8192) == 0 || ($answer['response'] & 65536) == 0) { Yii::app()->user->setFlash('error', 'Ключ в ссылке не дает нужных прав'); $this->render('autopost/token', ['group' => self::$group]); } else { $params = http_build_query(['extended' => 1, 'access_token' => $access_token, 'filter' => 'moder']); $answer = json_decode(file_get_contents('https://api.vk.com/method/groups.get?' . $params), true); Yii::app()->session->add('vk_access_token', $access_token); $groups = []; foreach ($answer['response'] as $group) { if ($group['gid']) { $groups[-(int) $group['gid']] = $group['name']; } } $this->render('autopost/page_and_hour', ['group' => self::$group, 'groups' => $groups, 'hours' => array_combine(array_values(GroupAutopost::$hours), array_values(GroupAutopost::$hours))]); } } } } break; case 2: $page_id = Yii::app()->request->getParam('page_id'); $hour = Yii::app()->request->getParam('hour'); $access_token = Yii::app()->session->get('vk_access_token'); if (!$access_token || !$page_id || !$hour || !in_array($hour, GroupAutopost::$hours)) { $params = http_build_query(['extended' => 1, 'access_token' => $access_token, 'filter' => 'moder']); $answer = json_decode(file_get_contents('https://api.vk.com/method/groups.get?' . $params), true); if (isset($answer['error'])) { Yii::app()->user->setFlash('error', 'Ключ неверный'); $this->render('autopost/token', ['group' => self::$group]); } else { Yii::app()->user->setFlash('error', 'Вы не указали час или группу'); Yii::app()->session->add('vk_access_token', $access_token); $groups = []; foreach ($answer['response'] as $group) { if ($group['gid']) { $groups[-(int) $group['gid']] = $group['name']; } } $this->render('autopost/page_and_hour', ['group' => self::$group, 'groups' => $groups, 'hours' => array_combine(array_values(GroupAutopost::$hours), array_values(GroupAutopost::$hours))]); } } else { Yii::app()->session->remove('access_token'); $autopost = new GroupAutopost(); $autopost->setAttributes(['group_id' => self::$group->id, 'page_id' => $page_id, 'hour' => $hour, 'access_token' => $access_token]); $autopost->save(); Yii::app()->user->setFlash('success', 'Автопостинг в ВК успешно настроен'); $this->redirect(['site/dashboard']); } break; } } }