/** * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully) * Sender name and email can be specified, if not specified * name and email of the platform admin are used * * @author Bert Vanderkimpen ICT&O UGent * @author Yannick Warnier <*****@*****.**> * * @param string name of recipient * @param string email of recipient * @param string email subject * @param string email body * @param string sender name * @param string sender e-mail * @param array extra headers in form $headers = array($name => $value) to allow parsing * @param array data file (path and filename) * @param array data to attach a file (optional) * @param bool True for attaching a embedded file inside content html (optional) * @return returns true if mail was sent * @see class.phpmailer.php */ function api_mail_html($recipient_name, $recipient_email, $subject, $message, $senderName = '', $senderEmail = '', $extra_headers = array(), $data_file = array(), $embedded_image = false, $additionalParameters = array()) { // Default values $notification = new Notification(); $defaultEmail = $notification->getDefaultPlatformSenderEmail(); $defaultName = $notification->getDefaultPlatformSenderName(); // If the parameter is set don't use the admin. $senderName = !empty($senderName) ? $senderName : $defaultName; $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultEmail; $link = isset($additionalParameters['link']) ? $additionalParameters['link'] : ''; $swiftMessage = \Swift_Message::newInstance()->setSubject($subject)->setFrom($senderEmail, $senderName)->setTo($recipient_email, $recipient_name)->setBody(Container::getTemplating()->render('ChamiloCoreBundle:default/mail:mail.html.twig', array('content' => $message, 'link' => $link)), 'text/html'); if (!empty($additionalParameters)) { $plugin = new AppPlugin(); $smsPlugin = $plugin->getSMSPluginLibrary(); if ($smsPlugin) { $smsPlugin->send($additionalParameters); } } Container::getMailer()->send($swiftMessage); return 1; global $platform_email; $mail = new PHPMailer(); $mail->Mailer = $platform_email['SMTP_MAILER']; $mail->Host = $platform_email['SMTP_HOST']; $mail->Port = $platform_email['SMTP_PORT']; $mail->CharSet = $platform_email['SMTP_CHARSET']; // Stay far below SMTP protocol 980 chars limit. $mail->WordWrap = 200; if ($platform_email['SMTP_AUTH']) { $mail->SMTPAuth = 1; $mail->Username = $platform_email['SMTP_USER']; $mail->Password = $platform_email['SMTP_PASS']; } // 5 = low, 1 = high $mail->Priority = 3; $mail->SMTPKeepAlive = true; // Default values $notification = new Notification(); $defaultEmail = $notification->getDefaultPlatformSenderEmail(); $defaultName = $notification->getDefaultPlatformSenderName(); // Error to admin. $mail->AddCustomHeader('Errors-To: ' . $defaultEmail); // If the parameter is set don't use the admin. $senderName = !empty($senderName) ? $senderName : $defaultName; $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultEmail; // Reply to first if (isset($extra_headers['reply_to'])) { $mail->AddReplyTo($extra_headers['reply_to']['mail'], $extra_headers['reply_to']['name']); $mail->Sender = $extra_headers['reply_to']['mail']; unset($extra_headers['reply_to']); } //If the SMTP configuration only accept one sender if ($platform_email['SMTP_UNIQUE_SENDER']) { $senderName = $platform_email['SMTP_FROM_NAME']; $senderEmail = $platform_email['SMTP_FROM_EMAIL']; } $mail->SetFrom($senderEmail, $senderName); $mail->Subject = $subject; $mail->AltBody = strip_tags(str_replace('<br />', "\n", api_html_entity_decode($message))); // Send embedded image. if ($embedded_image) { // Get all images html inside content. preg_match_all("/<img\\s+.*?src=[\"\\']?([^\"\\' >]*)[\"\\']?[^>]*>/i", $message, $m); // Prepare new tag images. $new_images_html = array(); $i = 1; if (!empty($m[1])) { foreach ($m[1] as $image_path) { $real_path = realpath($image_path); $filename = basename($image_path); $image_cid = $filename . '_' . $i; $encoding = 'base64'; $image_type = mime_content_type($real_path); $mail->AddEmbeddedImage($real_path, $image_cid, $filename, $encoding, $image_type); $new_images_html[] = '<img src="cid:' . $image_cid . '" />'; $i++; } } // Replace origin image for new embedded image html. $x = 0; if (!empty($m[0])) { foreach ($m[0] as $orig_img) { $message = str_replace($orig_img, $new_images_html[$x], $message); $x++; } } } $message = str_replace(array("\n\r", "\n", "\r"), '<br />', $message); $mailView = new Template(null, false, false, false, false, false, false); $mailView->assign('content', $message); $link = $additionalParameters['link']; $mailView->assign('link', $link); $layout = $mailView->get_template('mail/mail.tpl'); $mail->Body = $mailView->fetch($layout); // Attachment ... if (!empty($data_file)) { $mail->AddAttachment($data_file['path'], $data_file['filename']); } // Only valid addresses are accepted. if (is_array($recipient_email)) { foreach ($recipient_email as $dest) { if (api_valid_email($dest)) { $mail->AddAddress($dest, $recipient_name); } } } else { if (api_valid_email($recipient_email)) { $mail->AddAddress($recipient_email, $recipient_name); } else { return 0; } } if (is_array($extra_headers) && count($extra_headers) > 0) { foreach ($extra_headers as $key => $value) { switch (strtolower($key)) { case 'encoding': case 'content-transfer-encoding': $mail->Encoding = $value; break; case 'charset': $mail->Charset = $value; break; case 'contenttype': case 'content-type': $mail->ContentType = $value; break; default: $mail->AddCustomHeader($key . ':' . $value); break; } } } else { if (!empty($extra_headers)) { $mail->AddCustomHeader($extra_headers); } } // WordWrap the html body (phpMailer only fixes AltBody) FS#2988 $mail->Body = $mail->WrapText($mail->Body, $mail->WordWrap); // Send the mail message. if (!$mail->Send()) { error_log('ERROR: mail not sent to ' . $recipient_name . ' (' . $recipient_email . ') because of ' . $mail->ErrorInfo . '<br />'); return 0; } if (!empty($additionalParameters)) { $plugin = new AppPlugin(); $smsPlugin = $plugin->getSMSPluginLibrary(); if ($smsPlugin) { $smsPlugin->send($additionalParameters); } } // Clear all the addresses. $mail->ClearAddresses(); return 1; }
/** * Show the Session Catalogue with filtered session by a query term * @param array $limit */ public function sessionListBySearch(array $limit) { $q = isset($_REQUEST['q']) ? Security::remove_XSS($_REQUEST['q']) : null; $hiddenLinks = isset($_GET['hidden_links']) ? intval($_GET['hidden_links']) == 1 : false; $courseUrl = CourseCategoryManager::getCourseCategoryUrl(1, $limit['length'], null, 0, 'subscribe'); $searchDate = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d'); $sessions = $this->model->browseSessionsBySearch($q, $limit); $sessionsBlocks = $this->getFormatedSessionsBlock($sessions); echo Container::getTemplating()->render('@temaplte_style/auth/session_catalog.html.twig', ['show_courses' => CoursesAndSessionsCatalog::showCourses(), 'show_sessions' => CoursesAndSessionsCatalog::showSessions(), 'show_tutor' => api_get_setting('session.show_session_coach') === 'true' ? true : false, 'course_url' => $courseUrl, 'already_subscribed_label' => $this->getAlreadyRegisteredInSessionLabel(), 'hidden_links' => $hiddenLinks, 'search_token' => Security::get_token(), 'search_date' => Security::remove_XSS($searchDate), 'search_tag' => Security::remove_XSS($q), 'sessions' => $sessionsBlocks]); }
$objSkill = new Skill(); $skills = $objSkill->get($skillId); $unbakedBadge = api_get_path(SYS_UPLOAD_PATH) . "badges/" . $skills['icon']; $unbakedBadge = file_get_contents($unbakedBadge); $badgeInfoError = false; $personalBadge = ""; $png = new PNGImageBaker($unbakedBadge); if ($png->checkChunks("tEXt", "openbadges")) { $bakedInfo = $png->addChunk("tEXt", "openbadges", $assertionUrl); $bakedBadge = UserManager::getUserPathById($userId, "system"); $bakedBadge = $bakedBadge . 'badges'; if (!file_exists($bakedBadge)) { mkdir($bakedBadge, api_get_permissions_for_new_directories(), true); } $skillRelUserId = $userSkills[0]->getId(); if (!file_exists($bakedBadge . "/badge_" . $skillRelUserId)) { file_put_contents($bakedBadge . "/badge_" . $skillRelUserId . ".png", $bakedInfo); } //Process to validate a baked badge $badgeContent = file_get_contents($bakedBadge . "/badge_" . $skillRelUserId . ".png"); $verifyBakedBadge = $png->extractBadgeInfo($badgeContent); if (!is_array($verifyBakedBadge)) { $badgeInfoError = true; } if (!$badgeInfoError) { $personalBadge = UserManager::getUserPathById($userId, "web"); $personalBadge = $personalBadge . "badges/badge_" . $skillRelUserId . ".png"; } } echo Container::getTemplating()->render('@template_style/skill/issued.html.twig', ['assertions' => $badgeAssertions, 'skill_info' => $skillInfo, 'user_info' => $userInfo, 'allow_export' => $allowExport, 'badge_error' => $badgeInfoError, 'personal_badge' => $personalBadge]); //$template->assign('header', get_lang('IssuedBadgeInformation'));
} $courses_controller->sessionsList($action, $nameTools, $limit); break; case 'subscribe_to_session': if (!$user_can_view_page) { api_not_allowed(true); } $userId = api_get_user_id(); $confirmed = isset($_GET['confirm']); $sessionId = intval($_GET['session_id']); if (empty($userId)) { api_not_allowed(); exit; } if (!$confirmed) { echo Container::getTemplating()->render('@template_style/auth/confirm_session_subscription.html.twig', ['session_id' => $sessionId]); exit; } $registrationAllowed = api_get_setting('session.catalog_allow_session_auto_subscription'); if ($registrationAllowed === 'true') { $entityManager = Database::getManager(); $repository = $entityManager->getRepository('ChamiloCoreBundle:SequenceResource'); $sequences = $repository->getRequirements($sessionId, SequenceResource::SESSION_TYPE); if (count($sequences) > 0) { $requirementsData = SequenceResourceManager::checkRequirementsForUser($sequences, SequenceResource::SESSION_TYPE, $userId); $continueWithSubscription = SequenceResourceManager::checkSequenceAreCompleted($requirementsData); if (!$continueWithSubscription) { header('Location: ' . api_get_path(WEB_CODE_PATH) . 'auth/courses.php'); exit; } }
/** * Subscribes students to the given session and optionally (default) unsubscribes previous users * * @author Carlos Vargas from existing code * @author Julio Montoya. Cleaning code. * @param int $id_session * @param array $user_list * @param int $session_visibility * @param bool $empty_users * @return bool */ public static function suscribe_users_to_session($id_session, $user_list, $session_visibility = SESSION_VISIBLE_READ_ONLY, $empty_users = true) { if ($id_session != strval(intval($id_session))) { return false; } foreach ($user_list as $intUser) { if ($intUser != strval(intval($intUser))) { return false; } } $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE); $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER); $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION); $entityManager = Database::getManager(); $session = $entityManager->find('ChamiloCoreBundle:Session', $id_session); // from function parameter if (empty($session_visibility)) { $session_visibility = $session->getVisibility(); //default status loaded if empty if (empty($session_visibility)) { $session_visibility = SESSION_VISIBLE_READ_ONLY; } // by default readonly 1 } else { if (!in_array($session_visibility, array(SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_INVISIBLE))) { $session_visibility = SESSION_VISIBLE_READ_ONLY; } } $sql = "SELECT user_id FROM {$tbl_session_rel_course_rel_user}\n WHERE session_id = {$id_session} AND status = 0"; $result = Database::query($sql); $existingUsers = array(); while ($row = Database::fetch_array($result)) { $existingUsers[] = $row['user_id']; } $sql = "SELECT c_id FROM {$tbl_session_rel_course}\n WHERE session_id = {$id_session}"; $result = Database::query($sql); $course_list = array(); while ($row = Database::fetch_array($result)) { $course_list[] = $row['c_id']; } if ($session->getSendSubscriptionNotification() && is_array($user_list)) { // Sending emails only foreach ($user_list as $user_id) { if (in_array($user_id, $existingUsers)) { continue; } $subject = Container::getTemplating()->render('@template_style/mail/subject_subscription_to_session_confirmation.html.twig'); $user_info = api_get_user_info($user_id); $content = Container::getTemplating()->render('@template_style/mail/content_subscription_to_session_confirmation.html.twig', ['complete_name' => stripslashes($user_info['complete_name']), 'session_name' => $session->getName(), 'session_coach' => $session->getGeneralCoach()->getCompleteName()]); api_mail_html($user_info['complete_name'], $user_info['mail'], $subject, $content, api_get_person_name(api_get_setting('admin.administrator_name'), api_get_setting('admin.administrator_surname')), api_get_setting('admin.administrator_email')); } } foreach ($course_list as $courseId) { // for each course in the session $nbr_users = 0; $courseId = intval($courseId); $sql = "SELECT DISTINCT user_id\n FROM {$tbl_session_rel_course_rel_user}\n WHERE\n session_id = {$id_session} AND\n c_id = {$courseId} AND\n status = 0\n "; $result = Database::query($sql); $existingUsers = array(); while ($row = Database::fetch_array($result)) { $existingUsers[] = $row['user_id']; } // Delete existing users if ($empty_users) { foreach ($existingUsers as $existing_user) { if (!in_array($existing_user, $user_list)) { $sql = "DELETE FROM {$tbl_session_rel_course_rel_user}\n WHERE\n session_id = {$id_session} AND\n c_id = {$courseId} AND\n user_id = {$existing_user} AND\n status = 0 "; $result = Database::query($sql); Event::addEvent(LOG_SESSION_DELETE_USER_COURSE, LOG_USER_ID, $existing_user, api_get_utc_datetime(), api_get_user_id(), $courseId, $id_session); if (Database::affected_rows($result)) { $nbr_users--; } } } } // Replace with this new function // insert new users into session_rel_course_rel_user and ignore if they already exist foreach ($user_list as $enreg_user) { if (!in_array($enreg_user, $existingUsers)) { $enreg_user = Database::escape_string($enreg_user); $sql = "INSERT IGNORE INTO {$tbl_session_rel_course_rel_user} (session_id, c_id, user_id, visibility, status)\n VALUES({$id_session}, {$courseId}, {$enreg_user}, {$session_visibility}, 0)"; $result = Database::query($sql); Event::addEvent(LOG_SESSION_ADD_USER_COURSE, LOG_USER_ID, $enreg_user, api_get_utc_datetime(), api_get_user_id(), $courseId, $id_session); if (Database::affected_rows($result)) { $nbr_users++; } } } // Count users in this session-course relation $sql = "SELECT COUNT(user_id) as nbUsers\n FROM {$tbl_session_rel_course_rel_user}\n WHERE session_id = {$id_session} AND c_id = {$courseId} AND status<>2"; $rs = Database::query($sql); list($nbr_users) = Database::fetch_array($rs); // update the session-course relation to add the users total $sql = "UPDATE {$tbl_session_rel_course} SET nbr_users = {$nbr_users}\n WHERE session_id = {$id_session} AND c_id = {$courseId}"; Database::query($sql); } // Delete users from the session if ($empty_users === true) { $sql = "DELETE FROM {$tbl_session_rel_user}\n WHERE session_id = {$id_session} AND relation_type<>" . SESSION_RELATION_TYPE_RRHH . ""; Database::query($sql); } // Insert missing users into session $nbr_users = 0; foreach ($user_list as $enreg_user) { $enreg_user = Database::escape_string($enreg_user); $nbr_users++; $sql = "INSERT IGNORE INTO {$tbl_session_rel_user} (relation_type, session_id, user_id, registered_at)\n VALUES (0, {$id_session}, {$enreg_user}, '" . api_get_utc_datetime() . "')"; Database::query($sql); } // update number of users in the session $nbr_users = count($user_list); if ($empty_users) { // update number of users in the session $sql = "UPDATE {$tbl_session} SET nbr_users= {$nbr_users}\n WHERE id = {$id_session} "; Database::query($sql); } else { $sql = "UPDATE {$tbl_session} SET nbr_users = nbr_users + {$nbr_users}\n WHERE id = {$id_session}"; Database::query($sql); } }
exit; } $userInfo = ['id' => $user->getId(), 'complete_name' => $user->getCompleteName()]; $skillInfo = ['id' => $skill->getId(), 'name' => $skill->getName(), 'short_code' => $skill->getShortCode(), 'description' => $skill->getDescription(), 'criteria' => $skill->getCriteria(), 'badge_image' => $skill->getWebIconPath(), 'courses' => []]; $badgeAssertions = []; foreach ($userSkills as $userSkill) { $sessionId = 0; $course = $entityManager->find('ChamiloCoreBundle:Course', $userSkill->getCourseId()); $courseName = $course ? $course->getTitle() : ''; if ($userSkill->getSessionId()) { $session = $entityManager->find('ChamiloCoreBundle:Session', $userSkill->getSessionId()); $sessionId = $session->getId(); $courseName = "[{$session->getName()}] {$course->getTitle()}"; } $userSkillDate = api_get_local_time($userSkill->getAcquiredSkillAt()); $skillInfo['courses'][] = ['name' => $courseName, 'date_issued' => api_format_date($userSkillDate, DATE_TIME_FORMAT_LONG)]; $assertionUrl = api_get_path(WEB_CODE_PATH) . "badge/assertion.php?"; $assertionUrl .= http_build_query(array('user' => $user->getId(), 'skill' => $skill->getId(), 'course' => $userSkill->getCourseId(), 'session' => $userSkill->getSessionId())); $badgeAssertions[] = $assertionUrl; } $allowExport = api_get_user_id() == $user->getId(); if ($allowExport) { $backpack = 'https://backpack.openbadges.org/'; $configBackpack = api_get_setting('gradebook.openbadges_backpack'); if (strcmp($backpack, $configBackpack) !== 0) { $backpack = $configBackpack; } $htmlHeadXtra[] = '<script src="' . $backpack . 'issuer.js"></script>'; } echo Container::getTemplating()->render('@template_style/skill/issued.html.twig', ['assertions' => $badgeAssertions, 'skill_info' => $skillInfo, 'user_info' => $userInfo, 'allow_export' => $allowExport]); //$template->assign('header', get_lang('IssuedBadgeInformation'));
/** * Get HTML code block for user skills * @param int $userId The user ID * @return string */ public static function getSkillBlock($userId) { if (api_get_setting('skill.allow_skills_tool') !== 'true') { return null; } $skill = new Skill(); $ranking = $skill->get_user_skill_ranking($userId); $skills = $skill->get_user_skills($userId, true); return Container::getTemplating()->render('@template_style/social/skills_block.html.twig', ['ranking' => $ranking, 'skills' => $skills, 'user_id' => $userId, 'show_skills_report_link' => api_is_student() || api_is_student_boss() || api_is_drh()]); }
$more_info .= '<div class="social-actions-message"><strong>' . get_lang('MyPersonalOpenArea') . '</strong></div>'; $more_info .= '<div class="social-profile-extended">' . $user_info['openarea'] . '</div>'; $more_info .= '<br />'; } if (!empty($user_info['teach'])) { $more_info .= '<div class="social-actions-message"><strong>' . get_lang('MyTeach') . '</strong></div>'; $more_info .= '<div class="social-profile-extended">' . $user_info['teach'] . '</div>'; $more_info .= '<br />'; } $socialRightInformation .= SocialManager::social_wrapper_div($more_info, 4); } } //$tpl = new Template(get_lang('Social')); $tpl = Container::getTwig(); // Block Avatar Social SocialManager::setSocialUserBlock($tpl, $user_id, 'shared_profile', 0, $show_full_profile); $tpl->addGlobal('social_friend_block', $friend_html); $tpl->addGlobal('social_menu_block', $social_menu_block); $tpl->addGlobal('social_wall_block', $social_wall_block); $tpl->addGlobal('social_post_wall_block', $social_post_wall_block); $tpl->addGlobal('social_extra_info_block', $social_extra_info_block); $tpl->addGlobal('social_course_block', $social_course_block); $tpl->addGlobal('social_group_info_block', $social_group_info_block); $tpl->addGlobal('social_rss_block', $social_rss_block); $tpl->addGlobal('social_skill_block', SocialManager::getSkillBlock($my_user_id)); $tpl->addGlobal('sessionList', $social_session_block); $tpl->addGlobal('social_right_information', $socialRightInformation); $tpl->addGlobal('social_auto_extend_link', $socialAutoExtendLink); $formModals = Container::getTemplating()->render('@template_style/social/form_modals.html.twig', ['invitation_form' => MessageManager::generate_invitation_form('send_invitation')]); $tpl->addGlobal('form_modals', $formModals); echo $tpl->render('@template_style/social/profile.html.twig');
/** * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully) * Sender name and email can be specified, if not specified * name and email of the platform admin are used * * @author Bert Vanderkimpen ICT&O UGent * @author Yannick Warnier <*****@*****.**> * * @param string name of recipient * @param string email of recipient * @param string email subject * @param string email body * @param string sender name * @param string sender e-mail * @param array extra headers in form $headers = array($name => $value) to allow parsing * @param array data file (path and filename) * @param array data to attach a file (optional) * @param bool True for attaching a embedded file inside content html (optional) * @return returns true if mail was sent * @see class.phpmailer.php */ function api_mail_html($recipient_name, $recipient_email, $subject, $message, $senderName = '', $senderEmail = '', $extra_headers = array(), $data_file = array(), $embedded_image = false, $additionalParameters = array()) { // Default values $notification = new Notification(); $defaultEmail = $notification->getDefaultPlatformSenderEmail(); $defaultName = $notification->getDefaultPlatformSenderName(); // If the parameter is set don't use the admin. $senderName = !empty($senderName) ? $senderName : $defaultName; $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultEmail; $link = isset($additionalParameters['link']) ? $additionalParameters['link'] : ''; $swiftMessage = \Swift_Message::newInstance()->setSubject($subject)->setFrom($senderEmail, $senderName)->setTo($recipient_email, $recipient_name)->setBody(Container::getTemplating()->render('ChamiloCoreBundle:default/mail:mail.html.twig', array('content' => $message, 'link' => $link)), 'text/html'); if (!empty($additionalParameters)) { $plugin = new AppPlugin(); $smsPlugin = $plugin->getSMSPluginLibrary(); if ($smsPlugin) { $smsPlugin->send($additionalParameters); } } Container::getMailer()->send($swiftMessage); return 1; }
/** * Get the HTML code for an announcement * @param int $announcementId The announcement ID * @param int $visibility The announcement visibility * @return string The HTML code */ public static function displayAnnouncement($announcementId, $visibility) { $selectedUserLanguage = Database::escape_string(api_get_interface_language()); $announcementTable = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS); $now = api_get_utc_datetime(); $whereConditions = ["(lang = ? OR lang IS NULL) " => $selectedUserLanguage, "AND (? >= date_start AND ? <= date_end) " => [$now, $now], "AND id = ? " => intval($announcementId)]; switch ($visibility) { case self::VISIBLE_GUEST: $whereConditions["AND visible_guest = ? "] = 1; break; case self::VISIBLE_STUDENT: $whereConditions["AND visible_student = ? "] = 1; break; case self::VISIBLE_TEACHER: $whereConditions["AND visible_teacher = ? "] = 1; break; } if (api_is_multiple_url_enabled()) { $whereConditions["AND access_url_id IN (1, ?) "] = api_get_current_access_url_id(); } $announcement = Database::select("*", $announcementTable, ["where" => $whereConditions, "order" => "date_start"], 'first'); return Container::getTemplating()->render('@template_style/announcement/view.html.twig', ['announcement' => $announcement]); }
plusButton: "<em class=\\"fa fa-plus-circle \\"></em> ", minusButton: "<em class=\\"fa fa-minus-circle\\"></em> " }); }); </script>'; $skill = new Skill(); //obtain all skills $allSkills = $skill->get_all(); //order the skill list by a nested view array $skillList = $skill->get_nested_skill_view($allSkills); //$tpl = new Template(get_lang('ManageSkills')); echo $toolbar; echo Container::getTemplating()->render('@template_style/skill/nested.html.twig', ['skills' => $skillList]); break; case 'list': //no break //no break default: $interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin')); $interbreadcrumb[] = array("url" => '#', "name" => get_lang('ManageSkills')); $toolbar = Display::toolbarButton(get_lang('CreateSkill'), api_get_path(WEB_CODE_PATH) . 'admin/skill_create.php', 'plus', 'success', ['title' => get_lang('CreateSkill')]); $toolbar .= Display::toolbarButton(get_lang('SkillsWheel'), api_get_path(WEB_CODE_PATH) . 'admin/skills_wheel.php', 'bullseye', 'primary', ['title' => get_lang('CreateSkill')]); $toolbar .= Display::toolbarButton(get_lang('BadgesManagement'), api_get_path(WEB_CODE_PATH) . 'admin/skill_badge_list.php', 'shield', 'warning', ['title' => get_lang('BadgesManagement')]); $toolbar .= Display::toolbarButton(get_lang('NestedView'), api_get_path(WEB_CODE_PATH) . 'admin/skill_list.php?view=nested', 'eye', 'info pull-right', ['title' => get_lang('NestedView')]); /* List View */ $skill = new Skill(); $skillList = $skill->get_all(); echo $toolbar; echo Container::getTemplating()->render('@template_style/skill/list.html.twig', ['skills' => $skillList]); break; }
/* For licensing terms, see /license.txt */ use Chamilo\CoreBundle\Framework\Container; /** * @package chamilo.admin */ $cidReset = true; //require_once '../inc/global.inc.php'; $this_section = SECTION_SOCIAL; if (api_get_setting('skill.allow_skills_tool') != 'true') { api_not_allowed(); } api_block_anonymous_users(); //Adds the JS needed to use the jqgrid $htmlHeadXtra[] = api_get_js('js/d3/d3.v3.5.4.min.js'); $htmlHeadXtra[] = api_get_js('js/d3/colorbrewer.js'); $htmlHeadXtra[] = api_get_js('js/d3/jquery.xcolor.js'); $userId = api_get_user_id(); $userInfo = api_get_user_info(); $skill = new Skill(); $ranking = $skill->get_user_skill_ranking($userId); $skills = $skill->get_user_skills($userId, true); $dialogForm = new FormValidator('form', 'post', null, null, ['id' => 'add_item']); $dialogForm->addLabel(get_lang('Name'), Display::tag('p', null, ['id' => 'name', 'class' => 'form-control-static'])); $dialogForm->addLabel(get_lang('ShortCode'), Display::tag('p', null, ['id' => 'short_code', 'class' => 'form-control-static'])); $dialogForm->addLabel(get_lang('Parent'), Display::tag('p', null, ['id' => 'parent', 'class' => 'form-control-static'])); $dialogForm->addLabel([get_lang('Gradebook'), get_lang('WithCertificate')], Display::tag('ul', null, ['id' => 'gradebook', 'class' => 'form-control-static list-unstyled'])); $dialogForm->addLabel(get_lang('Description'), Display::tag('p', null, ['id' => 'description', 'class' => 'form-control-static'])); $wheelUrl = api_get_path(WEB_AJAX_PATH) . "skill.ajax.php?a=get_skills_tree_json&load_user={$userId}"; $url = api_get_path(WEB_AJAX_PATH) . 'skill.ajax.php?1=1'; echo Container::getTemplating()->render('@template_style/skill/skill_wheel_student.html.twig', ['skill_id_to_load' => 0, 'url' => $url, 'wheel_url' => $wheelUrl, 'dialogForm' => $dialogForm->returnForm(), 'user_info' => $userInfo, 'ranking' => $ranking, 'skills' => $skills]);
/** * Creates a new user for the platform * @author Hugues Peeters <*****@*****.**>, * @author Roan Embrechts <*****@*****.**> * @param string Firstname * @param string Lastname * @param int Status (1 for course tutor, 5 for student, 6 for anonymous) * @param string e-mail address * @param string Login * @param string Password * @param string Any official code (optional) * @param string User language (optional) (isocode) * @param string Phone number (optional) * @param string Picture URI (optional) * @param string Authentication source (optional, defaults to 'platform', dependind on constant) * @param string Account expiration date (optional, defaults to null) * @param int Whether the account is enabled or disabled by default * @param int The department of HR in which the user is registered (optional, defaults to 0) * @param array Extra fields * @param string Encrypt method used if password is given encrypted. Set to an empty string by default * @param bool $send_mail * @param bool $isAdmin * * @return mixed new user id - if the new user creation succeeds, false otherwise * @desc The function tries to retrieve user id from the session. * If it exists, the current user id is the creator id. If a problem arises, * it stores the error message in global $api_failureList * @assert ('Sam','Gamegie',5,'*****@*****.**','jo','jo') > 1 * @assert ('Pippin','Took',null,null,'jo','jo') === false */ public static function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language = '', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expirationDate = null, $active = 1, $hr_dept_id = 0, $extra = null, $encrypt_method = '', $send_mail = false, $isAdmin = false) { $currentUserId = api_get_user_id(); $hook = HookCreateUser::create(); if (!empty($hook)) { $hook->notifyCreateUser(HOOK_EVENT_TYPE_PRE); } global $_configuration; $original_password = $password; $access_url_id = 1; if (api_get_multiple_access_url()) { $access_url_id = api_get_current_access_url_id(); } if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_users']) && $_configuration[$access_url_id]['hosting_limit_users'] > 0) { $num = self::get_number_of_users(); if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) { api_warn_hosting_contact('hosting_limit_users'); Display::addFlash(Display::return_message(get_lang('PortalUsersLimitReached'), 'warning')); return false; } } if ($status === 1 && is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_teachers']) && $_configuration[$access_url_id]['hosting_limit_teachers'] > 0) { $num = self::get_number_of_users(1); if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) { Display::addFlash(Display::return_message(get_lang('PortalTeachersLimitReached'), 'warning')); api_warn_hosting_contact('hosting_limit_teachers'); return false; } } if (empty($password)) { Display::addFlash(Display::return_message(get_lang('ThisFieldIsRequired') . ': ' . get_lang('Password'), 'warning')); return false; } // database table definition $table_user = Database::get_main_table(TABLE_MAIN_USER); //Checking the user language $languages = api_get_languages(); if (!in_array($language, array_keys($languages))) { $language = api_get_setting('language.platform_language'); } if (!empty($currentUserId)) { $creator_id = $currentUserId; } else { $creator_id = 0; } // First check wether the login already exists if (!self::is_username_available($loginName)) { return api_set_failure('login-pass already taken'); } $currentDate = api_get_utc_datetime(); $now = new DateTime($currentDate); if (empty($expirationDate) || $expirationDate == '0000-00-00 00:00:00') { // Default expiration date // if there is a default duration of a valid account then // we have to change the expiration_date accordingly // Accept 0000-00-00 00:00:00 as a null value to avoid issues with // third party code using this method with the previous (pre-1.10) // value of 0000... if (api_get_setting('profile.account_valid_duration') != '') { $expirationDate = new DateTime($currentDate); $days = intval(api_get_setting('profile.account_valid_duration')); $expirationDate->modify('+' . $days . ' day'); } } else { $expirationDate = api_get_utc_datetime($expirationDate); $expirationDate = new \DateTime($expirationDate, new DateTimeZone('UTC')); } $userManager = self::getManager(); /** @var User $user */ $user = $userManager->createUser(); $user->setLastname($lastName)->setFirstname($firstName)->setUsername($loginName)->setStatus($status)->setPlainPassword($password)->setEmail($email)->setOfficialCode($official_code)->setPictureUri($picture_uri)->setCreatorId($creator_id)->setAuthSource($auth_source)->setPhone($phone)->setLanguage($language)->setRegistrationDate($now)->setHrDeptId($hr_dept_id)->setActive($active); if (!empty($expirationDate)) { $user->setExpirationDate($expirationDate); } $userManager->updateUser($user, true); $userId = $user->getId(); if (!empty($userId)) { $return = $userId; $sql = "UPDATE {$table_user} SET user_id = {$return} WHERE id = {$return}"; Database::query($sql); if ($isAdmin) { UserManager::add_user_as_admin($user); } if (api_get_multiple_access_url()) { UrlManager::add_user_to_url($return, api_get_current_access_url_id()); } else { //we are adding by default the access_url_user table with access_url_id = 1 UrlManager::add_user_to_url($return, 1); } if (!empty($email) && $send_mail) { $recipient_name = api_get_person_name($firstName, $lastName, null, PERSON_NAME_EMAIL_ADDRESS); $emailSubject = Container::getTemplating()->render('@template_style/mail/subject_registration_platform.html.twig'); $sender_name = api_get_person_name(api_get_setting('admin.administrator_name'), api_get_setting('admin.administrator_surname'), null, PERSON_NAME_EMAIL_ADDRESS); $email_admin = api_get_setting('admin.administrator_email'); $url = api_get_path(WEB_PATH); if (api_is_multiple_url_enabled()) { $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { $url = api_get_access_url($access_url_id); } } $emailBody = Container::getTemplating()->render('@template_style/mail/content_registration_platform.html.twig', ['complete_name' => stripslashes(api_get_person_name($firstName, $lastName)), 'login_name' => $loginName, 'original_password' => stripslashes($original_password), 'mail_web_path' => $url]); /* MANAGE EVENT WITH MAIL */ if (EventsMail::check_if_using_class('user_registration')) { $values["about_user"] = $return; $values["password"] = $original_password; $values["send_to"] = array($return); $values["prior_lang"] = null; EventsDispatcher::events('user_registration', $values); } else { $phoneNumber = isset($extra['mobile_phone_number']) ? $extra['mobile_phone_number'] : null; $additionalParameters = array('smsType' => SmsPlugin::WELCOME_LOGIN_PASSWORD, 'userId' => $return, 'mobilePhoneNumber' => $phoneNumber, 'password' => $original_password); api_mail_html($recipient_name, $email, $emailSubject, $emailBody, $sender_name, $email_admin, null, null, null, $additionalParameters); } /* ENDS MANAGE EVENT WITH MAIL */ } Event::addEvent(LOG_USER_CREATE, LOG_USER_ID, $return); } else { return api_set_failure('error inserting in Database'); } if (is_array($extra) && count($extra) > 0) { $res = true; foreach ($extra as $fname => $fvalue) { $res = $res && self::update_extra_field_value($return, $fname, $fvalue); } } self::update_extra_field_value($return, 'already_logged_in', 'false'); if (!empty($hook)) { $hook->setEventData(array('return' => $return, 'originalPassword' => $original_password)); $hook->notifyCreateUser(HOOK_EVENT_TYPE_POST); } return $return; }
if (!$existsBadgesDirectory) { $existsBadgesDirectory = api_create_protected_dir('badges', api_get_path(SYS_UPLOAD_PATH)); } if ($existsBadgesDirectory) { if (!empty($skill['icon'])) { $iconFileAbsolutePath = $badgePath . $skill['icon']; if (Security::check_abs_path($iconFileAbsolutePath, $badgePath)) { unlink($badgePath . $skill['icon']); } } $skillImagePath = sprintf("%s%s.png", $badgePath, $fileName); $skillImage = new Image($_FILES['image']['tmp_name']); $skillImage->send_image($skillImagePath, -1, 'png'); $skillThumbPath = sprintf("%s%s-small.png", $badgePath, $fileName); $skillImageThumb = new Image($skillImagePath); $skillImageThumb->resize(ICON_SIZE_BIG, ICON_SIZE_BIG); $skillImageThumb->send_image($skillThumbPath); $params['icon'] = sprintf("%s.png", $fileName); } else { Session::write('errorMessage', get_lang('UplUnableToSaveFile')); } } $objSkill->update($params); header('Location: ' . api_get_path(WEB_CODE_PATH) . 'admin/skill_badge_list.php'); exit; } $interbreadcrumb = array(array('url' => api_get_path(WEB_CODE_PATH) . 'admin/index.php', 'name' => get_lang('Administration')), array('url' => api_get_path(WEB_CODE_PATH) . 'admin/skill_badge.php', 'name' => get_lang('Badges')), array('url' => '#', 'name' => get_lang('CreateBadge'))); $toolbar = Display::toolbarButton(get_lang('ManageSkills'), api_get_path(WEB_CODE_PATH) . 'admin/skill_list.php', 'list', 'primary', ['title' => get_lang('ManageSkills')]); echo $toolbar; echo Container::getTemplating()->render('@template_style/skill/badge_create.html.twig', ['skill' => $skill]);
<?php /* For licensing terms, see /license.txt */ use Chamilo\CoreBundle\Framework\Container; /** * Show information about Mozilla OpenBadges * @author Angel Fernando Quiroz Campos <*****@*****.**> * @package chamilo.admin.openbadges */ $cidReset = true; //require_once '../inc/global.inc.php'; $this_section = SECTION_PLATFORM_ADMIN; if (!api_is_platform_admin() || api_get_setting('skill.allow_skills_tool') !== 'true') { api_not_allowed(true); } $backpack = 'https://backpack.openbadges.org/'; $configBackpack = api_get_setting('gradebook.openbadges_backpack'); if (strcmp($backpack, $configBackpack) !== 0) { $backpack = $configBackpack; } $interbreadcrumb = array(array('url' => api_get_path(WEB_CODE_PATH) . 'admin/index.php', 'name' => get_lang('Administration'))); $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Badges')); $toolbar = Display::toolbarButton(get_lang('ManageSkills'), api_get_path(WEB_CODE_PATH) . 'admin/skill_list.php', 'list', 'primary', ['title' => get_lang('ManageSkills')]); //$tpl = new Template(get_lang('Badges')); echo $toolbar; echo Container::getTemplating()->render('@template_style/skill/badge.html.twig', ['backpack' => $backpack]);
} else { // Update $sequenceResource->getSequence()->setGraphAndSerialize($graph); } $em->persist($sequenceResource); $em->flush(); echo Display::return_message(get_lang('Saved'), 'success'); break; } break; case 'get_requirements': $userId = api_get_user_id(); switch ($type) { case SequenceResource::SESSION_TYPE: $session = api_get_session_info($id); $sequences = $repository->getRequirements($session['id'], $type); if (count($sequences) === 0) { break; } $sequenceList = SequenceResourceManager::checkRequirementsForUser($sequences, $type, $userId); $allowSubscription = SequenceResourceManager::checkSequenceAreCompleted($sequenceList); $courseController = new CoursesController(); $subscribeButton = ''; if ($allowSubscription) { $subscribeButton = $courseController->getRegisteredInSessionButton($session['id'], $session['name'], false); } echo Container::getTemplating()->render('@template_style/sequence_resource/session_requirements.html.twig', ['sequences' => $sequenceList, 'allow_subscription' => $allowSubscription, 'subscribe_button' => $subscribeButton]); break; } break; }
$text_after_registration .= $form_register->returnForm(); // Just in case Session::erase('course_redirect'); Session::erase('exercise_redirect'); if (CustomPages::enabled()) { CustomPages::display(CustomPages::REGISTRATION_FEEDBACK, array('info' => $text_after_registration)); } else { //$tpl = new Template($tool_name); echo Container::getTemplating()->render('@template_style/auth/inscription.html.twig', ['inscription_content' => $content, 'text_after_registration' => $text_after_registration, 'hide_header' => $hideHeaders]); } } else { // Custom pages if (CustomPages::enabled()) { CustomPages::display(CustomPages::REGISTRATION, array('form' => $form)); } else { if (!api_is_anonymous()) { // Saving user to course if it was set. if (!empty($course_code_redirect)) { $course_info = api_get_course_info($course_code_redirect); if (!empty($course_info)) { if (in_array($course_info['visibility'], array(COURSE_VISIBILITY_OPEN_PLATFORM, COURSE_VISIBILITY_OPEN_WORLD))) { CourseManager::subscribe_user($user_id, $course_info['code']); } } } CourseManager::redirectToCourse([]); } //$tpl = new Template($tool_name); echo Container::getTemplating()->render('@template_style/auth/inscription.html.twig', ['inscription_header' => Display::page_header($tool_name), 'inscription_content' => $content, 'hide_header' => $hideHeaders, 'form', $form->returnForm()]); } }
<?php /* For licensing terms, see /license.txt */ use Chamilo\CoreBundle\Framework\Container; /** * Show information about OpenBadge criteria * @author Angel Fernando Quiroz Campos <*****@*****.**> * @package chamilo.badge */ //require_once '../inc/global.inc.php'; $entityManager = Database::getManager(); $skill = $entityManager->find('ChamiloCoreBundle:Skill', $_GET['id']); if (!$skill) { Display::addFlash(Display::return_message(get_lang('SkillNotFound'), 'error')); header('Location: ' . api_get_path(WEB_PATH)); exit; } $skillInfo = ['name' => $skill->getName(), 'short_code' => $skill->getShortCode(), 'description' => $skill->getDescription(), 'criteria' => $skill->getCriteria(), 'badge_image' => $skill->getWebIconPath()]; echo Container::getTemplating()->render('@template_style/skill/criteria.html.twig', ['skill_info' => $skillInfo]);