Пример #1
0
 /**
  * @param string $file
  * @param bool   $moveFile
  *
  * @return int
  */
 private function importCalendarStatic($file, $moveFile = true)
 {
     $data = Import::csv_to_array($file);
     if (!empty($data)) {
         $this->logger->addInfo(count($data) . " records found.");
         $eventsToCreate = array();
         $errorFound = false;
         foreach ($data as $row) {
             $sessionId = null;
             $externalSessionId = null;
             if (isset($row['external_sessionID'])) {
                 $externalSessionId = $row['external_sessionID'];
                 $sessionId = SessionManager::get_session_id_from_original_id($externalSessionId, $this->extraFieldIdNameList['session']);
             }
             $courseCode = null;
             if (isset($row['coursecode'])) {
                 $courseCode = $row['coursecode'];
             }
             $courseInfo = api_get_course_info($courseCode);
             if (empty($courseInfo)) {
                 $this->logger->addInfo("Course '{$courseCode}' does not exists");
             }
             if (empty($sessionId)) {
                 $this->logger->addInfo("external_sessionID: " . $externalSessionId . " does not exists.");
             }
             $teacherId = null;
             if (!empty($sessionId) && !empty($courseInfo)) {
                 $courseIncluded = SessionManager::relation_session_course_exist($sessionId, $courseInfo['code']);
                 if ($courseIncluded == false) {
                     $this->logger->addInfo("Course '{$courseCode}' is not included in session: {$sessionId}");
                     $errorFound = true;
                 } else {
                     $teachers = CourseManager::get_coach_list_from_course_code($courseInfo['code'], $sessionId);
                     // Getting first teacher.
                     if (!empty($teachers)) {
                         $teacher = current($teachers);
                         $teacherId = $teacher['user_id'];
                     } else {
                         $sessionInfo = api_get_session_info($sessionId);
                         $teacherId = $sessionInfo['id_coach'];
                     }
                 }
             } else {
                 $errorFound = true;
             }
             if (empty($teacherId)) {
                 $errorFound = true;
                 $this->logger->addInfo("No teacher found in course code : '{$courseCode}' and session: '{$sessionId}'");
             }
             $date = $row['date'];
             $startTime = $row['time_start'];
             $endTime = $row['time_end'];
             $title = $row['title'];
             $comment = $row['comment'];
             $color = isset($row['color']) ? $row['color'] : '';
             $startDateYear = substr($date, 0, 4);
             $startDateMonth = substr($date, 4, 2);
             $startDateDay = substr($date, 6, 8);
             $startDate = $startDateYear . '-' . $startDateMonth . '-' . $startDateDay . ' ' . $startTime . ":00";
             $endDate = $startDateYear . '-' . $startDateMonth . '-' . $startDateDay . ' ' . $endTime . ":00";
             if (!api_is_valid_date($startDate) || !api_is_valid_date($endDate)) {
                 $this->logger->addInfo("Verify your dates:  '{$startDate}' : '{$endDate}' ");
                 $errorFound = true;
             }
             // If old events do nothing.
             /*if (api_strtotime($startDate) < time()) {
                   continue;
               }*/
             if ($errorFound == false) {
                 $eventsToCreate[] = array('start' => $startDate, 'end' => $endDate, 'title' => $title, 'sender_id' => $teacherId, 'course_id' => $courseInfo['real_id'], 'session_id' => $sessionId, 'comment' => $comment, 'color' => $color, $this->extraFieldIdNameList['calendar_event'] => $row['external_calendar_itemID']);
             }
         }
         if (empty($eventsToCreate)) {
             $this->logger->addInfo("No events to add");
             return 0;
         }
         $this->logger->addInfo("Ready to insert events");
         $agenda = new Agenda();
         $extraFieldValue = new ExtraFieldValue('calendar_event');
         $extraFieldName = $this->extraFieldIdNameList['calendar_event'];
         $externalEventId = null;
         $extraField = new ExtraField('calendar_event');
         $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable($extraFieldName);
         if (empty($extraFieldInfo)) {
             $this->logger->addInfo("No calendar event extra field created: {$extraFieldName}");
             return 0;
         }
         foreach ($eventsToCreate as $event) {
             $update = false;
             $item = null;
             if (!isset($event[$extraFieldName])) {
                 $this->logger->addInfo("No external_calendar_itemID found. Skipping ...");
                 continue;
             } else {
                 $externalEventId = $event[$extraFieldName];
                 if (empty($externalEventId)) {
                     $this->logger->addInfo("external_calendar_itemID was set but empty. Skipping ...");
                     continue;
                 }
                 $items = $extraFieldValue->get_item_id_from_field_variable_and_field_value($extraFieldName, $externalEventId, false, false, true);
                 $item = null;
                 foreach ($items as $tempItem) {
                     if ($tempItem['c_id'] == $event['course_id']) {
                         $item = $tempItem;
                     }
                 }
                 if (!empty($item)) {
                     $this->logger->addInfo("Event #{$externalEventId} was already added. Updating ...");
                     $update = true;
                     //continue;
                 }
             }
             $courseInfo = api_get_course_info_by_id($event['course_id']);
             $agenda->set_course($courseInfo);
             $agenda->setType('course');
             $agenda->setSessionId($event['session_id']);
             $agenda->setSenderId($event['sender_id']);
             $agenda->setIsAllowedToEdit(true);
             $eventComment = $event['comment'];
             $color = $event['color'];
             // To use the event comment you need
             // ALTER TABLE c_calendar_event ADD COLUMN comment TEXT;
             // add in configuration.php allow_agenda_event_comment = true
             if (empty($courseInfo)) {
                 $this->logger->addInfo("No course found for added: #" . $event['course_id'] . " Skipping ...");
                 continue;
             }
             if (empty($event['sender_id'])) {
                 $this->logger->addInfo("No sender found: #" . $event['sender_id'] . " Skipping ...");
                 continue;
             }
             $content = '';
             if ($update && isset($item['calendar_event_id'])) {
                 //the event already exists, just update
                 $eventId = $agenda->edit_event($item['calendar_event_id'], $event['start'], $event['end'], false, $event['title'], $content, array('everyone'), array(), null, $eventComment, $color);
                 if ($eventId !== false) {
                     $this->logger->addInfo("Event updated: #{$eventId}");
                 } else {
                     $this->logger->addInfo("Error while updating event.");
                 }
             } else {
                 // New event. Create it.
                 $eventId = $agenda->add_event($event['start'], $event['end'], false, $event['title'], $content, array('everyone'), false, null, array(), null, $eventComment, $color);
                 if (!empty($eventId)) {
                     $extraFieldValue->is_course_model = true;
                     $extraFieldValue->save(array('field_value' => $externalEventId, 'field_id' => $extraFieldInfo['id'], 'calendar_event_id' => $eventId, 'c_id' => $event['course_id']));
                     $this->logger->addInfo("Event added: #{$eventId}");
                 } else {
                     $this->logger->addInfo("Error while creating event.");
                 }
             }
         }
     }
     if ($moveFile) {
         $this->moveFile($file);
     }
 }
