/** * Check if the ser has completed the requirements for the session sequences * @param array $sequences The sequences * @param int $userId Optional. The user ID * @return array */ private static function checkSessionRequirementsForUser(array $sequences, $userId = 0) { $sequenceList = []; $entityManager = Database::getManager(); $gradebookCategoryRepo = $entityManager->getRepository('ChamiloCoreBundle:GradebookCategory'); foreach ($sequences as $sequenceId => $sequence) { $item = ['name' => $sequence['name'], 'requirements' => []]; foreach ($sequence['requirements'] as $sessionRequired) { $itemSession = ['name' => $sessionRequired->getName(), 'status' => true]; $sessionsCourses = $sessionRequired->getCourses(); foreach ($sessionsCourses as $sessionCourse) { $course = $sessionCourse->getCourse(); $gradebooks = $gradebookCategoryRepo->findBy(['courseCode' => $course->getCode(), 'sessionId' => $sessionRequired->getId(), 'isRequirement' => true]); foreach ($gradebooks as $gradebook) { $category = Category::createCategoryObjectFromEntity($gradebook); if (!empty($userId)) { $itemSession['status'] = $itemSession['status'] && Category::userFinishedCourse($userId, $category, null, $course->getCode(), $sessionRequired->getId()); } } } $item['requirements'][$sessionRequired->getId()] = $itemSession; } $sequenceList[$sequenceId] = $item; } return $sequenceList; }
/** * Get the classes to display on the current page. */ function get_class_data($from, $number_of_items, $column, $direction) { $class_table = Database::get_main_table(TABLE_MAIN_CLASS); $class_user_table = Database::get_main_table(TABLE_MAIN_CLASS_USER); $courseId = api_get_course_int_id(); $em = Database::getManager(); $res = $em->getRepository('ChamiloCoreBundle:CourseRelClass')->findBy(['courseId' => $courseId]); $subscribed_classes = array(); foreach ($res as $obj) { $subscribed_classes[] = $obj->getClassId(); } $sql = "SELECT\n c.id AS col0,\n c.name AS col1,\n COUNT(cu.user_id) AS col2,\n c.id AS col3\n FROM {$class_table} c "; $sql .= " LEFT JOIN {$class_user_table} cu ON cu.class_id = c.id"; $sql .= " WHERE 1 = 1"; if (isset($_GET['keyword'])) { $keyword = Database::escape_string(trim($_GET['keyword'])); $sql .= " AND (c.name LIKE '%" . $keyword . "%')"; } if (count($subscribed_classes) > 0) { $sql .= " AND c.id NOT IN ('" . implode("','", $subscribed_classes) . "')"; } $sql .= " GROUP BY c.id, c.name "; $sql .= " ORDER BY col{$column} {$direction} "; $sql .= " LIMIT {$from},{$number_of_items}"; $res = Database::query($sql); $classes = array(); while ($class = Database::fetch_row($res)) { $classes[] = $class; } return $classes; }
/** * @return EntityManager */ public function getEntityManager() { if (empty($this->manager)) { $dbParams = array('driver' => 'pdo_mysql', 'host' => api_get_configuration_value('db_host'), 'user' => api_get_configuration_value('db_user'), 'password' => api_get_configuration_value('db_password'), 'dbname' => api_get_configuration_value('main_database')); $database = new \Database(); $database->connect($dbParams, __DIR__ . '/../../', __DIR__ . '/../../'); $this->manager = $database->getManager(); } return $this->manager; }
/** * Get all values for an item * @param int $itemId The item ID * @param boolean $onlyVisibleFields Get the visible extra field only * @return array */ public function getAllValuesForAnItem($itemId, $onlyVisibleFields = false) { $em = Database::getManager(); $queryBuilder = $em->createQueryBuilder(); $fieldOptionsRepo = $em->getRepository('ChamiloCoreBundle:ExtraFieldOptions'); $queryBuilder = $queryBuilder->select('fv')->from('ChamiloCoreBundle:ExtraFieldValues', 'fv')->innerJoin('ChamiloCoreBundle:ExtraField', 'f', Doctrine\ORM\Query\Expr\Join::WITH, 'fv.field = f')->where($queryBuilder->expr()->andX($queryBuilder->expr()->eq('fv.itemId', ':item'), $queryBuilder->expr()->eq('f.extraFieldType', ':field_type'))); if ($onlyVisibleFields) { $queryBuilder->andWhere($queryBuilder->expr()->eq('f.visible', true)); } $fieldValues = $queryBuilder->setParameter('item', $itemId)->setParameter('field_type', $this->getExtraField()->getExtraFieldType())->getQuery()->getResult(); $valueList = []; foreach ($fieldValues as $fieldValue) { $item = ['value' => $fieldValue]; switch ($fieldValue->getField()->getFieldType()) { case ExtraField::FIELD_TYPE_SELECT: $item['option'] = $fieldOptionsRepo->findOneBy(['field' => $fieldValue->getField(), 'value' => $fieldValue->getValue()]); break; } $valueList[] = $item; } return $valueList; }
/** * Save values in the *_field_values table * @param array Structured array with the values to save * @param boolean Whether to show the insert query (passed to the parent save() method) * @result mixed The result sent from the parent method * @assert (array()) === false */ public function save($params, $show_query = false) { $extra_field = new ExtraField($this->type); // Setting value to insert. $value = $params['field_value']; $value_to_insert = null; if (is_array($value)) { $value_to_insert = implode(';', $value); } else { $value_to_insert = Database::escape_string($value); } $params['field_value'] = $value_to_insert; //If field id exists $extra_field_info = $extra_field->get($params['field_id']); if ($extra_field_info) { switch ($extra_field_info['field_type']) { case ExtraField::FIELD_TYPE_RADIO: case ExtraField::FIELD_TYPE_SELECT: case ExtraField::FIELD_TYPE_SELECT_MULTIPLE: //$field_options = $session_field_option->get_field_options_by_field($params['field_id']); //$params['field_value'] = split(';', $value_to_insert); /* if ($field_options) { $check = false; foreach ($field_options as $option) { if (in_array($option['option_value'], $values)) { $check = true; break; } } if (!$check) { return false; //option value not found } } else { return false; //enumerated type but no option found }*/ break; case ExtraField::FIELD_TYPE_TEXT: case ExtraField::FIELD_TYPE_TEXTAREA: break; case ExtraField::FIELD_TYPE_DOUBLE_SELECT: if (is_array($value)) { if (isset($value['extra_' . $extra_field_info['field_variable']]) && isset($value['extra_' . $extra_field_info['field_variable'] . '_second'])) { $value_to_insert = $value['extra_' . $extra_field_info['field_variable']] . '::' . $value['extra_' . $extra_field_info['field_variable'] . '_second']; } else { $value_to_insert = null; } } break; default: break; } if ($extra_field_info['field_type'] == ExtraField::FIELD_TYPE_TAG) { $field_values = self::getAllValuesByItemAndFieldAndValue($params[$this->handler_id], $params['field_id'], $value); } else { $field_values = self::get_values_by_handler_and_field_id($params[$this->handler_id], $params['field_id']); } $params['field_value'] = $value_to_insert; $params['tms'] = api_get_utc_datetime(); $params[$this->author_id] = api_get_user_id(); // Insert if (empty($field_values)) { if ($extra_field_info['field_loggeable'] == 1) { switch ($this->type) { case 'question': $extraFieldValue = new QuestionFieldValues(); $extraFieldValue->setUserId(api_get_user_id()); $extraFieldValue->setQuestionId($params[$this->handler_id]); break; case 'course': $extraFieldValue = new CourseFieldValues(); $extraFieldValue->setUserId(api_get_user_id()); $extraFieldValue->setQuestionId($params[$this->handler_id]); break; case 'user': $extraFieldValue = new UserFieldValues(); $extraFieldValue->setUserId($params[$this->handler_id]); $extraFieldValue->setAuthorId(api_get_user_id()); break; case 'session': $extraFieldValue = new SessionFieldValues(); $extraFieldValue->setUserId(api_get_user_id()); $extraFieldValue->setSessionId($params[$this->handler_id]); break; } if (isset($extraFieldValue)) { if (!empty($params['field_value'])) { $extraFieldValue->setComment($params['comment']); $extraFieldValue->setFieldValue($params['field_value']); $extraFieldValue->setFieldId($params['field_id']); $extraFieldValue->setTms(api_get_utc_datetime(null, false, true)); Database::getManager()->persist($extraFieldValue); Database::getManager()->flush(); } } } else { if ($extra_field_info['field_type'] == ExtraField::FIELD_TYPE_TAG) { $option = new ExtraFieldOption($this->type); $optionExists = $option->get($params['field_value']); if (empty($optionExists)) { $optionParams = array('field_id' => $params['field_id'], 'option_value' => $params['field_value']); $optionId = $option->saveOptions($optionParams); } else { $optionId = $optionExists['id']; } $params['field_value'] = $optionId; if ($optionId) { return parent::save($params, $show_query); } } else { return parent::save($params, $show_query); } } } else { // Update if ($extra_field_info['field_loggeable'] == 1) { switch ($this->type) { case 'question': $extraFieldValue = Database::getManager()->getRepository('ChamiloCoreBundle:QuestionFieldValues')->find($field_values['id']); $extraFieldValue->setUserId(api_get_user_id()); $extraFieldValue->setQuestionId($params[$this->handler_id]); break; case 'course': $extraFieldValue = Database::getManager()->getRepository('ChamiloCoreBundle:CourseFieldValues')->find($field_values['id']); $extraFieldValue->setUserId(api_get_user_id()); $extraFieldValue->setCourseCode($params[$this->handler_id]); break; case 'user': $extraFieldValue = Database::getManager()->getRepository('ChamiloCoreBundle:UserFieldValues')->find($field_values['id']); $extraFieldValue->setUserId(api_get_user_id()); $extraFieldValue->setAuthorId(api_get_user_id()); break; case 'session': $extraFieldValue = Database::getManager()->getRepository('ChamiloCoreBundle:SessionFieldValues')->find($field_values['id']); $extraFieldValue->setUserId(api_get_user_id()); $extraFieldValue->setSessionId($params[$this->handler_id]); break; } if (isset($extraFieldValue)) { if (!empty($params['field_value'])) { /* * If the field value is similar to the previous value then the comment will be the same in order to no save in the log an empty record */ if ($extraFieldValue->getFieldValue() == $params['field_value']) { if (empty($params['comment'])) { $params['comment'] = $extraFieldValue->getComment(); } } $extraFieldValue->setComment($params['comment']); $extraFieldValue->setFieldValue($params['field_value']); $extraFieldValue->setFieldId($params['field_id']); $extraFieldValue->setTms(api_get_utc_datetime(null, false, true)); Database::getManager()->persist($extraFieldValue); Database::getManager()->flush(); } } } else { $params['id'] = $field_values['id']; return parent::update($params, $show_query); } } } }
static function delete_category($id) { $em = Database::getManager(); $item = $em->find('ChamiloCoreBundle:CLpCategory', $id); if ($item) { $courseId = $item->getCId(); $query = $em->createQuery('SELECT u FROM ChamiloCoreBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId'); $query->setParameter('id', $courseId); $query->setParameter('catId', $item->getId()); $lps = $query->getResult(); // Setting category = 0. if ($lps) { foreach ($lps as $lpItem) { $lpItem->setCategoryId(0); } } // Removing category. $em->remove($item); $em->flush(); } }
/** * @param User $user */ public static function sendResetEmail(User $user) { //if (null === $user->getConfirmationToken()) { $uniqueId = api_get_unique_id(); $user->setConfirmationToken($uniqueId); $user->setPasswordRequestedAt(new \DateTime()); Database::getManager()->persist($user); Database::getManager()->flush(); $url = api_get_path(WEB_CODE_PATH) . 'auth/reset.php?token=' . $uniqueId; $mailTemplate = new Template(null, false, false, false, false, false); $mailTemplate->assign('complete_user_name', $user->getCompleteName()); $mailTemplate->assign('link', $url); $mailLayout = $mailTemplate->get_template('mail/reset_password.tpl'); $mailSubject = get_lang('ResetPasswordInstructions'); $mailBody = $mailTemplate->fetch($mailLayout); api_mail_html($user->getCompleteName(), $user->getEmail(), $mailSubject, $mailBody); Display::addFlash(Display::return_message(get_lang('CheckYourEmailAndFollowInstructions'))); //} }
/** * Create a group * @param string $name The name for this group * @param int $category_id * @param int $tutor The user-id of the group's tutor * @param int $places How many people can subscribe to the new group */ public static function create_group($name, $category_id, $tutor, $places) { $courseObj = api_get_user_course_entity(); $_course = api_get_course_info(); $session_id = api_get_session_id(); $currentCourseRepository = $_course['path']; $category = self::get_category($category_id); $places = intval($places); if ($category) { if ($places == 0) { //if the amount of users per group is not filled in, use the setting from the category $places = $category['max_student']; } else { if ($places > $category['max_student'] && $category['max_student'] != 0) { $places = $category['max_student']; } } $docState = $category['doc_state']; $calendarState = $category['calendar_state']; $workState = $category['work_state']; $anonuncementState = $category['announcements_state']; $forumState = $category['forum_state']; $wikiState = $category['wiki_state']; $chatState = $category['chat_state']; $selfRegAllowed = $category['self_reg_allowed']; $selfUnregAllowed = $category['self_unreg_allowed']; } else { $docState = self::TOOL_PRIVATE; $calendarState = self::TOOL_PRIVATE; $workState = self::TOOL_PRIVATE; $anonuncementState = self::TOOL_PRIVATE; $forumState = self::TOOL_PRIVATE; $wikiState = self::TOOL_PRIVATE; $chatState = self::TOOL_PRIVATE; $selfRegAllowed = 0; $selfUnregAllowed = 0; } $group = new CGroupInfo(); $group->setName($name)->setStatus(1)->setDescription('')->setMaxStudent($places)->setAnnouncementsState($anonuncementState)->setDocState($docState)->setCalendarState($calendarState)->setChatState($chatState)->setForumState($forumState)->setWikiState($wikiState)->setWorkState($workState)->setSelfUnregistrationAllowed($selfUnregAllowed)->setSelfRegistrationAllowed($selfRegAllowed)->setSessionId($session_id)->setCourse($courseObj)->setCategoryId($category_id)->setDescription(''); $em = Database::getManager(); $em->persist($group); $em->flush(); $lastId = $group->getIid(); if ($lastId) { $desired_dir_name = '/' . api_replace_dangerous_char($name) . '_groupdocs'; $my_path = api_get_path(SYS_COURSE_PATH) . $currentCourseRepository . '/document'; $newFolderData = create_unexisting_directory($_course, api_get_user_id(), $session_id, $lastId, null, $my_path, $desired_dir_name, null, 1); $unique_name = $newFolderData['path']; $group->setId($lastId); $group->setSecretDirectory($unique_name); $group->setName($name); $em->merge($group); $em->flush(); // create a forum if needed if ($forumState >= 0) { require_once api_get_path(SYS_CODE_PATH) . 'forum/forumconfig.inc.php'; require_once api_get_path(SYS_CODE_PATH) . 'forum/forumfunction.inc.php'; $forum_categories = get_forum_categories(); if (empty($forum_categories)) { $categoryParam = array('forum_category_title' => get_lang('GroupForums')); store_forumcategory($categoryParam); $forum_categories = get_forum_categories(); } $counter = 0; foreach ($forum_categories as $key => $value) { if ($counter == 0) { $forum_category_id = $key; } $counter++; } // A sanity check. if (empty($forum_category_id)) { $forum_category_id = 0; } $values = array(); $values['forum_title'] = $name; $values['group_id'] = $lastId; $values['forum_category'] = $forum_category_id; $values['allow_anonymous_group']['allow_anonymous'] = 0; $values['students_can_edit_group']['students_can_edit'] = 0; $values['approval_direct_group']['approval_direct'] = 0; $values['allow_attachments_group']['allow_attachments'] = 1; $values['allow_new_threads_group']['allow_new_threads'] = 1; $values['default_view_type_group']['default_view_type'] = api_get_setting('forum.default_forum_view'); $values['group_forum'] = $lastId; if ($forumState == '1') { $values['public_private_group_forum_group']['public_private_group_forum'] = 'public'; } elseif ($forumState == '2') { $values['public_private_group_forum_group']['public_private_group_forum'] = 'private'; } elseif ($forumState == '0') { $values['public_private_group_forum_group']['public_private_group_forum'] = 'unavailable'; } store_forum($values); } } return $lastId; }
if ($intro_cmdUpdate) { if ($form->validate()) { $form_values = $form->exportValues(); $intro_content = Security::remove_XSS(stripslashes(api_html_entity_decode($form_values['intro_content'])), COURSEMANAGERLOWSECURITY); $criteria = ['cId' => $course_id, 'id' => $moduleId, 'sessionId' => $session_id]; if (!empty($intro_content)) { /** @var CToolIntro $toolIntro */ $toolIntro = Database::getManager()->getRepository('ChamiloCourseBundle:CToolIntro')->findOneBy($criteria); if ($toolIntro) { $toolIntro->setIntroText($intro_content); } else { $toolIntro = new CToolIntro(); $toolIntro->setSessionId($session_id)->setCId($course_id)->setIntroText($intro_content)->setId($moduleId); } Database::getManager()->persist($toolIntro); Database::getManager()->flush(); $introduction_section .= Display::return_message(get_lang('IntroductionTextUpdated'), 'confirmation', false); } else { // got to the delete command $intro_cmdDel = true; } } else { $intro_cmdEdit = true; } } /* Delete Command */ if ($intro_cmdDel) { $sql = "DELETE FROM {$TBL_INTRODUCTION}\n WHERE\n c_id = {$course_id} AND\n id='" . Database::escape_string($moduleId) . "' AND\n session_id='" . intval($session_id) . "'"; Database::query($sql); $introduction_section .= Display::return_message(get_lang('IntroductionTextDeleted'), 'confirmation'); }
/** * Retrieve all posts of a given thread * @param int $threadId The thread ID * @param string $orderDirection Optional. The direction for sort the posts * @param boolean $recursive Optional. If the list is recursive * @param int $postId Optional. The post ID for recursive list * @param int $depth Optional. The depth to indicate the indent * @todo move to a repository * * @return array containing all the information about the posts of a given thread */ function getPosts($threadId, $orderDirection = 'ASC', $recursive = false, $postId = 0, $depth = -1) { $list = []; $em = Database::getManager(); if (api_is_allowed_to_edit(false, true)) { $visibleCriteria = Criteria::expr()->neq('visible', 2); } else { $visibleCriteria = Criteria::expr()->eq('visible', 1); } $criteria = Criteria::create(); $criteria->where(Criteria::expr()->eq('threadId', $threadId))->andWhere(Criteria::expr()->eq('cId', api_get_course_int_id()))->andWhere($visibleCriteria); if ($recursive) { $criteria->andWhere(Criteria::expr()->eq('postParentId', $postId)); } $qb = $em->getRepository('ChamiloCourseBundle:CForumPost')->createQueryBuilder('p'); $qb->select('p')->addCriteria($criteria)->addOrderBy('p.postId', $orderDirection); $posts = $qb->getQuery()->getResult(); $depth++; /** @var \Chamilo\CourseBundle\Entity\CForumPost $post */ foreach ($posts as $post) { $user = $em->find('ChamiloUserBundle:User', $post->getPosterId()); $list[$post->getPostId()] = ['c_id' => $post->getCId(), 'post_id' => $post->getPostId(), 'post_title' => $post->getPostTitle(), 'post_text' => $post->getPostText(), 'thread_id' => $post->getThreadId(), 'forum_id' => $post->getForumId(), 'poster_id' => $post->getPosterId(), 'poster_name' => $post->getPosterName(), 'post_date' => $post->getPostDate(), 'post_notification' => $post->getPostNotification(), 'post_parent_id' => $post->getPostParentId(), 'visible' => $post->getVisible(), 'indent_cnt' => $depth, 'user_id' => $user->getUserId(), 'username' => $user->getUsername(), 'username_canonical' => $user->getUsernameCanonical(), 'lastname' => $user->getLastname(), 'firstname' => $user->getFirstname()]; if (!$recursive) { continue; } $list = array_merge($list, getPosts($threadId, $orderDirection, $recursive, $post->getPostId(), $depth)); } return $list; }
/** * Function register_course to create a record in the course table of the main database * @param array Course details (see code for details) * @return int Created course ID * @todo use an array called $params instead of lots of params * @assert (null) === false */ public static function register_course($params) { global $error_msg; $title = $params['title']; $code = $params['code']; $visual_code = $params['visual_code']; $directory = $params['directory']; $tutor_name = isset($params['tutor_name']) ? $params['tutor_name'] : null; //$description = $params['description']; $category_code = isset($params['course_category']) ? $params['course_category'] : ''; $course_language = isset($params['course_language']) && !empty($params['course_language']) ? $params['course_language'] : api_get_setting('language.platform_language'); $user_id = empty($params['user_id']) ? api_get_user_id() : intval($params['user_id']); $department_name = isset($params['department_name']) ? $params['department_name'] : null; $department_url = isset($params['department_url']) ? $params['department_url'] : null; $disk_quota = isset($params['disk_quota']) ? $params['disk_quota'] : null; if (!isset($params['visibility'])) { $default_course_visibility = api_get_setting('course.courses_default_creation_visibility'); if ($default_course_visibility != '') { $visibility = $default_course_visibility; } else { $visibility = COURSE_VISIBILITY_OPEN_PLATFORM; } } else { $visibility = $params['visibility']; } $subscribe = isset($params['subscribe']) ? intval($params['subscribe']) : ($visibility == COURSE_VISIBILITY_OPEN_PLATFORM ? 1 : 0); $unsubscribe = isset($params['unsubscribe']) ? intval($params['unsubscribe']) : 0; $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : null; $teachers = isset($params['teachers']) ? $params['teachers'] : null; $status = isset($params['status']) ? $params['status'] : null; $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER); $ok_to_register_course = true; // Check whether all the needed parameters are present. if (empty($code)) { $error_msg[] = 'courseSysCode is missing'; $ok_to_register_course = false; } if (empty($visual_code)) { $error_msg[] = 'courseScreenCode is missing'; $ok_to_register_course = false; } if (empty($directory)) { $error_msg[] = 'courseRepository is missing'; $ok_to_register_course = false; } if (empty($title)) { $error_msg[] = 'title is missing'; $ok_to_register_course = false; } if (empty($expiration_date)) { $expiration_date = api_get_utc_datetime(time() + FIRST_EXPIRATION_DELAY, false, true); } else { $expiration_date = api_get_utc_datetime($expiration_date, false, true); } if ($visibility < 0 || $visibility > 4) { $error_msg[] = 'visibility is invalid'; $ok_to_register_course = false; } if (empty($disk_quota)) { $disk_quota = api_get_setting('document.default_document_quotum'); } if (stripos($department_url, 'http://') === false && stripos($department_url, 'https://') === false) { $department_url = 'http://' . $department_url; } //just in case if ($department_url == 'http://') { $department_url = ''; } $course_id = 0; if ($ok_to_register_course) { $manager = Database::getManager(); $url = $manager->getRepository('ChamiloCoreBundle:AccessUrl')->find(api_get_current_access_url_id()); $accessRelCourse = new AccessUrlRelCourse(); $accessRelCourse->setUrl($url); $course = new Course(); $course->setCode($code)->setDirectory($directory)->setCourseLanguage($course_language)->setTitle($title)->setDescription(self::lang2db(get_lang('CourseDescription')))->setCategoryCode($category_code)->setVisibility($visibility)->setShowScore(1)->setExpirationDate($expiration_date)->setDiskQuota(intval($disk_quota))->setTutorName($tutor_name)->setDepartmentName($department_name)->setDepartmentUrl($department_url)->setSubscribe(intval($subscribe))->setVisualCode($visual_code)->addUrls($accessRelCourse); $manager->persist($course); $manager->flush(); $course_id = $course->getId(); if ($course_id) { $sort = api_max_sort_value('0', api_get_user_id()); // Default true $addTeacher = isset($params['add_user_as_teacher']) ? $params['add_user_as_teacher'] : true; if ($addTeacher) { $i_course_sort = CourseManager::userCourseSort($user_id, $code); if (!empty($user_id)) { $sql = "INSERT INTO " . $TABLECOURSUSER . " SET\n c_id = '" . $course_id . "',\n user_id = '" . intval($user_id) . "',\n status = '1',\n is_tutor = '0',\n sort = '" . $i_course_sort . "',\n relation_type = 0,\n user_course_cat = '0'"; Database::query($sql); } } if (!empty($teachers)) { if (!is_array($teachers)) { $teachers = array($teachers); } foreach ($teachers as $key) { //just in case if ($key == $user_id) { continue; } if (empty($key)) { continue; } $sql = "INSERT INTO " . $TABLECOURSUSER . " SET\n c_id = '" . Database::escape_string($course_id) . "',\n user_id = '" . Database::escape_string($key) . "',\n status = '1',\n is_tutor = '0',\n sort = '" . ($sort + 1) . "',\n relation_type = 0,\n user_course_cat = '0'"; Database::query($sql); } } // Adding the course to an URL. if (api_is_multiple_url_enabled()) { $url_id = 1; if (api_get_current_access_url_id() != -1) { $url_id = api_get_current_access_url_id(); } UrlManager::add_course_to_url($course_id, $url_id); } else { UrlManager::add_course_to_url($course_id, 1); } // Add event to the system log. $user_id = api_get_user_id(); Event::addEvent(LOG_COURSE_CREATE, LOG_COURSE_CODE, $code, api_get_utc_datetime(), $user_id, $course_id); $send_mail_to_admin = api_get_setting('course.send_email_to_admin_when_create_course'); // @todo Improve code to send to all current portal administrators. if ($send_mail_to_admin == 'true') { $siteName = api_get_setting('platform.site_name'); $recipient_email = api_get_setting('admin.administrator_email'); $recipient_name = api_get_person_name(api_get_setting('admin.administrator_name'), api_get_setting('admin.administrator_surname')); $iname = api_get_setting('platform.institution'); $subject = get_lang('NewCourseCreatedIn') . ' ' . $siteName . ' - ' . $iname; $message = get_lang('Dear') . ' ' . $recipient_name . ",\n\n" . get_lang('MessageOfNewCourseToAdmin') . ' ' . $siteName . ' - ' . $iname . "\n"; $message .= get_lang('CourseName') . ' ' . $title . "\n"; $message .= get_lang('Category') . ' ' . $category_code . "\n"; $message .= get_lang('Tutor') . ' ' . $tutor_name . "\n"; $message .= get_lang('Language') . ' ' . $course_language; $userInfo = api_get_user_info($user_id); $additionalParameters = array('smsType' => SmsPlugin::NEW_COURSE_BEEN_CREATED, 'userId' => $user_id, 'courseName' => $title, 'creatorUsername' => $userInfo['username']); api_mail_html($recipient_name, $recipient_email, $subject, $message, $siteName, $recipient_email, null, null, null, $additionalParameters); } } } return $course_id; }
/** * Get the formated data for sessions block to be displayed on Session Catalog page * @param array $sessions The session list * @return array */ private function getFormatedSessionsBlock(array $sessions) { $extraFieldValue = new ExtraFieldValue('session'); $userId = api_get_user_id(); $sessionsBlocks = []; $entityManager = Database::getManager(); $sessionRelCourseRepo = $entityManager->getRepository('ChamiloCoreBundle:SessionRelCourse'); $extraFieldRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraField'); $extraFieldRelTagRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraFieldRelTag'); $tagsField = $extraFieldRepo->findOneBy(['extraFieldType' => Chamilo\CoreBundle\Entity\ExtraField::COURSE_FIELD_TYPE, 'variable' => 'tags']); /** @var \Chamilo\CoreBundle\Entity\Session $session */ foreach ($sessions as $session) { $sessionDates = SessionManager::parseSessionDates(['display_start_date' => $session->getDisplayStartDate(), 'display_end_date' => $session->getDisplayEndDate(), 'access_start_date' => $session->getAccessStartDate(), 'access_end_date' => $session->getAccessEndDate(), 'coach_access_start_date' => $session->getCoachAccessStartDate(), 'coach_access_end_date' => $session->getCoachAccessEndDate()]); $imageField = $extraFieldValue->get_values_by_handler_and_field_variable($session->getId(), 'image'); $sessionCourseTags = []; if (!is_null($tagsField)) { $sessionRelCourses = $sessionRelCourseRepo->findBy(['session' => $session]); foreach ($sessionRelCourses as $sessionRelCourse) { $courseTags = $extraFieldRelTagRepo->getTags($tagsField, $sessionRelCourse->getCourse()->getId()); foreach ($courseTags as $tag) { $sessionCourseTags[] = $tag->getTag(); } } } if (!empty($sessionCourseTags)) { $sessionCourseTags = array_unique($sessionCourseTags); } $repo = $entityManager->getRepository('ChamiloCoreBundle:SequenceResource'); $sequences = $repo->getRequirementsAndDependenciesWithinSequences($session->getId(), SequenceResource::SESSION_TYPE); $hasRequirements = false; foreach ($sequences['sequences'] as $sequence) { if (count($sequence['requirements']) === 0) { continue; } $hasRequirements = true; break; } $sessionsBlock = array('id' => $session->getId(), 'name' => $session->getName(), 'image' => isset($imageField['value']) ? $imageField['value'] : null, 'nbr_courses' => $session->getNbrCourses(), 'nbr_users' => $session->getNbrUsers(), 'coach_name' => $session->getGeneralCoach()->getCompleteName(), 'is_subscribed' => SessionManager::isUserSubscribedAsStudent($session->getId(), $userId), 'icon' => $this->getSessionIcon($session->getName()), 'date' => $sessionDates['display'], 'subscribe_button' => $this->getRegisteredInSessionButton($session->getId(), $session->getName(), $hasRequirements), 'show_description' => $session->getShowDescription(), 'tags' => $sessionCourseTags); $sessionsBlock = array_merge($sessionsBlock, $sequences); $sessionsBlocks[] = $sessionsBlock; } return $sessionsBlocks; }
/* For licensing terms, see /license.txt */ //require_once '../global.inc.php'; $action = isset($_GET['a']) ? $_GET['a'] : ''; switch ($action) { case 'get_second_select_options': $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : null; $field_id = isset($_REQUEST['field_id']) ? $_REQUEST['field_id'] : null; $option_value_id = isset($_REQUEST['option_value_id']) ? $_REQUEST['option_value_id'] : null; if (!empty($type) && !empty($field_id) && !empty($option_value_id)) { $field_options = new ExtraFieldOption($type); echo $field_options->get_second_select_field_options_by_field($field_id, $option_value_id, true); } break; case 'search_tags': $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : null; $fieldId = isset($_REQUEST['field_id']) ? $_REQUEST['field_id'] : null; $tag = isset($_REQUEST['tag']) ? $_REQUEST['tag'] : null; $extraFieldOption = new ExtraFieldOption($type); $result = []; $tags = Database::getManager()->getRepository('ChamiloCoreBundle:Tag')->createQueryBuilder('t')->where("t.tag LIKE :tag")->andWhere('t.fieldId = :field')->setParameter('field', $fieldId)->setParameter('tag', "{$tag}%")->getQuery()->getResult(); foreach ($tags as $tag) { $result[] = ['caption' => $tag->getTag(), 'value' => $tag->getTag()]; } echo json_encode($result); break; default: exit; break; } exit;
/** * Check if the $fromUser can comment the $toUser skill issue * @param Chamilo\UserBundle\Entity\User $fromUser * @param Chamilo\UserBundle\Entity\User $toUser * @return boolean */ public static function userCanAddFeedbackToUser(User $fromUser, User $toUser) { if (api_is_platform_admin()) { return true; } $entityManager = Database::getManager(); $userRepo = $entityManager->getRepository('ChamiloUserBundle:User'); $fromUserStatus = $fromUser->getStatus(); switch ($fromUserStatus) { case SESSIONADMIN: if (api_get_setting('allow_session_admins_to_manage_all_sessions') === 'true') { if ($toUser->getCreatorId() === $fromUser->getId()) { return true; } } $sessionAdmins = $userRepo->getSessionAdmins($toUser); foreach ($sessionAdmins as $sessionAdmin) { if ($sessionAdmin->getId() !== $fromUser->getId()) { continue; } return true; } break; case STUDENT_BOSS: $studentBosses = $userRepo->getStudentBosses($toUser); foreach ($studentBosses as $studentBoss) { if ($studentBoss->getId() !== $fromUser->getId()) { continue; } return true; } case DRH: return UserManager::is_user_followed_by_drh($toUser->getId(), $fromUser->getId()); } return false; }
switch ($user['relation_type']) { case 1: $status = get_lang('Drh'); $link = Display::url(Display::return_icon('edit.png', get_lang('Edit')), api_get_path(WEB_CODE_PATH) . 'admin/dashboard_add_sessions_to_user.php?user='******'Student'); } $table->setCellContents($row, 1, $status); $table->setCellContents($row, 2, $link); $row++; } $userListToShow .= $table->toHtml(); } /** @var SequenceRepository $repo */ $repo = Database::getManager()->getRepository('ChamiloCoreBundle:SequenceResource'); $requirementAndDependencies = $repo->getRequirementAndDependencies($sessionId, SequenceResource::SESSION_TYPE); $requirements = ''; if (!empty($requirementAndDependencies['requirements'])) { $requirements = Display::page_subheader(get_lang('Requirements')); $requirements .= implode(' + ', array_column($requirementAndDependencies['requirements'], 'admin_link')); } $dependencies = ''; if (!empty($requirementAndDependencies['dependencies'])) { $dependencies = Display::page_subheader(get_lang('Dependencies')); $dependencies .= implode(', ', array_column($requirementAndDependencies['dependencies'], 'admin_link')); } //$tpl = new Template(get_lang('Session')); $tpl = Container::getTwig(); $tpl->addGlobal('session_header', $sessionHeader); $tpl->addGlobal('title', $sessionTitle);
/** * @param int $userId * @return array * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException * @throws \Doctrine\ORM\TransactionRequiredException */ private function getPersonalTemplates($userId = 0) { if (empty($userId)) { $userId = api_get_user_id(); } $entityManager = \Database::getManager(); $templatesRepo = $entityManager->getRepository('ChamiloCoreBundle:Templates'); $user = $entityManager->find('ChamiloUserBundle:User', $userId); $course = $entityManager->find('ChamiloCoreBundle:Course', api_get_course_int_id()); if (!$user || !$course) { return []; } $courseTemplates = $templatesRepo->getCourseTemplates($course, $user); $templateList = []; foreach ($courseTemplates as $templateData) { $template = $templateData[0]; $courseDirectory = $course->getDirectory(); $templateItem = []; $templateItem['title'] = $template->getTitle(); $templateItem['description'] = $template->getDescription(); $templateItem['image'] = api_get_path(WEB_APP_PATH) . 'home/default_platform_document/template_thumb/noimage.gif'; $templateItem['html'] = file_get_contents(api_get_path(SYS_COURSE_PATH) . $courseDirectory . '/document' . $templateData['path']); $image = $template->getImage(); if (!empty($image)) { $templateItem['image'] = api_get_path(WEB_COURSE_PATH) . $courseDirectory . '/upload/template_thumbnails/' . $template->getImage(); } $templateList[] = $templateItem; } return $templateList; }
/** * Connect to the database and returns the entity manager * @param string $dbHostForm DB host * @param string $dbUsernameForm DB username * @param string $dbPassForm DB password * @param string $dbNameForm DB name * * @return EntityManager */ function connectToDatabase($dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm) { $dbParams = array('driver' => 'pdo_mysql', 'host' => $dbHostForm, 'user' => $dbUsernameForm, 'password' => $dbPassForm, 'dbname' => $dbNameForm); $database = new \Database(); $database->connect($dbParams); return $database->getManager(); }
} $teachers = isset($course['course_teachers']) ? $course['course_teachers'] : ''; $title = $course['title']; $category_code = isset($course['category_code']) ? $course['category_code'] : ''; $department_name = $course['department_name']; $department_url = $course['department_url']; $course_language = $course['course_language']; $course['disk_quota'] = $course['disk_quota'] * 1024 * 1024; $disk_quota = $course['disk_quota']; $subscribe = $course['subscribe']; $unsubscribe = isset($course['unsubscribe']) ? $course['unsubscribe'] : ''; $course['course_code'] = $course_code; if (!stristr($department_url, 'http://')) { $department_url = 'http://' . $department_url; } $manager = Database::getManager(); $courseObj = $manager->getRepository('ChamiloCoreBundle:Course')->find($courseId); if ($courseObj) { $url = $manager->getRepository('ChamiloCoreBundle:AccessUrl')->find(api_get_current_access_url_id()); $courseObj->setTitle($title)->setCourseLanguage($course_language)->setCategoryCode($category_code)->setVisualCode($visual_code)->setDepartmentName($department_name)->setDepartmentUrl($department_url)->setDiskQuota(intval($disk_quota))->setVisibility($visibility)->setSubscribe(intval($subscribe))->setUnsubscribe(intval($unsubscribe))->setCurrentUrl($url); $manager->persist($courseObj); $manager->flush(); } // update the extra fields $courseFieldValue = new ExtraFieldValue('course'); $courseFieldValue->saveFieldValues($course); $addTeacherToSessionCourses = isset($course['add_teachers_to_sessions_courses']) && !empty($course['add_teachers_to_sessions_courses']) ? 1 : 0; $sessionCoaches = isset($course['session_coaches']) ? $course['session_coaches'] : ''; // Updating teachers if ($addTeacherToSessionCourses) { if (!empty($sessionCoaches)) {
/** * This function deletes a survey (and also all the question in that survey * * @param int $survey_id id of the survey that has to be deleted * @return true * * @author Patrick Cool <*****@*****.**>, Ghent University * @version January 2007 */ public static function delete_survey($survey_id, $shared = false, $course_id = '') { // Database table definitions if (empty($course_id)) { $course_id = api_get_course_int_id(); } $survey_id = intval($survey_id); if (empty($survey_id)) { return false; } $em = Database::getManager(); $course_info = api_get_course_info_by_id($course_id); $course_id = $course_info['real_id']; $table_survey = Database::get_course_table(TABLE_SURVEY); $table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP); if ($shared) { // Deleting the survey $sharedSurvey = $em->find('ChamiloCoreBundle:SharedSurvey', $survey_id); if ($sharedSurvey) { $em->remove($sharedSurvey); $em->flush(); } } else { $sql = "DELETE FROM {$table_survey}\n WHERE c_id = {$course_id} AND survey_id='" . $survey_id . "'"; Database::query($sql); } // Deleting groups of this survey $sql = "DELETE FROM {$table_survey_question_group}\n WHERE c_id = {$course_id} AND survey_id='" . $survey_id . "'"; Database::query($sql); // Deleting the questions of the survey SurveyManager::delete_all_survey_questions($survey_id, $shared); // Update into item_property (delete) api_item_property_update($course_info, TOOL_SURVEY, $survey_id, 'SurveyDeleted', api_get_user_id()); return true; }
/** * 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; }
/** * Search sessions by the tags in their courses * @param string $termTag Term for search in tags * @param array $limit Limit info * @return array The sessions */ public function browseSessionsByTags($termTag, array $limit) { $em = Database::getManager(); $qb = $em->createQueryBuilder(); $sessions = $qb->select('s')->distinct(true)->from('ChamiloCoreBundle:Session', 's')->innerJoin('ChamiloCoreBundle:SessionRelCourse', 'src', \Doctrine\ORM\Query\Expr\Join::WITH, 's.id = src.session')->innerJoin('ChamiloCoreBundle:ExtraFieldRelTag', 'frt', \Doctrine\ORM\Query\Expr\Join::WITH, 'src.course = frt.itemId')->innerJoin('ChamiloCoreBundle:Tag', 't', \Doctrine\ORM\Query\Expr\Join::WITH, 'frt.tagId = t.id')->innerJoin('ChamiloCoreBundle:ExtraField', 'f', \Doctrine\ORM\Query\Expr\Join::WITH, 'frt.fieldId = f.id')->where($qb->expr()->like('t.tag', ":tag"))->andWhere($qb->expr()->eq('f.extraFieldType', Chamilo\CoreBundle\Entity\ExtraField::COURSE_FIELD_TYPE))->setFirstResult($limit['start'])->setMaxResults($limit['length'])->setParameter('tag', "{$termTag}%")->getQuery()->getResult(); $sessionsToBrowse = []; foreach ($sessions as $session) { if ($session->getNbrCourses() === 0) { continue; } $sessionsToBrowse[] = $session; } return $sessionsToBrowse; }
/** * Display code for one specific course a logged in user is subscribed to. * Shows a link to the course, what's new icons... * * $my_course['d'] - course directory * $my_course['i'] - course title * $my_course['c'] - visual course code * $my_course['k'] - system course code * * @param array Course details * @param integer Session ID * @param string CSS class to apply to course entry * @param boolean Whether the session is supposedly accessible now * (not in the case it has passed and is in invisible/unaccessible mode) * @param bool Whether to show the document quick-loader or not * @return string The HTML to be printed for the course entry * * @version 1.0.3 * @todo refactor into different functions for database calls | logic | display * @todo replace single-character $my_course['d'] indices * @todo move code for what's new icons to a separate function to clear things up * @todo add a parameter user_id so that it is possible to show the * courselist of other users (=generalisation). * This will prevent having to write a new function for this. */ public static function get_logged_user_course_html($course, $session_id = 0, $class = 'courses', $session_accessible = true, $load_dirs = false) { $entityManager = Database::getManager(); $user_id = api_get_user_id(); $course_info = api_get_course_info_by_id($course['real_id']); $status_course = CourseManager::get_user_in_course_status($user_id, $course_info['code']); $course_info['status'] = empty($session_id) ? $status_course : STUDENT; $course_info['id_session'] = $session_id; $objUser = $entityManager->find('ChamiloUserBundle:User', $user_id); $objCourse = $entityManager->find('ChamiloCoreBundle:Course', $course['real_id']); $objSession = $entityManager->find('ChamiloCoreBundle:Session', $session_id); /*$date_start = $sess[$course_info['id_session']]['access_start_date']; $date_end = $sess[$course_info['id_session']]['access_end_date'];*/ $now = date('Y-m-d h:i:s'); // Table definitions $main_user_table = Database::get_main_table(TABLE_MAIN_USER); $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION); $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY); $course_access_settings = CourseManager::get_access_settings($course_info['code']); $course_visibility = $course_access_settings['visibility']; if ($course_visibility == COURSE_VISIBILITY_HIDDEN) { return ''; } $user_in_course_status = CourseManager::get_user_in_course_status(api_get_user_id(), $course_info['code']); $is_coach = api_is_coach($course_info['id_session'], $course_info['real_id']); // Display course entry. // Show a hyperlink to the course, unless the course is closed and user is not course admin. $session_url = ''; $session_title = ''; $params = array(); $params['icon'] = Display::return_icon('blackboard_blue.png', api_htmlentities($course_info['name']), array(), ICON_SIZE_LARGE); // Display the "what's new" icons $notifications = ''; if ($course_visibility != COURSE_VISIBILITY_CLOSED && $course_visibility != COURSE_VISIBILITY_HIDDEN) { $notifications .= Display::show_notification($course_info); } if ($session_accessible) { if ($course_visibility != COURSE_VISIBILITY_CLOSED || $user_in_course_status == COURSEMANAGER) { if (empty($course_info['id_session'])) { $course_info['id_session'] = 0; } $sessionCourseAvailable = false; $sessionCourseStatus = api_get_session_visibility($session_id, $course_info['real_id']); if (in_array($sessionCourseStatus, array(SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_AVAILABLE))) { $sessionCourseAvailable = true; } if ($user_in_course_status == COURSEMANAGER || $sessionCourseAvailable) { $session_url = $course_info['course_public_url'] . '?id_session=' . $course_info['id_session']; $session_title = '<h4><a href="' . $session_url . '">' . $course_info['name'] . '</a>' . $notifications . '</h4>'; } else { $session_title = $course_info['name']; } } else { $session_title = $course_info['name'] . ' ' . Display::tag('span', get_lang('CourseClosed'), array('class' => 'item_closed')); } } else { $session_title = $course_info['name']; } $showCustomIcon = api_get_setting('course.course_images_in_courses_list'); $iconName = basename($course_info['course_image']); if ($showCustomIcon === 'true' && $iconName != 'course.png') { $params['icon'] = Display::img($course_info['course_image'], api_htmlentities($course_info['name']), array()); } $params['link'] = $session_url; $params['title'] = $session_title; $params['right_actions'] = ''; if ($course_visibility != COURSE_VISIBILITY_CLOSED && $course_visibility != COURSE_VISIBILITY_HIDDEN) { if ($load_dirs) { $params['right_actions'] .= '<a id="document_preview_' . $course_info['real_id'] . '_' . $course_info['id_session'] . '" class="document_preview" href="javascript:void(0);">' . Display::return_icon('folder.png', get_lang('Documents'), array('align' => 'absmiddle'), ICON_SIZE_SMALL) . '</a>'; $params['right_actions'] .= Display::div('', array('id' => 'document_result_' . $course_info['real_id'] . '_' . $course_info['id_session'], 'class' => 'document_preview_container')); } } if (api_get_setting('course.display_coursecode_in_courselist') == 'true') { $session_title .= ' (' . $course_info['visual_code'] . ') '; } if (api_get_setting('course.display_teacher_in_courselist') == 'true') { $teacher_list = CourseManager::getTeacherListFromCourseToString($course_info['real_id'], self::USER_SEPARATOR, true); $course_coachs = self::get_coachs_from_course($course_info['id_session'], $course_info['real_id']); if ($course_info['status'] == COURSEMANAGER || $course_info['status'] == STUDENT && empty($course_info['id_session']) || empty($course_info['status'])) { $params['teachers'] = $teacher_list; } if ($course_info['status'] == STUDENT && !empty($course_info['id_session']) || $is_coach && $course_info['status'] != COURSEMANAGER) { $params['coaches'] = $course_coachs; } } $session_title .= isset($course['special_course']) ? ' ' . Display::return_icon('klipper.png', get_lang('CourseAutoRegister')) : ''; $params['title'] = $session_title; $params['extra'] = ''; $html = $params; $session_category_id = null; if (1) { $session = ''; $active = false; if (!empty($course_info['session_name'])) { // Request for the name of the general coach $sql = 'SELECT lastname, firstname,sc.name FROM ' . $tbl_session . ' ts LEFT JOIN ' . $main_user_table . ' tu ON ts.id_coach = tu.user_id INNER JOIN ' . $tbl_session_category . ' sc ON ts.session_category_id = sc.id WHERE ts.id=' . (int) $course_info['id_session'] . ' LIMIT 1'; $rs = Database::query($sql); $sessioncoach = Database::store_result($rs); $sessioncoach = $sessioncoach[0]; $session = array(); $session['title'] = $course_info['session_name']; $session_category_id = CourseManager::get_session_category_id_by_session_id($course_info['id_session']); $session['category'] = $sessioncoach['name']; if ($course_info['access_start_date'] == '0000-00-00') { //$session['dates'] = get_lang('WithoutTimeLimits'); $session['dates'] = ''; if (api_get_setting('session.show_session_coach') === 'true') { $session['coach'] = get_lang('GeneralCoach') . ': ' . api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']); } $active = true; } else { $session['dates'] = ' - ' . get_lang('From') . ' ' . $course_info['access_start_date'] . ' ' . get_lang('To') . ' ' . $course_info['access_end_date']; if (api_get_setting('session.show_session_coach') === 'true') { $session['coach'] = get_lang('GeneralCoach') . ': ' . api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']); } $active = $date_start <= $now && $date_end >= $now; } } $user_course_category = ''; if (isset($course_info['user_course_cat'])) { $user_course_category = $course_info['user_course_cat']; } $output = array($user_course_category, $html, $course_info['id_session'], $session, 'active' => $active, 'session_category_id' => $session_category_id); if (api_get_setting('skill.allow_skills_tool') === 'true') { $skill = $entityManager->getRepository('ChamiloCoreBundle:Skill')->getLastByUser($objUser, $objCourse, $objSession); $output['skill'] = null; if ($skill) { $output['skill']['name'] = $skill->getName(); $output['skill']['icon'] = $skill->getIcon(); } } } else { $output = array($course_info['user_course_cat'], $html); } return $output; }
/** * @param FormValidator $form * @param array $extraData * @param string $form_name * @param bool $admin_permissions * @param int $user_id * @param array $extra * @param int $itemId * * @return array */ public function set_extra_fields_in_form($form, $extraData, $form_name, $admin_permissions = false, $user_id = null, $extra = array(), $itemId = null) { $user_id = intval($user_id); $type = $this->type; // User extra fields if ($type == 'user') { $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC', true, null, true); } $jquery_ready_content = null; if (!empty($extra)) { foreach ($extra as $field_details) { // Getting default value id if is set $defaultValueId = null; if (isset($field_details['options']) && !empty($field_details['options'])) { $valueToFind = null; if (isset($field_details['field_default_value'])) { $valueToFind = $field_details['field_default_value']; } // If a value is found we override the default value if (isset($extraData['extra_' . $field_details['field_variable']])) { $valueToFind = $extraData['extra_' . $field_details['field_variable']]; } foreach ($field_details['options'] as $option) { if ($option['option_value'] == $valueToFind) { $defaultValueId = $option['id']; } } } if (!$admin_permissions) { if ($field_details['field_visible'] == 0) { continue; } } switch ($field_details['field_type']) { case ExtraField::FIELD_TYPE_TEXT: $form->addElement('text', 'extra_' . $field_details['field_variable'], $field_details['field_display_text'], array('class' => 'span4')); $form->applyFilter('extra_' . $field_details['field_variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['field_variable'], 'trim'); if (!$admin_permissions) { if ($field_details['field_visible'] == 0) { $form->freeze('extra_' . $field_details['field_variable']); } } break; case ExtraField::FIELD_TYPE_TEXTAREA: $form->add_html_editor('extra_' . $field_details['field_variable'], $field_details['field_display_text'], false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130')); $form->applyFilter('extra_' . $field_details['field_variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['field_variable'], 'trim'); if (!$admin_permissions) { if ($field_details['field_visible'] == 0) { $form->freeze('extra_' . $field_details['field_variable']); } } break; case ExtraField::FIELD_TYPE_RADIO: $group = array(); if (isset($field_details['options']) && !empty($field_details['options'])) { foreach ($field_details['options'] as $option_details) { $options[$option_details['option_value']] = $option_details['option_display_text']; $group[] = $form->createElement('radio', 'extra_' . $field_details['field_variable'], $option_details['option_value'], $option_details['option_display_text'] . '<br />', $option_details['option_value']); } } $form->addGroup($group, 'extra_' . $field_details['field_variable'], $field_details['field_display_text'], ''); if (!$admin_permissions) { if ($field_details['field_visible'] == 0) { $form->freeze('extra_' . $field_details['field_variable']); } } break; case ExtraField::FIELD_TYPE_CHECKBOX: $group = array(); if (isset($field_details['options']) && !empty($field_details['options'])) { foreach ($field_details['options'] as $option_details) { $options[$option_details['option_value']] = $option_details['option_display_text']; $group[] = $form->createElement('checkbox', 'extra_' . $field_details['field_variable'], $option_details['option_value'], $option_details['option_display_text'] . '<br />', $option_details['option_value']); } } else { // We assume that is a switch on/off with 1 and 0 as values $group[] = $form->createElement('checkbox', 'extra_' . $field_details['field_variable'], null, 'Yes <br />', null); } $form->addGroup($group, 'extra_' . $field_details['field_variable'], $field_details['field_display_text'], ''); if (!$admin_permissions) { if ($field_details['field_visible'] == 0) { $form->freeze('extra_' . $field_details['field_variable']); } } break; case ExtraField::FIELD_TYPE_SELECT: $get_lang_variables = false; if (in_array($field_details['field_variable'], array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) { $get_lang_variables = true; } // Get extra field workflow $userInfo = api_get_user_info(); $addOptions = array(); $optionsExists = Database::getManager()->getRepository('ChamiloCoreBundle:ExtraFieldOptionRelFieldOption')->findOneBy(array('fieldId' => $field_details['id'])); if ($optionsExists) { if (isset($userInfo['status']) && !empty($userInfo['status'])) { $fieldWorkFlow = Database::getManager()->getRepository('ChamiloCoreBundle:ExtraFieldOptionRelFieldOption')->findBy(array('fieldId' => $field_details['id'], 'relatedFieldOptionId' => $defaultValueId, 'roleId' => $userInfo['status'])); foreach ($fieldWorkFlow as $item) { $addOptions[] = $item->getFieldOptionId(); } } } $options = array(); if (empty($defaultValueId)) { $options[''] = get_lang('SelectAnOption'); } $optionList = array(); if (!empty($field_details['options'])) { foreach ($field_details['options'] as $option_details) { $optionList[$option_details['id']] = $option_details; if ($get_lang_variables) { $options[$option_details['option_value']] = get_lang($option_details['option_display_text']); } else { if ($optionsExists) { // Adding always the default value if ($option_details['id'] == $defaultValueId) { $options[$option_details['option_value']] = $option_details['option_display_text']; } else { if (isset($addOptions) && !empty($addOptions)) { // Parsing filters if (in_array($option_details['id'], $addOptions)) { $options[$option_details['option_value']] = $option_details['option_display_text']; } } } } else { // Normal behaviour $options[$option_details['option_value']] = $option_details['option_display_text']; } } } if (isset($optionList[$defaultValueId])) { if (isset($optionList[$defaultValueId]['option_value']) && $optionList[$defaultValueId]['option_value'] == 'aprobada') { if (api_is_question_manager() == false) { $form->freeze(); } } } // Setting priority message if (isset($optionList[$defaultValueId]) && isset($optionList[$defaultValueId]['priority'])) { if (!empty($optionList[$defaultValueId]['priority'])) { $priorityId = $optionList[$defaultValueId]['priority']; $option = new ExtraFieldOption($this->type); $messageType = $option->getPriorityMessageType($priorityId); $form->addElement('label', null, Display::return_message($optionList[$defaultValueId]['priority_message'], $messageType)); } } } if ($get_lang_variables) { $field_details['field_display_text'] = get_lang($field_details['field_display_text']); } // chzn-select doesn't work for sessions?? $form->addElement('select', 'extra_' . $field_details['field_variable'], $field_details['field_display_text'], $options, array('id' => 'extra_' . $field_details['field_variable'])); if ($optionsExists && $field_details['field_loggeable'] && !empty($defaultValueId)) { $form->addElement('textarea', 'extra_' . $field_details['field_variable'] . '_comment', $field_details['field_display_text'] . ' ' . get_lang('Comment')); $em = Database::getManager(); $extraFieldValue = new ExtraFieldValue($this->type); $repo = $em->getRepository($extraFieldValue->entityName); $repoLog = $em->getRepository('Gedmo\\Loggable\\Entity\\LogEntry'); $newEntity = $repo->findOneBy(array($this->handlerEntityId => $itemId, 'fieldId' => $field_details['id'])); // @todo move this in a function inside the class if ($newEntity) { $logs = $repoLog->getLogEntries($newEntity); if (!empty($logs)) { $html = '<b>' . get_lang('LatestChanges') . '</b><br /><br />'; $table = new HTML_Table(array('class' => 'data_table')); $table->setHeaderContents(0, 0, get_lang('Value')); $table->setHeaderContents(0, 1, get_lang('Comment')); $table->setHeaderContents(0, 2, get_lang('ModifyDate')); $table->setHeaderContents(0, 3, get_lang('Username')); $row = 1; foreach ($logs as $log) { $column = 0; $data = $log->getData(); $fieldValue = isset($data['fieldValue']) ? $data['fieldValue'] : null; $comment = isset($data['comment']) ? $data['comment'] : null; $table->setCellContents($row, $column, $fieldValue); $column++; $table->setCellContents($row, $column, $comment); $column++; $table->setCellContents($row, $column, api_get_local_time($log->getLoggedAt()->format('Y-m-d H:i:s'))); $column++; $table->setCellContents($row, $column, $log->getUsername()); $row++; } $form->addElement('label', null, $html . $table->toHtml()); } } } if (!$admin_permissions) { if ($field_details['field_visible'] == 0) { $form->freeze('extra_' . $field_details['field_variable']); } } break; case ExtraField::FIELD_TYPE_SELECT_MULTIPLE: $options = array(); foreach ($field_details['options'] as $option_id => $option_details) { $options[$option_details['option_value']] = $option_details['option_display_text']; } $form->addElement('select', 'extra_' . $field_details['field_variable'], $field_details['field_display_text'], $options, array('multiple' => 'multiple')); if (!$admin_permissions) { if ($field_details['field_visible'] == 0) { $form->freeze('extra_' . $field_details['field_variable']); } } break; case ExtraField::FIELD_TYPE_DATE: $form->addElement('datepickerdate', 'extra_' . $field_details['field_variable'], $field_details['field_display_text'], array('form_name' => $form_name)); $form->_elements[$form->_elementIndex['extra_' . $field_details['field_variable']]]->setLocalOption('minYear', 1900); $defaults['extra_' . $field_details['field_variable']] = date('Y-m-d 12:00:00'); if (!isset($form->_defaultValues['extra_' . $field_details['field_variable']])) { $form->setDefaults($defaults); } if (!$admin_permissions) { if ($field_details['field_visible'] == 0) { $form->freeze('extra_' . $field_details['field_variable']); } } $form->applyFilter('theme', 'trim'); break; case ExtraField::FIELD_TYPE_DATETIME: $form->addElement('datepicker', 'extra_' . $field_details['field_variable'], $field_details['field_display_text'], array('form_name' => $form_name)); $form->_elements[$form->_elementIndex['extra_' . $field_details['field_variable']]]->setLocalOption('minYear', 1900); $defaults['extra_' . $field_details['field_variable']] = date('Y-m-d 12:00:00'); if (!isset($form->_defaultValues['extra_' . $field_details['field_variable']])) { $form->setDefaults($defaults); } if (!$admin_permissions) { if ($field_details['field_visible'] == 0) { $form->freeze('extra_' . $field_details['field_variable']); } } $form->applyFilter('theme', 'trim'); break; case ExtraField::FIELD_TYPE_DOUBLE_SELECT: $first_select_id = 'first_extra_' . $field_details['field_variable']; $url = api_get_path(WEB_AJAX_PATH) . 'extra_field.ajax.php?1=1'; $jquery_ready_content .= ' $("#' . $first_select_id . '").on("change", function() { var id = $(this).val(); if (id) { $.ajax({ url: "' . $url . '&a=get_second_select_options", dataType: "json", data: "type=' . $type . '&field_id=' . $field_details['id'] . '&option_value_id="+id, success: function(data) { $("#second_extra_' . $field_details['field_variable'] . '").empty(); $.each(data, function(index, value) { $("#second_extra_' . $field_details['field_variable'] . '").append($("<option/>", { value: index, text: value })); }); }, }); } else { $("#second_extra_' . $field_details['field_variable'] . '").empty(); } });'; $first_id = null; $second_id = null; if (!empty($extraData)) { $first_id = $extraData['extra_' . $field_details['field_variable']]['extra_' . $field_details['field_variable']]; $second_id = $extraData['extra_' . $field_details['field_variable']]['extra_' . $field_details['field_variable'] . '_second']; } $options = ExtraField::extra_field_double_select_convert_array_to_ordered_array($field_details['options']); $values = array('' => get_lang('Select')); $second_values = array(); if (!empty($options)) { foreach ($options as $option) { foreach ($option as $sub_option) { if ($sub_option['option_value'] == '0') { $values[$sub_option['id']] = $sub_option['option_display_text']; } else { if ($first_id === $sub_option['option_value']) { $second_values[$sub_option['id']] = $sub_option['option_display_text']; } } } } } $group = array(); $group[] = $form->createElement('select', 'extra_' . $field_details['field_variable'], null, $values, array('id' => $first_select_id)); $group[] = $form->createElement('select', 'extra_' . $field_details['field_variable'] . '_second', null, $second_values, array('id' => 'second_extra_' . $field_details['field_variable'])); $form->addGroup($group, 'extra_' . $field_details['field_variable'], $field_details['field_display_text'], ' '); if (!$admin_permissions) { if ($field_details['field_visible'] == 0) { $form->freeze('extra_' . $field_details['field_variable']); } } break; case ExtraField::FIELD_TYPE_DIVIDER: $form->addElement('static', $field_details['field_variable'], '<br /><strong>' . $field_details['field_display_text'] . '</strong>'); break; case ExtraField::FIELD_TYPE_TAG: $field_variable = $field_details['field_variable']; $field_id = $field_details['id']; if ($this->type == 'user') { // The magic should be here $user_tags = UserManager::get_user_tags($user_id, $field_details['id']); $tag_list = ''; if (is_array($user_tags) && count($user_tags) > 0) { foreach ($user_tags as $tag) { $tag_list .= '<option value="' . $tag['tag'] . '" class="selected">' . $tag['tag'] . '</option>'; } } $url = api_get_path(WEB_AJAX_PATH) . 'user_manager.ajax.php?'; } else { $extraFieldValue = new ExtraFieldValue($this->type); $tags = array(); if (!empty($itemId)) { $tags = $extraFieldValue->getAllValuesByItemAndField($itemId, $field_id); } $tag_list = ''; if (is_array($tags) && count($tags) > 0) { $extraFieldOption = new ExtraFieldOption($this->type); foreach ($tags as $tag) { $option = $extraFieldOption->get($tag['field_value']); $tag_list .= '<option value="' . $option['id'] . '" class="selected">' . $option['option_display_text'] . '</option>'; } } $url = api_get_path(WEB_AJAX_PATH) . 'extra_field.ajax.php'; } $form->addElement('hidden', 'extra_' . $field_details['field_variable'] . '__persist__', 1); $multiSelect = '<select id="extra_' . $field_details['field_variable'] . '" name="extra_' . $field_details['field_variable'] . '"> ' . $tag_list . ' </select>'; $form->addElement('label', $field_details['field_display_text'], $multiSelect); $complete_text = get_lang('StartToType'); //if cache is set to true the jquery will be called 1 time $jquery_ready_content .= <<<EOF \$("#extra_{$field_variable}").fcbkcomplete({ json_url: "{$url}?a=search_tags&field_id={$field_id}&type={$this->type}", cache: false, filter_case: true, filter_hide: true, complete_text:"{$complete_text}", firstselected: false, filter_selected: true, newel: true }); EOF; $jquery_ready_content = null; break; case ExtraField::FIELD_TYPE_TIMEZONE: $form->addElement('select', 'extra_' . $field_details['field_variable'], $field_details['field_display_text'], api_get_timezones(), ''); if ($field_details['field_visible'] == 0) { $form->freeze('extra_' . $field_details['field_variable']); } break; case ExtraField::FIELD_TYPE_SOCIAL_PROFILE: // get the social network's favicon $icon_path = UserManager::get_favicon_from_url($extraData['extra_' . $field_details['field_variable']], $field_details['field_default_value']); // special hack for hi5 $leftpad = '1.7'; $top = '0.4'; $domain = parse_url($icon_path, PHP_URL_HOST); if ($domain == 'www.hi5.com' or $domain == 'hi5.com') { $leftpad = '3'; $top = '0'; } // print the input field $form->addElement('text', 'extra_' . $field_details['field_variable'], $field_details['field_display_text'], array('size' => 60, 'style' => 'background-image: url(\'' . $icon_path . '\'); background-repeat: no-repeat; background-position: 0.4em ' . $top . 'em; padding-left: ' . $leftpad . 'em; ')); $form->applyFilter('extra_' . $field_details['field_variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['field_variable'], 'trim'); if ($field_details['field_visible'] == 0) { $form->freeze('extra_' . $field_details['field_variable']); } break; } } } $return = array(); $return['jquery_ready_content'] = $jquery_ready_content; return $return; }
<?php /* For licensing terms, see /license.txt */ require_once '../../../global.inc.php'; if (api_is_anonymous()) { api_not_allowed(true); } $roomId = isset($_GET['room']) ? $_GET['room'] : null; $entityManager = Database::getManager(); $chatVideo = $entityManager->find('ChamiloCoreBundle:ChatVideo', $roomId); if (!$chatVideo) { header('Location: ' . api_get_path(WEB_PATH)); exit; } $friend_html = SocialManager::listMyFriendsBlock($user_id, '', false); $isSender = $chatVideo->getFromUser() === api_get_user_id(); $isReceiver = $chatVideo->getToUser() === api_get_user_id(); if (!$isSender && !$isReceiver) { header('Location: ' . api_get_path(WEB_PATH)); exit; } if ($isSender) { $chatUser = api_get_user_info($chatVideo->getToUser()); } elseif ($isReceiver) { $chatUser = api_get_user_info($chatVideo->getFromUser()); } $idUserLocal = api_get_user_id(); $userLocal = api_get_user_info($idUserLocal, true); $htmlHeadXtra[] = '<script type="text/javascript" src="' . api_get_path(WEB_PATH) . 'web/assets/SimpleWebRTC/latest.js' . '"></script>' . "\n"; $template = new Template(); $template->assign('room_name', $chatVideo->getRoomName());
/** * Create/update/delete methods are available in the UserManager * (based in the Sonata\UserBundle\Entity\UserManager) * * @return Chamilo\UserBundle\Entity\Manager\UserManager */ public static function getManager() { $encoderFactory = self::getEncoderFactory(); $userManager = new Chamilo\UserBundle\Entity\Manager\UserManager($encoderFactory, new \FOS\UserBundle\Util\Canonicalizer(), new \FOS\UserBundle\Util\Canonicalizer(), Database::getManager(), 'Chamilo\\UserBundle\\Entity\\User'); return $userManager; }
/** * Functions to get the data for the mysql diagnostics * @return array of data */ public function get_database_data() { $array = array(); $em = Database::getManager(); $connection = $em->getConnection(); $host = $connection->getHost(); $db = $connection->getDatabase(); $port = $connection->getPort(); $driver = $connection->getDriver()->getName(); $array[] = $this->build_setting(self::STATUS_INFORMATION, '[Database]', 'driver', '', $driver, null, null, get_lang('Driver')); $array[] = $this->build_setting(self::STATUS_INFORMATION, '[Database]', 'host', '', $host, null, null, get_lang('MysqlHostInfo')); $array[] = $this->build_setting(self::STATUS_INFORMATION, '[Database]', 'port', '', $port, null, null, get_lang('Port')); $array[] = $this->build_setting(self::STATUS_INFORMATION, '[Database]', 'Database name', '', $db, null, null, get_lang('Name')); return $array; }
// Setting the tabs $this_section = SECTION_COURSES; $htmlHeadXtra[] = api_get_jqgrid_js(); // Access control api_protect_course_script(true, false, true); // including additional libraries require_once 'hotpotatoes.lib.php'; $_course = api_get_course_info(); // document path $documentPath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . "/document"; $origin = isset($origin) ? $origin : null; $path = isset($_GET['path']) ? Security::remove_XSS($_GET['path']) : null; /* Constants and variables */ $is_allowedToEdit = api_is_allowed_to_edit(null, true) || api_is_drh() || api_is_student_boss(); $is_tutor = api_is_allowed_to_edit(true); $em = Database::getManager(); $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION); $TBL_TRACK_EXERCISES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES); $TBL_TRACK_ATTEMPT_RECORDING = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); $TBL_LP_ITEM_VIEW = Database::get_course_table(TABLE_LP_ITEM_VIEW); $allowCoachFeedbackExercises = api_get_setting('exercise.allow_coach_feedback_exercises') === 'true'; $course_id = api_get_course_int_id(); $exercise_id = isset($_REQUEST['exerciseId']) ? intval($_REQUEST['exerciseId']) : null; $filter_user = isset($_REQUEST['filter_by_user']) ? intval($_REQUEST['filter_by_user']) : null; $locked = api_resource_is_locked_by_gradebook($exercise_id, LINK_EXERCISE); if (empty($exercise_id)) { api_not_allowed(true); } if (!$is_allowedToEdit && !$allowCoachFeedbackExercises) { api_not_allowed(true); }
function display_categories($type = 'simple') { $options = array('decorate' => true, 'rootOpen' => '<ul>', 'rootClose' => '</ul>', 'childOpen' => '<li>', 'childClose' => '</li>', 'nodeDecorator' => function ($row) use($type) { $category_id = $row['iid']; $courseId = $row['cId']; $tmpobj = new Testcategory($category_id); $nb_question = $tmpobj->getCategoryQuestionsNumber(); $nb_question_label = $nb_question == 1 ? $nb_question . ' ' . get_lang('Question') : $nb_question . ' ' . get_lang('Questions'); $nb_question_label = Display::label($nb_question_label, 'info'); $actions = null; if ($courseId == 0 && $type == 'simple') { $actions .= Display::return_icon('edit_na.png', get_lang('Edit'), array(), ICON_SIZE_SMALL); } else { $actions .= '<a href="' . api_get_self() . '?action=editcategory&category_id=' . $category_id . '&type=' . $type . '">' . Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>'; } if ($nb_question > 0 && $courseId == 0 && $type == 'simple') { $actions .= '<a href="javascript:void(0)" onclick="alert(\'' . protectJSDialogQuote(get_lang('CannotDeleteCategory')) . '\')">'; $actions .= Display::return_icon('delete_na.png', get_lang('CannotDeleteCategory'), array(), ICON_SIZE_SMALL); $actions .= '</a>'; } else { $rowname = protectJSDialogQuote($row['title']); $actions .= ' <a href="' . api_get_self() . '?action=deletecategory&category_id=' . $category_id . '&type=' . $type . '"'; $actions .= 'onclick="return confirmDelete(\'' . protectJSDialogQuote(get_lang('DeleteCategoryAreYouSure') . '[' . $rowname) . '] ?\', \'id_cat' . $category_id . '\');">'; $actions .= Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>'; } return $row['title'] . ' ' . $nb_question_label . ' ' . $actions; }); // @todo put this in a function $repo = Database::getManager()->getRepository('ChamiloCoreBundle:CQuizCategory'); $query = null; if ($type == 'global') { $query = Database::getManager()->createQueryBuilder()->select('node')->from('ChamiloCoreBundle:CQuizCategory', 'node')->where('node.cId = 0')->orderBy('node.root, node.lft', 'ASC')->getQuery(); } else { $query = Database::getManager()->createQueryBuilder()->select('node')->from('ChamiloCoreBundle:CQuizCategory', 'node')->where('node.cId = :courseId')->orderBy('node.root, node.lft', 'ASC')->setParameter('courseId', api_get_course_int_id())->getQuery(); } $htmlTree = $repo->buildTree($query->getArrayResult(), $options); /* $htmlTree = $repo->childrenHierarchy( null, //starting from root nodes false, //load all children, not only direct $options );*/ echo $htmlTree; return true; }
/** * Returns a category summary report * * @param int exercise id * @param array prefilled array with the category_id, score, and weight example: array(1 => array('score' => '10', 'total' => 20)); * @param bool $categoryMinusOne shows category - 1 see BT#6540 * @return string */ public static function get_stats_table_by_attempt($exercise_id, $category_list = array(), $categoryMinusOne = false) { if (empty($category_list)) { return null; } $category_name_list = Testcategory::getListOfCategoriesNameForTest($exercise_id, false); $table = new HTML_Table(array('class' => 'data_table')); $table->setHeaderContents(0, 0, get_lang('Categories')); $table->setHeaderContents(0, 1, get_lang('AbsoluteScore')); $table->setHeaderContents(0, 2, get_lang('RelativeScore')); $row = 1; $none_category = array(); if (isset($category_list['none'])) { $none_category = $category_list['none']; unset($category_list['none']); } $total = array(); if (isset($category_list['total'])) { $total = $category_list['total']; unset($category_list['total']); } $em = Database::getManager(); $repo = $em->getRepository('ChamiloCoreBundle:CQuizCategory'); $redefineCategoryList = array(); if (!empty($category_list) && count($category_list) > 1) { $globalCategoryScore = array(); foreach ($category_list as $category_id => $category_item) { $cat = $em->find('ChamiloCoreBundle:CQuizCategory', $category_id); $path = $repo->getPath($cat); $categoryName = $category_name_list[$category_id]; $index = 0; if ($categoryMinusOne) { $index = 1; } if (isset($path[$index])) { $category_id = $path[$index]->getIid(); $categoryName = $path[$index]->getTitle(); } if (!isset($globalCategoryScore[$category_id])) { $globalCategoryScore[$category_id] = array(); $globalCategoryScore[$category_id]['score'] = 0; $globalCategoryScore[$category_id]['total'] = 0; $globalCategoryScore[$category_id]['title'] = ''; } $globalCategoryScore[$category_id]['score'] += $category_item['score']; $globalCategoryScore[$category_id]['total'] += $category_item['total']; $globalCategoryScore[$category_id]['title'] = $categoryName; } foreach ($globalCategoryScore as $category_item) { $table->setCellContents($row, 0, $category_item['title']); $table->setCellContents($row, 1, ExerciseLib::show_score($category_item['score'], $category_item['total'], false)); $table->setCellContents($row, 2, ExerciseLib::show_score($category_item['score'], $category_item['total'], true, false, true)); $class = 'class="row_odd"'; if ($row % 2) { $class = 'class="row_even"'; } $table->setRowAttributes($row, $class, true); $row++; } if (!empty($none_category)) { $table->setCellContents($row, 0, get_lang('None')); $table->setCellContents($row, 1, ExerciseLib::show_score($none_category['score'], $none_category['total'], false)); $table->setCellContents($row, 2, ExerciseLib::show_score($none_category['score'], $none_category['total'], true, false, true)); $row++; } if (!empty($total)) { $table->setCellContents($row, 0, get_lang('Total')); $table->setCellContents($row, 1, ExerciseLib::show_score($total['score'], $total['total'], false)); $table->setCellContents($row, 2, ExerciseLib::show_score($total['score'], $total['total'], true, false, true)); $table->setRowAttributes($row, 'class="row_total"', true); } return $table->toHtml(); } return null; }
/** * @param FormValidator $form * @param array $extraData * @param bool $admin_permissions * @param int $user_id * @param array $extra * @param int $itemId * @param array $exclude variables of extra field to exclude * @return array */ public function set_extra_fields_in_form($form, $extraData, $admin_permissions = false, $extra = array(), $itemId = null, $exclude = []) { $type = $this->type; $jquery_ready_content = null; if (!empty($extra)) { foreach ($extra as $field_details) { // Getting default value id if is set $defaultValueId = null; if (isset($field_details['options']) && !empty($field_details['options'])) { $valueToFind = null; if (isset($field_details['field_default_value'])) { $valueToFind = $field_details['field_default_value']; } // If a value is found we override the default value if (isset($extraData['extra_' . $field_details['variable']])) { $valueToFind = $extraData['extra_' . $field_details['variable']]; } foreach ($field_details['options'] as $option) { if ($option['option_value'] == $valueToFind) { $defaultValueId = $option['id']; } } } if (!$admin_permissions) { if ($field_details['visible'] == 0) { continue; } if (in_array($field_details['variable'], $exclude)) { continue; } } switch ($field_details['field_type']) { case ExtraField::FIELD_TYPE_TEXT: $form->addElement('text', 'extra_' . $field_details['variable'], $field_details['display_text'], array()); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_TEXTAREA: $form->addHtmlEditor('extra_' . $field_details['variable'], $field_details['display_text'], false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130')); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_RADIO: $group = array(); if (isset($field_details['options']) && !empty($field_details['options'])) { foreach ($field_details['options'] as $option_details) { $options[$option_details['option_value']] = $option_details['display_text']; $group[] = $form->createElement('radio', 'extra_' . $field_details['variable'], $option_details['option_value'], $option_details['display_text'] . '<br />', $option_details['option_value']); } } $form->addGroup($group, 'extra_' . $field_details['variable'], $field_details['display_text'], ''); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_CHECKBOX: $group = array(); if (isset($field_details['options']) && !empty($field_details['options'])) { foreach ($field_details['options'] as $option_details) { $options[$option_details['option_value']] = $option_details['display_text']; $group[] = $form->createElement('checkbox', 'extra_' . $field_details['variable'], $option_details['option_value'], $option_details['display_text'] . '<br />', $option_details['option_value']); } } else { $fieldVariable = "extra_{$field_details['variable']}"; $checkboxAttributes = array(); if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) { $checkboxAttributes['checked'] = true; } // We assume that is a switch on/off with 1 and 0 as values $group[] = $form->createElement('checkbox', 'extra_' . $field_details['variable'], null, get_lang('Yes'), $checkboxAttributes); } $form->addGroup($group, 'extra_' . $field_details['variable'], $field_details['display_text'], ''); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_SELECT: $get_lang_variables = false; if (in_array($field_details['variable'], array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) { $get_lang_variables = true; } // Get extra field workflow $userInfo = api_get_user_info(); $addOptions = array(); $optionsExists = false; global $app; // Check if exist $app['orm.em'] object if (isset($app['orm.em']) && is_object($app['orm.em'])) { $optionsExists = $app['orm.em']->getRepository('ChamiloLMS\\Entity\\ExtraFieldOptionRelFieldOption')->findOneBy(array('fieldId' => $field_details['id'])); } if ($optionsExists) { if (isset($userInfo['status']) && !empty($userInfo['status'])) { $fieldWorkFlow = $app['orm.em']->getRepository('ChamiloLMS\\Entity\\ExtraFieldOptionRelFieldOption')->findBy(array('fieldId' => $field_details['id'], 'relatedFieldOptionId' => $defaultValueId, 'roleId' => $userInfo['status'])); foreach ($fieldWorkFlow as $item) { $addOptions[] = $item->getFieldOptionId(); } } } $options = array(); if (empty($defaultValueId)) { $options[''] = get_lang('SelectAnOption'); } $optionList = array(); if (!empty($field_details['options'])) { foreach ($field_details['options'] as $option_details) { $optionList[$option_details['id']] = $option_details; if ($get_lang_variables) { $options[$option_details['option_value']] = get_lang($option_details['display_text']); } else { if ($optionsExists) { // Adding always the default value if ($option_details['id'] == $defaultValueId) { $options[$option_details['option_value']] = $option_details['display_text']; } else { if (isset($addOptions) && !empty($addOptions)) { // Parsing filters if (in_array($option_details['id'], $addOptions)) { $options[$option_details['option_value']] = $option_details['display_text']; } } } } else { // Normal behaviour $options[$option_details['option_value']] = $option_details['display_text']; } } } if (isset($optionList[$defaultValueId])) { if (isset($optionList[$defaultValueId]['option_value']) && $optionList[$defaultValueId]['option_value'] == 'aprobada') { // @todo function don't exists api_is_question_manager /*if (api_is_question_manager() == false) { $form->freeze(); }*/ } } // Setting priority message if (isset($optionList[$defaultValueId]) && isset($optionList[$defaultValueId]['priority'])) { if (!empty($optionList[$defaultValueId]['priority'])) { $priorityId = $optionList[$defaultValueId]['priority']; $option = new ExtraFieldOption($this->type); $messageType = $option->getPriorityMessageType($priorityId); $form->addElement('label', null, Display::return_message($optionList[$defaultValueId]['priority_message'], $messageType)); } } } if ($get_lang_variables) { $field_details['display_text'] = get_lang($field_details['display_text']); } // chzn-select doesn't work for sessions?? $form->addElement('select', 'extra_' . $field_details['variable'], $field_details['display_text'], $options, array('id' => 'extra_' . $field_details['variable'])); /* Enable this when field_loggeable is introduced as a table field (2.0) if ($optionsExists && $field_details['field_loggeable'] && !empty($defaultValueId)) { $form->addElement( 'textarea', 'extra_' . $field_details['variable'] . '_comment', $field_details['display_text'] . ' ' . get_lang('Comment') ); $extraFieldValue = new ExtraFieldValue($this->type); $repo = $app['orm.em']->getRepository($extraFieldValue->entityName); $repoLog = $app['orm.em']->getRepository('Gedmo\Loggable\Entity\LogEntry'); $newEntity = $repo->findOneBy( array( $this->handlerEntityId => $itemId, 'fieldId' => $field_details['id'] ) ); // @todo move this in a function inside the class if ($newEntity) { $logs = $repoLog->getLogEntries($newEntity); if (!empty($logs)) { $html = '<b>' . get_lang('LatestChanges') . '</b><br /><br />'; $table = new HTML_Table(array('class' => 'data_table')); $table->setHeaderContents(0, 0, get_lang('Value')); $table->setHeaderContents(0, 1, get_lang('Comment')); $table->setHeaderContents(0, 2, get_lang('ModifyDate')); $table->setHeaderContents(0, 3, get_lang('Username')); $row = 1; foreach ($logs as $log) { $column = 0; $data = $log->getData(); $fieldValue = isset($data['fieldValue']) ? $data['fieldValue'] : null; $comment = isset($data['comment']) ? $data['comment'] : null; $table->setCellContents($row, $column, $fieldValue); $column++; $table->setCellContents($row, $column, $comment); $column++; $table->setCellContents($row, $column, api_get_local_time($log->getLoggedAt()->format('Y-m-d H:i:s'))); $column++; $table->setCellContents($row, $column, $log->getUsername()); $row++; } $form->addElement('label', null, $html.$table->toHtml()); } } } */ if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_SELECT_MULTIPLE: $options = array(); foreach ($field_details['options'] as $option_id => $option_details) { $options[$option_details['option_value']] = $option_details['display_text']; } $form->addElement('select', 'extra_' . $field_details['variable'], $field_details['display_text'], $options, array('multiple' => 'multiple')); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_DATE: $form->addDatePicker('extra_' . $field_details['variable'], $field_details['display_text']); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } $form->applyFilter('theme', 'trim'); break; case ExtraField::FIELD_TYPE_DATETIME: $form->addDateTimePicker('extra_' . $field_details['variable'], $field_details['display_text']); $defaults['extra_' . $field_details['variable']] = api_get_local_time(); if (!isset($form->_defaultValues['extra_' . $field_details['variable']])) { $form->setDefaults($defaults); } if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } $form->applyFilter('theme', 'trim'); break; case ExtraField::FIELD_TYPE_DOUBLE_SELECT: $first_select_id = 'first_extra_' . $field_details['variable']; $url = api_get_path(WEB_AJAX_PATH) . 'extra_field.ajax.php?1=1'; $jquery_ready_content .= ' $("#' . $first_select_id . '").on("change", function() { var id = $(this).val(); if (id) { $.ajax({ url: "' . $url . '&a=get_second_select_options", dataType: "json", data: "type=' . $type . '&field_id=' . $field_details['id'] . '&option_value_id="+id, success: function(data) { $("#second_extra_' . $field_details['variable'] . '").empty(); $.each(data, function(index, value) { $("#second_extra_' . $field_details['variable'] . '").append($("<option/>", { value: index, text: value })); }); }, }); } else { $("#second_extra_' . $field_details['variable'] . '").empty(); } });'; $first_id = null; $second_id = null; if (!empty($extraData)) { $first_id = $extraData['extra_' . $field_details['variable']]['extra_' . $field_details['variable']]; $second_id = $extraData['extra_' . $field_details['variable']]['extra_' . $field_details['variable'] . '_second']; } $options = ExtraField::extra_field_double_select_convert_array_to_ordered_array($field_details['options']); $values = array('' => get_lang('Select')); $second_values = array(); if (!empty($options)) { foreach ($options as $option) { foreach ($option as $sub_option) { if ($sub_option['option_value'] == '0') { $values[$sub_option['id']] = $sub_option['display_text']; } else { if ($first_id === $sub_option['option_value']) { $second_values[$sub_option['id']] = $sub_option['display_text']; } } } } } $group = array(); $group[] = $form->createElement('select', 'extra_' . $field_details['variable'], null, $values, array('id' => $first_select_id)); $group[] = $form->createElement('select', 'extra_' . $field_details['variable'] . '_second', null, $second_values, array('id' => 'second_extra_' . $field_details['variable'])); $form->addGroup($group, 'extra_' . $field_details['variable'], $field_details['display_text'], ' '); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_DIVIDER: $form->addElement('static', $field_details['variable'], '<br /><strong>' . $field_details['display_text'] . '</strong>'); break; case ExtraField::FIELD_TYPE_TAG: $variable = $field_details['variable']; $field_id = $field_details['id']; //Added for correctly translate the extra_field $get_lang_variables = false; if (in_array($variable, ['tags'])) { $get_lang_variables = true; } if ($get_lang_variables) { $field_details['display_text'] = get_lang($field_details['display_text']); } $tagsSelect = $form->addSelect("extra_{$field_details['variable']}", $field_details['display_text']); $tagsSelect->setAttribute('class', null); $tagsSelect->setAttribute('id', "extra_{$field_details['variable']}"); $tagsSelect->setMultiple(true); if ($this->type == 'user') { /* //the magic should be here $user_tags = UserManager::get_user_tags($user_id, $field_details[0]); $tag_list = ''; if (is_array($user_tags) && count($user_tags) > 0) { foreach ($user_tags as $tag) { $tag_list .= '<option value="'.$tag['tag'].'" class="selected">'.$tag['tag'].'</option>'; } } $multi_select = '<select id="extra_'.$field_details[1].'" name="extra_'.$field_details[1].'"> '.$tag_list.' </select>'; $form->addElement('label', $field_details[3], $multi_select); $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php'; $complete_text = get_lang('StartToType'); //if cache is set to true the jquery will be called 1 time $jquery_ready_content = <<<EOF $("#extra_$field_details[1]").fcbkcomplete({ json_url: "$url?a=search_tags&field_id=$field_details[0]", cache: false, filter_case: true, filter_hide: true, complete_text:"$complete_text", firstselected: true, //onremove: "testme", //onselect: "testme", filter_selected: true, newel: true }); EOF; break;*/ // The magic should be here $user_tags = UserManager::get_user_tags($itemId, $field_details['id']); if (is_array($user_tags) && count($user_tags) > 0) { foreach ($user_tags as $tag) { $tagsSelect->addOption($tag['tag'], $tag['tag'], ['selected' => 'selected', 'class' => 'selected']); } } $url = api_get_path(WEB_AJAX_PATH) . 'user_manager.ajax.php'; } else { $em = Database::getManager(); $fieldTags = $em->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')->findBy(['fieldId' => $field_id, 'itemId' => $itemId]); foreach ($fieldTags as $fieldTag) { $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId()); if (empty($tag)) { continue; } $tagsSelect->addOption($tag->getTag(), $tag->getTag(), ['selected' => 'selected', 'class' => 'selected']); } $url = api_get_path(WEB_AJAX_PATH) . 'extra_field.ajax.php'; } $complete_text = get_lang('StartToType'); //if cache is set to true the jquery will be called 1 time $jquery_ready_content .= <<<EOF \$("#extra_{$variable}").fcbkcomplete({ json_url: "{$url}?a=search_tags&field_id={$field_id}&type={$this->type}", cache: false, filter_case: true, filter_hide: true, complete_text:"{$complete_text}", firstselected: false, filter_selected: true, newel: true }); EOF; break; case ExtraField::FIELD_TYPE_TIMEZONE: $form->addElement('select', 'extra_' . $field_details['variable'], $field_details['display_text'], api_get_timezones(), ''); if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } break; case ExtraField::FIELD_TYPE_SOCIAL_PROFILE: // get the social network's favicon $extra_data_variable = isset($extraData['extra_' . $field_details['variable']]) ? $extraData['extra_' . $field_details['variable']] : null; $field_default_value = isset($field_details['field_default_value']) ? $field_details['field_default_value'] : null; $icon_path = UserManager::get_favicon_from_url($extra_data_variable, $field_default_value); // special hack for hi5 $leftpad = '1.7'; $top = '0.4'; $domain = parse_url($icon_path, PHP_URL_HOST); if ($domain == 'www.hi5.com' or $domain == 'hi5.com') { $leftpad = '3'; $top = '0'; } // print the input field $form->addElement('text', 'extra_' . $field_details['variable'], $field_details['display_text'], array('size' => 60, 'style' => 'background-image: url(\'' . $icon_path . '\'); background-repeat: no-repeat; background-position: 0.4em ' . $top . 'em; padding-left: ' . $leftpad . 'em; ')); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } break; case ExtraField::FIELD_TYPE_MOBILE_PHONE_NUMBER: $form->addElement('text', 'extra_' . $field_details[1], $field_details[3] . " (" . get_lang('CountryDialCode') . ")", array('size' => 40, 'placeholder' => '(xx)xxxxxxxxx')); $form->applyFilter('extra_' . $field_details[1], 'stripslashes'); $form->applyFilter('extra_' . $field_details[1], 'trim'); $form->applyFilter('extra_' . $field_details[1], 'mobile_phone_number_filter'); $form->addRule('extra_' . $field_details[1], get_lang('MobilePhoneNumberWrong'), 'mobile_phone_number'); if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } break; case ExtraField::FIELD_TYPE_INTEGER: $form->addElement('number', 'extra_' . $field_details['variable'], $field_details['display_text'], array('class' => 'span1', 'step' => 1)); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); $form->applyFilter('extra_' . $field_details['variable'], 'intval'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_FILE_IMAGE: $fieldVariable = "extra_{$field_details['variable']}"; $fieldTexts = array($field_details['display_text']); if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) { if (file_exists(api_get_path(SYS_UPLOAD_PATH) . $extraData[$fieldVariable])) { $fieldTexts[] = Display::img(api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable], $field_details['display_text'], array('width' => '300')); } } $form->addElement('file', $fieldVariable, $fieldTexts, array('accept' => 'image/*')); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); $allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif'); $form->addRule('extra_' . $field_details['variable'], get_lang('OnlyImagesAllowed') . ' (' . implode(',', $allowed_picture_types) . ')', 'filetype', $allowed_picture_types); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_FLOAT: $form->addElement('number', 'extra_' . $field_details['variable'], $field_details['display_text'], array('class' => 'span1', 'step' => '0.01')); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); $form->applyFilter('extra_' . $field_details['variable'], 'floatval'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_FILE: $fieldVariable = "extra_{$field_details['variable']}"; $fieldTexts = array($field_details['display_text']); if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) { if (file_exists(api_get_path(SYS_UPLOAD_PATH) . $extraData[$fieldVariable])) { $fieldTexts[] = Display::url(api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable], api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable], array('title' => $field_details['display_text'], 'target' => '_blank')); } } $form->addElement('file', $fieldVariable, $fieldTexts, array()); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_VIDEO_URL: //Added for correctly translate the extra_field $get_lang_variables = false; if (in_array($field_details['variable'], ['video_url'])) { $get_lang_variables = true; } if ($get_lang_variables) { $field_details['display_text'] = get_lang($field_details['display_text']); } $form->addUrl("extra_{$field_details['variable']}", $field_details['display_text'], false, ['placeholder' => 'https://']); break; case ExtraField::FIELD_TYPE_LETTERS_ONLY: $form->addTextLettersOnly("extra_{$field_details['variable']}", $field_details['display_text']); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_ALPHANUMERIC: $form->addTextAlphanumeric("extra_{$field_details['variable']}", $field_details['display_text']); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_LETTERS_SPACE: $form->addTextLettersAndSpaces("extra_{$field_details['variable']}", $field_details['display_text']); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_ALPHANUMERIC_SPACE: $form->addTextAlphanumericAndSpaces("extra_{$field_details['variable']}", $field_details['display_text']); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; } } } $return = array(); $return['jquery_ready_content'] = $jquery_ready_content; return $return; }