/**
  * Проверяем, что текущий пользователь имеет право редактировать записи
  *
  * @param CModel $model
  * @return bool
  */
 public function onUpdate(CModel $model)
 {
     $result = true;
     if (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_NO_ACCESS) {
         /**
          * Проверим, что пользователь имеет доступ к текущей задаче
          */
         $result = false;
     } elseif (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_READ_OWN_ONLY || CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_READ_ALL) {
         /**
          * Пользователь с правом только на чтение не может что-либо сохранять
          */
         $result = false;
     } elseif (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_WRITE_OWN_ONLY) {
         /**
          * Проверим, что текущий пользователь есть в authors-полях модели,
          * которую будет сохранять
          */
         $result = false;
         $coreModel = CCoreObjectsManager::getCoreModel($model);
         if (is_null($coreModel)) {
             /**
              * Если модели нет, то будем считать, что отвалидировано
              * успешно. Иначе сломается все остальное
              */
             $result = true;
         } else {
             if ($coreModel->getAuthorsFields()->getCount() == 0) {
                 /**
                  * Не стопорим систему если она не настроена.
                  * Если поля не указаны, то не валидируем
                  */
                 $result = true;
             } else {
                 /**
                  * Проверяем, что текущий пользователь прописан в authors-полях модели
                  */
                 foreach ($coreModel->getAuthorsFields()->getItems() as $field) {
                     $fieldName = $field->field_name;
                     if ($model->{$fieldName} == CSession::getCurrentPerson()->getId()) {
                         $result = true;
                     }
                 }
             }
         }
     }
     return $result;
 }
 public function actionIndex()
 {
     $selectedYear = null;
     $set = new CRecordSet();
     $query = new CQuery();
     $set->setQuery($query);
     $query->select("p.*")->from(TABLE_PERSON . " as p")->order("p.fio asc");
     if (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_WRITE_OWN_ONLY || CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_READ_OWN_ONLY) {
         if (is_null(CSession::getCurrentPerson())) {
             $query->condition("p.id = 0");
         } else {
             $query->condition("p.id = " . CSession::getCurrentPerson()->getId());
         }
     }
     // фильтр по году
     if (!is_null(CRequest::getFilter("year.id"))) {
         $query->innerJoin(TABLE_IND_PLAN_LOADS . " as l", "l.person_id = p.id");
         $query->innerJoin(TABLE_YEARS . " as year", "l.year_id = year.id");
         $selectedYear = CRequest::getFilter("year.id");
     }
     $yearsQuery = new CQuery();
     $yearsQuery->select("year.*")->from(TABLE_YEARS . " as year")->order("year.name asc");
     $years = array();
     foreach ($yearsQuery->execute()->getItems() as $ar) {
         $year = new CTimeIntervals(new CActiveRecord($ar));
         $years[$year->getId()] = $year->name;
     }
     $persons = new CArrayList();
     foreach ($set->getPaginated()->getItems() as $ar) {
         $person = new CPerson($ar);
         $persons->add($person->getId(), $person);
     }
     $this->addActionsMenuItem(array(array("title" => "Назад", "link" => "index.php", "icon" => "actions/edit-undo.png"), array("title" => "Печать по шаблону", "link" => "#", "icon" => "devices/printer.png", "template" => "formset_ind_plan_view")));
     $this->setData("paginator", $set->getPaginator());
     $this->setData("persons", $persons);
     $this->setData("years", $years);
     $this->setData("selectedYear", $selectedYear);
     $this->renderView("_individual_plan/load/index.tpl");
 }
 public function actionIndex()
 {
     $set = new CRecordSet(true);
     $query = new CQuery();
     $set->setQuery($query);
     $query->select("p.*")->from(TABLE_PERSON . " as p")->order("p.fio asc");
     if (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_WRITE_OWN_ONLY || CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_READ_OWN_ONLY) {
         if (is_null(CSession::getCurrentPerson())) {
             $query->condition("p.id = 0");
         } else {
             $query->condition("p.id = " . CSession::getCurrentPerson()->getId());
         }
     }
     $persons = new CArrayList();
     foreach ($set->getPaginated()->getItems() as $ar) {
         $person = new CPerson($ar);
         $persons->add($person->getId(), $person);
     }
     $this->addActionsMenuItem(array(array("title" => "Назад", "link" => "index.php", "icon" => "actions/edit-undo.png"), array("title" => "Печать по шаблону", "link" => "#", "icon" => "devices/printer.png", "template" => "formset_ind_plan_view")));
     $this->setData("paginator", $set->getPaginator());
     $this->setData("persons", $persons);
     $this->renderView("_individual_plan/load/index.tpl");
 }
