123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454 |
- <?php
- /* For licensing terms, see /license.txt */
- /**
- * Class ScheduledAnnouncement
- * Requires DB change:.
- *
- * CREATE TABLE scheduled_announcements (id INT AUTO_INCREMENT NOT NULL, subject VARCHAR(255) NOT NULL, message LONGTEXT NOT NULL, date DATETIME DEFAULT NULL, sent TINYINT(1) NOT NULL, session_id INT NOT NULL, c_id INT DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
- *
- * Config setting:
- * $_configuration['allow_scheduled_announcements'] = true;
- *
- * Setup linux cron file:
- * main/cron/scheduled_announcement.php
- *
- * Requires:
- * composer update
- *
- * @package chamilo.library
- */
- class ScheduledAnnouncement extends Model
- {
- public $table;
- public $columns = ['id', 'subject', 'message', 'date', 'sent', 'session_id'];
- /**
- * Constructor.
- */
- public function __construct()
- {
- parent::__construct();
- $this->table = 'scheduled_announcements';
- }
- /**
- * @param array $where_conditions
- *
- * @return array
- */
- public function get_all($where_conditions = [])
- {
- return Database::select(
- '*',
- $this->table,
- ['where' => $where_conditions, 'order' => 'subject ASC']
- );
- }
- /**
- * @return mixed
- */
- public function get_count()
- {
- $row = Database::select(
- 'count(*) as count',
- $this->table,
- [],
- 'first'
- );
- return $row['count'];
- }
- /**
- * Displays the title + grid.
- *
- * @param int $sessionId
- *
- * @return string
- */
- public function getGrid($sessionId)
- {
- // action links
- $action = '<div class="actions" style="margin-bottom:20px">';
- $action .= Display::url(
- Display::return_icon('back.png', get_lang('Back'), '', ICON_SIZE_MEDIUM),
- api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$sessionId
- );
- $action .= '<a href="'.api_get_self().'?action=add&session_id='.$sessionId.'">'.
- Display::return_icon('add.png', get_lang('Add'), '', ICON_SIZE_MEDIUM).'</a>';
- $action .= '<a href="scheduled_announcement.php?action=run&session_id='.$sessionId.'">'.
- Display::return_icon('tuning.png', get_lang('SendManuallyPendingAnnouncements'), '', ICON_SIZE_MEDIUM).
- '</a>';
- $action .= '</div>';
- $html = $action;
- $html .= '<div id="session-table" class="table-responsive">';
- $html .= Display::grid_html('programmed');
- $html .= '</div>';
- return $html;
- }
- /**
- * Returns a Form validator Obj.
- *
- * @param int $id
- * @param string $url
- * @param string $action add, edit
- * @param array $sessionInfo
- *
- * @return FormValidator form validator obj
- */
- public function returnSimpleForm($id, $url, $action, $sessionInfo = [])
- {
- $form = new FormValidator(
- 'announcement',
- 'post',
- $url
- );
- $form->addHidden('session_id', $sessionInfo['id']);
- $form->addDateTimePicker('date', get_lang('Date'));
- $form->addText('subject', get_lang('Subject'));
- $form->addHtmlEditor('message', get_lang('Message'));
- $extraField = new ExtraField('scheduled_announcement');
- $extra = $extraField->addElements($form, $id);
- $js = $extra['jquery_ready_content'];
- $form->addHtml("<script> $(function() { $js }); </script> ");
- $this->setTagsInForm($form);
- $form->addCheckBox('sent', null, get_lang('MessageSent'));
- if ($action == 'edit') {
- $form->addButtonUpdate(get_lang('Modify'));
- }
- return $form;
- }
- /**
- * Returns a Form validator Obj.
- *
- * @todo the form should be auto generated
- *
- * @param string $url
- * @param string $action add, edit
- * @param array
- *
- * @return FormValidator form validator obj
- */
- public function returnForm($url, $action, $sessionInfo = [])
- {
- // Setting the form elements
- $header = get_lang('Add');
- if ($action == 'edit') {
- $header = get_lang('Modify');
- }
- $form = new FormValidator(
- 'announcement',
- 'post',
- $url
- );
- $form->addHeader($header);
- if ($action == 'add') {
- $form->addHtml(
- Display::return_message(
- nl2br(get_lang('ScheduleAnnouncementDescription')),
- 'normal',
- false
- )
- );
- }
- $form->addHidden('session_id', $sessionInfo['id']);
- $useBaseDate = false;
- $startDate = $sessionInfo['access_start_date'];
- $endDate = $sessionInfo['access_end_date'];
- if (!empty($startDate) || !empty($endDate)) {
- $useBaseDate = true;
- }
- $typeOptions = [
- 'specific_date' => get_lang('SpecificDate'),
- ];
- if ($useBaseDate) {
- $typeOptions['base_date'] = get_lang('BaseDate');
- }
- $form->addSelect(
- 'type',
- get_lang('Type'),
- $typeOptions,
- [
- 'onchange' => "javascript:
- if (this.options[this.selectedIndex].value == 'base_date') {
- document.getElementById('options').style.display = 'block';
- document.getElementById('specific_date').style.display = 'none';
- } else {
- document.getElementById('options').style.display = 'none';
- document.getElementById('specific_date').style.display = 'block';
- }
- ", ]
- );
- $form->addHtml('<div id="specific_date">');
- $form->addDateTimePicker('date', get_lang('Date'));
- $form->addHtml('</div>');
- $form->addHtml('<div id="options" style="display:none">');
- $startDate = $sessionInfo['access_start_date'];
- $endDate = $sessionInfo['access_end_date'];
- $form->addText(
- 'days',
- get_lang('Days'),
- false
- );
- $form->addSelect(
- 'moment_type',
- get_lang('AfterOrBefore'),
- [
- 'after' => get_lang('After'),
- 'before' => get_lang('Before'),
- ]
- );
- if (!empty($startDate)) {
- $options['start_date'] = get_lang('StartDate').' - '.$startDate;
- }
- if (!empty($endDate)) {
- $options['end_date'] = get_lang('EndDate').' - '.$endDate;
- }
- if (!empty($options)) {
- $form->addSelect('base_date', get_lang('BaseDate'), $options);
- }
- $form->addHtml('</div>');
- $form->addText('subject', get_lang('Subject'));
- $form->addHtmlEditor('message', get_lang('Message'));
- $extraField = new ExtraField('scheduled_announcement');
- $extra = $extraField->addElements($form);
- $js = $extra['jquery_ready_content'];
- $form->addHtml("<script> $(function() { $js }); </script> ");
- $this->setTagsInForm($form);
- if ($action == 'edit') {
- $form->addButtonUpdate(get_lang('Modify'));
- } else {
- $form->addButtonCreate(get_lang('Add'));
- }
- return $form;
- }
- /**
- * @param int $id
- *
- * @return string
- */
- public function getAttachmentToString($id)
- {
- $file = $this->getAttachment($id);
- if (!empty($file) && !empty($file['value'])) {
- $url = api_get_path(WEB_UPLOAD_PATH).$file['value'];
- return get_lang('Attachment').': '.Display::url(basename($file['value']), $url, ['target' => '_blank']);
- }
- return '';
- }
- /**
- * @param int $id
- *
- * @return array
- */
- public function getAttachment($id)
- {
- $extraFieldValue = new ExtraFieldValue('scheduled_announcement');
- $attachment = $extraFieldValue->get_values_by_handler_and_field_variable($id, 'attachment');
- return $attachment;
- }
- /**
- * @param int $urlId
- *
- * @return int
- */
- public function sendPendingMessages($urlId = 0)
- {
- if (!$this->allowed()) {
- return 0;
- }
- $messagesSent = 0;
- $now = api_get_utc_datetime();
- $result = $this->get_all();
- foreach ($result as $result) {
- if (empty($result['sent'])) {
- if (!empty($result['date']) && $result['date'] < $now) {
- $sessionId = $result['session_id'];
- $sessionInfo = api_get_session_info($sessionId);
- if (empty($sessionInfo)) {
- continue;
- }
- $users = SessionManager::get_users_by_session(
- $sessionId,
- 0,
- false,
- $urlId
- );
- $coachId = $sessionInfo['id_coach'];
- if (empty($users) || empty($coachId)) {
- continue;
- }
- if ($users) {
- $this->update(['id' => $result['id'], 'sent' => 1]);
- $attachments = $this->getAttachmentToString($result['id']);
- $subject = $result['subject'];
- foreach ($users as $user) {
- // Take original message
- $message = $result['message'];
- $userInfo = api_get_user_info($user['user_id']);
- $courseList = SessionManager::getCoursesInSession($sessionId);
- $courseInfo = [];
- if (!empty($courseList)) {
- $courseId = current($courseList);
- $courseInfo = api_get_course_info_by_id($courseId);
- }
- $progress = '';
- if (!empty($sessionInfo) && !empty($courseInfo)) {
- $progress = Tracking::get_avg_student_progress(
- $user['user_id'],
- $courseInfo['code'],
- [],
- $sessionId
- );
- }
- if (is_numeric($progress)) {
- $progress = $progress.'%';
- } else {
- $progress = '0%';
- }
- $startTime = api_get_local_time(
- $sessionInfo['access_start_date'],
- null,
- null,
- true
- );
- $endTime = api_get_local_time(
- $sessionInfo['access_end_date'],
- null,
- null,
- true
- );
- $generalCoach = '';
- $generalCoachEmail = '';
- if (!empty($sessionInfo['id_coach'])) {
- $coachInfo = api_get_user_info($sessionInfo['id_coach']);
- if (!empty($coachInfo)) {
- $generalCoach = $coachInfo['complete_name'];
- $generalCoachEmail = $coachInfo['email'];
- }
- }
- $tags = [
- '((session_name))' => $sessionInfo['name'],
- '((session_start_date))' => $startTime,
- '((general_coach))' => $generalCoach,
- '((general_coach_email))' => $generalCoachEmail,
- '((session_end_date))' => $endTime,
- '((user_complete_name))' => $userInfo['complete_name'],
- '((user_first_name))' => $userInfo['firstname'],
- '((user_last_name))' => $userInfo['lastname'],
- '((lp_progress))' => $progress,
- ];
- $message = str_replace(array_keys($tags), $tags, $message);
- $message .= $attachments;
- MessageManager::send_message_simple(
- $userInfo['user_id'],
- $subject,
- $message,
- $coachId
- );
- }
- }
- $messagesSent++;
- }
- }
- }
- return $messagesSent;
- }
- /**
- * @return array
- */
- public function getTags()
- {
- $tags = [
- '((session_name))',
- '((session_start_date))',
- '((session_end_date))',
- '((general_coach))',
- '((general_coach_email))',
- '((user_complete_name))',
- '((user_first_name))',
- '((user_last_name))',
- '((lp_progress))',
- ];
- return $tags;
- }
- /**
- * @return bool
- */
- public function allowed()
- {
- return api_get_configuration_value('allow_scheduled_announcements');
- }
- /**
- * @param FormValidator $form
- */
- private function setTagsInForm(&$form)
- {
- $form->addLabel(
- get_lang('Tags'),
- Display::return_message(
- implode('<br />', $this->getTags()),
- 'normal',
- false
- )
- );
- }
- }
|