Пример #2
0
 /**
  * Fills the course database with some required content and example content.
  * @param int Course (int) ID
  * @param string Course directory name (e.g. 'ABC')
  * @param string Language used for content (e.g. 'spanish')
  * @param bool Whether to fill the course with example content
  * @return bool False on error, true otherwise
  * @version 1.2
  * @assert (null, '', '', null) === false
  * @assert (1, 'ABC', null, null) === false
  * @assert (1, 'TEST', 'spanish', true) === true
  */
 public static function fill_db_course($course_id, $course_repository, $language, $fill_with_exemplary_content = null)
 {
     if (is_null($fill_with_exemplary_content)) {
         $fill_with_exemplary_content = api_get_setting('course.example_material_course_creation') != 'false';
     }
     $course_id = intval($course_id);
     if (empty($course_id)) {
         return false;
     }
     $entityManager = Database::getManager();
     $course = $entityManager->getRepository('ChamiloCoreBundle:Course')->find($course_id);
     $tools = array();
     $settingsManager = CourseManager::getCourseSettingsManager();
     $settingsManager->setCourse($course);
     $toolList = CourseManager::getToolList();
     $toolList = $toolList->getTools();
     /** @var Chamilo\CourseBundle\Tool\BaseTool $tool */
     foreach ($toolList as $tool) {
         $visibility = self::string2binary(api_get_setting_in_list('course.active_tools_on_create', $tool->getName()));
         $toolObject = new CTool();
         $toolObject->setName($tool->getName())->setCategory($tool->getCategory())->setLink($tool->getLink())->setImage($tool->getImage())->setVisibility($visibility)->setAdmin(0)->setTarget($tool->getTarget());
         $tools[] = $toolObject;
         $settings = $settingsManager->loadSettings($tool->getName());
         $settingsManager->saveSettings($tool->getName(), $settings);
     }
     $course->setTools($tools);
     $entityManager->persist($course);
     $entityManager->flush($course);
     $courseInfo = api_get_course_info_by_id($course_id);
     $now = api_get_utc_datetime(time());
     $tbl_course_homepage = Database::get_course_table(TABLE_TOOL_LIST);
     $TABLEINTROS = Database::get_course_table(TABLE_TOOL_INTRO);
     $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY);
     $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $TABLETOOLAGENDA = Database::get_course_table(TABLE_AGENDA);
     $TABLETOOLANNOUNCEMENTS = Database::get_course_table(TABLE_ANNOUNCEMENT);
     $TABLETOOLDOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
     $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
     $TABLEQUIZ = Database::get_course_table(TABLE_QUIZ_TEST);
     $TABLEQUIZQUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
     $TABLEQUIZQUESTIONLIST = Database::get_course_table(TABLE_QUIZ_QUESTION);
     $TABLEQUIZANSWERSLIST = Database::get_course_table(TABLE_QUIZ_ANSWER);
     $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
     $TABLEFORUMCATEGORIES = Database::get_course_table(TABLE_FORUM_CATEGORY);
     $TABLEFORUMS = Database::get_course_table(TABLE_FORUM);
     $TABLEFORUMTHREADS = Database::get_course_table(TABLE_FORUM_THREAD);
     $TABLEFORUMPOSTS = Database::get_course_table(TABLE_FORUM_POST);
     $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
     $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
     $TABLEGRADEBOOKCERT = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
     $visible_for_all = 1;
     $visible_for_course_admin = 0;
     $visible_for_platform_admin = 2;
     /*    Course tools  */
     $alert = api_get_setting('exercise.email_alert_manager_on_new_quiz');
     if ($alert === 'true') {
         $defaultEmailExerciseAlert = 1;
     } else {
         $defaultEmailExerciseAlert = 0;
     }
     /* course_setting table (courseinfo tool)   */
     $settings = ['email_alert_manager_on_new_doc' => ['default' => 0, 'category' => 'work'], 'email_alert_on_new_doc_dropbox' => ['default' => 0, 'category' => 'dropbox'], 'allow_user_edit_agenda' => ['default' => 0, 'category' => 'agenda'], 'allow_user_edit_announcement' => ['default' => 0, 'category' => 'announcement'], 'email_alert_manager_on_new_quiz' => ['default' => $defaultEmailExerciseAlert, 'category' => 'quiz'], 'allow_user_image_forum' => ['default' => 1, 'category' => 'forum'], 'course_theme' => ['default' => '', 'category' => 'theme'], 'allow_learning_path_theme' => ['default' => 1, 'category' => 'theme'], 'allow_open_chat_window' => ['default' => 1, 'category' => 'chat'], 'email_alert_to_teacher_on_new_user_in_course' => ['default' => 0, 'category' => 'registration'], 'allow_user_view_user_list' => ['default' => 1, 'category' => 'user'], 'display_info_advance_inside_homecourse' => ['default' => 1, 'category' => 'thematic_advance'], 'email_alert_students_on_new_homework' => ['default' => 0, 'category' => 'work'], 'enable_lp_auto_launch' => ['default' => 0, 'category' => 'learning_path'], 'pdf_export_watermark_text' => ['default' => '', 'category' => 'learning_path'], 'allow_public_certificates' => ['default' => api_get_setting('course.allow_public_certificates') === 'true' ? 1 : '', 'category' => 'certificates'], 'documents_default_visibility' => ['default' => 'visible', 'category' => 'document']];
     /*$counter = 1;
       foreach ($settings as $variable => $setting) {
           Database::query(
               "INSERT INTO $TABLESETTING (id, c_id, variable, value, category)
                VALUES ($counter, $course_id, '".$variable."', '".$setting['default']."', '".$setting['category']."')"
           );
           $counter++;
       }*/
     /* Course homepage tools for platform admin only */
     /* Group tool */
     Database::query("INSERT INTO {$TABLEGROUPCATEGORIES}  (c_id, id, title , description, max_student, self_reg_allowed, self_unreg_allowed, groups_per_user, display_order)\n             VALUES ({$course_id}, '2', '" . self::lang2db(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
     /*    Example Material  */
     $language_interface = !empty($language_interface) ? $language_interface : api_get_setting('language.platform_language');
     // Example material should be in the same language as the course is.
     $language_interface_original = $language_interface;
     $now = api_get_utc_datetime();
     $files = [['path' => '/shared_folder', 'title' => get_lang('UserFolders'), 'filetype' => 'folder', 'size' => 0], ['path' => '/chat_files', 'title' => get_lang('ChatFiles'), 'filetype' => 'folder', 'size' => 0]];
     $counter = 1;
     foreach ($files as $file) {
         self::insertDocument($course_id, $counter, $file);
         $counter++;
     }
     $sys_course_path = api_get_path(SYS_COURSE_PATH);
     $perm = api_get_permissions_for_new_directories();
     $perm_file = api_get_permissions_for_new_files();
     $chat_path = $sys_course_path . $course_repository . '/document/chat_files';
     if (!is_dir($chat_path)) {
         @mkdir($chat_path, api_get_permissions_for_new_directories());
     }
     /*    Documents   */
     if ($fill_with_exemplary_content) {
         $files = [['path' => '/images', 'title' => get_lang('Images'), 'filetype' => 'folder', 'size' => 0], ['path' => '/images/gallery', 'title' => get_lang('DefaultCourseImages'), 'filetype' => 'folder', 'size' => 0], ['path' => '/audio', 'title' => get_lang('Audio'), 'filetype' => 'folder', 'size' => 0], ['path' => '/flash', 'title' => get_lang('Flash'), 'filetype' => 'folder', 'size' => 0], ['path' => '/video', 'title' => get_lang('Video'), 'filetype' => 'folder', 'size' => 0], ['path' => '/certificates', 'title' => get_lang('Certificates'), 'filetype' => 'folder', 'size' => 0]];
         foreach ($files as $file) {
             self::insertDocument($course_id, $counter, $file);
             $counter++;
         }
         // FILL THE COURSE DOCUMENT WITH DEFAULT COURSE PICTURES
         $folders_to_copy_from_default_course = array('images', 'audio', 'flash', 'video', 'certificates');
         $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document/';
         $default_document_array = array();
         foreach ($folders_to_copy_from_default_course as $folder) {
             $default_course_folder_path = $default_course_path . $folder . '/';
             $files = self::browse_folders($default_course_folder_path, array(), $folder);
             $sorted_array = self::sort_pictures($files, 'dir');
             $sorted_array = array_merge($sorted_array, self::sort_pictures($files, 'file'));
             $default_document_array[$folder] = $sorted_array;
         }
         //Light protection (adding index.html in every document folder)
         $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n  </head>\n  <body>\n  </body>\n</html>";
         $example_cert_id = 0;
         if (is_array($default_document_array) && count($default_document_array) > 0) {
             foreach ($default_document_array as $media_type => $array_media) {
                 $path_documents = "/{$media_type}/";
                 //hack until feature #5242 is implemented
                 if ($media_type == 'images') {
                     $media_type = 'images/gallery';
                     $images_folder = $sys_course_path . $course_repository . "/document/images/";
                     if (!is_dir($images_folder)) {
                         //Creating index.html
                         mkdir($images_folder, $perm);
                         $fd = fopen($images_folder . 'index.html', 'w');
                         fwrite($fd, $htmlpage);
                         @chmod($images_folder . 'index.html', $perm_file);
                     }
                 }
                 $course_documents_folder = $sys_course_path . $course_repository . "/document/{$media_type}/";
                 $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document' . $path_documents;
                 if (!is_dir($course_documents_folder)) {
                     // Creating index.html
                     mkdir($course_documents_folder, $perm);
                     $fd = fopen($course_documents_folder . 'index.html', 'w');
                     fwrite($fd, $htmlpage);
                     @chmod($course_documents_folder . 'index.html', $perm_file);
                 }
                 if (is_array($array_media) && count($array_media) > 0) {
                     foreach ($array_media as $key => $value) {
                         if (isset($value['dir']) && !empty($value['dir'])) {
                             if (!is_dir($course_documents_folder . $value['dir'])) {
                                 //Creating folder
                                 mkdir($course_documents_folder . $value['dir'], $perm);
                                 //Creating index.html (for light protection)
                                 $index_html = $course_documents_folder . $value['dir'] . '/index.html';
                                 $fd = fopen($index_html, 'w');
                                 fwrite($fd, $htmlpage);
                                 @chmod($index_html, $perm_file);
                                 //Inserting folder in the DB
                                 $folder_path = substr($value['dir'], 0, strlen($value['dir']) - 1);
                                 $temp = explode('/', $folder_path);
                                 $title = $temp[count($temp) - 1];
                                 //hack until feature #5242 is implemented
                                 if ($title == 'gallery') {
                                     $title = get_lang('DefaultCourseImages');
                                 }
                                 if ($media_type == 'images/gallery') {
                                     $folder_path = 'gallery/' . $folder_path;
                                 }
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size)\n                                        VALUES ({$course_id},'{$path_documents}" . $folder_path . "','" . $title . "','folder','0')");
                                 $image_id = Database::insert_id();
                                 Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                                        VALUES ({$course_id},'document',1,'{$now}','{$now}',{$image_id},'DocumentAdded',1,NULL,NULL,0)");
                             }
                         }
                         if (isset($value['file']) && !empty($value['file'])) {
                             if (!file_exists($course_documents_folder . $value['file'])) {
                                 //Copying file
                                 copy($default_course_path . $value['file'], $course_documents_folder . $value['file']);
                                 chmod($course_documents_folder . $value['file'], $perm_file);
                                 //echo $default_course_path.$value['file']; echo ' - '; echo $course_documents_folder.$value['file']; echo '<br />';
                                 $temp = explode('/', $value['file']);
                                 $file_size = filesize($course_documents_folder . $value['file']);
                                 //hack until feature #5242 is implemented
                                 if ($media_type == 'images/gallery') {
                                     $value["file"] = 'gallery/' . $value["file"];
                                 }
                                 //Inserting file in the DB
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size)\n                                        VALUES ({$course_id},'{$path_documents}" . $value["file"] . "','" . $temp[count($temp) - 1] . "','file','{$file_size}')");
                                 $image_id = Database::insert_id();
                                 if ($image_id) {
                                     $sql = "UPDATE {$TABLETOOLDOCUMENT} SET id = iid WHERE iid = {$image_id}";
                                     Database::query($sql);
                                     if ($path_documents . $value['file'] == '/certificates/default.html') {
                                         $example_cert_id = $image_id;
                                     }
                                     Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                                            VALUES ({$course_id},'document',1,'{$now}','{$now}',{$image_id},'DocumentAdded',1,NULL,NULL,1)");
                                     $docId = Database::insert_id();
                                     if ($docId) {
                                         $sql = "UPDATE {$TABLEITEMPROPERTY} SET id = iid WHERE iid = {$docId}";
                                         Database::query($sql);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $agenda = new Agenda();
         $agenda->setType('course');
         $agenda->set_course($courseInfo);
         $agenda->addEvent($now, $now, 0, get_lang('AgendaCreationTitle'), get_lang('AgendaCreationContenu'));
         /*  Links tool */
         $link = new Link();
         $link->setCourse($courseInfo);
         $links = [['c_id' => $course_id, 'url' => 'http://www.google.com', 'title' => 'Google', 'description' => get_lang('Google'), 'category_id' => 0, 'on_homepage' => 0, 'target' => '_self', 'session_id' => 0], ['c_id' => $course_id, 'url' => 'http://www.wikipedia.org', 'title' => 'Wikipedia', 'description' => get_lang('Wikipedia'), 'category_id' => 0, 'on_homepage' => 0, 'target' => '_self', 'session_id' => 0]];
         foreach ($links as $params) {
             $link->save($params);
         }
         /* Announcement tool */
         AnnouncementManager::add_announcement(get_lang('AnnouncementExampleTitle'), get_lang('AnnouncementEx'), ['everyone' => 'everyone'], null, null, $now);
         $manager = Database::getManager();
         /* Introduction text */
         $intro_text = '<p style="text-align: center;">
                         <img src="' . api_get_path(REL_CODE_PATH) . 'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
                         <h2>' . self::lang2db(get_lang('IntroductionText')) . '</h2>
                      </p>';
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_COURSE_HOMEPAGE)->setSessionId(0)->setIntroText($intro_text);
         $manager->persist($toolIntro);
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_STUDENTPUBLICATION)->setSessionId(0)->setIntroText(get_lang('IntroductionTwo'));
         $manager->persist($toolIntro);
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_WIKI)->setSessionId(0)->setIntroText(get_lang('IntroductionWiki'));
         $manager->persist($toolIntro);
         $manager->flush();
         /*  Exercise tool */
         $exercise = new Exercise($course_id);
         $exercise->exercise = get_lang('ExerciceEx');
         $html = '<table width="100%" border="0" cellpadding="0" cellspacing="0">
                     <tr>
                     <td width="110" valign="top" align="left">
                         <img src="' . api_get_path(WEB_CODE_PATH) . 'default_course_document/images/mr_dokeos/thinking.jpg">
                     </td>
                     <td valign="top" align="left">' . get_lang('Antique') . '</td></tr>
                 </table>';
         $exercise->type = 1;
         $exercise->setRandom(0);
         $exercise->active = 1;
         $exercise->results_disabled = 0;
         $exercise->description = $html;
         $exercise->save();
         $exercise_id = $exercise->id;
         $question = new MultipleAnswer();
         $question->question = get_lang('SocraticIrony');
         $question->description = get_lang('ManyAnswers');
         $question->weighting = 10;
         $question->position = 1;
         $question->course = $courseInfo;
         $question->save($exercise_id);
         $questionId = $question->id;
         $answer = new Answer($questionId, $courseInfo['real_id']);
         $answer->createAnswer(get_lang('Ridiculise'), 0, get_lang('NoPsychology'), -5, 1);
         $answer->createAnswer(get_lang('AdmitError'), 0, get_lang('NoSeduction'), -5, 2);
         $answer->createAnswer(get_lang('Force'), 1, get_lang('Indeed'), 5, 3);
         $answer->createAnswer(get_lang('Contradiction'), 1, get_lang('NotFalse'), 5, 4);
         $answer->save();
         /* Forum tool */
         require_once api_get_path(SYS_CODE_PATH) . 'forum/forumfunction.inc.php';
         $params = ['forum_category_title' => get_lang('ExampleForumCategory'), 'forum_category_comment' => ''];
         $forumCategoryId = store_forumcategory($params, $courseInfo, false);
         $params = ['forum_category' => $forumCategoryId, 'forum_title' => get_lang('ExampleForum'), 'forum_comment' => '', 'default_view_type_group' => ['default_view_type' => 'flat']];
         $forumId = store_forum($params, $courseInfo, true);
         $forumInfo = get_forum_information($forumId, $courseInfo['real_id']);
         $params = ['post_title' => get_lang('ExampleThread'), 'forum_id' => $forumId, 'post_text' => get_lang('ExampleThreadContent'), 'calification_notebook_title' => '', 'numeric_calification' => '', 'weight_calification' => '', 'forum_category' => $forumCategoryId, 'thread_peer_qualify' => 0];
         store_thread($forumInfo, $params, $courseInfo, false);
         /* Gradebook tool */
         $course_code = $courseInfo['code'];
         // father gradebook
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id)\n                VALUES ('{$course_code}','',1,'{$course_code}',0,100,0,75,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id)\n                VALUES ('{$course_code}','',1,'{$course_code}',{$gbid},100,1,75,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOKLINK} (type, ref_id, user_id, course_code, category_id, created_at, weight, visible, locked)\n                VALUES (1,{$exercise_id},1,'{$course_code}',{$gbid},'{$now}',100,1,0)");
     }
     //Installing plugins in course
     $app_plugin = new AppPlugin();
     $app_plugin->install_course_plugins($course_id);
     $language_interface = $language_interface_original;
     return true;
 }
Пример #3
0
$DaysLong = api_get_week_days_long();
// Defining the months of the year to allow translation of the months
$MonthsLong = api_get_months_long();
if (empty($_GET['id'])) {
    api_not_allowed();
}
$id = explode('_', $_GET['id']);
$type = $id[0];
$id = $id[1];
$agenda = new Agenda();
$agenda->type = $type;
//course,admin or personal
if (isset($_GET['course_id'])) {
    $course_info = api_get_course_info_by_id($_GET['course_id']);
    if (!empty($course_info)) {
        $agenda->set_course($course_info);
    }
}
$event = $agenda->get_event($id);
if (!empty($event)) {
    define('ICAL_LANG', api_get_language_isocode());
    $ical = new vcalendar();
    $ical->setConfig('unique_id', api_get_path(WEB_PATH));
    $ical->setProperty('method', 'PUBLISH');
    $ical->setConfig('url', api_get_path(WEB_PATH));
    $vevent = new vevent();
    switch ($_GET['class']) {
        case 'public':
            $vevent->setClass('PUBLIC');
            break;
        case 'private':
Пример #4
0
/**
 * @param int $workId
 * @param array $params
 * @param array $courseInfo
 * @param int $groupId
 */
function updatePublicationAssignment($workId, $params, $courseInfo, $groupId)
{
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
    $workId = intval($workId);
    $time = time();
    $course_id = $courseInfo['real_id'];

    // Insert into agenda
    $agendaId = 0;

    if (isset($params['add_to_calendar']) && $params['add_to_calendar'] == 1) {
        require_once api_get_path(SYS_CODE_PATH).'calendar/agenda.inc.php';
        require_once api_get_path(SYS_CODE_PATH).'resourcelinker/resourcelinker.inc.php';

        // Setting today date
        $date = $end_date = $time;

        if (!empty($params['enableExpiryDate'])) {
            $end_date = $params['expires_on'];
            $date = $end_date;
        }

        $title = sprintf(get_lang('HandingOverOfTaskX'), $params['new_dir']);
        $description = isset($params['description']) ? $params['description'] : '';
        $content = '<a href="'.api_get_path(WEB_CODE_PATH).'work/work_list.php?'.api_get_cidreq().'&id='.$workId.'">'
            .$params['new_dir'].'</a>'.$description;

        $agendaId = agendaExistsForWork($workId, $courseInfo);

        // Add/edit agenda
        $agenda = new Agenda();
        $agenda->set_course($courseInfo);
        $agenda->type = 'course';

        if (empty($agendaId)) {
            $agendaId = $agenda->add_event(
                $date,
                $end_date,
                'false',
                $title,
                $content,
                array('GROUP:'.$groupId)
            );
        } else {
            $agenda->edit_event(
                $agendaId,
                $end_date,
                $end_date,
                'false',
                $title,
                $content
            );
        }
    }

    $qualification = isset($params['qualification']) && !empty($params['qualification']) ? 1 : 0;
    $expiryDate = (isset($params['enableExpiryDate']) && $params['enableExpiryDate'] == 1) ? api_get_utc_datetime($params['expires_on']) : '0000-00-00 00:00:00';
    $endDate = ((isset($params['enableEndDate']) && $params['enableEndDate']==1) ? api_get_utc_datetime($params['ends_on']) : '0000-00-00 00:00:00');

    $data = get_work_assignment_by_id($workId, $course_id);

    if (empty($data)) {

        $sql = "INSERT INTO $table SET
                c_id = $course_id ,
                expires_on              = '".Database::escape_string($expiryDate)."',
                ends_on                 = '".Database::escape_string($endDate)."',
                add_to_calendar         = $agendaId,
                enable_qualification    = '$qualification',
                publication_id          = '$workId'";
        Database::query($sql);

        $my_last_id = Database::insert_id();

        $sql = "UPDATE $workTable SET
                    has_properties  = $my_last_id ,
                    view_properties = 1
                WHERE c_id = $course_id AND id = $workId";
        Database::query($sql);
    } else {
        $sql = "UPDATE $table SET
                    expires_on = '".$expiryDate."',
                    ends_on = '".$endDate."',
                    add_to_calendar  = $agendaId,
                    enable_qualification = '".$qualification."'
                WHERE
                    publication_id = $workId AND
                    c_id = $course_id AND
                    id = ".$data['id'];
        Database::query($sql);
    }

    if (!empty($params['category_id'])) {

        require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/gradebookitem.class.php';
        require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/evaluation.class.php';
        require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be/abstractlink.class.php';
        require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';

        $link_info = is_resource_in_course_gradebook(
            $courseInfo['code'],
            LINK_STUDENTPUBLICATION,
            $workId,
            api_get_session_id()
        );

        $linkId = null;
        if (!empty($link_info)) {
            $linkId = $link_info['id'];
        }

        if (isset($params['make_calification']) && $params['make_calification'] == 1) {
            if (empty($linkId)) {
                add_resource_to_course_gradebook(
                    $params['category_id'],
                    $courseInfo['code'],
                    LINK_STUDENTPUBLICATION,
                    $workId,
                    $params['dir_name'],
                    (float)$params['weight'],
                    (float)$params['qualification'],
                    $params['description'],
                    1,
                    api_get_session_id()
                );
            } else {
                update_resource_from_course_gradebook(
                    $linkId,
                    $courseInfo['code'],
                    $params['weight']
                );
            }
        } else {
            // Delete everything of the gradebook for this $linkId
            remove_resource_from_course_gradebook($linkId);
        }
    }
}
Пример #5
0
/**
 * @param int $workId
 * @param array $params
 * @param array $courseInfo
 * @param int $groupId
 */
function updatePublicationAssignment($workId, $params, $courseInfo, $groupId)
{
    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
    $workId = intval($workId);
    $time = api_get_utc_datetime();
    $course_id = $courseInfo['real_id'];
    // Insert into agenda
    $agendaId = 0;
    if (isset($params['add_to_calendar']) && $params['add_to_calendar'] == 1) {
        require_once api_get_path(SYS_CODE_PATH) . 'resourcelinker/resourcelinker.inc.php';
        // Setting today date
        $date = $end_date = $time;
        if (isset($params['enableExpiryDate'])) {
            $end_date = $params['expires_on'];
            $date = $end_date;
        }
        $title = sprintf(get_lang('HandingOverOfTaskX'), $params['new_dir']);
        $description = isset($params['description']) ? $params['description'] : '';
        $content = '<a href="' . api_get_path(WEB_CODE_PATH) . 'work/work_list.php?' . api_get_cidreq() . '&id=' . $workId . '">' . $params['new_dir'] . '</a>' . $description;
        $agendaId = agendaExistsForWork($workId, $courseInfo);
        // Add/edit agenda
        $agenda = new Agenda();
        $agenda->set_course($courseInfo);
        $agenda->type = 'course';
        if (empty($agendaId)) {
            $agendaId = $agenda->addEvent($date, $end_date, 'false', $title, $content, array('GROUP:' . $groupId));
        } else {
            $agenda->editEvent($agendaId, $end_date, $end_date, 'false', $title, $content);
        }
    }
    $qualification = isset($params['qualification']) && !empty($params['qualification']) ? 1 : 0;
    $expiryDate = isset($params['enableExpiryDate']) && $params['enableExpiryDate'] == 1 ? api_get_utc_datetime($params['expires_on']) : '';
    $endDate = isset($params['enableEndDate']) && $params['enableEndDate'] == 1 ? api_get_utc_datetime($params['ends_on']) : '';
    $data = get_work_assignment_by_id($workId, $course_id);
    if (!empty($expiryDate)) {
        $expiryDateCondition = "expires_on = '" . Database::escape_string($expiryDate) . "', ";
    } else {
        $expiryDateCondition = "expires_on = null, ";
    }
    if (!empty($endDate)) {
        $endOnCondition = "ends_on = '" . Database::escape_string($endDate) . "', ";
    } else {
        $endOnCondition = "ends_on = null, ";
    }
    if (empty($data)) {
        $sql = "INSERT INTO {$table} SET\n                c_id = {$course_id} ,\n                {$expiryDateCondition}\n                {$endOnCondition}\n                add_to_calendar = {$agendaId},\n                enable_qualification = '{$qualification}',\n                publication_id = '{$workId}'";
        Database::query($sql);
        $my_last_id = Database::insert_id();
        if ($my_last_id) {
            $sql = "UPDATE {$table} SET\n                        id = iid\n                    WHERE iid = {$my_last_id}";
            Database::query($sql);
            $sql = "UPDATE {$workTable} SET\n                        has_properties  = {$my_last_id},\n                        view_properties = 1\n                    WHERE c_id = {$course_id} AND id = {$workId}";
            Database::query($sql);
        }
    } else {
        $sql = "UPDATE {$table} SET\n                    {$expiryDateCondition}\n                    {$endOnCondition}\n                    add_to_calendar  = {$agendaId},\n                    enable_qualification = '" . $qualification . "'\n                WHERE\n                    publication_id = {$workId} AND\n                    c_id = {$course_id} AND\n                    id = " . $data['id'];
        Database::query($sql);
    }
    if (!empty($params['category_id'])) {
        $link_info = GradebookUtils::is_resource_in_course_gradebook($courseInfo['code'], LINK_STUDENTPUBLICATION, $workId, api_get_session_id());
        $linkId = null;
        if (!empty($link_info)) {
            $linkId = $link_info['id'];
        }
        if (isset($params['make_calification']) && $params['make_calification'] == 1) {
            if (empty($linkId)) {
                GradebookUtils::add_resource_to_course_gradebook($params['category_id'], $courseInfo['code'], LINK_STUDENTPUBLICATION, $workId, $params['new_dir'], (double) $params['weight'], (double) $params['qualification'], $params['description'], 1, api_get_session_id());
            } else {
                GradebookUtils::update_resource_from_course_gradebook($linkId, $courseInfo['code'], $params['weight']);
            }
        } else {
            // Delete everything of the gradebook for this $linkId
            GradebookUtils::remove_resource_from_course_gradebook($linkId);
        }
    }
}
Пример #6
0
/**
 * Show the form for adding a new agenda item. This is the same function that is used whenever we are editing an
 * agenda item. When the id parameter is empty (default behaviour), then we show an empty form, else we are editing and
 * we have to retrieve the information that is in the database and use this information in the forms.
 * @author Patrick Cool <*****@*****.**>, Ghent University
 * @param integer id, the id of the agenda item we are editing. By default this is empty which means that we are adding an
 * 		 agenda item.
 * @deprecated
 */
function show_add_form($id = '', $type = null)
{
    $htmlHeadXtra[] = to_javascript();
    $course_info = null;
    $agendaObj = new Agenda();
    // if the id is set then we are editing an agenda item
    if (!empty($id)) {
        $course_info = api_get_course_info();
        if (!empty($course_info)) {
            $agendaObj->set_course($course_info);
            $agendaObj->type = 'course';
        } else {
            if (api_is_platform_admin() && $type == 'platform') {
                $agendaObj->type = 'admin';
            } else {
                $agendaObj->type = 'personal';
            }
        }
        $agendaItem = $agendaObj->get_event($id);
        $title = $agendaItem['title'];
        $content = $agendaItem['description'];
        // start date
        if ($agendaItem['start_date'] != '0000-00-00 00:00:00') {
            $agendaItem['start_date'] = api_get_local_time($agendaItem['start_date']);
            list($datepart, $timepart) = explode(" ", $agendaItem['start_date']);
            list($year, $month, $day) = explode("-", $datepart);
            list($hours, $minutes, $seconds) = explode(":", $timepart);
        }
        // end date
        if (!empty($agendaItem['end_date']) && $agendaItem['end_date'] != '0000-00-00 00:00:00') {
            $agendaItem['end_date'] = api_get_local_time($agendaItem['end_date']);
            list($datepart, $timepart) = explode(" ", $agendaItem['end_date']);
            list($end_year, $end_month, $end_day) = explode("-", $datepart);
            list($end_hours, $end_minutes, $end_seconds) = explode(":", $timepart);
        } else {
            if ($agendaItem['all_day']) {
                $end_year = $year;
                $end_month = $month;
                $end_day = $day;
                $end_hours = $hours;
                $end_minutes = $minutes;
                $end_seconds = $seconds;
            }
        }
        // attachments
        //edit_added_resources("Agenda", $id);
        //$to = $item_2_edit['to'];
    } else {
        $to = load_edit_users(TOOL_CALENDAR_EVENT, $id);
    }
    // we start a completely new item, we do not come from the resource linker
    if (isset($_GET['originalresource']) && $_GET['originalresource'] !== "no" and $_GET['action'] == "add") {
        $_SESSION["formelements"] = null;
        unset_session_resources();
    }
    $origin = isset($_GET['origin']) ? Security::remove_XSS($_GET['origin']) : null;
    $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null;
    $idAttach = isset($_GET['id_attach']) ? Security::remove_XSS($_GET['id_attach']) : null;
    $course_url = empty($course_info) ? null : api_get_cidreq();
    $id = isset($id) ? intval($id) : null;
    $url = api_get_self() . '?type=' . Security::remove_XSS($type) . '&origin=' . $origin . '&' . $course_url . '&sort=asc&toolgroup=' . api_get_group_id() . '&action=' . Security::remove_XSS($_GET['action']);
    $form = new FormValidator('new_calendar_item', 'post', $url, null, array('enctype' => 'multipart/form-data'));
    $form->addElement('hidden', 'id', $id);
    $form->addElement('hidden', 'action', $action);
    $form->addElement('hidden', 'id_attach', $idAttach);
    $form->addElement('hidden', 'sort', 'asc');
    $form->addElement('hidden', 'submit_event', 'ok');
    // The form title
    if (isset($id) and $id != '') {
        $form_title = get_lang('ModifyCalendarItem');
    } else {
        $form_title = get_lang('AddCalendarItem');
    }
    $form->addElement('header', $form_title);
    $form->addElement('text', 'title', get_lang('ItemTitle'));
    // selecting the users / groups
    $group_id = api_get_group_id();
    if (empty($id)) {
        if (isset($group_id) && !empty($group_id)) {
            $form->addElement('hidden', 'selected_form[0]', "GROUP:'.{$group_id}.'");
            $form->addElement('hidden', 'To', 'true');
            //$form .= '<input type="hidden" name="selected_form[0]" value="GROUP:'.$group_id.'"/>';
            //$form .= '<input type="hidden" name="To" value="true"/>';
        } else {
            $agendaObj->show_to_form($form, $to);
        }
    }
    // start date and time
    $form->addElement('text', 'start_date', get_lang('StartDate'));
    $form->addElement('text', 'end_date', get_lang('EndDate'));
    // Repeating the calendar item
    if (empty($id)) {
        $form->addElement('label', null, '<a href="javascript://" onclick="return plus_repeated_event();"><span id="plus2">
             <img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;' . get_lang('RepeatEvent') . '</span>
            </a>');
        $form->addElement('html', '<div id="options2" style="display: none;">');
        $form->addElement('checkbox', 'repeat', get_lang('RepeatEvent'));
        $form->addElement('select', 'repeat_type', get_lang('RepeatType'), $agendaObj->getRepeatTypes());
        $form->addElement('text', 'repeat_end_day', get_lang('RepeatEnd'));
        $form->addElement('html', '</div>');
    }
    if (isset($agendaItem['all_day'])) {
        $checked = null;
        if ($agendaItem['all_day']) {
            $checked = 'checked';
        }
        $form->addElement('checkbox', 'all_day', get_lang('AllDay'));
    }
    $form->addElement('html_editor', 'content', get_lang('Description'));
    $form->addElement('checkbox', 'add_announcement', get_lang('AddAnnouncement') . '&nbsp(' . get_lang('SendMail') . ')');
    if ($agendaObj->type == 'course') {
        // File attachment
        $form->addElement('file', 'user_upload', get_lang('AddAnAttachment'));
        $form->addElement('textarea', 'file_comment', get_lang('Comment'));
        $form->add_progress_bar();
    }
    if (isset($_GET['id'])) {
        $text = get_lang('ModifyEvent');
    } else {
        $text = get_lang('AgendaAdd');
    }
    $form->addElement('button', 'submit', $text);
    return $form->return_form();
}
Пример #7
0
/**
 * Show the form for adding a new agenda item. This is the same function that is used whenever we are editing an
 * agenda item. When the id parameter is empty (default behaviour), then we show an empty form, else we are editing and
 * we have to retrieve the information that is in the database and use this information in the forms.
 * @author Patrick Cool <*****@*****.**>, Ghent University
 * @param integer id, the id of the agenda item we are editing. By default this is empty which means that we are adding an
 * 		 agenda item.
 */
function show_add_form($id = '', $type = null)
{
    $showImg = Display::return_icon('div_show.gif');
    $hideImg = Display::return_icon('div_hide.gif');
    $MonthsLong = api_get_months_long();
    $htmlHeadXtra[] = to_javascript();
    // the default values for the forms
    if (!isset($_GET['originalresource'])) {
        $day = date('d');
        $month = date('m');
        $year = date('Y');
        $hours = 9;
        $minutes = '00';
        $title = null;
        $content = null;
        $repeat = false;
    } else {
        // we are coming from the resource linker so there might already have been some information in the form.
        // When we clicked on the button to add resources we stored every form information into a session and now we
        // are doing the opposite thing: getting the information out of the session and putting it into variables to
        // display it in the forms.
        $title = $form_elements['title'];
        $content = $form_elements['content'];
        $id = $form_elements['id'];
        $to = $form_elements['to'];
        $repeat = $form_elements['repeat'];
    }
    //	switching the send to all/send to groups/send to users
    if (isset($_POST['To']) && $_POST['To']) {
        $day = $_POST['fday'];
        $month = $_POST['fmonth'];
        $year = $_POST['fyear'];
        $hours = $_POST['fhour'];
        $minutes = $_POST['fminute'];
        $end_day = $_POST['end_fday'];
        $end_month = $_POST['end_fmonth'];
        $end_year = $_POST['end_fyear'];
        $end_hours = $_POST['end_fhour'];
        $end_minutes = $_POST['end_fminute'];
        $title = $_POST['title'];
        $content = $_POST['content'];
        // the invisible fields
        $action = $_POST['action'];
        $id = $_POST['id'];
        $repeat = !empty($_POST['repeat']) ? true : false;
    }
    $default_no_empty_end_date = 0;
    $course_info = null;
    // if the id is set then we are editing an agenda item
    if (!empty($id)) {
        $course_info = api_get_course_info();
        $agendaObj = new Agenda();
        if (!empty($course_info)) {
            $agendaObj->set_course($course_info);
            $agendaObj->type = 'course';
        } else {
            if (api_is_platform_admin() && $type == 'platform') {
                $agendaObj->type = 'admin';
            } else {
                $agendaObj->type = 'personal';
            }
        }
        $agendaItem = $agendaObj->get_event($id);
        $title = $agendaItem['title'];
        $content = $agendaItem['description'];
        // start date
        if ($agendaItem['start_date'] != '0000-00-00 00:00:00') {
            $agendaItem['start_date'] = api_get_local_time($agendaItem['start_date']);
            list($datepart, $timepart) = explode(" ", $agendaItem['start_date']);
            list($year, $month, $day) = explode("-", $datepart);
            list($hours, $minutes, $seconds) = explode(":", $timepart);
        }
        // end date
        if (!empty($agendaItem['end_date']) && $agendaItem['end_date'] != '0000-00-00 00:00:00') {
            $agendaItem['end_date'] = api_get_local_time($agendaItem['end_date']);
            list($datepart, $timepart) = explode(" ", $agendaItem['end_date']);
            list($end_year, $end_month, $end_day) = explode("-", $datepart);
            list($end_hours, $end_minutes, $end_seconds) = explode(":", $timepart);
        }
    } else {
        $to = load_edit_users(TOOL_CALENDAR_EVENT, $id);
    }
    $content = stripslashes($content);
    $title = stripslashes($title);
    $origin = isset($_GET['origin']) ? Security::remove_XSS($_GET['origin']) : null;
    $course_url = empty($course_info) ? null : api_get_cidreq();
    // The form title
    if (isset($id) and $id != '') {
        $form_title = get_lang('ModifyCalendarItem');
    } else {
        $form_title = get_lang('AddCalendarItem');
    }
    $url = api_get_self() . '?type=' . Security::remove_XSS($type) . '&origin=' . $origin . '&' . $course_url . "&sort=asc&toolgroup=" . api_get_group_id() . '&action=' . Security::remove_XSS($_GET['action']);
    $idAttach = isset($_REQUEST['id_attach']) ? intval($_REQUEST['id_attach']) : null;
    $form = new FormValidator('new_calendar_item', 'post', $url, array('enctype' => 'multipart/form-data'));
    $form->addElement('header', $form_title);
    $form->addElement('hidden', 'id', $id);
    $form->addElement('hidden', 'action', Security::remove_XSS($_GET['action']));
    $form->addElement('hidden', 'id_attach', $idAttach);
    $form->addElement('hidden', 'sort', 'asc');
    $form->addElement('hidden', 'submit_event', 'ok');
    $form->addElement('text', 'title', get_lang('ItemTitle'));
    // selecting the users / groups
    $group_id = api_get_group_id();
    if (empty($id)) {
        CourseManager::addUserGroupMultiSelect($form, array());
    }
    $form->addElement('datepicker', 'start_date', get_lang('StartDate'), array('form_name' => $form->getAttribute('name')));
    $form->addElement('datepicker', 'end_date', get_lang('EndDate'), array('form_name' => $form->getAttribute('name')));
    // Repeating the calendar item
    if (empty($id)) {
        $form->addElement('label', null, '
            <a href="javascript://" onclick="return plus_repeated_event();">
            <span id="plus2">
            ' . $showImg . '&nbsp;' . get_lang('RepeatEvent') . '
            </span></a>');
        $form->addElement('html', '<div id="options2" style="display:none">');
        $form->addElement('checkbox', 'repeat', null, get_lang('RepeatEvent'));
        $options = array('daily' => get_lang('RepeatDaily'), 'weekly' => get_lang('RepeatWeekly'), 'monthlyByDate' => get_lang('RepeatMonthlyByDate'), 'yearly' => get_lang('RepeatYearly'));
        $form->addElement('select', 'repeat_type', get_lang('RepeatType'), $options);
        $form->addElement('datepicker', 'repeat_end_day', get_lang('RepeatEnd'));
        $form->addElement('html', '</div>');
        if (isset($agendaItem['all_day'])) {
            $checked = null;
            if ($agendaItem['all_day']) {
                $checked = 'checked';
            }
            $form->addElement('checkbox', 'all_day', null, get_lang('AllDay'));
        }
        $form->addElement('html_editor', 'content', get_lang('Description'));
        if (isset($agendaObj) && $agendaObj->type == 'course') {
            $form->addElement('file', 'user_upload', null, get_lang('AddAnAttachment'));
            $form->addElement('text', 'file_comment', null, get_lang('Comment'));
        }
        if (isset($_GET['id'])) {
            $class = 'save';
            $text = get_lang('ModifyEvent');
        } else {
            $class = 'add';
            $text = get_lang('AgendaAdd');
        }
        $form->addElement('button', 'submit', $text);
        $form->display();
    }
}
Пример #8
0
 /**
  * @param string $file
  * @param bool   $moveFile
  *
  * @return int
  */
 private function importCalendarStatic($file, $moveFile = true)
 {
     $data = Import::csvToArray($file);
     if ($this->getDumpValues()) {
         // Remove all calendar items
         $truncateTables = array(Database::get_course_table(TABLE_AGENDA), Database::get_course_table(TABLE_AGENDA_ATTACHMENT), Database::get_course_table(TABLE_AGENDA_REPEAT), Database::get_course_table(TABLE_AGENDA_REPEAT_NOT), Database::get_main_table(TABLE_PERSONAL_AGENDA), Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT_NOT), Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT));
         foreach ($truncateTables as $table) {
             $sql = "TRUNCATE {$table}";
             Database::query($sql);
         }
         $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
         $sql = "DELETE FROM {$table} WHERE tool = 'calendar_event'";
         Database::query($sql);
     }
     if (!empty($data)) {
         $this->logger->addInfo(count($data) . " records found.");
         $eventsToCreate = array();
         $errorFound = false;
         foreach ($data as $row) {
             $sessionId = null;
             $externalSessionId = null;
             if (isset($row['external_sessionID'])) {
                 $externalSessionId = $row['external_sessionID'];
                 $sessionId = SessionManager::getSessionIdFromOriginalId($externalSessionId, $this->extraFieldIdNameList['session']);
             }
             $courseCode = null;
             if (isset($row['coursecode'])) {
                 $courseCode = $row['coursecode'];
             }
             $courseInfo = api_get_course_info($courseCode);
             if (empty($courseInfo)) {
                 $this->logger->addInfo("Course '{$courseCode}' does not exists");
             }
             if (empty($sessionId)) {
                 $this->logger->addInfo("external_sessionID: " . $externalSessionId . " does not exists.");
             }
             $teacherId = null;
             if (!empty($sessionId) && !empty($courseInfo)) {
                 $courseIncluded = SessionManager::relation_session_course_exist($sessionId, $courseInfo['real_id']);
                 if ($courseIncluded == false) {
                     $this->logger->addInfo("Course '{$courseCode}' is not included in session: {$sessionId}");
                     $errorFound = true;
                 } else {
                     $teachers = CourseManager::get_coach_list_from_course_code($courseInfo['code'], $sessionId);
                     // Getting first teacher.
                     if (!empty($teachers)) {
                         $teacher = current($teachers);
                         $teacherId = $teacher['user_id'];
                     } else {
                         $sessionInfo = api_get_session_info($sessionId);
                         $teacherId = $sessionInfo['id_coach'];
                     }
                 }
             } else {
                 $errorFound = true;
             }
             if (empty($teacherId)) {
                 $errorFound = true;
                 $this->logger->addInfo("No teacher found in course code : '{$courseCode}' and session: '{$sessionId}'");
             }
             $date = $row['date'];
             $startTime = $row['time_start'];
             $endTime = $row['time_end'];
             $title = $row['title'];
             $startDateYear = substr($date, 0, 4);
             $startDateMonth = substr($date, 4, 2);
             $startDateDay = substr($date, 6, 8);
             $startDate = $startDateYear . '-' . $startDateMonth . '-' . $startDateDay . ' ' . $startTime . ":00";
             $endDate = $startDateYear . '-' . $startDateMonth . '-' . $startDateDay . ' ' . $endTime . ":00";
             if (!api_is_valid_date($startDate) or !api_is_valid_date($endDate)) {
                 $this->logger->addInfo("Verify your dates:  '{$startDate}' : '{$endDate}' ");
                 $errorFound = true;
             }
             if ($errorFound == false) {
                 $eventsToCreate[] = array('start' => $startDate, 'end' => $endDate, 'title' => $title, 'sender_id' => $teacherId, 'course_id' => $courseInfo['real_id'], 'session_id' => $sessionId, $this->extraFieldIdNameList['calendar_event'] => $row['external_calendar_itemID']);
             }
         }
         if (empty($eventsToCreate)) {
             $this->logger->addInfo("No events to add");
             return 0;
         }
         $this->logger->addInfo("Ready to insert events");
         $content = null;
         $agenda = new Agenda();
         $extraFieldValue = new ExtraFieldValue('calendar_event');
         $extraFieldName = $this->extraFieldIdNameList['calendar_event'];
         $externalEventId = null;
         $extraField = new ExtraField('calendar_event');
         $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable($extraFieldName);
         if (empty($extraFieldInfo)) {
             $this->logger->addInfo("No calendar event extra field created: {$extraFieldName}");
             return 0;
         }
         foreach ($eventsToCreate as $event) {
             if (!isset($event[$extraFieldName])) {
                 $this->logger->addInfo("No external_calendar_itemID found. Skipping ...");
                 continue;
             } else {
                 $externalEventId = $event[$extraFieldName];
                 $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value($extraFieldName, $externalEventId);
                 if (!empty($item) || empty($externalEventId)) {
                     $this->logger->addInfo("Event #{$externalEventId} was already added . Skipping ...");
                     continue;
                 }
             }
             $courseInfo = api_get_course_info_by_id($event['course_id']);
             $agenda->set_course($courseInfo);
             $agenda->setType('course');
             $agenda->setSessionId($event['session_id']);
             $agenda->setSenderId($event['sender_id']);
             $agenda->setIsAllowedToEdit(true);
             $eventComment = $event['comment'];
             if (empty($courseInfo)) {
                 $this->logger->addInfo("No course found for added: #" . $event['course_id'] . " Skipping ...");
                 continue;
             }
             if (empty($event['sender_id'])) {
                 $this->logger->addInfo("No sender found: #" . $event['sender_id'] . " Skipping ...");
                 continue;
             }
             $eventId = $agenda->addEvent($event['start'], $event['end'], false, $event['title'], $content, array('everyone'), false, null, array(), null, $eventComment);
             if (!empty($eventId)) {
                 $extraFieldValue->save(array('value' => $externalEventId, 'field_id' => $extraFieldInfo['id'], 'item_id' => $eventId));
                 $this->logger->addInfo("Event added: #{$eventId}");
             } else {
                 $this->logger->addInfo("Error while creating event.");
             }
         }
     }
     if ($moveFile) {
         $this->moveFile($file);
     }
 }