Esempio n. 4
0
 public function createGroupChangeHistoryPoint(CStudentGroup $source = null, CStudentGroup $target = null)
 {
     $history = new CStudentGroupChangeHistory();
     $history->student_id = $this->getId();
     $history->source_id = 0;
     if (!is_null($source)) {
         $history->source_id = $source->getId();
     }
     $history->target_id = 0;
     if (!is_null($target)) {
         $history->target_id = $target->getId();
     }
     $history->date = date("d.m.Y");
     $history->person_id = CSession::getCurrentPerson()->getId();
     $history->save();
 }
 public function actionIndex()
 {
     $set = new CRecordSet(false);
     $query = new CQuery();
     $query->select("activity.*")->from(TABLE_STUDENTS_ACTIVITY . " as activity");
     // сортировки по столбцам
     if (CRequest::getString("order") == "") {
         $query->order("activity.id desc");
     } elseif (CRequest::getString("order") == "date_act") {
         if (CRequest::getString("direction") == "") {
             $query->order("activity.date_act desc");
         } else {
             $query->order("activity.id " . CRequest::getString("direction"));
         }
     } elseif (CRequest::getString("order") == "subject_id") {
         $query->leftJoin(TABLE_DISCIPLINES . " as discipline", "activity.subject_id = discipline.id");
         if (CRequest::getString("direction") == "") {
             $query->order("discipline.name asc");
         } else {
             $query->order("discipline.name " . CRequest::getString("direction"));
         }
     } elseif (CRequest::getString("order") == "kadri_id") {
         $query->leftJoin(TABLE_PERSON . " as person", "activity.kadri_id = person.id");
         if (CRequest::getString("direction") == "") {
             $query->order("person.fio asc");
         } else {
             $query->order("person.fio " . CRequest::getString("direction"));
         }
     } elseif (CRequest::getString("order") == "student_id") {
         $query->leftJoin(TABLE_STUDENTS . " as student_f", "student_f.id = activity.student_id");
         if (CRequest::getString("direction") == "") {
             $query->order("student_f.fio asc");
         } else {
             $query->order("student_f.fio " . CRequest::getString("direction"));
         }
     } else {
         $query = new CQuery();
         $query->select("activity.*")->from(TABLE_STUDENTS_ACTIVITY)->order("activity.id desc");
     }
     // запросы для получения списка групп и списка преподавателей
     $personQuery = new CQuery();
     $personQuery->select("distinct(person.id) as id, person.fio as name")->from(TABLE_STUDENTS_ACTIVITY . " as activity")->innerJoin(TABLE_PERSON . " as person", "activity.kadri_id = person.id")->order("person.fio asc");
     $groupQuery = new CQuery();
     $groupQuery->select("distinct(st_group.id) as id, st_group.name as name")->from(TABLE_STUDENTS_ACTIVITY . " as activity")->innerJoin(TABLE_STUDENTS . " as student", "student.id = activity.student_id")->innerJoin(TABLE_STUDENT_GROUPS . " as st_group", "st_group.id = student.group_id")->order("st_group.name asc");
     $disciplineQuery = new CQuery();
     $disciplineQuery->select("distinct(subject.id) as id, subject.name as name")->from(TABLE_STUDENTS_ACTIVITY . " as activity")->innerJoin(TABLE_DISCIPLINES . " as subject", "activity.subject_id = subject.id")->order("subject.name asc");
     // фильтры
     $selectedPerson = null;
     $selectedGroup = null;
     $selectedDiscipline = null;
     $selectedStudent = null;
     $selectedControl = null;
     if (CRequest::getString("filter") !== "") {
         $filters = explode("_", CRequest::getString("filter"));
         foreach ($filters as $filter) {
             $f = explode(":", $filter);
             if (count($f) > 1) {
                 $key = $f[0];
                 $value = $f[1];
                 if ($key == "person") {
                     if ($value != 0) {
                         $selectedPerson = $value;
                         $query->condition("kadri_id=" . $value);
                     }
                 } elseif ($key == "group") {
                     if ($value != 0) {
                         $selectedGroup = $value;
                         $query->innerJoin(TABLE_STUDENTS . " as student", "activity.student_id = student.id");
                         $query->innerJoin(TABLE_STUDENT_GROUPS . " as st_group", "student.group_id = st_group.id AND st_group.id=" . $value);
                     }
                 } elseif ($key == "discipline") {
                     if ($value != 0) {
                         $selectedDiscipline = $value;
                         $query->innerJoin(TABLE_DISCIPLINES . " as subject", "subject.id = activity.subject_id AND subject.id=" . $value);
                     }
                 } elseif ($key == "student") {
                     if ($value != 0) {
                         $selectedStudent = CStaffManager::getStudent($value);
                         $query->innerJoin(TABLE_STUDENTS . " as student", "activity.student_id = student.id AND student.id=" . $value);
                     }
                 } elseif ($key == "control") {
                     if ($value != 0) {
                         $selectedControl = CTaxonomyManager::getControlType($value);
                         $query->innerJoin(TABLE_STUDENTS_CONTROL_TYPES . " as control", "activity.study_act_id = control.id AND control.id=" . $value);
                     }
                 }
             }
         }
         /**
          * Дополняем фильтры по преподавателям, группам и дисциплинам
          */
         if (!is_null($selectedPerson)) {
             $groupQuery->innerJoin(TABLE_PERSON . " as person", "person.id = activity.kadri_id AND person.id=" . $selectedPerson);
             $disciplineQuery->innerJoin(TABLE_PERSON . " as person", "person.id = activity.kadri_id AND person.id=" . $selectedPerson);
         }
         if (!is_null($selectedGroup)) {
             $personQuery->innerJoin(TABLE_STUDENTS . " as student", "student.id = activity.student_id");
             $personQuery->innerJoin(TABLE_STUDENT_GROUPS . " as st_group", "st_group.id = student.group_id and st_group.id=" . $selectedGroup);
             $disciplineQuery->innerJoin(TABLE_STUDENTS . " as student", "student.id = activity.student_id");
             $disciplineQuery->innerJoin(TABLE_STUDENT_GROUPS . " as st_group", "st_group.id = student.group_id and st_group.id=" . $selectedGroup);
         }
         if (!is_null($selectedDiscipline)) {
             $personQuery->innerJoin(TABLE_DISCIPLINES . " as subject", "subject.id = activity.subject_id AND subject.id=" . $selectedDiscipline);
             $groupQuery->innerJoin(TABLE_DISCIPLINES . " as subject", "subject.id = activity.subject_id AND subject.id=" . $selectedDiscipline);
         }
         if (!is_null($selectedStudent)) {
             $personQuery->innerJoin(TABLE_STUDENTS . " as student_s", "student_s.id = activity.student_id AND student_s.id=" . $selectedStudent->getId());
             $groupQuery->innerJoin(TABLE_STUDENTS . " as student_s", "student_s.id = activity.student_id AND student_s.id=" . $selectedStudent->getId());
             $disciplineQuery->innerJoin(TABLE_STUDENTS . " as student_s", "student_s.id = activity.student_id AND student_s.id=" . $selectedStudent->getId());
         }
         if (!is_null($selectedControl)) {
             $personQuery->innerJoin(TABLE_STUDENTS_CONTROL_TYPES . " as control", "activity.study_act_id = control.id AND control.id=" . $selectedControl->getId());
             $groupQuery->innerJoin(TABLE_STUDENTS_CONTROL_TYPES . " as control", "activity.study_act_id = control.id AND control.id=" . $selectedControl->getId());
             $disciplineQuery->innerJoin(TABLE_STUDENTS_CONTROL_TYPES . " as control", "activity.study_act_id = control.id AND control.id=" . $selectedControl->getId());
         }
     }
     /**
      * Ограничения по уровню доступа
      */
     if (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_READ_OWN_ONLY) {
         $query->condition("activity.kadri_id=" . CSession::getCurrentPerson()->getId());
     } elseif (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_WRITE_OWN_ONLY) {
         $query->condition("activity.kadri_id=" . CSession::getCurrentPerson()->getId());
     }
     $set->setQuery($query);
     // ищем преподавателей, у которых есть оценки в списке
     $persons = array();
     foreach ($personQuery->execute()->getItems() as $item) {
         $persons[$item["id"]] = $item["name"];
     }
     // ищем группы, из которых студенты есть в списке
     $groups = array();
     foreach ($groupQuery->execute()->getItems() as $item) {
         $groups[$item["id"]] = $item["name"];
     }
     // ищем дисциплины, по которым ставились оценки
     $disciplines = array();
     foreach ($disciplineQuery->execute()->getItems() as $item) {
         $disciplines[$item["id"]] = $item["name"];
     }
     // остальные данные
     $items = new CArrayList();
     foreach ($set->getPaginated()->getItems() as $item) {
         $a = new CStudentActivity($item);
         $items->add($a->getId(), $a);
     }
     /**
      * Формируем меню
      */
     $this->addActionsMenuItem(array(array("title" => "Добавить", "link" => "?action=add", "icon" => "actions/list-add.png"), array("title" => "Групповое добавление", "link" => "index.php?action=addGroup", "icon" => "actions/mail-reply-all.png"), array("title" => "Групповые операции", "link" => "#", "icon" => "actions/address-book-new.png", "child" => array(array("title" => "Удалить выбранные", "link" => "index.php", "action" => "removeGroup", "icon" => "actions/edit-clear.png", "form" => "#gradebookForm"))), array("title" => "Мои журналы", "link" => "index.php?action=myGradebooks", "icon" => "actions/format-justify-fill.png")));
     $this->setData("persons", $persons);
     $this->setData("selectedPerson", $selectedPerson);
     $this->setData("groups", $groups);
     $this->setData("selectedGroup", $selectedGroup);
     $this->setData("disciplines", $disciplines);
     $this->setData("selectedDiscipline", $selectedDiscipline);
     $this->setData("selectedStudent", $selectedStudent);
     $this->setData("selectedControl", $selectedControl);
     $this->setData("records", $items);
     $this->setData("paginator", $set->getPaginator());
     $this->renderView("_gradebook/index.tpl");
 }
 public function actionView()
 {
     $mail = CStaffManager::getMessage(CRequest::getInt("id"));
     $isMy = false;
     if (!is_null($mail->getSender())) {
         if ($mail->getSender()->getId() == CSession::getCurrentUser()->getId()) {
             $isMy = true;
         }
     }
     if (!is_null($mail->getRecipient())) {
         if ($mail->getRecipient()->getId() == CSession::getCurrentUser()->getId()) {
             $isMy = true;
         }
     }
     if (!is_null($mail->getSender())) {
         if (!is_null(CSession::getCurrentPerson())) {
             if ($mail->getSender()->getId() == CSession::getCurrentPerson()->getId()) {
                 $isMy = true;
             }
         }
     }
     if (!is_null($mail->getRecipient())) {
         if (!is_null(CSession::getCurrentPerson())) {
             if ($mail->getRecipient()->getId() == CSession::getCurrentPerson()->getId()) {
                 $isMy = true;
             }
         }
     }
     if (!$isMy) {
         // со студентом тупняк. Он ненормальный адресат
         //exit;
     }
     if (!$mail->isRead()) {
         //   if (!is_null($mail->getRecipient())) {
         //       if ($mail->getRecipient()->getId() == CSession::getCurrentUser()->getId()) {
         $mail->read_status = 1;
         $mail->save();
         //       }
         //   }
     }
     $this->setData("mail", $mail);
     $this->renderView("_messages/view.tpl");
 }
 public function actionSaveCalendar()
 {
     if (!CSession::isAuth()) {
         $this->redirectNoAccess();
     }
     $cal = CFactory::createCalendar();
     $cal->setName(CRequest::getString("name"));
     $cal->setDescription(CRequest::getString("description"));
     $cal->setDefault(false);
     $cal->setResource(CSession::getCurrentPerson()->getResource());
     $cal->save();
     $this->redirect(WEB_ROOT . "_modules/_calendar/");
 }
 public function actionSave()
 {
     if (!CSession::isAuth()) {
         $this->redirectNoAccess();
     }
     $event = CFactory::createEvent();
     $event->setName(CRequest::getString("name"));
     $event->setDescription(CRequest::getString("description"));
     $event->setStartTime(CRequest::getString("eventStart"));
     $event->setEndTime(CRequest::getString("eventEnd"));
     $members = new CArrayList();
     $members->add(CSession::getCurrentPerson()->getResource()->getId(), CSession::getCurrentPerson()->getResource());
     foreach (CRequest::getArray("members") as $m) {
         $member = CResourcesManager::getResourceById($m);
         if (!is_null($member)) {
             $members->add($member->getId(), $member);
         }
     }
     $event->setMembers($members);
     $event->setCalendar(CResourcesManager::getCalendarById(CRequest::getInt("calendar_id")));
     $event->save();
     $this->redirect(WEB_ROOT . "_modules/_calendar/?resource_id=" . CSession::getCurrentPerson()->getResource()->getId() . "&calendar_id=" . CRequest::getInt("calendar_id"));
 }
 public function actionAdd()
 {
     /**
      * получим дисциплину, по которой делаем рабочую программу
      * @var CCorriculumDiscipline $discipline
      * @var CCorriculum $corriculum
      */
     $discipline = CCorriculumsManager::getDiscipline(CRequest::getInt("id"));
     $corriculum = $discipline->cycle->corriculum;
     //
     $plan = new CWorkPlan();
     $plan->title = "Наименование не указано";
     $plan->title_display = $plan->title;
     // дисциплина из учебного плана
     $plan->corriculum_discipline_id = $discipline->getId();
     // дисциплина из справочника
     if (!is_null($discipline->discipline)) {
         $plan->discipline_id = $discipline->discipline->getId();
     }
     // копируем информацию из учебного плана
     if (!is_null($corriculum)) {
         $plan->direction_id = $corriculum->speciality_direction_id;
         $plan->qualification_id = $corriculum->qualification_id;
         $plan->education_form_id = $corriculum->form_id;
     }
     $plan->year = date("Y");
     $plan->authors = new CArrayList();
     $plan->authors->add(CSession::getCurrentPerson()->getId(), CSession::getCurrentPerson()->getId());
     // место дисциплины в структуре плана
     if (!is_null($discipline->cycle)) {
         $plan->position = "Дисциплина относится к базовой части учебного цикла " . $discipline->cycle->title;
     }
     $plan->save();
     /**
      * Скопируем компетенции из плана
      * @var CCorriculumDisciplineCompetention $competention
      */
     foreach ($discipline->competentions->getItems() as $competention) {
         $planCompetention = new CWorkPlanCompetention();
         $planCompetention->plan_id = $plan->getId();
         $planCompetention->allow_delete = 0;
         $planCompetention->competention_id = $competention->competention_id;
         if ($competention->knowledge_id != 0) {
             $planCompetention->knowledges->add($competention->knowledge_id, $competention->knowledge_id);
         }
         if ($competention->skill_id != 0) {
             $planCompetention->skills->add($competention->skill_id, $competention->skill_id);
         }
         if ($competention->experience_id != 0) {
             $planCompetention->experiences->add($competention->experience_id, $competention->experience_id);
         }
         $planCompetention->save();
     }
     $this->redirect("?action=edit&id=" . $plan->getId());
 }
 public function actionSearch()
 {
     $res = array();
     $term = CRequest::getString("query");
     /**
      * Сначала поищем по названию публикации
      */
     $query = new CQuery();
     $query->select("distinct(pub.id) as id, pub.name as title")->from(TABLE_PUBLICATIONS . " as pub")->condition("pub.name like '%" . $term . "%'")->limit(0, 5);
     if (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_READ_OWN_ONLY or CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_WRITE_OWN_ONLY) {
         $query->innerJoin(TABLE_PUBLICATION_BY_PERSONS . " as p", "p.izdan_id = pub.id");
         $query->condition("p.kadri_id=" . CSession::getCurrentPerson()->getId());
     }
     foreach ($query->execute()->getItems() as $item) {
         $res[] = array("field" => "t.id", "value" => $item["id"], "label" => $item["title"], "class" => "CPublication");
     }
     echo json_encode($res);
 }
