/** * Get HTML code block for user skills * @param int $userId The user ID * @return string */ public static function getSkillBlock($userId) { if (api_get_setting('allow_skills_tool') !== 'true') { return null; } $skill = new Skill(); $ranking = $skill->get_user_skill_ranking($userId); $skills = $skill->get_user_skills($userId, true); $template = new Template(null, false, false, false, false, false); $template->assign('ranking', $ranking); $template->assign('skills', $skills); $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh()); $skillBlock = $template->get_template('social/skills_block.tpl'); return $template->fetch($skillBlock); }
/** * @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'))); //} }
$extraContentForm = new FormValidator('block_extra_data', 'post', '#', null, array('id' => 'block-extra-data', 'class' => ''), FormValidator::LAYOUT_BOX_NO_LABEL); $extraContentFormRenderer = $extraContentForm->getDefaultRenderer(); if ($extraContentForm->validate()) { $extraData = $extraContentForm->getSubmitValues(); $extraData = array_map(['Security', 'remove_XSS'], $extraData); if (!empty($extraData['block'])) { if (!is_dir($adminExtraContentDir)) { mkdir($adminExtraContentDir, api_get_permissions_for_new_directories(), true); } if (!is_writable($adminExtraContentDir)) { die; } $fullFilePath = $adminExtraContentDir . $extraData['block']; $fullFilePath .= "_extra.html"; file_put_contents($fullFilePath, $extraData['extra_content']); Header::location(api_get_self()); } } $extraContentForm->addTextarea('extra_content', null, ['id' => 'extra_content']); $extraContentFormRenderer->setElementTemplate('<div class="form-group">{element}</div>', 'extra_content'); $extraContentForm->addElement('hidden', 'block', null, array('id' => 'extra-block')); $extraContentForm->addButtonExport(get_lang('Save'), 'submit_extra_content'); $tpl->assign('extraDataForm', $extraContentForm->returnForm()); } // The template contains the call to the AJAX version checker $admin_template = $tpl->get_template('admin/settings_index.tpl'); $content = $tpl->fetch($admin_template); $tpl->assign('content', $content); $tpl->assign('message', $message); $tpl->display_one_col_template(); // Note: version checking mechanism has now been moved to main/inc/ajax/admin.ajax.php
/** * 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; }
function parse_includes() { $template = $this->get_template(); if (strpos($template, '{INCLUDE ') === false) { return; } $offset = 0; $y = 0; while (($begin = strpos($template, '{INCLUDE ', $offset)) !== false) { $y++; $start = $begin + 9; $offset = $start; $long = 0; if ($template[$start] == '"') { $long = 1; $start++; } $file = ''; $skip = 0; for ($x = $start; $x < strlen($template); $x++) { if ($template[$x] == "\n" || $template[$x] == "\r") { $skip = 1; break; } elseif ($long == 0 && $template[$x] == ' ') { $skip = 1; break; } elseif ($long == 1 && $template[$x] == '"') { if ($template[$x + 1] != '}') { $skip = 1; } break; } elseif ($long == 0 && $template[$x] == '}') { break; } else { $file .= $template[$x]; } } if ($skip == 1) { continue; } if ($file != '') { $filepath = $file; $is_absolute = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? preg_match('!^([a-z]:)?/!i', $file) : preg_match('!^/!', $file); if (!$is_absolute) { if (!empty($this->file)) { $dir = dirname($this->file); } else { $dir = '.'; } $dir = str_replace('\\', '/', $dir); if (!preg_match('!/+$!', $dir)) { $dir .= '/'; } $filepath = $dir . $file; } if (is_file($filepath)) { $inc = new Template(); $inc->read_file($filepath); $end = $long == 1 ? $start + strlen($file) + 2 : $start + strlen($file) + 1; $pre = substr($template, 0, $begin); $post = substr($template, $end); $template = $pre . $inc->get_template() . $post; $offset = strlen($pre) + strlen($inc->get_template()); unset($inc); } } } $this->set_template($template); }
public static function displayTrackingAccessOverView($courseId, $sessionId, $studentId) { $courseId = intval($courseId); $sessionId = intval($sessionId); $studentId = intval($studentId); $em = Database::getManager(); $sessionRepo = $em->getRepository('ChamiloCoreBundle:Session'); $courseList = []; $sessionList = []; $studentList = []; if (!empty($courseId)) { $course = $em->find('ChamiloCoreBundle:Course', $courseId); $courseList[$course->getId()] = $course->getTitle(); } if (!empty($sessionId)) { $session = $em->find('ChamiloCoreBundle:Session', $sessionId); $sessionList[$session->getId()] = $session->getName(); } if (!empty($studentId)) { $student = $em->find('ChamiloUserBundle:User', $studentId); $studentList[$student->getId()] = $student->getCompleteName(); } $form = new FormValidator('access_overview', 'GET'); $form->addElement('select_ajax', 'course_id', get_lang('SearchCourse'), $courseList, ['url' => api_get_path(WEB_AJAX_PATH) . 'course.ajax.php?' . http_build_query(['a' => 'search_course_by_session_all', 'session_id' => $sessionId])]); $form->addElement('select_ajax', 'session_id', get_lang('SearchSession'), $sessionList, ['url_function' => "\n function () {\n var params = \$.param({\n a: 'search_session_by_course',\n course_id: \$('#course_id').val() || 0\n });\n\n return '" . api_get_path(WEB_AJAX_PATH) . "session.ajax.php?' + params;\n }\n "]); $form->addSelect('profile', get_lang('Profile'), ['' => get_lang('Select'), STUDENT => get_lang('Student'), COURSEMANAGER => get_lang('CourseManager'), DRH => get_lang('Drh')], ['id' => 'profile']); $form->addElement('select_ajax', 'student_id', get_lang('SearchUsers'), $studentList, ['placeholder' => get_lang('All'), 'url_function' => "\n function () {\n var params = \$.param({\n a: 'search_user_by_course',\n session_id: \$('#session_id').val(),\n course_id: \$('#course_id').val()\n });\n\n return '" . api_get_path(WEB_AJAX_PATH) . "course.ajax.php?' + params;\n }\n "]); $form->addDateRangePicker('date', get_lang('DateRange'), true, ['id' => 'date_range', 'format' => 'YYYY-MM-DD', 'timePicker' => 'false', 'validate_format' => 'Y-m-d']); $form->addHidden('display', 'accessoverview'); $form->addRule('course_id', get_lang('Required'), 'required'); $form->addRule('profile', get_lang('Required'), 'required'); $form->addButton('submit', get_lang('Generate'), 'gear', 'primary'); $table = null; if ($form->validate()) { $table = new SortableTable('tracking_access_overview', ['MySpace', 'getNumberOfRrackingAccessOverview'], ['MySpace', 'getUserDataAccessTrackingOverview'], 0); $table->additional_parameters = $form->exportValues(); $table->set_header(0, get_lang('LoginDate'), true); $table->set_header(1, get_lang('Username'), true); if (api_is_western_name_order()) { $table->set_header(2, get_lang('FirstName'), true); $table->set_header(3, get_lang('LastName'), true); } else { $table->set_header(2, get_lang('LastName'), true); $table->set_header(3, get_lang('FirstName'), true); } $table->set_header(4, get_lang('Clicks'), false); $table->set_header(5, get_lang('IP'), false); $table->set_header(6, get_lang('TimeLoggedIn'), false); } $template = new Template(null, false, false, false, false, false, false); $template->assign('form', $form->returnForm()); $template->assign('table', $table ? $table->return_table() : null); echo $template->fetch($template->get_template('my_space/accessoverview.tpl')); }
$tpl->assign('text_after_registration', $text_after_registration); $tpl->assign('hide_header', $hideHeaders); $inscription = $tpl->get_template('auth/inscription.tpl'); $tpl->display($inscription); } } 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); $tpl->assign('inscription_header', Display::page_header($tool_name)); $tpl->assign('inscription_content', $content); $tpl->assign('form', $form->returnForm()); $tpl->assign('hide_header', $hideHeaders); $inscription = $tpl->get_template('auth/inscription.tpl'); $tpl->display($inscription); } }
<?php /* For licensing terms, see /license.txt */ /** * Show information about OpenBadge citeria * @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()]; $template = new Template(); $template->assign('skill_info', $skillInfo); $content = $template->fetch($template->get_template('skill/criteria.tpl')); $template->assign('content', $content); $template->display_one_col_template();
$form->addRule('comment', get_lang('ThisFieldIsRequired'), 'required'); $form->addSelect('value', [get_lang('Value'), get_lang('RateTheSkillInPractice')], ['-', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $form->addHidden('user', $skillIssue->getUser()->getId()); $form->addHidden('issue', $skillIssue->getId()); $form->addButtonSend(get_lang('Send')); if ($form->validate() && $allowComment) { $values = $form->exportValues(); $skillUserComment = new Chamilo\CoreBundle\Entity\SkillRelUserComment(); $skillUserComment->setFeedbackDateTime(new DateTime())->setFeedbackGiver($currentUser)->setFeedbackText($values['comment'])->setFeedbackValue($values['value'] ? $values['value'] : null)->setSkillRelUser($skillIssue); $entityManager->persist($skillUserComment); $entityManager->flush(); header("Location: " . $skillIssue->getIssueUrl()); exit; } if ($allowExport) { $backpack = 'https://backpack.openbadges.org/'; $configBackpack = api_get_setting('openbadges_backpack'); if (strcmp($backpack, $configBackpack) !== 0) { $backpack = $configBackpack; } $htmlHeadXtra[] = '<script src="' . $backpack . 'issuer.js"></script>'; } $template = new Template(get_lang('IssuedBadgeInformation')); $template->assign('issue_info', $skillIssueInfo); $template->assign('allow_comment', $allowComment); $template->assign('allow_export', $allowExport); $template->assign('comment_form', $form->returnForm()); $content = $template->fetch($template->get_template('skill/issued.tpl')); $template->assign('header', get_lang('IssuedBadgeInformation')); $template->assign('content', $content); $template->display_one_col_template();
$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->assign('session_header', $sessionHeader); $tpl->assign('title', $sessionTitle); $tpl->assign('general_coach', $generalCoach); $tpl->assign('session', $sessionInfo); $tpl->assign('session_category', is_null($sessionCategory) ? null : $sessionCategory->getName()); $tpl->assign('session_dates', SessionManager::parseSessionDates($sessionInfo)); $tpl->assign('session_visibility', SessionManager::getSessionVisibility($sessionInfo)); $tpl->assign('url_list', $urlList); $tpl->assign('extra_fields', $extraFieldData); $tpl->assign('course_list', $courseListToShow); $tpl->assign('user_list', $userListToShow); $tpl->assign('dependencies', $dependencies); $tpl->assign('requirements', $requirements); $layout = $tpl->get_template('session/resume_session.tpl'); $tpl->display($layout);
if (!empty($selectedGroupChoices)) { $defaults['groups'] = $selectedGroupChoices; } $form->setDefaults($defaults); $tpl = new Template(); $currentUser = $em->getRepository('ChamiloUserBundle:User')->find(api_get_user_id()); if ($form->validate()) { $values = $form->getSubmitValues(); // Subscribing users $users = isset($values['users']) ? $values['users'] : []; $userForm = isset($values['user_form']) ? $values['user_form'] : []; if (!empty($userForm)) { $em->getRepository('ChamiloCourseBundle:CItemProperty')->subscribeUsersToItem($currentUser, 'learnpath', $course, $session, $lpId, $users); Display::addFlash(Display::return_message(get_lang('Updated'))); } // Subscribing groups $groups = isset($values['groups']) ? $values['groups'] : []; $groupForm = isset($values['group_form']) ? $values['group_form'] : []; if (!empty($groupForm)) { $em->getRepository('ChamiloCourseBundle:CItemProperty')->subscribeGroupsToItem($currentUser, 'learnpath', $course, $session, $lpId, $groups); Display::addFlash(Display::return_message(get_lang('Updated'))); } header("Location: {$url}"); exit; } else { $headers = [get_lang('SubscribeUsersToLp'), get_lang('SubscribeGroupsToLp')]; $tabs = Display::tabs($headers, [$formUsers->toHtml(), $form->toHtml()]); $tpl->assign('tabs', $tabs); } $layout = $tpl->get_template('learnpath/subscribe_users.tpl'); $tpl->display($layout);
exit; } $htmlHeadXtra[] = to_javascript_work(); $tpl = new Template(); $content = null; if (!empty($work_id)) { if ($is_allowed_to_edit) { if (api_resource_is_locked_by_gradebook($work_id, LINK_STUDENTPUBLICATION)) { echo Display::display_warning_message(get_lang('ResourceLockedByGradebook')); } else { $comments = getWorkComments($work_item); $template = $tpl->get_template('work/comments.tpl'); $tpl->assign('work_comment_enabled', ALLOW_USER_COMMENTS); $tpl->assign('comments', $comments); $content .= $form->return_form(); $content .= $tpl->fetch($template); } } elseif ($is_author) { if (empty($work_item['qualificator_id']) || $work_item['qualificator_id'] == 0) { $content .= $form->return_form(); } else { $content .= Display::return_message(get_lang('ActionNotAllowed'), 'error'); } } elseif ($student_can_edit_in_session && $has_ended == false) { $content .= $form->return_form(); } else {
} $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(); $view = new Template(null, false, false, false, false, false); $view->assign('sequences', $sequenceList); $view->assign('allow_subscription', $allowSubscription); if ($allowSubscription) { $view->assign('subscribe_button', $courseController->getRegisteredInSessionButton($session['id'], $session['name'], false)); } $template = $view->get_template('sequence_resource/session_requirements.tpl'); $view->display($template); break; } break; }
} //$social_right_content .= SocialManager::display_user_list($user_list); } } $whoisonline_list .= SocialManager::display_user_list($user_list); if (isset($_GET['id'])) { if (api_get_setting('allow_social_tool') == 'true' && api_user_is_login()) { header("Location: " . api_get_path(WEB_CODE_PATH) . "social/profile.php?u=" . intval($_GET['id'])); exit; } else { $social_right_content .= SocialManager::display_individual_user($_GET['id']); } } } else { api_not_allowed(); exit; } $tpl = new Template(get_lang('UsersOnLineList')); if (api_get_setting('allow_social_tool') == 'true' && !api_is_anonymous()) { $tpl->assign('whoisonline', $whoisonline_list); $tpl->assign('social_search', $social_search); $social_layout = $tpl->get_template('social/whoisonline.tpl'); $tpl->display($social_layout); } else { $content = $social_right_content; $tpl->assign('actions', $actions); $tpl->assign('message', $show_message); $tpl->assign('header', get_lang('UsersOnLineList')); $tpl->assign('content', $content); $tpl->display_one_col_template(); }
/** * 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 = 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); $tpl = new Template(); $tpl->assign('show_courses', CoursesAndSessionsCatalog::showCourses()); $tpl->assign('show_sessions', CoursesAndSessionsCatalog::showSessions()); $tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true' ? true : false); $tpl->assign('course_url', $courseUrl); $tpl->assign('already_subscribed_label', $this->getAlreadyRegisteredInSessionLabel()); $tpl->assign('hidden_links', $hiddenLinks); $tpl->assign('search_token', Security::get_token()); $tpl->assign('search_date', Security::remove_XSS($searchDate)); $tpl->assign('search_tag', Security::remove_XSS($q)); $tpl->assign('sessions', $sessionsBlocks); $contentTemplate = $tpl->get_template('auth/session_catalog.tpl'); $tpl->display($contentTemplate); }
/** * Get HTML code block for user skills * @param int $userId The user ID * @return string */ public static function getSkillBlock($userId) { if (api_get_setting('allow_skills_tool') !== 'true') { return null; } $entityManager = Database::getManager(); $user = $entityManager->find('ChamiloUserBundle:User', $userId); if (!$user) { return null; } $achievedSkills = $user->getAchievedSkills(); $ranking = $achievedSkills->count(); $skillsInfo = []; foreach ($achievedSkills as $userSkill) { $skillsInfo[] = ['id' => $userSkill->getSkill()->getId(), 'name' => $userSkill->getSkill()->getName(), 'icon' => $userSkill->getSkill()->getWebIconPath(true), 'source_name' => $userSkill->getSourceName(), 'issue_url' => $userSkill->getIssueUrl()]; } $template = new Template(null, false, false, false, false, false); $template->assign('ranking', $ranking); $template->assign('skills', $skillsInfo); $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh()); $skillBlock = $template->get_template('social/skills_block.tpl'); return $template->fetch($skillBlock); }
require_once 'work.lib.php'; $id = isset($_GET['id']) ? intval($_GET['id']) : null; $work = get_work_data_by_id($id); if (empty($id) || empty($work)) { api_not_allowed(); } $interbreadcrumb[] = array('url' => 'work.php', 'name' => get_lang('StudentPublications')); $my_folder_data = get_work_data_by_id($work['parent_id']); $course_info = api_get_course_info(); allowOnlySubscribedUser(api_get_user_id(), $work['parent_id'], $course_info['real_id']); if (user_is_author($id) || $course_info['show_score'] == 0 && $work['active'] == 1 && $work['accepted'] == 1) { if (api_is_allowed_to_edit(null, true)) { $url_dir = 'work_list_all.php?id=' . $my_folder_data['id']; } else { $url_dir = 'work_list.php?id=' . $my_folder_data['id']; } $interbreadcrumb[] = array('url' => $url_dir, 'name' => $my_folder_data['title']); $interbreadcrumb[] = array('url' => '#', 'name' => $work['title']); if ($course_info['show_score'] == 0 && $work['active'] == 1 && $work['accepted'] == 1 || api_is_allowed_to_edit() || user_is_author($id)) { $tpl = new Template(); $tpl->assign('work', $work); $template = $tpl->get_template('work/view.tpl'); $content = $tpl->fetch($template); $tpl->assign('content', $content); $tpl->display_one_col_template(); } else { api_not_allowed(true); } } else { api_not_allowed(true); }
$entityManager = Database::getManager(); $sessionRepo = $entityManager->getRepository('ChamiloCoreBundle:Session'); $accessUrlRepo = $entityManager->getRepository('ChamiloCoreBundle:AccessUrl'); $sessions = $sessionRepo->createQueryBuilder('s')->where('s.accessEndDate LIKE :date')->setParameter('date', "{$endDate}%")->getQuery()->getResult(); if (empty($sessions)) { echo "No sessions finishing today {$endDate}" . PHP_EOL; exit; } $administrator = ['complete_name' => api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS), 'email' => api_get_setting('emailAdministrator')]; foreach ($sessions as $session) { $sessionUsers = $session->getUsers(); if (empty($sessionUsers)) { echo 'No users to send mail' . PHP_EOL; exit; } foreach ($sessionUsers as $sessionUser) { $user = $sessionUser->getUser(); $subjectTemplate = new Template(null, false, false, false, false, false); $subjectTemplate->assign('session_name', $session->getName()); $subjectLayout = $subjectTemplate->get_template('mail/cron_course_finished_subject.tpl'); $bodyTemplate = new Template(null, false, false, false, false, false); $bodyTemplate->assign('complete_user_name', $user->getCompleteName()); $bodyTemplate->assign('session_name', $session->getName()); $bodyLayout = $bodyTemplate->get_template('mail/cron_course_finished_body.tpl'); api_mail_html($user->getCompleteName(), $user->getEmail(), $subjectTemplate->fetch($subjectLayout), $bodyTemplate->fetch($bodyLayout), $administrator['complete_name'], $administrator['email']); echo '============' . PHP_EOL; echo "Email sent to: {$user->getCompleteName()} ({$user->getEmail()})" . PHP_EOL; echo "Session: {$session->getName()}" . PHP_EOL; echo "End date: {$session->getAccessEndDate()->format('Y-m-d h:i')}" . PHP_EOL; } }
/** * 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; } $tplSubject = new Template(null, false, false, false, false, false); $layoutSubject = $tplSubject->get_template('mail/subject_subscription_to_session_confirmation.tpl'); $subject = $tplSubject->fetch($layoutSubject); $user_info = api_get_user_info($user_id); $tplContent = new Template(null, false, false, false, false, false); // Variables for default template $tplContent->assign('complete_name', stripslashes($user_info['complete_name'])); $tplContent->assign('session_name', $session->getName()); $tplContent->assign('session_coach', $session->getGeneralCoach()->getCompleteName()); $layoutContent = $tplContent->get_template('mail/content_subscription_to_session_confirmation.tpl'); $content = $tplContent->fetch($layoutContent); api_mail_html($user_info['complete_name'], $user_info['mail'], $subject, $content, api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname')), api_get_setting('emailAdministrator')); } } 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); } }
break; case GROUP_USER_PERMISSION_READER: if (in_array($user_role, array(GROUP_USER_PERMISSION_ADMIN, GROUP_USER_PERMISSION_MODERATOR))) { $user['link'] = '<a href="group_members.php?id=' . $group_id . '&u=' . $user['user_id'] . '&action=delete">' . Display::return_icon('delete.png', get_lang('DeleteFromGroup')) . '</a>' . '<a href="group_members.php?id=' . $group_id . '&u=' . $user['user_id'] . '&action=set_moderator">' . Display::return_icon('social_moderator_add.png', get_lang('AddModerator')) . '</a>'; } break; case GROUP_USER_PERMISSION_PENDING_INVITATION: $user['link'] = '<a href="group_members.php?id=' . $group_id . '&u=' . $user['user_id'] . '&action=add">' . Display::return_icon('pending_invitation.png', get_lang('PendingInvitation')) . '</a>'; break; case GROUP_USER_PERMISSION_MODERATOR: $user['link'] = Display::return_icon('social_group_moderator.png', get_lang('Moderator')); //only group admin can manage moderators if ($user_role == GROUP_USER_PERMISSION_ADMIN) { $user['link'] .= '<a href="group_members.php?id=' . $group_id . '&u=' . $user['user_id'] . '&action=delete_moderator">' . Display::return_icon('social_moderator_delete.png', get_lang('DeleteModerator')) . '</a>'; } break; } $userPicture = UserManager::getUserPicture($user['user_id']); $user['image'] = '<img src="' . $userPicture . '" width="50px" height="50px" />'; $new_member_list[] = $user; } if (count($new_member_list) > 0) { $social_right_content .= Display::return_sortable_grid('list_members', array(), $new_member_list, array('hide_navigation' => true, 'per_page' => 100), array(), false, array(true, false, true, true, false, true, true)); } $tpl = new Template(null); $tpl->setHelp('Groups'); $tpl->assign('social_avatar_block', $social_avatar_block); $tpl->assign('social_menu_block', $social_menu_block); $tpl->assign('social_right_content', $social_right_content); $social_layout = $tpl->get_template('social/home.tpl'); $tpl->display($social_layout);
api_not_allowed(true); } $lpTable = Database::get_course_table(TABLE_LP_MAIN); $lpId = isset($_GET['lp_id']) ? boolval($_GET['lp_id']) : false; $sessionId = api_get_session_id(); $courseId = api_get_course_int_id(); $courseCode = api_get_course_id(); $sessionUsers = SessionManager::get_users_by_session($sessionId, 0); $userList = []; $lpInfo = Database::select('*', $lpTable, array('where' => array('c_id = ? AND ' => $courseId, 'id = ?' => $lpId)), 'first'); foreach ($sessionUsers as $user) { $lpTime = Tracking::get_time_spent_in_lp($user['user_id'], $courseCode, array($lpId), $sessionId); $lpScore = Tracking::get_avg_student_score($user['user_id'], $courseCode, array($lpId), $sessionId); $lpPogress = Tracking::get_avg_student_progress($user['user_id'], $courseCode, array($lpId), $sessionId); $lpLastConnection = Tracking::get_last_connection_time_in_lp($user['user_id'], $courseCode, array($lpId), $sessionId); $lpLastConnection = empty($lpLastConnection) ? '-' : api_convert_and_format_date($lpLastConnection, DATE_TIME_FORMAT_LONG); $userList[] = ['id' => $user['user_id'], 'first_name' => $user['firstname'], 'last_name' => $user['lastname'], 'lp_time' => api_time_to_hms($lpTime), 'lp_score' => is_numeric($lpScore) ? "{$lpScore}%" : $lpScore, 'lp_progress' => "{$lpPogress}%", 'lp_last_connection' => $lpLastConnection]; } // View $interbreadcrumb[] = ['url' => api_get_path(WEB_CODE_PATH) . 'newscorm/lp_controller.php', 'name' => get_lang('LearningPaths')]; $actions = Display::url(Display::return_icon('back.png', get_lang('Back'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH) . 'newscorm/lp_controller.php?' . api_get_cidreq()); $template = new Template(get_lang('StudentScore')); $template->assign('user_list', $userList); $template->assign('session_id', api_get_session_id()); $template->assign('course_code', api_get_course_id()); $template->assign('lp_id', $lpId); $layout = $template->get_template('learnpath/report.tpl'); $template->assign('header', $lpInfo['name']); $template->assign('actions', $actions); $template->assign('content', $template->fetch($layout)); $template->display_one_col_template();
/** * Render a template using data. Adds a few common parameters to data. * * @see /main/template/default/course_description/ * @param string $template * @param array $data */ protected function render($template_name, $data) { $data = (object) $data; $data->www = \Chamilo::url(); $data->messages = isset($data->messages) ? $data->messages : array(); $javascript = $this->javascript(); if ($javascript) { $data->javascript = $javascript; } $tpl = new Template(); foreach ($data as $key => $value) { $tpl->assign($key, $value); } $template = $tpl->get_template($template_name); $content = $tpl->fetch($template); $tpl->assign('content', $content); $tpl->display_one_col_template(); }
$sequence = new Sequence(); $sequence->setName($values['name']); $em->persist($sequence); $em->flush(); header('Location: ' . api_get_self()); exit; } $selectSequence = new FormValidator(''); $selectSequence->addHidden('sequence_type', 'session'); $em = Database::getManager(); $sequenceList = $em->getRepository('ChamiloCoreBundle:Sequence')->findAll(); $selectSequence->addSelect('sequence', get_lang('Sequence'), $sequenceList, ['id' => 'sequence_id', 'cols-size' => [3, 7, 2]]); $form = new FormValidator(''); $form->addHtml("<div class='col-md-6'>"); $form->addHidden('sequence_type', 'session'); $form->addSelect('sessions', get_lang('Sessions'), $sessionList, ['id' => 'item', 'cols-size' => [4, 7, 1]]); $form->addButtonNext(get_lang('UseAsReference'), 'use_as_reference', ['cols-size' => [4, 7, 1]]); $form->addHtml("</div>"); $form->addHtml("<div class='col-md-6'>"); $form->addSelect('requirements', get_lang('Requirements'), $sessionList, ['id' => 'requirements', 'cols-size' => [3, 7, 2]]); $form->addButtonCreate(get_lang('SetAsRequirement'), 'set_requirement', false, ['cols-size' => [3, 7, 2]]); $form->addHtml("</div>"); $formSave = new FormValidator(''); $formSave->addHidden('sequence_type', 'session'); $formSave->addButton('save_resource', get_lang('SaveSettings'), 'floppy-o', 'success', null, null, ['cols-size' => [1, 10, 1]]); $tpl->assign('create_sequence', $formSequence->returnForm()); $tpl->assign('select_sequence', $selectSequence->returnForm()); $tpl->assign('configure_sequence', $form->returnForm()); $tpl->assign('save_sequence', $formSave->returnForm()); $layout = $tpl->get_template('admin/resource_sequence.tpl'); $tpl->display($layout);
} } else { // Create a request for a new course. $request_id = CourseRequestManager::create_course_request($wanted_code, $title, $description, $category_code, $course_language, $objetives, $target_audience, api_get_user_id(), $exemplary_content); if ($request_id) { $course_request_info = CourseRequestManager::get_course_request_info($request_id); $message = (is_array($course_request_info) ? '<strong>' . $course_request_info['code'] . '</strong> : ' : '') . get_lang('CourseRequestCreated'); $message = Display::return_message($message, 'confirmation', false); $message .= Display::tag('div', Display::url(get_lang('Enter'), api_get_path(WEB_PATH) . 'user_portal.php', ['class' => 'btn btn-default']), ['style' => 'float: left; margin:0px; padding: 0px;']); } else { $message = Display::return_message(get_lang('CourseRequestCreationFailed'), 'error', false); // Display the form. $content = $form->return_form(); } } } else { $message = Display::return_message(get_lang('CourseCodeAlreadyExists'), 'error', false); // Display the form. $content = $form->return_form(); } } else { if (!$course_validation_feature) { $message = Display::return_message(get_lang('Explanation')); } // Display the form. $content = $form->returnForm(); } $tpl->assign('message', $message); $tpl->assign('content', $content); $template = $tpl->get_template('layout/layout_1_col.tpl'); $tpl->display($template);
if ($form->validate()) { $em = Database::getManager(); $values = $form->exportValues(); $password = $values['pass1']; $token = $values['token']; /** @var \Chamilo\UserBundle\Entity\User $user */ $user = UserManager::getManager()->findUserByConfirmationToken($token); if ($user) { if (!$user->isPasswordRequestNonExpired($ttl)) { Display::addFlash(Display::return_message(get_lang('LinkExpired')), 'warning'); header('Location: ' . api_get_path(WEB_CODE_PATH) . 'auth/lostPassword.php'); exit; } $user->setPlainPassword($password); $userManager = UserManager::getManager(); $userManager->updateUser($user, true); $user->setConfirmationToken(null); $user->setPasswordRequestedAt(null); Database::getManager()->persist($user); Database::getManager()->flush(); Display::addFlash(Display::return_message(get_lang('Updated'))); header('Location: ' . api_get_path(WEB_PATH)); exit; } else { Display::addFlash(Display::return_message(get_lang('LinkExpired'))); } } $tpl->assign('form', $form->toHtml()); $content = $tpl->get_template('auth/set_temp_password.tpl'); $tpl->assign('content', $tpl->fetch($content)); $tpl->display_one_col_template();
$form->addElement('text', 'email_address', get_lang('EmailDestination')); $form->addElement('text', 'email_title', get_lang('EmailTitle'), array('class' => 'span5')); $form->freeze('email_address'); $form->addElement('textarea', 'email_text', get_lang('EmailText'), array('class' => 'span5', 'rows' => '6')); $form->addRule('email_address', get_lang('ThisFieldIsRequired'), 'required'); $form->addRule('email_title', get_lang('ThisFieldIsRequired'), 'required'); $form->addRule('email_text', get_lang('ThisFieldIsRequired'), 'required'); $form->addRule('email_address', get_lang('EmailWrong'), 'email'); $form->addElement('button', 'submit', get_lang('SendMail')); switch ($action) { case 'subscribe_me_to_session': $sessionName = isset($_GET['session']) ? Security::remove_XSS($_GET['session']) : null; $objTemplate = new Template(); $objTemplate->assign('session_name', $sessionName); $objTemplate->assign('user', api_get_user_info()); $mailTemplate = $objTemplate->get_template('mail/subscribe_me_to_session.tpl'); $emailDest = api_get_setting('emailAdministrator'); $emailTitle = get_lang('SubscribeToSessionRequest'); $emailText = $objTemplate->fetch($mailTemplate); break; default: $emailDest = Security::remove_XSS($_REQUEST['dest']); $emailTitle = Security::remove_XSS($_REQUEST['email_title']); $emailText = Security::remove_XSS($_REQUEST['email_text']); } $defaults = array('dest' => $emailDest, 'email_address' => $emailDest, 'email_title' => $emailTitle, 'email_text' => $emailText); $form->setDefaults($defaults); if ($form->validate()) { $text = Security::remove_XSS($_POST['email_text']) . "\n\n---\n" . get_lang('EmailSentFromDokeos') . " " . api_get_path(WEB_PATH); $email_administrator = Security::remove_XSS($_POST['dest']); $user_id = api_get_user_id();
/** * 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) * @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(); $language = strtolower($language); if (!in_array($language, $languages['folder'])) { $language = api_get_setting('platformLanguage'); } if (!empty($currentUserId)) { $creator_id = $currentUserId; } else { $creator_id = ''; } // 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)) { // Default expiration date // if there is a default duration of a valid account then // we have to change the expiration_date accordingly if (api_get_setting('account_valid_duration') != '') { $expirationDate = new DateTime($currentDate); $days = intval(api_get_setting('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($userId); } 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); $tplSubject = new Template(null, false, false, false, false, false); $layoutSubject = $tplSubject->get_template('mail/subject_registration_platform.tpl'); $emailSubject = $tplSubject->fetch($layoutSubject); $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS); $email_admin = api_get_setting('emailAdministrator'); 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); } } else { $url = $_configuration['root_web']; } $tplContent = new Template(null, false, false, false, false, false); // variables for the default template $tplContent->assign('complete_name', stripslashes(api_get_person_name($firstName, $lastName))); $tplContent->assign('login_name', $loginName); $tplContent->assign('original_password', stripslashes($original_password)); $tplContent->assign('mailWebPath', $url); $layoutContent = $tplContent->get_template('mail/content_registration_platform.tpl'); $emailBody = $tplContent->fetch($layoutContent); /* 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; }
case 'xls': array_unshift($dataToExport, array($reportTitle), array($reportSubTitle), array()); Export::export_table_xls_html($dataToExport, $fileName); break; } die; } $form->addSelect('course', get_lang('Course'), $optionsCourses, ['id' => 'courses']); $form->addSelect('session', get_lang('Session'), $optionsSessions, ['id' => 'session']); $form->addSelect('teacher', get_lang('Teacher'), $optionsTeachers, ['id' => 'teacher']); $form->addDateRangePicker('daterange', get_lang('Date'), false, ['id' => 'daterange', 'maxDate' => $limitDate->format('Y-m-d'), 'format' => 'YYYY-MM-DD', 'timePicker' => 'false', 'value' => "{$selectedFrom} / {$selectedUntil}"]); $form->addButtonFilter(get_lang('Filter')); $form->addHidden('from', ''); $form->addHidden('until', ''); $form->setDefaults(['course' => $selectedCourse, 'session' => $selectedSession, 'teacher' => $selectedTeacher, 'date_range' => "{$selectedFrom} / {$selectedUntil}", 'from' => $selectedFrom, 'until' => $selectedUntil]); $tpl = new Template($toolName); $tpl->assign('reportTitle', $reportTitle); $tpl->assign('reportSubTitle', $reportSubTitle); $tpl->assign('selectedCourse', $selectedCourse); $tpl->assign('selectedSession', $selectedSession); $tpl->assign('selectedTeacher', $selectedTeacher); $tpl->assign('selectedFrom', $selectedFrom); $tpl->assign('selectedUntil', $selectedUntil); $tpl->assign('withFilter', $withFilter); $tpl->assign('courses', $courseList); $tpl->assign('sessions', $sessionsList); $tpl->assign('courseCoaches', $teacherList); $tpl->assign('form', $form->returnForm()); $tpl->assign('rows', $timeReport->data); $contentTemplate = $tpl->get_template('admin/teacher_time_report.tpl'); $tpl->display($contentTemplate);
$group_id ); $social_menu_block = SocialManager::show_social_menu('member_list', $group_id); if (!empty($show_message)) { $social_right_content .= Display::return_message( $show_message, 'confirmation' ); } $social_right_content .= MessageManager::display_message_for_group( $group_id, $topic_id, $is_member, $message_id ); $social_right_content = '<div class="span9">' . $social_right_content . '</div>'; $tpl = new Template($tool_name); $tpl->set_help('Groups'); $tpl->assign('social_avatar_block', $social_avatar_block); $tpl->assign('social_menu_block', $social_menu_block); $tpl->assign('social_right_content', $social_right_content); $tpl->assign('actions', $actions); $tpl->assign('message', $show_message); $tpl->assign('content', $content); $social_layout = $tpl->get_template('layout/social_layout.tpl'); $tpl->display($social_layout);
$sessionList[$session->getId()] = $session; } if ($currentSession && !$allowAccess) { api_not_allowed(true); } $template = new Template($nameTools); $template->assign('user', $user); $template->assign('user_avatar', SocialManager::show_social_avatar_block('home', 0, $user->getId())); $template->assign('gamification_stars', GamificationUtils::getTotalUserStars($user->getId(), $user->getStatus())); $template->assign('gamification_points', GamificationUtils::getTotalUserPoints($user->getId(), $user->getStatus())); $template->assign('gamification_progress', GamificationUtils::getTotalUserProgress($user->getId(), $user->getStatus())); $template->assign('sessions', $sessionList); $template->assign('current_session', $currentSession); if ($currentSession) { $sessionData = []; $sessionCourses = $currentSession->getCourses(); foreach ($sessionCourses as $sessionCourse) { $course = $sessionCourse->getCourse(); $courseData = ['title' => $course->getTitle(), 'stats' => []]; $learningPathList = new LearnpathList($user->getId(), $course->getCode(), $currentSession->getId()); foreach ($learningPathList->list as $learningPathId => $learningPath) { $courseData['stats'][] = [$learningPath['lp_name'], 'newscorm/lp_controller.php?' . http_build_query(['action' => 'stats', 'cidReq' => $course->getCode(), 'id_session' => $currentSession->getId(), 'gidReq' => 0, 'lp_id' => $learningPathId]) . api_get_cidreq()]; } $sessionData[$course->getId()] = $courseData; } $template->assign('session_data', $sessionData); } $layout = $template->get_template('gamification/my_progress.tpl'); $template->assign('header', $nameTools); $template->assign('content', $template->fetch($layout)); $template->display_one_col_template();