Esempio n. 11
0
 /**
  * Обновление существующей модели
  */
 private function updateModel()
 {
     // если эта модель поддерживает версионирование,
     // то сначала делаем копию текущей записи, а затем
     // сохраняем данные
     if (is_a($this, "IVersionControl")) {
         $currentAr = CActiveRecordProvider::getById($this->getTable(), $this->getId());
         $currentAr->setItemValue("_version_of", $this->getId());
         $currentAr->setItemValue("_created_at", date('Y-m-d G:i:s'));
         $currentAr->setItemValue("_created_by", CSession::getCurrentPerson()->getId());
         $currentAr->insert();
     }
     $this->getRecord()->update();
 }
 public function actionMy()
 {
     $set = CActiveRecordProvider::getDistinctWithCondition(TABLE_EXAMINATION_TICKETS, "person_id = " . CSession::getCurrentPerson()->getId(), "session_id");
     $tickets = new CArrayList();
     foreach ($set->getPaginated()->getItems() as $item) {
         $ticket = new CExamTicket($item);
         $tickets->add($ticket->getId(), $ticket);
     }
     $this->setData("tickets", $tickets);
     $this->setData("paginator", $set->getPaginator());
     $this->renderView("_examination/my.tpl");
 }
Esempio n. 13
0
 /**
  * Обновление поискового запроса с учетом прав доступа
  * Делается из допущения, что текущая задача - эта задача, по
  * которой выполняется основной запрос
  *
  * @return bool
  */
 private function updateQueryForACLLimitations()
 {
     /**
      * Для начала проверим, что текущая задача определяется
      * Если не определяется, то менять ничего мы не можем -
      * данных недостаточно
      */
     $task = CSession::getCurrentTask();
     if (is_null($task)) {
         return false;
     }
     /**
      * Теперь проверим, что найденная задача связана с какой-либо моделью
      * Если модель определить не можем, то тоже выходим
      */
     $targetModel = null;
     foreach ($task->models->getItems() as $model) {
         if (mb_strtolower($model->getModelTable()) == mb_strtolower($this->getTableName())) {
             $targetModel = $model;
         }
     }
     if (is_null($targetModel)) {
         return false;
     }
     /**
      * Теперь проверим, поддерживает ли эта модель работу с readers/authors-полями
      * Если таких полей нет, то тоже нет смысла что-либо проверять
      */
     if ($targetModel->getReadersFields()->getCount() == 0) {
         return false;
     }
     /**
      * Если у пользователя нет доступа к текущей задаче, то
      * ставим в поля, регламентирующие доступ 0 - нулевого пользователя у нас точно нет
      *
      * Если доступ на чтение/запись только своего, то добавляем в readers-поля
      * id текущего пользователя
      */
     $q = array();
     if (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_NO_ACCESS) {
         foreach ($targetModel->getReadersFields()->getItems() as $field) {
             $q[] = "(" . $this->getTableAlias() . "." . $field->field_name . "= 0)";
         }
     } elseif (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_READ_OWN_ONLY || CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_WRITE_OWN_ONLY) {
         foreach ($targetModel->getReadersFields()->getItems() as $field) {
             $q[] = "(" . $this->getTableAlias() . "." . $field->field_name . "=" . CSession::getCurrentPerson()->getId() . ")";
         }
     }
     if (count($q) > 0) {
         $query = $this->getQuery();
         $condition = $query->getCondition();
         if (!is_null($condition)) {
             $condition .= " AND ";
         }
         $condition .= "(" . implode(" OR ", $q) . ")";
         $this->getQuery()->condition($condition);
     }
 }
 public function actionFileUpload()
 {
     $grant = new CGrant();
     $grant->setAttributes(CRequest::getArray($grant::getClassName()));
     /**
      * На самом деле с самим грантом мы делать ничего
      * не будем, а создадим вложение
      */
     $attach = new CGrantAttachment();
     $attach->grant_id = $grant->getId();
     $attach->filename = $grant->upload;
     $attach->author_id = CSession::getCurrentPerson()->getId();
     $attach->attach_name = $grant->upload_filename;
     $attach->save();
     /**
      * Если загружать сразу несколько файлов, то
      * иногда возникают какие-то косяки
      */
 }
 public function actionIndex()
 {
     $set = new CRecordSet(false);
     $query = new CQuery();
     $currentPerson = null;
     $currentGroup = null;
     $query->select("diplom.*")->from(TABLE_DIPLOMS . " as diplom")->order("diplom.date_act desc");
     $managersQuery = new CQuery();
     $managersQuery->select("person.*")->from(TABLE_PERSON . " as person")->order("person.fio asc")->innerJoin(TABLE_DIPLOMS . " as diplom", "person.id = diplom.kadri_id");
     $groupsQuery = new CQuery();
     $groupsQuery->select("stgroup.*")->from(TABLE_STUDENT_GROUPS . " as stgroup")->order("stgroup.name asc")->innerJoin(TABLE_STUDENTS . " as student", "stgroup.id = student.group_id")->innerJoin(TABLE_DIPLOMS . " as diplom", "student.id =  diplom.student_id")->condition('diplom.date_act between "' . date("Y-m-d", strtotime(CUtils::getCurrentYear()->date_start)) . '" and "' . date("Y-m-d", strtotime(CUtils::getCurrentYear()->date_end)) . '"');
     $set->setQuery($query);
     if (CRequest::getString("order") == "st_group.name") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->innerJoin(TABLE_STUDENTS . " as student", "diplom.student_id=student.id");
         $query->innerJoin(TABLE_STUDENT_GROUPS . " as st_group", "student.group_id = st_group.id");
         $query->order("st_group.name " . $direction);
     } elseif (CRequest::getString("order") == "dipl_prew.date_preview") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->innerJoin(TABLE_STUDENTS . " as student", "diplom.student_id=student.id");
         $query->leftJoin(TABLE_DIPLOM_PREVIEWS . " as dipl_prew", "student.id = dipl_prew.student_id");
         $query->order("dipl_prew.date_preview " . $direction);
     } elseif (CRequest::getString("order") == "prepod.fio") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->innerJoin(TABLE_PERSON . " as prepod", "diplom.kadri_id = prepod.id");
         $query->order("prepod.fio " . $direction);
     } elseif (CRequest::getString("order") == "student.fio") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->innerJoin(TABLE_STUDENTS . " as student", "diplom.student_id=student.id");
         $query->order("student.fio " . $direction);
     } elseif (CRequest::getString("order") == "diplom_confirm") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->order("diplom_confirm " . $direction);
     } elseif (CRequest::getString("order") == "dipl_name") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->order("dipl_name " . $direction);
     } elseif (CRequest::getString("order") == "pract_place_id") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->order("pract_place_id " . $direction);
     } elseif (CRequest::getString("order") == "date_act") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->order("date_act " . $direction);
     } elseif (CRequest::getString("order") == "foreign_lang") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->order("foreign_lang " . $direction);
     } elseif (CRequest::getString("order") == "protocol_2aspir_id") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->order("protocol_2aspir_id " . $direction);
     } elseif (CRequest::getString("order") == "recenz_id") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->order("recenz_id " . $direction);
     } elseif (CRequest::getString("order") == "study_mark") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->order("study_mark " . $direction);
     } elseif (CRequest::getString("order") == "gak_num") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->order("gak_num " . $direction);
     } elseif (CRequest::getString("order") == "comment") {
         $direction = "asc";
         if (CRequest::getString("direction") != "") {
             $direction = CRequest::getString("direction");
         }
         $query->order("comment " . $direction);
     }
     // фильтр по руководителю
     if (!is_null(CRequest::getFilter("person"))) {
         $query->innerJoin(TABLE_PERSON . " as person", "diplom.kadri_id = person.id and person.id = " . CRequest::getFilter("person"));
         $currentPerson = CRequest::getFilter("person");
         // фильтруем еще и группы
         $groupsQuery->innerJoin(TABLE_PERSON . " as person", "diplom.kadri_id = person.id and person.id = " . CRequest::getFilter("person"));
     }
     // фильтр по группе
     if (!is_null(CRequest::getFilter("group"))) {
         $arr = explode(",", CRequest::getFilter("group"));
         foreach ($arr as $key => $value) {
             $arrs[] = 'st_group.id = ' . $value;
         }
         $currentGroup = CRequest::getFilter("group");
         $query->innerJoin(TABLE_STUDENTS . " as student", "diplom.student_id=student.id");
         $query->innerJoin(TABLE_STUDENT_GROUPS . " as st_group", "student.group_id = st_group.id and (" . implode(" or ", $arrs) . ")");
         $managersQuery->innerJoin(TABLE_STUDENTS . " as student", "diplom.student_id = student.id");
         $managersQuery->innerJoin(TABLE_STUDENT_GROUPS . " as st_group", "student.group_id = st_group.id and (" . implode(" or ", $arrs) . ")");
     }
     // фильтр по теме
     if (!is_null(CRequest::getFilter("theme"))) {
         $query->condition("diplom.id = " . CRequest::getFilter("theme"));
     }
     // фильтр по студенту
     if (!is_null(CRequest::getFilter("student"))) {
         $query->innerJoin(TABLE_STUDENTS . " as student", "diplom.student_id=student.id and student.id = " . CRequest::getFilter("student"));
     }
     // фильтр по степени утверждения
     if (!is_null(CRequest::getFilter("confirm"))) {
         $query->innerJoin(TABLE_DIPLOM_CONFIRMATIONS . " as confirm", "diplom.diplom_confirm = confirm.id and confirm.id = " . CRequest::getFilter("confirm"));
     }
     // фильтр по месту практики
     if (!is_null(CRequest::getFilter("pract"))) {
         $query->condition("diplom.id = " . CRequest::getFilter("pract"));
     }
     // фильтр по месту практики по id
     if (!is_null(CRequest::getFilter("practId"))) {
         $query->innerJoin(TABLE_PRACTICE_PLACES . " as pract", "diplom.pract_place_id = pract.id and pract.id = " . CRequest::getFilter("practId"));
     }
     // фильтр по ин.яз.
     if (!is_null(CRequest::getFilter("foreign"))) {
         $query->innerJoin(TABLE_LANGUAGES . " as lang", "diplom.foreign_lang=lang.id and lang.id = " . CRequest::getFilter("foreign"));
     }
     // фильтр по рецензенту
     if (!is_null(CRequest::getFilter("recenz"))) {
         $query->innerJoin(TABLE_PERSON . " as person", "diplom.recenz_id = person.id and person.id = " . CRequest::getFilter("recenz"));
     }
     // фильтр по оценке
     if (!is_null(CRequest::getFilter("mark"))) {
         $query->innerJoin(TABLE_MARKS . " as mark", "diplom.study_mark = mark.id and mark.id = " . CRequest::getFilter("mark"));
     }
     // фильтр по комментарию
     if (!is_null(CRequest::getFilter("comment"))) {
         $query->condition("diplom.id = " . CRequest::getFilter("comment"));
     }
     // получение дипломных тем
     $diploms = new CArrayList();
     $isApprove = CRequest::getString("isApprove") == "1";
     $isArchive = CRequest::getString("isArchive") == "1";
     if (!$isArchive) {
         if (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_READ_OWN_ONLY or CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_WRITE_OWN_ONLY) {
             $query->condition('diplom.kadri_id = "' . CSession::getCurrentPerson()->getId() . '" and diplom.date_act between "' . date("Y-m-d", strtotime(CUtils::getCurrentYear()->date_start)) . '" and "' . date("Y-m-d", strtotime(CUtils::getCurrentYear()->date_end)) . '"');
         } else {
             $query->condition('diplom.date_act between "' . date("Y-m-d", strtotime(CUtils::getCurrentYear()->date_start)) . '" and "' . date("Y-m-d", strtotime(CUtils::getCurrentYear()->date_end)) . '"');
         }
     } else {
         if (CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_READ_OWN_ONLY or CSession::getCurrentUser()->getLevelForCurrentTask() == ACCESS_LEVEL_WRITE_OWN_ONLY) {
             $query->condition("diplom.kadri_id = " . CSession::getCurrentPerson()->getId());
         }
     }
     //Не имеющие предзащиты зимой
     if (CRequest::getInt("winterNotPreviews") == 1) {
         $query->leftJoin(TABLE_DIPLOM_PREVIEWS . " as preview", "diplom.student_id = preview.student_id");
         $query->condition('preview.student_id is null and diplom.date_act between "' . (date("Y") - 1) . "-12-01" . '" and "' . date("Y") . "-02-28" . '"');
     }
     //Не имеющие предзащиты летом
     if (CRequest::getInt("summerNotPreviews") == 1) {
         $query->leftJoin(TABLE_DIPLOM_PREVIEWS . " as preview", "diplom.student_id = preview.student_id");
         $query->condition('preview.student_id is null and diplom.date_act between "' . date("Y") . "-05-01" . '" and "' . date("Y") . "-06-30" . '"');
     }
     foreach ($set->getPaginated()->getItems() as $item) {
         $diplom = new CDiplom($item);
         $diploms->add($diplom->getId(), $diplom);
     }
     /**
      * Формируем меню
      */
     $this->addActionsMenuItem(array(array("title" => "Печать по шаблону", "link" => "#", "icon" => "devices/printer.png", "template" => "formset_diploms_theme"), array("title" => "Добавить тему ВКР", "link" => "?action=add", "icon" => "actions/list-add.png"), array("title" => "Список студентов", "link" => WEB_ROOT . "_modules/_students/index.php", "icon" => "apps/system-users.png"), array("title" => "Групповые операции", "link" => "#", "icon" => "apps/utilities-terminal.png", "child" => array(array("title" => "Удалить выделенные", "icon" => "actions/edit-delete.png", "form" => "#MainView", "link" => "index.php", "action" => "Delete"), array("title" => "Сменить дату защиты", "icon" => "actions/edit-redo.png", "form" => "#MainView", "link" => "index.php", "action" => "changeDateAct"), array("title" => "Сменить место практики", "icon" => "actions/edit-redo.png", "form" => "#MainView", "link" => "index.php", "action" => "changePractPlace")))));
     if ($isArchive) {
         $requestParams = array();
         foreach (CRequest::getGlobalRequestVariables()->getItems() as $key => $value) {
             if ($key != "isArchive") {
                 $requestParams[] = $key . "=" . $value;
             }
         }
         $this->addActionsMenuItem(array(array("title" => "Текущий год", "link" => "?" . implode("&", $requestParams), "icon" => "mimetypes/x-office-calendar.png")));
     } else {
         $requestParams = array();
         foreach (CRequest::getGlobalRequestVariables()->getItems() as $key => $value) {
             $requestParams[] = $key . "=" . $value;
         }
         $requestParams[] = "isArchive=1";
         $this->addActionsMenuItem(array(array("title" => "Архив", "link" => "?" . implode("&", $requestParams), "icon" => "devices/media-floppy.png")));
     }
     $this->addActionsMenuItem(array(array("title" => "Утверждение темы", "link" => "#", "icon" => "apps/accessories-text-editor.png", "child" => array(array("title" => "Утвердили полностью", "icon" => "actions/edit-find-replace.png", "form" => "#MainView", "link" => "index.php?type=1", "action" => "approveTheme"), array("title" => "Утвердили c правкой", "icon" => "actions/edit-find-replace.png", "form" => "#MainView", "link" => "index.php?type=2", "action" => "approveTheme"), array("title" => "Утвердили c переформулировкой", "icon" => "actions/edit-find-replace.png", "form" => "#MainView", "link" => "index.php?type=3", "action" => "approveTheme"), array("title" => "Не утвердили, но смотрели", "icon" => "actions/edit-find-replace.png", "form" => "#MainView", "link" => "index.php?type=4", "action" => "approveTheme"), array("title" => "Отменить утверждение темы", "icon" => "actions/edit-find-replace.png", "form" => "#MainView", "link" => "index.php?type=0", "action" => "approveTheme")))));
     $managers = array();
     foreach ($managersQuery->execute()->getItems() as $ar) {
         $person = new CPerson(new CActiveRecord($ar));
         $managers[$person->getId()] = $person->getName();
     }
     $studentGroups = array();
     foreach ($groupsQuery->execute()->getItems() as $ar) {
         $group = new CStudentGroup(new CActiveRecord($ar));
         $studentGroups[$group->getId()] = $group->getName();
     }
     $this->setData("isArchive", $isArchive);
     $this->setData("isApprove", $isApprove);
     $this->setData("studentGroups", $studentGroups);
     $this->setData("diplomManagers", $managers);
     $this->setData("currentPerson", $currentPerson);
     $this->setData("currentGroup", $currentGroup);
     $this->setData("diploms", $diploms);
     $this->setData("paginator", $set->getPaginator());
     if (!$isApprove) {
         $requestParams = array();
         foreach (CRequest::getGlobalRequestVariables()->getItems() as $key => $value) {
             $requestParams[] = $key . "=" . $value;
         }
         $requestParams[] = "isApprove=1";
         $this->addActionsMenuItem(array(array("title" => "Утверждение тем ВКР", "link" => "?" . implode("&", $requestParams), "icon" => "actions/bookmark-new.png")));
         $this->renderView("_diploms/index.tpl");
     } else {
         $requestParams = array();
         foreach (CRequest::getGlobalRequestVariables()->getItems() as $key => $value) {
             if ($key != "isApprove") {
                 $requestParams[] = $key . "=" . $value;
             }
         }
         $this->addActionsMenuItem(array(array("title" => "Список тем ВКР", "link" => "?" . implode("&", $requestParams), "icon" => "actions/format-justify-center.png")));
         $this->renderView("_diploms/approve.tpl");
     }
 }