Update from 1.11.x

pull/3006/head
Julio Montoya 6 years ago
parent 15378b6c1f
commit c9c07a4d6d
  1. 2
      main/gradebook/lib/be/evaluation.class.php
  2. 2
      main/inc/ajax/message.ajax.php
  3. 1
      main/inc/lib/api.lib.php
  4. 44
      main/inc/lib/course.lib.php
  5. 88
      main/inc/lib/events.lib.php
  6. 60
      main/inc/lib/exercise.lib.php
  7. 38
      main/inc/lib/exercise_show_functions.lib.php
  8. 37
      main/inc/lib/internationalization.lib.php
  9. 533
      main/inc/lib/message.lib.php
  10. 89
      main/inc/lib/social.lib.php
  11. 35
      main/inc/lib/sortable_table.class.php
  12. 53
      main/inc/lib/text.lib.php
  13. 174
      main/inc/lib/tracking.lib.php
  14. 18
      main/inc/lib/usermanager.lib.php
  15. 23
      main/inc/lib/userportal.lib.php
  16. 28
      main/lp/learnpath.class.php
  17. 266
      main/lp/learnpathItem.class.php
  18. 2
      main/lp/lp_ajax_switch_item.php
  19. 2
      main/lp/lp_edit.php
  20. 2
      main/lp/lp_list.php
  21. 16
      main/lp/lp_view.php
  22. 45
      main/messages/inbox.php
  23. 99
      main/messages/new_message.php
  24. 82
      main/messages/outbox.php
  25. 2
      main/messages/view_message.php
  26. 244
      main/mySpace/access_details_session.php
  27. 3
      main/mySpace/myStudents.php
  28. 2
      main/session/add_users_to_session.php
  29. 8
      main/session/session_edit.php
  30. 2
      main/social/download.php
  31. 9
      main/social/home.php
  32. 12
      main/social/profile.php

@ -408,7 +408,7 @@ class Evaluation implements GradebookItem
{
$table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
$sql = 'DELETE FROM '.$table.'
WHERE id = '.intval($this->id);
WHERE id = '.$this->get_id();
Database::query($sql);
}

@ -163,7 +163,7 @@ switch ($action) {
'id' => $user->getId(),
];
}
header("Content-type:application/json");
header('Content-type:application/json');
echo json_encode($return);
break;
default:

@ -2307,6 +2307,7 @@ function api_format_course_array($course_data)
$_course['registration_code'] = !empty($course_data['registration_code']) ? sha1($course_data['registration_code']) : null;
$_course['disk_quota'] = $course_data['disk_quota'];
$_course['course_public_url'] = $webCourseHome.'/index.php';
$_course['course_sys_path'] = $courseSys.'/';
if (array_key_exists('add_teachers_to_sessions_courses', $course_data)) {
$_course['add_teachers_to_sessions_courses'] = $course_data['add_teachers_to_sessions_courses'];

@ -6387,6 +6387,50 @@ class CourseManager
return api_get_path(WEB_COURSE_PATH).$course->getDirectory().'/course-pic85x85.png';
}
/**
* @return int
*/
public static function getCountOpenCourses()
{
$visibility = [
COURSE_VISIBILITY_REGISTERED,
COURSE_VISIBILITY_OPEN_PLATFORM,
COURSE_VISIBILITY_OPEN_WORLD,
];
$table = Database::get_main_table(TABLE_MAIN_COURSE);
$sql = "SELECT count(id) count
FROM $table
WHERE visibility IN (".implode(',', $visibility).")";
$result = Database::query($sql);
$row = Database::fetch_array($result);
return (int) $row['count'];
}
/**
* @return int
*/
public static function getCountExercisesFromOpenCourse()
{
$visibility = [
COURSE_VISIBILITY_REGISTERED,
COURSE_VISIBILITY_OPEN_PLATFORM,
COURSE_VISIBILITY_OPEN_WORLD,
];
$table = Database::get_main_table(TABLE_MAIN_COURSE);
$tableExercise = Database::get_course_table(TABLE_QUIZ_TEST);
$sql = "SELECT count(e.iid) count
FROM $table c INNER JOIN $tableExercise e
ON (c.id = e.c_id)
WHERE e.active <> -1 AND visibility IN (".implode(',', $visibility).")";
$result = Database::query($sql);
$row = Database::fetch_array($result);
return (int) $row['count'];
}
/**
* @param ToolChain $toolList
*/

@ -58,9 +58,35 @@ class Event
return true;
}
/**
* @param int $sessionId
*
* @return bool
*/
public static function isSessionLogNeedToBeSave($sessionId)
{
if (!empty($sessionId)) {
$visibility = api_get_session_visibility($sessionId);
if (!empty($visibility) && $visibility != SESSION_AVAILABLE) {
$extraFieldValue = new ExtraFieldValue('session');
$value = $extraFieldValue->get_values_by_handler_and_field_variable(
$sessionId,
'disable_log_after_session_ends'
);
if (!empty($value) && isset($value['value']) && (int) $value['value'] == 1) {
return false;
}
}
}
return true;
}
/**
* @author Sebastien Piraux <piraux_seb@hotmail.com>
* @desc Record information for access event for courses
*
* @return bool
*/
public static function accessCourse()
{
@ -69,22 +95,26 @@ class Event
}
$TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
//for "what's new" notification
// For "what's new" notification
$TABLETRACK_LASTACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
$id_session = api_get_session_id();
$sessionId = api_get_session_id();
$now = api_get_utc_datetime();
$courseId = api_get_course_int_id();
$userId = api_get_user_id();
$ip = Database::escape_string(api_get_real_ip());
if (self::isSessionLogNeedToBeSave($sessionId) === false) {
return false;
}
if ($userId) {
$userId = $userId;
} else {
$userId = "0"; // no one
$userId = '0'; // no one
}
$sql = "INSERT INTO $TABLETRACK_ACCESS (user_ip, access_user_id, c_id, access_date, access_session_id)
VALUES ('$ip', $userId, $courseId, '$now', $id_session)";
VALUES ('$ip', $userId, $courseId, '$now', $sessionId)";
Database::query($sql);
@ -94,16 +124,16 @@ class Event
access_user_id = $userId AND
c_id = $courseId AND
access_tool IS NULL AND
access_session_id = $id_session";
access_session_id = $sessionId";
$result = Database::query($sql);
if (Database::affected_rows($result) == 0) {
$sql = "INSERT INTO $TABLETRACK_LASTACCESS (access_user_id, c_id, access_date, access_session_id)
VALUES ($userId, $courseId, '$now', $id_session)";
VALUES ($userId, $courseId, '$now', $sessionId)";
Database::query($sql);
}
return 1;
return true;
}
/**
@ -143,6 +173,11 @@ class Event
if (empty($courseInfo)) {
return false;
}
if (self::isSessionLogNeedToBeSave($sessionId) === false) {
return false;
}
$courseId = $courseInfo['real_id'];
$tableAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
@ -1794,6 +1829,12 @@ class Event
if (Session::read('login_as')) {
return false;
}
$sessionId = (int) $sessionId;
if (self::isSessionLogNeedToBeSave($sessionId) === false) {
return false;
}
$table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
$loginDate = $logoutDate = api_get_utc_datetime();
@ -1801,7 +1842,6 @@ class Event
$counter = 1;
$courseId = (int) $courseId;
$user_id = (int) $user_id;
$sessionId = (int) $sessionId;
$ip = Database::escape_string(api_get_real_ip());
$sql = "INSERT INTO $table(c_id, user_ip, user_id, login_course_date, logout_course_date, counter, session_id)
@ -1848,9 +1888,14 @@ class Event
return false;
}
$sessionId = (int) $sessionId;
if (self::isSessionLogNeedToBeSave($sessionId) === false) {
return false;
}
$courseId = (int) $courseId;
$userId = (int) $userId;
$sessionId = (int) $sessionId;
$table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
$sql = "SELECT course_access_id, logout_course_date
@ -1920,13 +1965,19 @@ class Event
$sessionLifetime = 3600; // 1 hour
}
if (!empty($logoutInfo) && !empty($logoutInfo['cid'])) {
$tableCourseAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
$userId = (int) $logoutInfo['uid'];
$courseId = (int) $logoutInfo['cid'];
$sessionId = 0;
if (!empty($logoutInfo['sid'])) {
$sessionId = (int) $logoutInfo['sid'];
}
if (self::isSessionLogNeedToBeSave($sessionId) === false) {
return false;
}
$tableCourseAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
$userId = (int) $logoutInfo['uid'];
$courseId = (int) $logoutInfo['cid'];
$currentDate = api_get_utc_datetime();
// UTC time
$diff = time() - $sessionLifetime;
@ -2096,7 +2147,14 @@ class Event
*/
public static function registerLog($logInfo)
{
if (!Tracking::minimunTimeAvailable(api_get_session_id(), api_get_course_int_id())) {
$sessionId = api_get_session_id();
$courseId = api_get_course_int_id();
if (!Tracking::minimumTimeAvailable($sessionId, $courseId)) {
return false;
}
if (self::isSessionLogNeedToBeSave($sessionId) === false) {
return false;
}
@ -2111,8 +2169,8 @@ class Event
$logInfo['action_details'] = !empty($logInfo['action_details']) ? $logInfo['action_details'] : '';
$logInfo['ip_user'] = api_get_real_ip();
$logInfo['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
$logInfo['session_id'] = api_get_session_id();
$logInfo['c_id'] = api_get_course_int_id();
$logInfo['session_id'] = $sessionId;
$logInfo['c_id'] = $courseId;
$logInfo['ch_sid'] = session_id();
$logInfo['login_as'] = $loginAs;
$logInfo['info'] = !empty($logInfo['info']) ? $logInfo['info'] : '';

@ -2828,6 +2828,7 @@ HOTSPOT;
$score = $result['score'];
$weight = $result['weight'];
}
$percentage = (100 * $score) / ($weight != 0 ? $weight : 1);
// Formats values
$percentage = float_format($percentage, 1);
@ -2885,6 +2886,13 @@ HOTSPOT;
$html = $scoreBasedInModel;
}
// Ignore other formats and use the configuratio['exercise_score_format'] value
// But also keep the round values settings.
$format = api_get_configuration_value('exercise_score_format');
if (!empty($format)) {
$html = ScoreDisplay::instance()->display_score([$score, $weight], $format);
}
$html = Display::span($html, ['class' => 'score_exercise']);
return $html;
@ -3184,17 +3192,16 @@ EOT;
}
$now = api_get_utc_datetime();
$time_conditions = '';
$timeConditions = '';
if ($check_publication_dates) {
//start and end are set
$time_conditions = " AND ((start_time <> '' AND start_time < '$now' AND end_time <> '' AND end_time > '$now' ) OR ";
// Start and end are set
$timeConditions = " AND ((start_time <> '' AND start_time < '$now' AND end_time <> '' AND end_time > '$now' ) OR ";
// only start is set
$time_conditions .= " (start_time <> '' AND start_time < '$now' AND end_time is NULL) OR ";
$timeConditions .= " (start_time <> '' AND start_time < '$now' AND end_time is NULL) OR ";
// only end is set
$time_conditions .= " (start_time IS NULL AND end_time <> '' AND end_time > '$now') OR ";
$timeConditions .= " (start_time IS NULL AND end_time <> '' AND end_time > '$now') OR ";
// nothing is set
$time_conditions .= ' (start_time IS NULL AND end_time IS NULL)) ';
$timeConditions .= ' (start_time IS NULL AND end_time IS NULL)) ';
}
$needle_where = !empty($search) ? " AND title LIKE '?' " : '';
@ -3213,7 +3220,7 @@ EOT;
if ($search_all_sessions == true) {
$conditions = [
'where' => [
$active_sql.' c_id = ? '.$needle_where.$time_conditions => [
$active_sql.' c_id = ? '.$needle_where.$timeConditions => [
$course_id,
$needle,
],
@ -3224,7 +3231,7 @@ EOT;
if (empty($session_id)) {
$conditions = [
'where' => [
$active_sql.' (session_id = 0 OR session_id IS NULL) AND c_id = ? '.$needle_where.$time_conditions => [
$active_sql.' (session_id = 0 OR session_id IS NULL) AND c_id = ? '.$needle_where.$timeConditions => [
$course_id,
$needle,
],
@ -3234,7 +3241,7 @@ EOT;
} else {
$conditions = [
'where' => [
$active_sql.' (session_id = 0 OR session_id IS NULL OR session_id = ? ) AND c_id = ? '.$needle_where.$time_conditions => [
$active_sql.' (session_id = 0 OR session_id IS NULL OR session_id = ? ) AND c_id = ? '.$needle_where.$timeConditions => [
$session_id,
$course_id,
$needle,
@ -3250,32 +3257,6 @@ EOT;
return Database::select('*', $table, $conditions);
}
/**
* Get exercise information by id.
*
* @param int $exerciseId Exercise Id
* @param int $courseId The course ID (necessary as c_quiz.id is not unique)
*
* @return array Exercise info
*/
public static function get_exercise_by_id($exerciseId = 0, $courseId = 0)
{
$table = Database::get_course_table(TABLE_QUIZ_TEST);
if (empty($courseId)) {
$courseId = api_get_course_int_id();
} else {
$courseId = intval($courseId);
}
$conditions = [
'where' => [
'id = ?' => [$exerciseId],
' AND c_id = ? ' => $courseId,
],
];
return Database::select('*', $table, $conditions);
}
/**
* Getting all exercises (active only or all)
* from a course from a session
@ -3790,10 +3771,10 @@ EOT;
$track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
$track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
$question_id = intval($question_id);
$exercise_id = intval($exercise_id);
$question_id = (int) $question_id;
$exercise_id = (int) $exercise_id;
$course_code = Database::escape_string($course_code);
$session_id = intval($session_id);
$session_id = (int) $session_id;
$courseId = api_get_course_int_id($course_code);
$sql = "SELECT MAX(marks) as max, MIN(marks) as min, AVG(marks) as average
@ -5061,7 +5042,6 @@ EOT;
$ribbon .= '<h3>'.get_lang('YourTotalScore').':&nbsp;';
$ribbon .= self::show_score($score, $weight, false, true);
$ribbon .= '</h3>';
$ribbon .= '</div>';
}

@ -339,23 +339,12 @@ class ExerciseShowFunctions
$studentChoiceInt = (int) $studentChoice;
$answerCorrectChoice = (int) $answerCorrect;
$hideStudentChoice = false;
$hide_expected_answer = false;
$status = '';
if ($exercise->showExpectedChoice()) {
$status = Display::label(get_lang('Incorrect'), 'danger');
if ($answerCorrect || ($answerCorrect && $studentChoiceInt === $answerCorrectChoice)) {
$status = Display::label(get_lang('Correct'), 'success');
}
}
$hide_expected_answer = false;
$showComment = false;
switch ($resultsDisabled) {
case RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER:
$hideStudentChoice = false;
$hide_expected_answer = true;
$status = Display::label(get_lang('Correct'), 'success');
$showComment = true;
if (!$answerCorrect && empty($studentChoice)) {
return '';
@ -397,17 +386,20 @@ class ExerciseShowFunctions
}
echo '<tr class="'.$studentChoiceClass.'">';
if ($hideStudentChoice === false) {
echo '<td width="5%">';
echo Display::return_icon($icon, null, null, ICON_SIZE_TINY);
echo '</td>';
}
if (!$hide_expected_answer) {
if ($exercise->showExpectedChoiceColumn()) {
echo '<td width="5%">';
echo Display::return_icon($icon, null, null, ICON_SIZE_TINY);
echo '</td>';
if ($exercise->showExpectedChoiceColumn()) {
if ($hide_expected_answer === false) {
echo '<td width="5%">';
echo Display::return_icon($iconAnswer, null, null, ICON_SIZE_TINY);
echo '</td>';
} else {
echo '<td width="5%">';
echo '-';
echo '</td>';
}
}
@ -416,6 +408,10 @@ class ExerciseShowFunctions
echo '</td>';
if ($exercise->showExpectedChoice()) {
$status = Display::label(get_lang('Incorrect'), 'danger');
if ($answerCorrect || ($answerCorrect && $studentChoiceInt === $answerCorrectChoice)) {
$status = Display::label(get_lang('Correct'), 'success');
}
echo '<td width="20%">';
echo $status;
echo '</td>';
@ -510,8 +506,8 @@ class ExerciseShowFunctions
}
// Expected choice
if (!$hide_expected_answer) {
if ($exercise->showExpectedChoiceColumn()) {
if ($exercise->showExpectedChoiceColumn()) {
if (!$hide_expected_answer) {
$content .= '<td width="5%">';
if (isset($new_options[$answerCorrect])) {
$content .= get_lang($new_options[$answerCorrect]['name']);

@ -272,13 +272,12 @@ function api_get_timezone()
* Returns the given date as a DATETIME in UTC timezone.
* This function should be used before entering any date in the DB.
*
* @param mixed $time date to be converted (can be a string supported by date() or a timestamp)
* @param bool $returnNullIfInvalidDate if the date is not correct return null instead of the current date
* @param bool $returnObj
* @param mixed $time Date to be converted (can be a string supported by date() or a timestamp)
* @param bool $returnNullIfInvalidDate If the date is not correct return null instead of the current date
* @param bool $returnObj Returns a DateTime object
*
* @return string|DateTime The DATETIME in UTC to be inserted in the DB,
* or null if the format of the argument is not supported
* or datetime
*
* @author Julio Montoya - Adding the 2nd parameter
* @author Guillaume Viguier <guillaume.viguier@beeznest.com>
@ -315,8 +314,6 @@ function api_get_utc_datetime(
return $date->format('Y-m-d H:i:s');
}
} catch (Exception $e) {
error_log($e->getMessage());
return null;
}
}
@ -324,11 +321,15 @@ function api_get_utc_datetime(
/**
* Returns a DATETIME string converted to the right timezone.
*
* @param mixed The time to be converted
* @param string The timezone to be converted to.
* If null, the timezone will be determined based on user preference,
* or timezone chosen by the admin for the platform.
* @param string The timezone to be converted from. If null, UTC will be assumed.
* @param mixed $time The time to be converted
* @param string $to_timezone The timezone to be converted to.
* If null, the timezone will be determined based on user preference,
* or timezone chosen by the admin for the platform.
* @param string $from_timezone The timezone to be converted from. If null, UTC will be assumed.
* @param bool $returnNullIfInvalidDate
* @param bool $showTime
* @param bool $humanForm
* @param string $format
*
* @return string The converted time formatted as Y-m-d H:i:s
*
@ -338,9 +339,10 @@ function api_get_local_time(
$time = null,
$to_timezone = null,
$from_timezone = null,
$return_null_if_invalid_date = false,
$returnNullIfInvalidDate = false,
$showTime = true,
$humanForm = false
$humanForm = false,
$format = ''
) {
// Determining the timezone to be converted from
if (is_null($from_timezone)) {
@ -349,7 +351,7 @@ function api_get_local_time(
// If time is a timestamp, convert it to a string
if (is_null($time) || empty($time) || $time == '0000-00-00 00:00:00') {
if ($return_null_if_invalid_date) {
if ($returnNullIfInvalidDate) {
return null;
}
$from_timezone = 'UTC';
@ -358,7 +360,7 @@ function api_get_local_time(
if (is_numeric($time)) {
$time = (int) $time;
if ($return_null_if_invalid_date) {
if ($returnNullIfInvalidDate) {
if (strtotime(date('d-m-Y H:i:s', $time)) !== (int) $time) {
return null;
}
@ -367,6 +369,7 @@ function api_get_local_time(
$from_timezone = 'UTC';
$time = gmdate('Y-m-d H:i:s', $time);
}
if ($time instanceof DateTime) {
$time = $time->format('Y-m-d H:i:s');
$from_timezone = 'UTC';
@ -381,6 +384,10 @@ function api_get_local_time(
$date = new DateTime($time, new DateTimezone($from_timezone));
$date->setTimezone(new DateTimeZone($to_timezone));
if (!empty($format)) {
return $date->format($format);
}
return api_get_human_date_time($date, $showTime, $humanForm);
} catch (Exception $e) {
return '';

@ -49,49 +49,40 @@ class MessageManager
/**
* Gets the total number of messages, used for the inbox sortable table.
*
* @param bool $unread
* @param bool $listRead
* @param array $params
*
* @return int
*/
public static function getNumberOfMessages($unread = false, $listRead = false)
public static function getNumberOfMessages($params = [])
{
$table = Database::get_main_table(TABLE_MESSAGE);
$list = null;
if ($unread) {
$condition_msg_status = ' msg_status = '.MESSAGE_STATUS_UNREAD.' ';
} else {
$condition_msg_status = ' msg_status IN('.MESSAGE_STATUS_NEW.','.MESSAGE_STATUS_UNREAD.') ';
$messageStatus = [MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD];
if (isset($params['message_status']) && !empty($params['message_status'])) {
$messageStatus = $params['message_status'];
}
$messageStatus = array_map('intval', $messageStatus);
$messageStatusCondition = implode("','", $messageStatus);
$table = Database::get_main_table(TABLE_MESSAGE);
$keyword = isset($params['keyword']) ? $params['keyword'] : '';
$keyword = Session::read('message_search_keyword');
$keywordCondition = '';
if (!empty($keyword)) {
$keyword = Database::escape_string($keyword);
$keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
}
if ($listRead) {
$sql = "SELECT * ";
} else {
$sql = "SELECT COUNT(id) as number_messages ";
}
$sql .= " FROM $table
WHERE $condition_msg_status AND
user_receiver_id=".api_get_user_id()."
$sql = "SELECT COUNT(id) as number_messages
FROM $table
WHERE
msg_status IN ('$messageStatusCondition') AND
user_receiver_id = ".api_get_user_id()."
$keywordCondition
";
$result = Database::query($sql);
if ($listRead) {
while ($row = Database::fetch_array($result, 'ASSOC')) {
$list[] = $row;
}
$result = Database::fetch_array($result);
return $list;
} else {
$count = Database::fetch_array($result);
if ($result) {
return (int) $count['number_messages'];
}
if ($result) {
return (int) $result['number_messages'];
}
return 0;
@ -101,23 +92,23 @@ class MessageManager
* Gets information about some messages, used for the inbox sortable table.
*
* @param int $from
* @param int $number_of_items
* @param int $numberOfItems
* @param string $column
* @param string $direction
* @param int $userId
* @param array $extraParams
*
* @return array
*/
public static function get_message_data(
public static function getMessageData(
$from,
$number_of_items,
$numberOfItems,
$column,
$direction,
$userId = 0
$extraParams = []
) {
$from = (int) $from;
$number_of_items = (int) $number_of_items;
$userId = empty($userId) ? api_get_user_id() : (int) $userId;
$numberOfItems = (int) $numberOfItems;
$userId = api_get_user_id();
// Forcing this order.
if (!isset($direction)) {
@ -134,13 +125,22 @@ class MessageManager
$column = 2;
}
$keyword = Session::read('message_search_keyword');
$keyword = isset($extraParams['keyword']) ? $extraParams['keyword'] : '';
$viewUrl = isset($extraParams['view_url']) ? $extraParams['view_url'] : api_get_path(WEB_CODE_PATH).'message/view_message.php';
$keywordCondition = '';
if (!empty($keyword)) {
$keyword = Database::escape_string($keyword);
$keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
}
$messageStatus = [MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD];
if (isset($extraParams['message_status']) && !empty($extraParams['message_status'])) {
$messageStatus = $extraParams['message_status'];
}
$messageStatus = array_map('intval', $messageStatus);
$messageStatusCondition = implode("','", $messageStatus);
$table = Database::get_main_table(TABLE_MESSAGE);
$sql = "SELECT
id as col0,
@ -150,15 +150,18 @@ class MessageManager
user_sender_id
FROM $table
WHERE
user_receiver_id=".$userId." AND
msg_status IN (".MESSAGE_STATUS_NEW.", ".MESSAGE_STATUS_UNREAD.")
user_receiver_id = $userId AND
msg_status IN ('$messageStatusCondition')
$keywordCondition
ORDER BY col$column $direction
LIMIT $from, $number_of_items";
LIMIT $from, $numberOfItems";
$result = Database::query($sql);
$messageList = [];
$newMessageLink = api_get_path(WEB_CODE_PATH).'messages/new_message.php';
$actions = $extraParams['actions'];
$url = api_get_self();
while ($row = Database::fetch_array($result, 'ASSOC')) {
$messageId = $row['col0'];
$title = $row['col1'];
@ -175,45 +178,65 @@ class MessageManager
}
$userInfo = api_get_user_info($senderId);
$message[3] = '';
if (!empty($senderId) && !empty($userInfo)) {
$message[1] = '<img class="rounded-circle mr-2" src="'.$userInfo['avatar_small'].'"/>';
$message[1] = '<a '.$class.' href="'.$viewUrl.'?id='.$messageId.'">'.$title.'</a><br />';
$message[1] .= $userInfo['complete_name_with_username'];
$message[2] = '<a '.$class.' href="view_message.php?id='.$messageId.'">'.$title.'</a>';
$message[4] = '<div class="btn-group" role="group">'.
Display::url(
Display::returnFontAwesomeIcon('reply', 'sm'),
$newMessageLink.'?re_id='.$messageId,
['title' => get_lang('ReplyToMessage'), 'class' => 'btn btn-outline-secondary btn-sm']
);
if (in_array('reply', $actions)) {
$message[3] =
Display::url(
Display::returnFontAwesomeIcon('reply', 2),
$newMessageLink.'?re_id='.$messageId,
['title' => get_lang('ReplyToMessage')]
);
}
} else {
$message[1] = '<img class="rounded-circle" src="'.$userInfo['avatar_small'].'"/>';
$message[1] = '<a '.$class.' href="'.$viewUrl.'?id='.$messageId.'">'.$title.'</a><br />';
$message[1] .= get_lang('UnknownUser');
if (in_array('reply', $actions)) {
$message[3] =
Display::url(
Display::returnFontAwesomeIcon('reply', 2),
'#',
['title' => get_lang('ReplyToMessage')]
);
}
}
$message[2] = '<a '.$class.' href="view_message.php?id='.$messageId.'">'.$title.'</a>';
$message[0] = $messageId;
$message[2] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
$message[4] = '<div class="btn-group" role="group">'.
// Actions
if (in_array('edit', $actions)) {
$message[3] .=
'&nbsp;&nbsp;'.
Display::url(
Display::returnFontAwesomeIcon('reply', 'sm'),
'#',
['title' => get_lang('ReplyToMessage'), 'class' => 'btn btn-outline-secondary btn-sm']
Display::returnFontAwesomeIcon('pencil', 2),
$newMessageLink.'?action=edit&id='.$messageId,
['title' => get_lang('ForwardMessage')]
);
}
$message[0] = $messageId;
$message[3] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
$message[4] .=
Display::url(
Display::returnFontAwesomeIcon('share', 'sm'),
$newMessageLink.'?forward_id='.$messageId,
['title' => get_lang('ForwardMessage'), 'class' => 'btn btn-outline-secondary btn-sm']
).
'<a class="btn btn-outline-secondary btn-sm" title="'.addslashes(
// Actions
if (in_array('forward', $actions)) {
$message[3] .=
'&nbsp;&nbsp;'.
Display::url(
Display::returnFontAwesomeIcon('share', 2),
$newMessageLink.'?forward_id='.$messageId,
['title' => get_lang('ForwardMessage')]
);
}
if (in_array('delete', $actions)) {
$message[3] .= '&nbsp;&nbsp;<a title="'.addslashes(
get_lang('DeleteMessage')
).'" onclick="javascript:if(!confirm('."'".addslashes(
api_htmlentities(get_lang('ConfirmDeleteMessage'))
)."'".')) return false;" href="inbox.php?action=deleteone&id='.$messageId.'">'.
Display::returnFontAwesomeIcon('trash', 'sm').'</a></div>';
)."'".')) return false;" href="'.$url.'?action=deleteone&id='.$messageId.'">'.
Display::returnFontAwesomeIcon('trash', 2).'</a>';
}
foreach ($message as $key => $value) {
$message[$key] = api_xml_http_response_encode($value);
}
@ -404,7 +427,8 @@ class MessageManager
$forwardId = 0,
$smsParameters = [],
$checkCurrentAudioId = false,
$forceTitleWhenSendingEmail = false
$forceTitleWhenSendingEmail = false,
$status = 0
) {
$table = Database::get_main_table(TABLE_MESSAGE);
$group_id = (int) $group_id;
@ -413,6 +437,8 @@ class MessageManager
$editMessageId = (int) $editMessageId;
$topic_id = (int) $topic_id;
$status = empty($status) ? MESSAGE_STATUS_UNREAD : (int) $status;
if (!empty($receiver_user_id)) {
$receiverUserInfo = api_get_user_info($receiver_user_id);
@ -505,7 +531,7 @@ class MessageManager
} else {
$params = [
'user_sender_id' => $user_sender_id,
'msg_status' => MESSAGE_STATUS_UNREAD,
'msg_status' => $status,
'send_date' => $now,
'title' => $subject,
'content' => $content,
@ -555,8 +581,8 @@ class MessageManager
}
}
if (empty($group_id)) {
// message in outbox for user friend or group
// Save message in the outbox for user friend or group.
if (empty($group_id) && $status == MESSAGE_STATUS_UNREAD) {
$params = [
'user_sender_id' => $user_sender_id,
'user_receiver_id' => $receiver_user_id,
@ -780,30 +806,32 @@ class MessageManager
public static function delete_message_by_user_receiver($user_receiver_id, $id)
{
$table = Database::get_main_table(TABLE_MESSAGE);
if ($id != strval(intval($id))) {
return false;
}
$id = (int) $id;
$user_receiver_id = (int) $user_receiver_id;
if (empty($id) || empty($user_receiver_id)) {
return false;
}
$sql = "SELECT * FROM $table
WHERE id = ".$id." AND msg_status <>".MESSAGE_STATUS_OUTBOX;
WHERE id = $id AND msg_status <> ".MESSAGE_STATUS_OUTBOX;
$rs = Database::query($sql);
if (Database::num_rows($rs) > 0) {
// delete attachment file
// Delete attachment file.
self::delete_message_attachment_file($id, $user_receiver_id);
// delete message
// Soft delete message.
$query = "UPDATE $table
SET msg_status = ".MESSAGE_STATUS_DELETED."
WHERE
user_receiver_id=".$user_receiver_id." AND
id = ".$id;
WHERE
id = $id AND
user_receiver_id = $user_receiver_id ";
Database::query($query);
return true;
} else {
return false;
}
return false;
}
/**
@ -834,7 +862,7 @@ class MessageManager
// delete attachment file
self::delete_message_attachment_file($id, $user_sender_id);
// delete message
$sql = "UPDATE $table
$sql = "UPDATE $table
SET msg_status = ".MESSAGE_STATUS_DELETED."
WHERE user_sender_id='$user_sender_id' AND id='$id'";
Database::query($sql);
@ -950,12 +978,12 @@ class MessageManager
$message_uid = (int) $message_uid;
$table_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
$sql = "SELECT * FROM $table_message_attach
$sql = "SELECT * FROM $table_message_attach
WHERE message_id = '$message_id'";
$rs = Database::query($sql);
while ($row = Database::fetch_array($rs)) {
$path = $row['path'];
$attach_id = $row['id'];
$attach_id = (int) $row['id'];
$new_path = $path.'_DELETED_'.$attach_id;
if (!empty($group_id)) {
@ -975,8 +1003,9 @@ class MessageManager
$path_message_attach = $path_user_info['dir'].'message_attachments/';
if (is_file($path_message_attach.$path)) {
if (rename($path_message_attach.$path, $path_message_attach.$new_path)) {
$sql = "UPDATE $table_message_attach set path='$new_path'
WHERE id ='$attach_id'";
$sql = "UPDATE $table_message_attach
SET path = '$new_path'
WHERE id = $attach_id ";
Database::query($sql);
}
}
@ -1018,12 +1047,13 @@ class MessageManager
*/
public static function get_messages_by_group($group_id)
{
if ($group_id != strval(intval($group_id))) {
$group_id = (int) $group_id;
if (empty($group_id)) {
return false;
}
$table = Database::get_main_table(TABLE_MESSAGE);
$group_id = intval($group_id);
$sql = "SELECT * FROM $table
WHERE
group_id= $group_id AND
@ -1050,11 +1080,13 @@ class MessageManager
*/
public static function get_messages_by_group_by_message($group_id, $message_id)
{
if ($group_id != strval(intval($group_id))) {
$group_id = (int) $group_id;
if (empty($group_id)) {
return false;
}
$table = Database::get_main_table(TABLE_MESSAGE);
$group_id = intval($group_id);
$sql = "SELECT * FROM $table
WHERE
group_id = $group_id AND
@ -1112,7 +1144,7 @@ class MessageManager
$sql = "SELECT * FROM $table
WHERE
parent_id='$parentId' AND
msg_status NOT IN (".MESSAGE_STATUS_OUTBOX.", ".MESSAGE_STATUS_WALL_DELETE.")
msg_status NOT IN (".MESSAGE_STATUS_OUTBOX.", ".MESSAGE_STATUS_WALL_DELETE.")
$condition_group_id
ORDER BY send_date DESC $condition_limit ";
$rs = Database::query($sql);
@ -1138,12 +1170,13 @@ class MessageManager
*/
public static function get_message_data_sent(
$from,
$number_of_items,
$numberOfItems,
$column,
$direction
$direction,
$extraParams = []
) {
$from = (int) $from;
$number_of_items = (int) $number_of_items;
$numberOfItems = (int) $numberOfItems;
if (!isset($direction)) {
$column = 2;
$direction = 'DESC';
@ -1159,7 +1192,7 @@ class MessageManager
}
$table = Database::get_main_table(TABLE_MESSAGE);
$request = api_is_xml_http_request();
$keyword = Session::read('message_sent_search_keyword');
$keyword = isset($extraParams['keyword']) ? $extraParams['keyword'] : '';
$keywordCondition = '';
if (!empty($keyword)) {
$keyword = Database::escape_string($keyword);
@ -1167,10 +1200,10 @@ class MessageManager
}
$sql = "SELECT
id as col0,
title as col1,
send_date as col2,
user_receiver_id,
id as col0,
title as col1,
send_date as col2,
user_receiver_id,
msg_status,
user_sender_id
FROM $table
@ -1179,7 +1212,7 @@ class MessageManager
msg_status = ".MESSAGE_STATUS_OUTBOX."
$keywordCondition
ORDER BY col$column $direction
LIMIT $from, $number_of_items";
LIMIT $from, $numberOfItems";
$result = Database::query($sql);
$message_list = [];
@ -1187,7 +1220,6 @@ class MessageManager
$messageId = $row['col0'];
$title = $row['col1'];
$sendDate = $row['col2'];
$status = $row['msg_status'];
$senderId = $row['user_sender_id'];
if ($request === true) {
@ -1214,16 +1246,14 @@ class MessageManager
).'" onclick="delete_one_message_outbox('.$messageId.')" href="javascript:void(0)" >'.
Display::returnFontAwesomeIcon('trash', 2).'</a>';
} else {
$message[1] = '<img class="rounded-circle mr-2" src="'.$userInfo['avatar_small'].'"/>';
$message[1] .= $userInfo['complete_name_with_username'];
$message[2] = '<a '.$class.' onclick="show_sent_message('.$messageId.')" href="../messages/view_message.php?id_send='.$messageId.'">'.$title.'</a>';
$message[3] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
$message[4] = '<a class="btn btn-outline-secondary btn-sm" title="'.addslashes(
$message[1] = '<a '.$class.' onclick="show_sent_message('.$messageId.')" href="../messages/view_message.php?id_send='.$messageId.'">'.$title.'</a><br />'.$userInfo['complete_name_with_username'];
$message[2] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
$message[3] = '<a title="'.addslashes(
get_lang('DeleteMessage')
).'" href="outbox.php?action=deleteone&id='.$messageId.'" onclick="javascript:if(!confirm('."'".addslashes(
api_htmlentities(get_lang('ConfirmDeleteMessage'))
)."'".')) return false;" >'.
Display::returnFontAwesomeIcon('trash', 'fa-sm').'</a>';
Display::returnFontAwesomeIcon('trash', 2).'</a>';
}
$message_list[] = $message;
@ -1232,38 +1262,6 @@ class MessageManager
return $message_list;
}
/**
* Gets information about number messages sent.
*
* @author Isaac FLores Paz <isaac.flores@dokeos.com>
*
* @param void
*
* @return int
*/
public static function getNumberOfMessagesSent()
{
$table = Database::get_main_table(TABLE_MESSAGE);
$keyword = Session::read('message_sent_search_keyword');
$keywordCondition = '';
if (!empty($keyword)) {
$keyword = Database::escape_string($keyword);
$keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
}
$sql = "SELECT COUNT(id) as number_messages
FROM $table
WHERE
msg_status = ".MESSAGE_STATUS_OUTBOX." AND
user_sender_id = ".api_get_user_id()."
$keywordCondition
";
$result = Database::query($sql);
$result = Database::fetch_array($result);
return $result['number_messages'];
}
/**
* display message box in the inbox.
*
@ -1272,16 +1270,15 @@ class MessageManager
*
* @todo replace numbers with letters in the $row array pff...
*
* @return array the message content
* @return string html with the message content
*/
public static function showMessageBox($messageId, $source = 'inbox')
{
$table = Database::get_main_table(TABLE_MESSAGE);
$messageId = (int) $messageId;
$currentUserId = api_get_user_id();
$msg = [];
if ($source == 'outbox') {
if ($source === 'outbox') {
if (isset($messageId) && is_numeric($messageId)) {
$query = "SELECT * FROM $table
WHERE
@ -1310,65 +1307,126 @@ class MessageManager
$row = Database::fetch_array($result, 'ASSOC');
if (empty($row)) {
return $msg;
return '';
}
$user_sender_id = $row['user_sender_id'];
$msg['id'] = $row['id'];
$msg['status'] = $row['msg_status'];
$msg['user_id'] = $user_sender_id;
// get file attachments by message id
$files_attachments = self::getAttachmentLinkList(
$messageId,
$source
);
$msg['title'] = Security::remove_XSS($row['title'], STUDENT, true);
$msg['attachments'] = $files_attachments;
$contentMsg = str_replace('</br>', '<br />', $row['content']);
$content = Security::remove_XSS($contentMsg, STUDENT, true);
$msg['content'] = $content;
$fromUser = api_get_user_info($user_sender_id);
$row['content'] = str_replace('</br>', '<br />', $row['content']);
$title = Security::remove_XSS($row['title'], STUDENT, true);
$content = Security::remove_XSS($row['content'], STUDENT, true);
$name = get_lang('UnknownUser');
$fromUser = api_get_user_info($user_sender_id);
$userImage = '';
if (!empty($user_sender_id) && !empty($fromUser)) {
$msg['form_user'] = [
'id' => $fromUser['id'],
'name' => $fromUser['complete_name'],
'username' => $fromUser['username'],
'avatar' => $fromUser['avatar_small'],
'email' => $fromUser['email'],
];
$name = $fromUser['complete_name_with_username'];
$userImage = Display::img(
$fromUser['avatar_small'],
$name,
['title' => $name, 'class' => 'img-responsive img-circle', 'style' => 'max-width:35px'],
false
);
}
$msg['date'] = Display::dateToStringAgoAndLongDate($row['send_date']);
$message_content = Display::page_subheader(str_replace("\\", "", $title));
$receiverUserInfo = [];
if (!empty($row['user_receiver_id'])) {
$receiverUserInfo = api_get_user_info($row['user_receiver_id']);
$msg['receiver_user'] = [
'id' => $receiverUserInfo['id'],
'name' => $receiverUserInfo['complete_name'],
'username' => $receiverUserInfo['username'],
'avatar' => $receiverUserInfo['avatar'],
'email' => $receiverUserInfo['email'],
];
}
$urlMessage = [];
$message_content .= '<tr>';
if (api_get_setting('allow_social_tool') === 'true') {
$message_content .= '<div class="row">';
if ($source === 'outbox') {
$message_content .= '<div class="col-md-12">';
$message_content .= '<ul class="list-message">';
$message_content .= '<li>'.$userImage.'</li>';
$message_content .= '<li>'.$name.'&nbsp;';
if (!empty($receiverUserInfo)) {
$message_content .= api_strtolower(
get_lang('To')
).'&nbsp;<b>'.$receiverUserInfo['complete_name_with_username'].'</b></li>';
} else {
$message_content .= api_strtolower(get_lang('To')).'&nbsp;<b>-</b></li>';
}
$message_content .= '<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
$message_content .= '</ul>';
$message_content .= '</div>';
} else {
$message_content .= '<div class="col-md-12">';
$message_content .= '<ul class="list-message">';
if (!empty($user_sender_id)) {
$message_content .= '<li>'.$userImage.'</li>';
$message_content .= '<li><a href="'.api_get_path(
WEB_PATH
).'main/social/profile.php?u='.$user_sender_id.'">'.$name.'</a>';
} else {
$message_content .= '<li>'.$name;
}
if ($source === 'inbox') {
$message_content .= '&nbsp;'.api_strtolower(get_lang('To')).'&nbsp;'.get_lang('Me');
}
$message_content .= '<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
$message_content .= '</ul>';
$message_content .= '</div>';
}
$message_content .= '</div>';
} else {
if ($source === 'outbox') {
$message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
$receiverUserInfo['complete_name_with_username'].'</b>';
} else {
$message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
get_lang('Me').'</b>';
}
}
$message_content .= '
<hr style="color:#ddd" />
<table width="100%">
<tr>
<td valign=top class="view-message-content">'.str_replace("\\", "", $content).'</td>
</tr>
</table>
<div id="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>
<div style="padding: 15px 0px 5px 0px">';
$social_link = '';
if (isset($_GET['f']) && $_GET['f'] == 'social') {
$social_link = 'f=social';
}
if ($source == 'outbox') {
$urlMessage['return'] = 'outbox.php?'.$social_link;
} else {
$urlMessage['back'] = 'inbox.php?'.$social_link;
$urlMessage['new_message'] = 'new_message.php?re_id='.$messageId.'&'.$social_link;
$message_content .= '<a href="outbox.php?'.$social_link.'">'.
Display::return_icon('back.png', get_lang('ReturnToOutbox')).'</a> &nbsp';
} elseif ($source === 'inbox') {
$message_content .= '<a href="inbox.php?'.$social_link.'">'.
Display::return_icon('back.png', get_lang('ReturnToInbox')).'</a> &nbsp';
$message_content .= '<a href="new_message.php?re_id='.$messageId.'&'.$social_link.'">'.
Display::return_icon('message_reply.png', get_lang('ReplyToMessage')).'</a> &nbsp';
}
$urlMessage['delete'] = 'inbox.php?action=deleteone&id='.$messageId.'&'.$social_link;
$msg['url'] = $urlMessage;
if (in_array($source, ['inbox', 'outbox'])) {
$message_content .= '<a href="inbox.php?action=deleteone&id='.$messageId.'&'.$social_link.'" >'.
Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>&nbsp';
}
$message_content .= '</div></td>
<td width=10></td>
</tr>
</table>';
return $msg;
return $message_content;
}
/**
@ -1381,7 +1439,7 @@ class MessageManager
public static function get_user_id_by_email($user_email)
{
$table = Database::get_main_table(TABLE_MAIN_USER);
$sql = 'SELECT user_id
$sql = 'SELECT user_id
FROM '.$table.'
WHERE email="'.Database::escape_string($user_email).'";';
$rs = Database::query($sql);
@ -1490,8 +1548,8 @@ class MessageManager
$image = $user_sender_info['avatar'];
$user_info = '<div class="author text-center"><img class="img-responsive rounded-circle" src="'.$image.'" alt="'.$name.'" width="64" height="64" title="'.$name.'" /></div>';
$user_info .= '<div class="name text-center"><a href="'.api_get_path(
$user_info = '<div class="author"><img class="img-responsive img-circle" src="'.$image.'" alt="'.$name.'" width="64" height="64" title="'.$name.'" /></div>';
$user_info .= '<div class="name"><a href="'.api_get_path(
WEB_PATH
).'main/social/profile.php?u='.$topic['user_sender_id'].'">'.$name.'&nbsp;</a></div>';
@ -2047,27 +2105,32 @@ class MessageManager
}
/**
* @param string $keyword
* @param string $statusList
* @param array $keyword
* @param array $actions
* @param string $viewUrl
*
* @return string
*/
public static function inbox_display($keyword = '')
public static function getMessageGrid($statusList, $keyword, $actions = [], $viewUrl = '')
{
if (empty($statusList)) {
return '';
}
$success = get_lang('SelectedMessagesDeleted');
$success_read = get_lang('SelectedMessagesRead');
$success_unread = get_lang('SelectedMessagesUnRead');
$currentUserId = api_get_user_id();
$html = '';
Session::write('message_search_keyword', $keyword);
if (isset($_REQUEST['action'])) {
switch ($_REQUEST['action']) {
case 'mark_as_unread':
if (is_array($_POST['id'])) {
foreach ($_POST['id'] as $index => $message_id) {
foreach ($_POST['id'] as $index => $messageId) {
self::update_message_status(
api_get_user_id(),
$message_id,
$currentUserId,
$messageId,
MESSAGE_STATUS_UNREAD
);
}
@ -2080,10 +2143,10 @@ class MessageManager
break;
case 'mark_as_read':
if (is_array($_POST['id'])) {
foreach ($_POST['id'] as $index => $message_id) {
foreach ($_POST['id'] as $index => $messageId) {
self::update_message_status(
api_get_user_id(),
$message_id,
$currentUserId,
$messageId,
MESSAGE_STATUS_NEW
);
}
@ -2095,8 +2158,8 @@ class MessageManager
);
break;
case 'delete':
foreach ($_POST['id'] as $index => $message_id) {
self::delete_message_by_user_receiver(api_get_user_id(), $message_id);
foreach ($_POST['id'] as $index => $messageId) {
self::delete_message_by_user_receiver($currentUserId, $messageId);
}
$html .= Display::return_message(
api_xml_http_response_encode($success),
@ -2105,7 +2168,7 @@ class MessageManager
);
break;
case 'deleteone':
self::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
self::delete_message_by_user_receiver($currentUserId, $_GET['id']);
$html .= Display::return_message(
api_xml_http_response_encode($success),
'confirmation',
@ -2119,33 +2182,72 @@ class MessageManager
$table = new SortableTable(
'message_inbox',
['MessageManager', 'getNumberOfMessages'],
['MessageManager', 'get_message_data'],
['MessageManager', 'getMessageData'],
2,
20,
'DESC',
null,
'table-custom'
'DESC'
);
$table->setDataFunctionParams(
['keyword' => $keyword, 'message_status' => $statusList, 'actions' => $actions, 'view_url' => $viewUrl]
);
$table->set_header(0, '', false, ['style' => 'width:15px;']);
$table->set_header(1, get_lang('Messages'), false);
$table->set_header(2, get_lang('Subject'), false);
$table->set_header(3, get_lang('Date'), true, ['style' => 'width:180px;']);
$table->set_header(4, get_lang('Modify'), false, ['style' => 'width:120px;']);
$table->set_header(2, get_lang('Date'), true, ['style' => 'width:180px;']);
$table->set_header(3, get_lang('Modify'), false, ['style' => 'width:120px;']);
if (isset($_REQUEST['f']) && $_REQUEST['f'] == 'social') {
if (isset($_REQUEST['f']) && $_REQUEST['f'] === 'social') {
$parameters['f'] = 'social';
$table->set_additional_parameters($parameters);
}
$table->set_form_actions(
[
'delete' => get_lang('DeleteSelectedMessages'),
'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),
'mark_as_read' => get_lang('MailMarkSelectedAsRead'),
]
);
$defaultActions = [
'delete' => get_lang('DeleteSelectedMessages'),
'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),
'mark_as_read' => get_lang('MailMarkSelectedAsRead'),
];
if (!in_array('delete', $actions)) {
unset($defaultActions['delete']);
}
if (!in_array('mark_as_unread', $actions)) {
unset($defaultActions['mark_as_unread']);
}
if (!in_array('mark_as_read', $actions)) {
unset($defaultActions['mark_as_read']);
}
$table->set_form_actions($defaultActions);
$html .= $table->return_table();
Session::erase('message_search_keyword');
return $html;
}
/**
* @param string $keyword
*
* @return string
*/
public static function inboxDisplay($keyword = '')
{
$actions = ['reply', 'mark_as_unread', 'mark_as_read', 'forward', 'delete'];
$html = self::getMessageGrid([MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD], $keyword, $actions);
return $html;
}
/**
* @param string $keyword
*
* @return string
*/
public static function getPromotedMessagesGrid($keyword = '')
{
//$actions = ['edit', 'delete'];
$actions = ['delete'];
$url = api_get_path(WEB_CODE_PATH).'social/view_promoted_message.php';
$html = self::getMessageGrid([MESSAGE_STATUS_PROMOTED], $keyword, $actions, $url);
return $html;
}
@ -2165,12 +2267,12 @@ class MessageManager
if (isset($_REQUEST['action'])) {
switch ($_REQUEST['action']) {
case 'delete':
$number_of_selected_messages = count($_POST['id']);
if ($number_of_selected_messages != 0) {
foreach ($_POST['id'] as $index => $message_id) {
$count = count($_POST['id']);
if ($count != 0) {
foreach ($_POST['id'] as $index => $messageId) {
self::delete_message_by_user_receiver(
api_get_user_id(),
$message_id
$messageId
);
}
}
@ -2187,24 +2289,24 @@ class MessageManager
// display sortable table with messages of the current user
$table = new SortableTable(
'message_outbox',
['MessageManager', 'getNumberOfMessagesSent'],
['MessageManager', 'getNumberOfMessages'],
['MessageManager', 'get_message_data_sent'],
2,
20,
'DESC'
);
$table->setDataFunctionParams(
['keyword' => $keyword, 'message_status' => [MESSAGE_STATUS_OUTBOX]]
);
$table->set_header(0, '', false, ['style' => 'width:15px;']);
$table->set_header(1, get_lang('Messages'), false);
$table->set_header(2, get_lang('Subject'), false);
$table->set_header(3, get_lang('Date'), true, ['style' => 'width:180px;']);
$table->set_header(4, get_lang('Modify'), false, ['style' => 'width:70px;']);
$table->set_header(2, get_lang('Date'), true, ['style' => 'width:180px;']);
$table->set_header(3, get_lang('Modify'), false, ['style' => 'width:70px;']);
$table->set_form_actions(['delete' => get_lang('DeleteSelectedMessages')]);
$html .= $table->return_table();
Session::erase('message_sent_search_keyword');
return $html;
}
@ -2462,7 +2564,6 @@ class MessageManager
$i = 1;
while (!feof($file)) {
$line = fgets($file);
// $line = trim($line);
if (trim($line) == '') {
continue;

@ -561,25 +561,6 @@ class SocialManager extends UserManager
return true;
}
/**
* Allow attaching to group.
*
* @author Isaac Flores Paz
*
* @param int $id_friend_qualify User to qualify
* @param int $type_qualify Kind of rating
*
* @deprecated 2017-03
*/
public static function qualify_friend($id_friend_qualify, $type_qualify)
{
$table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
$user_id = api_get_user_id();
$sql = 'UPDATE '.$table.' SET relation_type='.((int) $type_qualify).'
WHERE user_id = '.$user_id.' AND friend_user_id='.(int) $id_friend_qualify;
Database::query($sql);
}
/**
* Get user's feeds.
*
@ -934,7 +915,7 @@ class SocialManager extends UserManager
];
// get count unread message and total invitations
$count_unread_message = MessageManager::getNumberOfMessages(true);
$count_unread_message = MessageManager::getNumberOfMessages(['message_status' => [MESSAGE_STATUS_UNREAD]]);
$count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
$number_of_new_messages_of_friend = self::get_message_number_invitation_by_user_id(api_get_user_id());
@ -981,7 +962,7 @@ class SocialManager extends UserManager
'.$homeIcon.' '.get_lang('Home').'
</a>
</li>';
$active = $show == 'messages' ? 'active' : null;
$active = $show === 'messages' ? 'active' : null;
$links .= '
<li class="messages-icon '.$active.'">
<a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
@ -990,7 +971,7 @@ class SocialManager extends UserManager
</li>';
// Invitations
$active = $show == 'invitations' ? 'active' : null;
$active = $show === 'invitations' ? 'active' : null;
$links .= '
<li class="invitations-icon '.$active.'">
<a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
@ -999,14 +980,14 @@ class SocialManager extends UserManager
</li>';
// Shared profile and groups
$active = $show == 'shared_profile' ? 'active' : null;
$active = $show === 'shared_profile' ? 'active' : null;
$links .= '
<li class="shared-profile-icon'.$active.'">
<a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
'.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
</a>
</li>';
$active = $show == 'friends' ? 'active' : null;
$active = $show === 'friends' ? 'active' : null;
$links .= '
<li class="friends-icon '.$active.'">
<a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
@ -1022,7 +1003,7 @@ class SocialManager extends UserManager
</li>';
// Search users
$active = $show == 'search' ? 'active' : null;
$active = $show === 'search' ? 'active' : null;
$links .= '
<li class="search-icon '.$active.'">
<a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
@ -1031,7 +1012,7 @@ class SocialManager extends UserManager
</li>';
// My files
$active = $show == 'myfiles' ? 'active' : null;
$active = $show === 'myfiles' ? 'active' : null;
$myFiles = '
<li class="myfiles-icon '.$active.'">
@ -1046,7 +1027,7 @@ class SocialManager extends UserManager
$links .= $myFiles;
if (api_get_configuration_value('allow_portfolio_tool')) {
$links .= '
<li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
<li class="portoflio-icon '.($show === 'portfolio' ? 'active' : '').'">
<a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
'.$portfolioIcon.' '.get_lang('Portfolio').'
</a>
@ -1055,7 +1036,7 @@ class SocialManager extends UserManager
}
if (!api_get_configuration_value('disable_gdpr')) {
$active = $show == 'personal-data' ? 'active' : null;
$active = $show === 'personal-data' ? 'active' : null;
$personalData = '
<li class="personal-data-icon '.$active.'">
<a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
@ -1063,10 +1044,19 @@ class SocialManager extends UserManager
</a>
</li>';
$links .= $personalData;
$links .= '</ul>';
}
if (api_is_platform_admin()) {
$active = $show === 'promoted_messages' ? 'active' : null;
$personalData = '
<li class="personal-data-icon '.$active.'">
<a href="'.api_get_path(WEB_CODE_PATH).'social/promoted_messages.php">
'.$personalDataIcon.' '.get_lang('PromotedMessages').'
</a>
</li>';
$links .= $personalData;
}
$links .= '</ul>';
$html .= Display::panelCollapse(
get_lang('SocialNetwork'),
$links,
@ -1077,7 +1067,7 @@ class SocialManager extends UserManager
);
}
if (in_array($show, $show_groups) && !empty($group_id)) {
if (!empty($group_id) && in_array($show, $show_groups)) {
$html .= $usergroup->show_group_column_information(
$group_id,
api_get_user_id(),
@ -1206,10 +1196,10 @@ class SocialManager extends UserManager
}
// Check if I already sent an invitation message
$invitation_sent_list = self::get_list_invitation_sent_by_user_id(api_get_user_id());
$invitationSentList = self::get_list_invitation_sent_by_user_id(api_get_user_id());
if (isset($invitation_sent_list[$user_id]) && is_array($invitation_sent_list[$user_id]) &&
count($invitation_sent_list[$user_id]) > 0
if (isset($invitationSentList[$user_id]) && is_array($invitationSentList[$user_id]) &&
count($invitationSentList[$user_id]) > 0
) {
$links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.
Display::return_icon('invitation.png', get_lang('YouAlreadySentAnInvitation'))
@ -1647,7 +1637,6 @@ class SocialManager extends UserManager
$userId = (int) $userId;
$start = (int) $start;
$length = (int) $length;
$startDate = Database::escape_string($startDate);
$select = " SELECT
id,
@ -1668,20 +1657,23 @@ class SocialManager extends UserManager
}
$sql = "$select
FROM $tblMessage tm
FROM $tblMessage m
WHERE
msg_status <> ".MESSAGE_STATUS_WALL_DELETE.' AND ';
// My own posts
// Get my own posts
$userReceiverCondition = ' (
user_receiver_id = '.$userId.' AND
msg_status IN ('.MESSAGE_STATUS_WALL_POST.', '.MESSAGE_STATUS_WALL.') AND
parent_id = '.$parentId.'
)';
// User condition
$sql .= $userReceiverCondition;
$sql .= ' OR (
msg_status IN ('.MESSAGE_STATUS_PROMOTED.')
) ';
// Get my group posts
$groupCondition = '';
if (!empty($groupId)) {
@ -1696,8 +1688,8 @@ class SocialManager extends UserManager
$groupCondition .= ' AND msg_status IN ('.MESSAGE_STATUS_NEW.', '.MESSAGE_STATUS_UNREAD.')) ';
}
$friendCondition = '';
// Get my friend posts
$friendCondition = '';
if (!empty($friendId)) {
if (is_array($friendId)) {
$friendId = array_map('intval', $friendId);
@ -1730,7 +1722,7 @@ class SocialManager extends UserManager
forum_id,
thread_id,
c_id
";
";
}
$threadList = array_map('intval', $threadList);
@ -1762,7 +1754,6 @@ class SocialManager extends UserManager
$repo = $em->getRepository('ChamiloCourseBundle:CForumPost');
$repoThread = $em->getRepository('ChamiloCourseBundle:CForumThread');
$groups = [];
$forums = [];
$userGroup = new UserGroup();
$urlGroup = api_get_path(WEB_CODE_PATH).'social/group_view.php?id=';
while ($row = Database::fetch_array($res, 'ASSOC')) {
@ -1778,14 +1769,14 @@ class SocialManager extends UserManager
}
}
// forums
// Forums
$row['post_title'] = '';
$row['forum_title'] = '';
$row['thread_url'] = '';
if ($row['msg_status'] == MESSAGE_STATUS_FORUM) {
/** @var \Chamilo\CourseBundle\Entity\CForumPost $post */
/** @var CForumPost $post */
$post = $repo->find($row['id']);
/** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
/** @var CForumThread $thread */
$thread = $repoThread->find($row['thread_id']);
if ($post && $thread) {
$courseInfo = api_get_course_info_by_id($post->getCId());
@ -2525,7 +2516,7 @@ class SocialManager extends UserManager
foreach ($messages as $message) {
$post = $message['html'];
$comments = '';
if ($message['msg_status'] == MESSAGE_STATUS_WALL_POST) {
if (in_array($message['msg_status'], [MESSAGE_STATUS_WALL_POST, MESSAGE_STATUS_PROMOTED])) {
$comments = self::getWallPostComments($userId, $message);
}
@ -2555,7 +2546,10 @@ class SocialManager extends UserManager
}
/**
* @param int $userId
* @param int $userId
* @param array $groupList
* @param array $friendList
* @param array $threadList
*
* @return int
*/
@ -2626,7 +2620,8 @@ class SocialManager extends UserManager
}
/**
* @param int $user_id
* @param int $user_id
* @param bool $isArray
*
* @return string|array
*/

@ -100,6 +100,7 @@ class SortableTable extends HTML_Table
* Columns to hide
*/
private $columnsToHide = [];
private $dataFunctionParams;
/**
* Create a new SortableTable.
@ -204,6 +205,27 @@ class SortableTable extends HTML_Table
$this->td_attributes = [];
$this->th_attributes = [];
$this->other_tables = [];
$this->dataFunctionParams = [];
}
/**
* @return array
*/
public function getDataFunctionParams()
{
return $this->dataFunctionParams;
}
/**
* @param array $dataFunctionParams
*
* @return $this
*/
public function setDataFunctionParams($dataFunctionParams)
{
$this->dataFunctionParams = $dataFunctionParams;
return $this;
}
/**
@ -749,7 +771,6 @@ class SortableTable extends HTML_Table
public function processHeaders()
{
$counter = 0;
foreach ($this->headers as $column => $columnInfo) {
$label = $columnInfo['label'];
$sortable = $columnInfo['sortable'];
@ -997,7 +1018,10 @@ class SortableTable extends HTML_Table
public function get_total_number_of_items()
{
if ($this->total_number_of_items == -1 && !is_null($this->get_total_number_function)) {
$this->total_number_of_items = call_user_func($this->get_total_number_function);
$this->total_number_of_items = call_user_func(
$this->get_total_number_function,
$this->getDataFunctionParams()
);
}
return $this->total_number_of_items;
@ -1034,13 +1058,14 @@ class SortableTable extends HTML_Table
$sort = null
) {
$data = [];
if (!is_null($this->get_data_function)) {
if ($this->get_data_function !== null) {
$data = call_user_func(
$this->get_data_function,
$from,
$this->per_page,
$this->column,
$this->direction
$this->direction,
$this->dataFunctionParams
);
}
@ -1106,7 +1131,7 @@ class SortableTableFromArray extends SortableTable
$content = TableSort::sort_table(
$this->table_data,
$this->column,
$this->direction == 'ASC' ? SORT_ASC : SORT_DESC
$this->direction === 'ASC' ? SORT_ASC : SORT_DESC
);
} else {
$content = $this->table_data;

@ -10,6 +10,13 @@
*/
define('EXERCISE_NUMBER_OF_DECIMALS', 2);
/* XML processing functions */
// A regular expression for accessing declared encoding within xml-formatted text.
// Published by Steve Minutillo,
// http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss/
define('_PCRE_XML_ENCODING', '/<\?xml.*encoding=[\'"](.*?)[\'"].*\?>/m');
/**
* This function strips all html-tags found in the input string and outputs a pure text.
* Mostly, the function is to be used before language or encoding detection of the input string.
@ -128,19 +135,13 @@ function api_get_title_html(&$string, $output_encoding = null, $input_encoding =
return '';
}
/* XML processing functions */
// A regular expression for accessing declared encoding within xml-formatted text.
// Published by Steve Minutillo,
// http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss/
define('_PCRE_XML_ENCODING', '/<\?xml.*encoding=[\'"](.*?)[\'"].*\?>/m');
/**
* Detects encoding of xml-formatted text.
*
* @param string $string the input xml-formatted text
* @param string $default_encoding This is the default encoding to be returned
* if there is no way the xml-text's encoding to be detected. If it not spesified, the system encoding is assumed then.
* if there is no way the xml-text's encoding to be detected.
* If it not spesified, the system encoding is assumed then.
*
* @return string returns the detected encoding
*
@ -316,8 +317,6 @@ function api_contains_asciisvg($html)
return false;
}
/* Miscellaneous text processing functions */
/**
* Convers a string from camel case into underscore.
* Works correctly with ASCII strings only, implementation for human-language strings is not necessary.
@ -525,34 +524,6 @@ function esc_url($url, $protocols = null, $_context = 'display')
}
return Security::remove_XSS($url);
/*// Replace ampersands and single quotes only when displaying.
if ( 'display' == $_context ) {
$url = wp_kses_normalize_entities( $url );
$url = str_replace( '&amp;', '&#038;', $url );
$url = str_replace( "'", '&#039;', $url );
}
if ( '/' === $url[0] ) {
$good_protocol_url = $url;
} else {
if ( ! is_array( $protocols ) )
$protocols = wp_allowed_protocols();
$good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
return '';
}
/**
* Filter a string cleaned and escaped for output as a URL.
*
* @since 2.3.0
*
* @param string $good_protocol_url The cleaned URL to be returned.
* @param string $original_url The URL prior to cleaning.
* @param string $_context If 'display', replace ampersands and single quotes only.
*/
//return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );98
}
/**
@ -872,9 +843,9 @@ function get_week_from_day($date)
$time = api_strtotime($date, 'UTC');
return date('W', $time);
} else {
return date('W');
}
return date('W');
}
/**
@ -938,7 +909,7 @@ function implode_with_key($glue, $array)
*/
function format_file_size($file_size)
{
$file_size = intval($file_size);
$file_size = (int) $file_size;
if ($file_size >= 1073741824) {
$file_size = (round($file_size / 1073741824 * 100) / 100).'G';
} elseif ($file_size >= 1048576) {

@ -288,7 +288,7 @@ class Tracking
$chapterTypes = learnpath::getChapterTypes();
$accessToPdfExport = api_is_allowed_to_edit(false, false, true);
$minimunAvailable = self::minimunTimeAvailable($session_id, $course_id);
$minimunAvailable = self::minimumTimeAvailable($session_id, $course_id);
$timeCourse = [];
if ($minimunAvailable) {
$timeCourse = self::getCalculateTime($user_id, $course_id, $session_id);
@ -1679,7 +1679,7 @@ class Tracking
*
* @return bool
*/
public static function minimunTimeAvailable($sessionId, $courseId)
public static function minimumTimeAvailable($sessionId, $courseId)
{
if (!api_get_configuration_value('lp_minimum_time')) {
return false;
@ -1725,7 +1725,7 @@ class Tracking
return 0;
}
if (self::minimunTimeAvailable($session_id, $courseId)) {
if (self::minimumTimeAvailable($session_id, $courseId)) {
$courseTime = self::getCalculateTime($user_id, $courseId, $session_id);
$time = isset($courseTime['total_time']) ? $courseTime['total_time'] : 0;
@ -1902,7 +1902,7 @@ class Tracking
$courseId = (int) $courseId;
$session_id = (int) $session_id;
if (self::minimunTimeAvailable($session_id, $courseId)) {
if (self::minimumTimeAvailable($session_id, $courseId)) {
$tbl_track_e_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
$sql = 'SELECT access_date
FROM '.$tbl_track_e_access.'
@ -1974,25 +1974,25 @@ class Tracking
$session_id = (int) $session_id;
$courseId = $courseInfo['real_id'];
if (self::minimunTimeAvailable($session_id, $courseId)) {
$table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
if (self::minimumTimeAvailable($session_id, $courseId)) {
// Show the last date on which the user acceed the session when it was active
$where_condition = '';
$userInfo = api_get_user_info($student_id);
if ($userInfo['status'] == 5 && $session_id > 0) {
if ($userInfo['status'] == STUDENT && !empty($session_id)) {
// fin de acceso a la sesión
$sessionInfo = SessionManager::fetch($session_id);
$last_access = $sessionInfo['access_end_date'];
$where_condition = ' AND logout_course_date < "'.$last_access.'" ';
}
$tbl_track_e_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
$sql = "SELECT logout_course_date
FROM $tbl_track_e_course_access
WHERE user_id = $student_id AND
c_id = $courseId AND
session_id = $session_id $where_condition
ORDER BY logout_course_date DESC
LIMIT 0,1";
FROM $table
WHERE user_id = $student_id AND
c_id = $courseId AND
session_id = $session_id $where_condition
ORDER BY logout_course_date DESC
LIMIT 0,1";
$rs = Database::query($sql);
if (Database::num_rows($rs) > 0) {
@ -2000,21 +2000,16 @@ class Tracking
if (empty($last_login_date)) {
return false;
}
//see #5736
$last_login_date_timestamp = api_strtotime($last_login_date);
$now = time();
if ($convert_date) {
return api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT);
} else {
return $last_login_date;
}
//}
return $last_login_date;
}
}
} else {
$tbl_track_e_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
$sql = "SELECT logout_course_date
FROM $tbl_track_e_course_access
FROM $table
WHERE user_id = $student_id AND
c_id = $courseId AND
session_id = $session_id
@ -2035,26 +2030,25 @@ class Tracking
if ($now - $last_login_date_timestamp > 604800) {
if ($convert_date) {
$last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT);
$icon = api_is_allowed_to_edit() ?
'<a href="'.api_get_path(
WEB_CODE_PATH
).'announcements/announcements.php?action=add&remind_inactive='.$student_id.'&cidReq='.$courseInfo['code'].'" title="'.get_lang(
'RemindInactiveUser'
).'">
'.Display::return_icon('messagebox_warning.gif').'
</a>'
: null;
$icon = null;
if (api_is_allowed_to_edit()) {
$url = api_get_path(WEB_CODE_PATH).
'announcements/announcements.php?action=add&remind_inactive='.$student_id.'&cidReq='.$courseInfo['code'];
$icon = '<a href="'.$url.'" title="'.get_lang('RemindInactiveUser').'">
'.Display::return_icon('messagebox_warning.gif').'
</a>';
}
return $icon.Display::label($last_login_date, 'warning');
} else {
return $last_login_date;
}
return $last_login_date;
} else {
if ($convert_date) {
return api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT);
} else {
return $last_login_date;
}
return $last_login_date;
}
}
}
@ -4212,9 +4206,9 @@ class Tracking
$count = $row[0];
return $count;
} else {
return null;
}
return 0;
}
/**
@ -4244,7 +4238,7 @@ class Tracking
$condition_session = '';
if (isset($session_id)) {
$session_id = intval($session_id);
$session_id = (int) $session_id;
$condition_session = ' AND f.session_id = '.$session_id;
}
@ -4280,9 +4274,9 @@ class Tracking
$count = $row[0];
return $count;
} else {
return null;
}
return 0;
}
/**
@ -4309,11 +4303,11 @@ class Tracking
$condition_session = '';
if (isset($session_id)) {
$session_id = intval($session_id);
$session_id = (int) $session_id;
$condition_session = ' AND f.session_id = '.$session_id;
}
$groupId = intval($groupId);
$groupId = (int) $groupId;
if (!empty($groupId)) {
$groupCondition = " i.to_group_id = $groupId ";
} else {
@ -4338,9 +4332,9 @@ class Tracking
$count = $row[0];
return $count;
} else {
return null;
}
return 0;
}
/**
@ -4364,8 +4358,9 @@ class Tracking
$course_id = $course_info['real_id'];
// Protect data
$last_days = intval($last_days);
$session_id = intval($session_id);
$last_days = (int) $last_days;
$session_id = (int) $session_id;
$tbl_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
$now = api_get_utc_datetime();
@ -4374,16 +4369,16 @@ class Tracking
DATE_SUB('$now',INTERVAL $last_days DAY) <= access_date AND
c_id = '$course_id' AND
access_tool='".TOOL_CHAT."' AND
access_session_id='$session_id' ";
access_session_id = '$session_id' ";
$result = Database::query($sql);
if (Database::num_rows($result)) {
$row = Database::fetch_row($result);
$count = $row[0];
return $count;
} else {
return null;
}
return 0;
}
/**
@ -4400,9 +4395,9 @@ class Tracking
$courseId,
$session_id = 0
) {
$student_id = intval($student_id);
$courseId = intval($courseId);
$session_id = intval($session_id);
$student_id = (int) $student_id;
$courseId = (int) $courseId;
$session_id = (int) $session_id;
$date_time = '';
// table definition
@ -4439,9 +4434,9 @@ class Tracking
*/
public static function count_student_visited_links($student_id, $courseId, $session_id = 0)
{
$student_id = intval($student_id);
$courseId = intval($courseId);
$session_id = intval($session_id);
$student_id = (int) $student_id;
$courseId = (int) $courseId;
$session_id = (int) $session_id;
// table definition
$table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
@ -4469,9 +4464,9 @@ class Tracking
*/
public static function count_student_downloaded_documents($student_id, $courseId, $session_id = 0)
{
$student_id = intval($student_id);
$courseId = intval($courseId);
$session_id = intval($session_id);
$student_id = (int) $student_id;
$courseId = (int) $courseId;
$session_id = (int) $session_id;
// table definition
$table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
@ -4601,59 +4596,6 @@ class Tracking
return $users;
}
/**
* Get count login per student.
*
* @param int $student_id Student id
* @param int $courseId
* @param int $session_id Session id (optional)
*
* @return int count login
*/
public static function count_login_per_student($student_id, $courseId, $session_id = 0)
{
$student_id = intval($student_id);
$courseId = intval($courseId);
$session_id = intval($session_id);
$table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
$sql = 'SELECT '.$student_id.'
FROM '.$table.'
WHERE
access_user_id='.$student_id.' AND
c_id="'.$courseId.'" AND
access_session_id = "'.$session_id.'" ';
$rs = Database::query($sql);
$nb_login = Database::num_rows($rs);
return $nb_login;
}
/**
* Get students followed by a human resources manager.
*
* @param int Drh id
*
* @return array Student list
*/
public static function get_student_followed_by_drh($hr_dept_id)
{
$hr_dept_id = intval($hr_dept_id);
$a_students = [];
$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
$sql = 'SELECT DISTINCT user_id FROM '.$tbl_user.' as user
WHERE hr_dept_id='.$hr_dept_id;
$rs = Database::query($sql);
while ($user = Database::fetch_array($rs)) {
$a_students[$user['user_id']] = $user['user_id'];
}
return $a_students;
}
/**
* get count clicks about tools most used by course.
*
@ -4666,12 +4608,12 @@ class Tracking
*/
public static function get_tools_most_used_by_course($courseId, $session_id = null)
{
$courseId = intval($courseId);
$courseId = (int) $courseId;
$data = [];
$TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
$condition_session = '';
if (isset($session_id)) {
$session_id = intval($session_id);
$session_id = (int) $session_id;
$condition_session = ' AND access_session_id = '.$session_id;
}
$sql = "SELECT
@ -7718,8 +7660,8 @@ class TrackingCourseLog
$url_table = null;
$url_condition = null;
if (api_is_multiple_url_enabled()) {
$url_table = ", ".$tbl_url_rel_user." as url_users";
$url_condition = " AND user.user_id = url_users.user_id AND access_url_id='$access_url_id'";
$url_table = ", $tbl_url_rel_user as url_users";
$url_condition = " AND user.user_id = url_users.user_id AND access_url_id = '$access_url_id'";
}
$invitedUsersCondition = '';
@ -7744,7 +7686,7 @@ class TrackingCourseLog
$number_of_items = (int) $number_of_items;
$sql .= " ORDER BY col$column $direction ";
$sql .= " LIMIT $from,$number_of_items";
$sql .= " LIMIT $from, $number_of_items";
$res = Database::query($sql);
$users = [];

@ -185,6 +185,9 @@ class UserManager
$redirectToURLAfterLogin = ''
) {
$creatorId = empty($creatorId) ? api_get_user_id() : 0;
$creatorInfo = api_get_user_info($creatorId);
$creatorEmail = isset($creatorInfo['email']) ? $creatorInfo['email'] : '';
$hook = HookCreateUser::create();
if (!empty($hook)) {
$hook->notifyCreateUser(HOOK_EVENT_TYPE_PRE);
@ -404,7 +407,7 @@ class UserManager
'false'
);
if (api_get_configuration_value('plugin_redirection_enabled') && !empty($redirectToURLAfterLogin)) {
if (!empty($redirectToURLAfterLogin) && api_get_configuration_value('plugin_redirection_enabled')) {
RedirectionPlugin::insert($userId, $redirectToURLAfterLogin);
}
@ -909,7 +912,6 @@ class UserManager
// Delete user from database
$em->remove($user);
$em->flush();
// Add event to system log
@ -1107,6 +1109,7 @@ class UserManager
}
$original_password = $password;
$user_id = (int) $user_id;
$creator_id = (int) $creator_id;
if (empty($user_id)) {
return false;
@ -1259,13 +1262,22 @@ class UserManager
$userInfo = api_get_user_info($user_id);
$emailBody = $mailTemplateManager->parseTemplate($emailTemplate['user_edit_content.tpl'], $userInfo);
}
$creatorInfo = api_get_user_info($creator_id);
$creatorEmail = isset($creatorInfo['email']) ? $creatorInfo['email'] : '';
api_mail_html(
$recipient_name,
$email,
$emailsubject,
$emailBody,
$sender_name,
$email_admin
$email_admin,
null,
null,
null,
null,
$creatorEmail
);
}

@ -1046,7 +1046,7 @@ class IndexManager
$loadHistory = false
) {
$gameModeIsActive = api_get_setting('gamification_mode');
$viewGridCourses = api_get_configuration_value('view_grid_courses');
$showSimpleSessionInfo = api_get_configuration_value('show_simple_session_info');
$coursesTemplate = '/user_portal/list_courses.html.twig';
$showAllSessions = api_get_configuration_value('show_all_sessions_on_my_course_page') === true;
@ -1065,7 +1065,6 @@ class IndexManager
// Student info code check (shows student progress information on
// courses list
$studentInfo = api_get_configuration_value('course_student_info');
$viewGrid = api_get_configuration_value('view_grid_courses');
$studentInfoProgress = !empty($studentInfo['progress']) && $studentInfo['progress'] === true;
$studentInfoScore = !empty($studentInfo['score']) && $studentInfo['score'] === true;
@ -1077,7 +1076,7 @@ class IndexManager
$specialCourseList = '';
// If we're not in the history view...
if ($loadHistory == false) {
if ($loadHistory === false) {
// Display special courses.
$specialCourses = CourseManager::returnSpecialCourses(
$user_id,
@ -1145,10 +1144,11 @@ class IndexManager
foreach ($courses['in_category'] as $key1 => $value) {
if (isset($courses['in_category'][$key1]['courses'])) {
foreach ($courses['in_category'][$key1]['courses'] as $key2 => $courseInCatInfo) {
$courseCode = $courseInCatInfo['course_code'];
if ($studentInfoProgress) {
$progress = Tracking::get_avg_student_progress(
$user_id,
$courseInCatInfo['course_code']
$courseCode
);
$courses['in_category'][$key1]['courses'][$key2]['student_info']['progress'] = $progress === false ? null : $progress;
}
@ -1156,7 +1156,7 @@ class IndexManager
if ($studentInfoScore) {
$percentage_score = Tracking::get_avg_student_score(
$user_id,
$specialCourseInfo['course_code'],
$courseCode,
[]
);
$courses['in_category'][$key1]['courses'][$key2]['student_info']['score'] = $percentage_score;
@ -1166,7 +1166,7 @@ class IndexManager
$category = Category::load(
null,
null,
$courseInCatInfo['course_code'],
$courseCode,
null,
null,
null
@ -1174,7 +1174,7 @@ class IndexManager
$courses['in_category'][$key1]['student_info']['certificate'] = null;
$isCertificateAvailable = $category[0]->is_certificate_available($user_id);
if (isset($category[0])) {
if ($viewGrid) {
if ($viewGridCourses) {
if ($isCertificateAvailable) {
$courses['in_category'][$key1]['student_info']['certificate'] = get_lang(
'Yes'
@ -1206,10 +1206,11 @@ class IndexManager
if (isset($courses['not_category'])) {
foreach ($courses['not_category'] as $key => $courseNotInCatInfo) {
$courseCode = $courseNotInCatInfo['course_code'];
if ($studentInfoProgress) {
$progress = Tracking::get_avg_student_progress(
$user_id,
$courseNotInCatInfo['course_code']
$courseCode
);
$courses['not_category'][$key]['student_info']['progress'] = $progress === false ? null : $progress;
}
@ -1217,7 +1218,7 @@ class IndexManager
if ($studentInfoScore) {
$percentage_score = Tracking::get_avg_student_score(
$user_id,
$courseNotInCatInfo['course_code'],
$courseCode,
[]
);
$courses['not_category'][$key]['student_info']['score'] = $percentage_score;
@ -1227,7 +1228,7 @@ class IndexManager
$category = Category::load(
null,
null,
$courseNotInCatInfo['course_code'],
$courseCode,
null,
null,
null
@ -1236,7 +1237,7 @@ class IndexManager
if (isset($category[0])) {
$certificateAvailable = $category[0]->is_certificate_available($user_id);
if ($viewGrid) {
if ($viewGridCourses) {
if ($certificateAvailable) {
$courses['not_category'][$key]['student_info']['certificate'] = get_lang('Yes');
} else {

@ -1870,12 +1870,14 @@ class learnpath
/**
* Gets the navigation bar for the learnpath display screen.
*
* @param string $barId
*
* @return string The HTML string to use as a navigation bar
*/
public function get_navigation_bar($idBar = null, $display = null)
public function get_navigation_bar($barId = '')
{
if (empty($idBar)) {
$idBar = 'control-top';
if (empty($barId)) {
$barId = 'control-top';
}
$lpId = $this->lp_id;
$mycurrentitemid = $this->get_current_item_id();
@ -1898,7 +1900,7 @@ class learnpath
if (!empty($display)) {
$showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
if ($showReporting == false) {
if ($showReporting === false) {
$reportingIcon = '';
}
}
@ -1926,7 +1928,7 @@ class learnpath
if ($this->mode === 'fullscreen') {
$navbar = '
<span id="'.$idBar.'" class="buttons">
<span id="'.$barId.'" class="buttons">
'.$reportingIcon.'
'.$previousIcon.'
'.$nextIcon.'
@ -1937,11 +1939,11 @@ class learnpath
</span>';
} else {
$navbar = '
<span id="'.$idBar.'" class="buttons text-right">
'.$reportingIcon.'
'.$previousIcon.'
'.$nextIcon.'
</span>';
<span id="'.$barId.'" class="buttons text-right">
'.$reportingIcon.'
'.$previousIcon.'
'.$nextIcon.'
</span>';
}
return $navbar;
@ -2289,7 +2291,7 @@ class learnpath
$isBlocked = true;
}
if (Tracking::minimunTimeAvailable($sessionId, $courseId)) {
if (Tracking::minimumTimeAvailable($sessionId, $courseId)) {
// Block if it does not exceed minimum time
// Minimum time (in minutes) to pass the learning path
$accumulateWorkTime = self::getAccumulateWorkTimePrerequisite($prerequisite, $courseId);
@ -4309,7 +4311,7 @@ class learnpath
$debug = $this->debug;
if ($debug > 0) {
error_log('In learnpath::prerequisites_match()', 0);
error_log('In learnpath::prerequisites_match()');
}
if (empty($itemId)) {
@ -4333,11 +4335,13 @@ class learnpath
return true;
}
// Clean spaces.
$prereq_string = str_replace(' ', '', $prereq_string);
if ($debug > 0) {
error_log('Found prereq_string: '.$prereq_string, 0);
}
// Now send to the parse_prereq() function that will check this component's prerequisites.
$result = $currentItem->parse_prereq(
$prereq_string,

@ -539,7 +539,7 @@ class learnpathItem
c_id = $course_id AND
lp_item_id = ".$this->db_id." AND
lp_view_id = ".$this->view_id." AND
view_count = ".$this->attempt_id;
view_count = ".$this->get_view_count();
$res = Database::query($sql);
if (Database::num_rows($res) > 0) {
$row = Database::fetch_array($res);
@ -573,6 +573,10 @@ class learnpathItem
public function get_interactions_count($checkdb = false)
{
$return = 0;
if (api_is_invitee()) {
// If the user is an invitee, we consider there's no interaction
return 0;
}
$course_id = api_get_course_int_id();
if ($checkdb) {
@ -688,9 +692,9 @@ class learnpathItem
['\r', '\n', "\\'"],
$this->lesson_location
);
} else {
return '';
}
return '';
}
/**
@ -860,8 +864,8 @@ class learnpathItem
if (!empty($this->lp_id)) {
$table = Database::get_course_table(TABLE_LP_MAIN);
$sql = "SELECT prevent_reinit
FROM $table
WHERE iid = ".$this->lp_id;
FROM $table
WHERE iid = ".$this->lp_id;
$res = Database::query($sql);
if (Database::num_rows($res) < 1) {
$this->error = "Could not find parent learnpath in lp table";
@ -1511,62 +1515,22 @@ class learnpathItem
c_id = $course_id AND
iid = '".$this->db_item_view_id."' AND
view_count = '".$this->get_attempt_id()."'";
if ($debug > 2) {
error_log(
'learnpathItem::get_status() - Checking DB: '.$sql,
0
);
}
$res = Database::query($sql);
if (Database::num_rows($res) == 1) {
$row = Database::fetch_array($res);
if ($update_local) {
if ($debug > 2) {
error_log(
'learnpathItem::set_status() :'.$row['status'],
0
);
}
$this->set_status($row['status']);
}
if ($debug > 2) {
error_log(
'learnpathItem::get_status() - Returning db value '.$row['status'],
0
);
}
return $row['status'];
}
}
} else {
if ($debug > 2) {
error_log(
'learnpathItem::get_status() - in get_status: using attrib',
0
);
}
if (!empty($this->status)) {
if ($debug > 2) {
error_log(
'learnpathItem::get_status() - Returning attrib: '.$this->status,
0
);
}
return $this->status;
}
}
if ($debug > 2) {
error_log(
'learnpathItem::get_status() - Returning default '.$this->possible_status[0],
0
);
}
return $this->possible_status[0];
}
@ -1602,12 +1566,12 @@ class learnpathItem
if (!isset($time)) {
if ($origin == 'js') {
return '00 : 00: 00';
} else {
return '00 '.$h.' 00 \' 00"';
}
} else {
return api_format_time($time, $origin);
return '00 '.$h.' 00 \' 00"';
}
return api_format_time($time, $origin);
}
/**
@ -1786,7 +1750,7 @@ class learnpathItem
$sessionLifetime = 3600;
}
if (!Tracking::minimunTimeAvailable(api_get_session_id(), api_get_course_int_id())) {
if (!Tracking::minimumTimeAvailable(api_get_session_id(), api_get_course_int_id())) {
$fixedAddedMinute = 5 * 60; // Add only 5 minutes
if ($time > $sessionLifetime) {
error_log("fixAbusiveTime: Total time is too big: $time replaced with: $fixedAddedMinute");
@ -2031,6 +1995,7 @@ class learnpathItem
// Deal with &, |, ~, =, <>, {}, ,, X*, () in reverse order.
$this->prereq_alert = '';
// First parse all parenthesis by using a sequential loop
// (looking for less-inclusives first).
if ($prereqs_string == '_true_') {
@ -2369,13 +2334,6 @@ class learnpathItem
} else {
// Nothing found there either. Now return the
// value of the corresponding resource completion status.
if ($debug) {
error_log(
'New LP - Didnt find any group, returning value for '.$prereqs_string,
0
);
}
if (isset($refs_list[$prereqs_string]) &&
isset($items[$refs_list[$prereqs_string]])
) {
@ -2393,26 +2351,12 @@ class learnpathItem
$itemToCheck->get_title()
);
$this->prereq_alert = $explanation;
if ($debug) {
error_log(
'New LP - Prerequisite '.$prereqs_string.' not complete',
0
);
}
} else {
if ($debug) {
error_log(
'New LP - Prerequisite '.$prereqs_string.' complete',
0
);
}
}
// For one and first attempt.
if ($this->prevent_reinit == 1) {
// 2. If is completed we check the results in the DB of the quiz.
if ($returnstatus) {
//AND origin_lp_item_id = '.$user_id.'
$sql = 'SELECT score, max_score
FROM '.Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES).'
WHERE
@ -2431,14 +2375,6 @@ class learnpathItem
$minScore = $myItemToCheck->getPrerequisiteMinScore();
$maxScore = $myItemToCheck->getPrerequisiteMaxScore();
/*if (empty($minScore)) {
// Try with mastery_score
$masteryScoreAsMin = $myItemToCheck->get_mastery_score();
if (!empty($masteryScoreAsMin)) {
$minScore = $masteryScoreAsMin;
}
}*/
if (isset($minScore) && isset($minScore)) {
// Taking min/max prerequisites values see BT#5776
if ($quiz['score'] >= $minScore &&
@ -2483,7 +2419,7 @@ class learnpathItem
exe_exo_id = '.$items[$refs_list[$prereqs_string]]->path.' AND
exe_user_id = '.$user_id.' AND
orig_lp_id = '.$this->lp_id.' AND
orig_lp_item_id = '.$prereqs_string.' ';
orig_lp_item_id = '.$prereqs_string;
$rs_quiz = Database::query($sql);
if (Database::num_rows($rs_quiz) > 0) {
@ -2532,6 +2468,18 @@ class learnpathItem
}
}
if ($returnstatus === false) {
// Check results from another sessions.
$checkOtherSessions = api_get_configuration_value('validate_lp_prerequisite_from_other_session');
if ($checkOtherSessions) {
$returnstatus = $this->getStatusFromOtherSessions(
$user_id,
$prereqs_string,
$refs_list
);
}
}
return $returnstatus;
} elseif ($itemToCheck->type === 'student_publication') {
require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
@ -2542,62 +2490,53 @@ class learnpathItem
} else {
$returnstatus = false;
$this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
if (self::DEBUG > 1) {
error_log(
'Student pub, prereq'.$prereqs_string.' not completed',
0
);
}
}
return $returnstatus;
} else {
$status = $itemToCheck->get_status(false);
$returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
// Check results from another sessions.
$checkOtherSessions = api_get_configuration_value('validate_lp_prerequisite_from_other_session');
if ($checkOtherSessions && !$returnstatus) {
$returnstatus = $this->getStatusFromOtherSessions(
$user_id,
$prereqs_string,
$refs_list
);
}
if (!$returnstatus) {
$explanation = sprintf(
get_lang('ItemXBlocksThisElement'),
$itemToCheck->get_title()
);
$this->prereq_alert = $explanation;
if (self::DEBUG > 1) {
error_log(
'New LP - Prerequisite '.$prereqs_string.' not complete',
0
);
}
} else {
if (self::DEBUG > 1) {
error_log(
'New LP - Prerequisite '.$prereqs_string.' complete',
0
);
}
}
if ($returnstatus && $this->prevent_reinit == 1) {
// I would prefer check in the database.
$lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
$lp_view = Database::get_course_table(TABLE_LP_VIEW);
$lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
$lp_view = Database::get_course_table(TABLE_LP_VIEW);
$sql = 'SELECT iid FROM '.$lp_view.'
if ($returnstatus && $this->prevent_reinit == 1) {
$sql = "SELECT iid FROM $lp_view
WHERE
c_id = '.$course_id.' AND
user_id = '.$user_id.' AND
lp_id = '.$this->lp_id.' AND
session_id = '.$sessionId.'
LIMIT 0, 1';
c_id = $course_id AND
user_id = $user_id AND
lp_id = $this->lp_id AND
session_id = $sessionId
LIMIT 0, 1";
$rs_lp = Database::query($sql);
if (Database::num_rows($rs_lp)) {
$lp_id = Database::fetch_row($rs_lp);
$my_lp_id = $lp_id[0];
$sql = 'SELECT status FROM '.$lp_item_view.'
$sql = "SELECT status FROM $lp_item_view
WHERE
c_id = '.$course_id.' AND
lp_view_id = '.$my_lp_id.' AND
lp_item_id = '.$refs_list[$prereqs_string].'
LIMIT 0, 1';
c_id = $course_id AND
lp_view_id = $my_lp_id AND
lp_item_id = $refs_list[$prereqs_string]
LIMIT 0, 1";
$rs_lp = Database::query($sql);
$status_array = Database::fetch_row($rs_lp);
$status = $status_array[0];
@ -2606,33 +2545,18 @@ class learnpathItem
if (!$returnstatus && empty($this->prereq_alert)) {
$this->prereq_alert = get_lang('LearnpathPrereqNotCompleted');
}
if (!$returnstatus) {
if (self::DEBUG > 1) {
error_log(
'New LP - Prerequisite '.$prereqs_string.' not complete'
);
}
} else {
if (self::DEBUG > 1) {
error_log('New LP - Prerequisite '.$prereqs_string.' complete');
}
}
}
return $returnstatus;
if ($checkOtherSessions && $returnstatus === false) {
$returnstatus = $returnstatus = $this->getStatusFromOtherSessions(
$user_id,
$prereqs_string,
$refs_list
);
}
} else {
return $returnstatus;
}
}
} else {
if (self::DEBUG > 1) {
error_log(
'New LP - Could not find '.$prereqs_string.' in '.print_r(
$refs_list,
true
),
0
);
return $returnstatus;
}
}
}
@ -3208,9 +3132,6 @@ class learnpathItem
*/
public function set_max_score($score)
{
if (self::DEBUG > 0) {
error_log('learnpathItem::set_max_score('.$score.')', 0);
}
if (is_int($score) || $score == '') {
$this->view_max_score = $score;
@ -3596,6 +3517,10 @@ class learnpathItem
if (self::DEBUG > 0) {
error_log('learnpathItem::write_objectives_to_db()', 0);
}
if (api_is_invitee()) {
// If the user is an invitee, we don't write anything to DB
return true;
}
$course_id = api_get_course_int_id();
if (is_array($this->objectives) && count($this->objectives) > 0) {
// Save objectives.
@ -3688,6 +3613,10 @@ class learnpathItem
return false;
}
if (api_is_invitee()) {
// If the user is an invitee, we don't write anything to DB
return true;
}
$course_id = api_get_course_int_id();
$mode = $this->get_lesson_mode();
@ -3781,7 +3710,7 @@ class learnpathItem
c_id = $course_id AND
lp_item_id = ".$this->db_id." AND
lp_view_id = ".$this->view_id." AND
view_count = ".intval($this->get_attempt_id());
view_count = ".$this->get_attempt_id();
if ($debug) {
error_log(
'learnpathItem::write_to_db() - Querying item_view: '.$sql,
@ -3821,7 +3750,7 @@ class learnpathItem
Database::query($sql);
}
} else {
if ($this->type == 'hotpotatoes') {
if ($this->type === 'hotpotatoes') {
$params = [
'total_time' => $this->get_total_time(),
'start_time' => $this->get_current_start_time(),
@ -4535,4 +4464,55 @@ class learnpathItem
{
return $this->iId;
}
/**
* @param int $user_id
* @param string $prereqs_string
* @param array $refs_list
*
* @return bool
*/
public function getStatusFromOtherSessions($user_id, $prereqs_string, $refs_list)
{
$lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
$lp_view = Database::get_course_table(TABLE_LP_VIEW);
$course_id = api_get_course_int_id();
$user_id = (int) $user_id;
// Check results from another sessions:
$checkOtherSessions = api_get_configuration_value('validate_lp_prerequisite_from_other_session');
if ($checkOtherSessions) {
// Check items
$sql = "SELECT iid FROM $lp_view
WHERE
c_id = $course_id AND
user_id = $user_id AND
lp_id = $this->lp_id AND
session_id <> 0
";
$result = Database::query($sql);
$resultFromOtherSessions = false;
while ($row = Database::fetch_array($result)) {
$lpIid = $row['iid'];
$sql = "SELECT status FROM $lp_item_view
WHERE
c_id = $course_id AND
lp_view_id = $lpIid AND
lp_item_id = $refs_list[$prereqs_string]
LIMIT 1";
$resultRow = Database::query($sql);
if (Database::num_rows($resultRow)) {
$statusResult = Database::fetch_array($resultRow);
$status = $statusResult['status'];
$checked = $status == $this->possible_status[2] || $status == $this->possible_status[3];
if ($checked) {
$resultFromOtherSessions = true;
break;
}
}
}
return $resultFromOtherSessions;
}
}
}

@ -218,7 +218,7 @@ function switch_item_details($lp_id, $user_id, $view_id, $current_item, $next_it
"olms.asset_timer = 0;";
$updateMinTime = '';
if (Tracking::minimunTimeAvailable(api_get_session_id(), api_get_course_int_id())) {
if (Tracking::minimumTimeAvailable(api_get_session_id(), api_get_course_int_id())) {
$timeLp = $mylp->getAccumulateWorkTime();
$timeTotalCourse = $mylp->getAccumulateWorkTimeTotalCourse();
// Minimum connection percentage

@ -159,7 +159,7 @@ $form->addElement('html', '</div>');
$form->addElement('html', '<div class="col-md-2"></div>');
$form->addElement('html', '</div>');
// Time Control
if (Tracking::minimunTimeAvailable(api_get_session_id(), api_get_course_int_id())) {
if (Tracking::minimumTimeAvailable(api_get_session_id(), api_get_course_int_id())) {
$accumulateTime = $_SESSION['oLP']->getAccumulateWorkTime();
$form->addText('accumulate_work_time', [get_lang('LpMinTime'), get_lang('LpMinTimeDescription')]);
$defaults['accumulate_work_time'] = $accumulateTime;

@ -151,7 +151,7 @@ if ($filteredCategoryId) {
$test_mode = api_get_setting('server_type');
$showBlockedPrerequisite = api_get_configuration_value('show_prerequisite_as_blocked');
$allowLpChamiloExport = api_get_configuration_value('allow_lp_chamilo_export');
$allowMinTime = Tracking::minimunTimeAvailable($sessionId, $courseId);
$allowMinTime = Tracking::minimumTimeAvailable($sessionId, $courseId);
$accumulateWorkTimeTotal = 0;
if ($allowMinTime) {
$accumulateWorkTimeTotal = learnpath::getAccumulateWorkTimeTotal($courseId);

@ -33,7 +33,6 @@ if (isset($_REQUEST['origin']) && $_REQUEST['origin'] === 'learnpath') {
}
// To prevent the template class
$show_learnpath = true;
$lp_id = !empty($_GET['lp_id']) ? (int) $_GET['lp_id'] : 0;
$sessionId = api_get_session_id();
$course_code = api_get_course_id();
@ -169,7 +168,7 @@ if ($allowLpItemTip) {
}
// Impress js
if ($lp->mode == 'impress') {
if ($lp->mode === 'impress') {
$lp_id = $lp->get_id();
$url = api_get_path(WEB_CODE_PATH)."lp/lp_impress.php?lp_id=$lp_id&".api_get_cidreq();
header("Location: $url");
@ -419,7 +418,7 @@ if (!api_is_invitee()) {
$progress_bar = $lp->getProgressBar();
}
$navigation_bar = $lp->get_navigation_bar();
$navigation_bar_bottom = $lp->get_navigation_bar('control-bottom', 'display:none');
$navigation_bar_bottom = $lp->get_navigation_bar('control-bottom');
$mediaplayer = $lp->get_mediaplayer($lp->current, $autostart);
$tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
@ -546,6 +545,15 @@ $template->assign('iframe_src', $src);
$template->assign('navigation_bar_bottom', $navigation_bar_bottom);
$template->assign('show_left_column', $lp->getHideTableOfContents() == 0);
$showMenu = 0;
$settings = api_get_configuration_value('lp_view_settings');
$display = isset($settings['display']) ? $settings['display'] : false;
if (!empty($display)) {
$showMenu = isset($display['show_toolbar_by_default']) && $display['show_toolbar_by_default'] ? 1 : 0;
}
$template->assign('show_toolbar_by_default', $showMenu);
if ($gamificationMode == 1) {
$template->assign('gamification_stars', $lp->getCalculateStars($sessionId));
$template->assign('gamification_points', $lp->getCalculateScore($sessionId));
@ -554,7 +562,7 @@ if ($gamificationMode == 1) {
$template->assign('lp_author', $lp->get_author());
$lpMinTime = '';
if (Tracking::minimunTimeAvailable(api_get_session_id(), api_get_course_int_id())) {
if (Tracking::minimumTimeAvailable(api_get_session_id(), api_get_course_int_id())) {
// Calulate minimum and accumulated time
$timeLp = $_SESSION['oLP']->getAccumulateWorkTime();
$timeTotalCourse = $_SESSION['oLP']->getAccumulateWorkTimeTotalCourse();

@ -16,10 +16,7 @@ if (api_get_setting('allow_message_tool') != 'true') {
$logInfo = [
'tool' => 'Messages',
'tool_id' => 0,
'tool_id_detail' => 0,
'action' => isset($_GET['action']) ? $_GET['action'] : 'inbox',
'action_details' => '',
];
Event::registerLog($logInfo);
@ -35,8 +32,6 @@ if (isset($_GET['messages_page_nr'])) {
$nameTools = get_lang('Messages');
$show_message = null;
$messageContent = null;
if (isset($_GET['form_reply']) || isset($_GET['form_delete'])) {
$info_reply = [];
$info_delete = [];
@ -56,7 +51,7 @@ if (isset($_GET['form_reply']) || isset($_GET['form_delete'])) {
if (isset($button_sent)) {
$title = urldecode($info_reply[0]);
$content = str_replace("\\", "", urldecode($info_reply[1]));
$content = str_replace("\\", '', urldecode($info_reply[1]));
$user_reply = $info_reply[2];
$user_email_base = str_replace(')', '(', $info_reply[5]);
@ -74,12 +69,12 @@ if (isset($_GET['form_reply']) || isset($_GET['form_delete'])) {
if (isset($user_reply) && !is_null($user_id_by_email) && strlen($info_reply[0]) > 0) {
MessageManager::send_message($user_id_by_email, $title, $content);
$show_message .= MessageManager::return_message($user_id_by_email, 'confirmation');
$messageContent .= MessageManager::inbox_display();
$social_right_content .= MessageManager::inboxDisplay();
exit;
} elseif (is_null($user_id_by_email)) {
$message_box = get_lang('ErrorSendingMessage');
$show_message .= Display::return_message(api_xml_http_response_encode($message_box), 'error');
$messageContent .= MessageManager::inbox_display();
$social_right_content .= MessageManager::inboxDisplay();
exit;
}
} elseif (trim($info_delete[0]) == 'delete') {
@ -91,7 +86,7 @@ if (isset($_GET['form_reply']) || isset($_GET['form_delete'])) {
}
$message_box = get_lang('SelectedMessagesDeleted');
$show_message .= Display::return_message(api_xml_http_response_encode($message_box));
$messageContent .= MessageManager::inbox_display();
$social_right_content .= MessageManager::inboxDisplay();
exit;
}
}
@ -117,7 +112,6 @@ $interbreadcrumb[] = [
$interbreadcrumb[] = ['url' => '#', 'name' => get_lang('Inbox')];
$actions = '';
// Comes from normal profile
if ($allowSocial === false && $allowMessage) {
$actions .= '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php">'.
@ -128,8 +122,15 @@ if ($allowSocial === false && $allowMessage) {
Display::return_icon('outbox.png', get_lang('Outbox')).'</a>';
}
// Right content
// LEFT CONTENT
$social_menu_block = '';
if ($allowSocial) {
// Block Social Menu
$social_menu_block = SocialManager::show_social_menu('messages');
}
// Right content
$social_right_content = '';
$keyword = '';
if ($allowSocial) {
$actionsLeft = '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php">'.
@ -143,23 +144,23 @@ if ($allowSocial) {
$keyword = $values['keyword'];
}
$actionsRight = $form->returnForm();
$toolbar = Display::toolbarAction('toolbar', [$actionsLeft, $actionsRight]);
$social_right_content .= Display::toolbarAction('toolbar', [$actionsLeft, $actionsRight]);
}
if (!isset($_GET['del_msg'])) {
$messageContent .= MessageManager::inbox_display($keyword);
$social_right_content .= MessageManager::inboxDisplay($keyword);
} else {
$num_msg = (int) $_POST['total'];
for ($i = 0; $i < $num_msg; $i++) {
if ($_POST[$i]) {
//the user_id was necessary to delete a message??
// The user_id was necessary to delete a message??
$show_message .= MessageManager::delete_message_by_user_receiver(
api_get_user_id(),
$_POST['_'.$i]
);
}
}
$messageContent .= MessageManager::inbox_display();
$social_right_content .= MessageManager::inboxDisplay();
}
$tpl = new Template(null);
@ -168,11 +169,15 @@ if ($actions) {
$tpl->assign('actions', Display::toolbarAction('toolbar', [$actions]));
}
// Block Social Avatar
$tpl->assign('content_inbox', $messageContent);
$social_layout = $tpl->get_template('social/inbox.html.twig');
$content = $tpl->fetch($social_layout);
SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'messages');
if ($allowSocial) {
$tpl->assign('social_menu_block', $social_menu_block);
$tpl->assign('social_right_content', $social_right_content);
$social_layout = $tpl->get_template('social/inbox.tpl');
$tpl->display($social_layout);
} else {
$content = $social_right_content;
$tpl->assign('message', $show_message);
$tpl->assign('actions', $toolbar);
$tpl->assign('content', $content);
$tpl->display_one_col_template();
}

@ -24,14 +24,12 @@ if (api_get_setting('allow_message_tool') !== 'true') {
$logInfo = [
'tool' => 'Messages',
'tool_id' => 0,
'tool_id_detail' => 0,
'action' => 'new_message',
'action_details' => isset($_GET['re_id']) ? 're_id' : '',
];
Event::registerLog($logInfo);
$allowSocial = api_get_setting('allow_social_tool') == 'true';
$allowSocial = api_get_setting('allow_social_tool') === 'true';
$nameTools = api_xml_http_response_encode(get_lang('Messages'));
$htmlHeadXtra[] = '<script>
@ -59,7 +57,6 @@ function add_image_form() {
}
</script>';
$nameTools = get_lang('ComposeMessage');
$tpl = new Template(get_lang('ComposeMessage'));
/**
@ -315,7 +312,7 @@ function manageForm($default, $select_from_user_list = null, $sent_to = '', $tpl
}
}
Security::clear_token();
header('Location: '.api_get_path(WEB_PATH).'main/messages/inbox.php');
header('Location: '.api_get_path(WEB_CODE_PATH).'messages/inbox.php');
exit;
} else {
$token = Security::get_token();
@ -330,55 +327,74 @@ function manageForm($default, $select_from_user_list = null, $sent_to = '', $tpl
if ($allowSocial) {
$this_section = SECTION_SOCIAL;
$interbreadcrumb[] = [
'url' => api_get_path(WEB_PATH).'main/social/home.php',
'url' => api_get_path(WEB_CODE_PATH).'social/home.php',
'name' => get_lang('SocialNetwork'),
];
} else {
$this_section = SECTION_MYPROFILE;
$interbreadcrumb[] = [
'url' => api_get_path(WEB_PATH).'main/auth/profile.php',
'url' => api_get_path(WEB_CODE_PATH).'auth/profile.php',
'name' => get_lang('Profile'),
];
}
$interbreadcrumb[] = [
'url' => api_get_path(WEB_PATH).'main/messages/inbox.php',
'url' => api_get_path(WEB_CODE_PATH).'messages/inbox.php',
'name' => get_lang('Messages'),
];
$group_id = isset($_REQUEST['group_id']) ? (int) $_REQUEST['group_id'] : 0;
$message_content = null;
$actions = null;
$social_right_content = null;
if ($group_id != 0) {
$actions .= '<a href="'.api_get_path(WEB_PATH).'main/social/group_view.php?id='.$group_id.'">'.
$social_right_content .= '<div class=actions>';
$social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'social/group_view.php?id='.$group_id.'">'.
Display::return_icon('back.png', api_xml_http_response_encode(get_lang('ComposeMessage'))).'</a>';
$actions .= '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php?group_id='.$group_id.'">'.
$social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/new_message.php?group_id='.$group_id.'">'.
Display::return_icon('message_new.png', api_xml_http_response_encode(get_lang('ComposeMessage'))).'</a>';
$social_right_content .= '</div>';
} else {
$actions .= '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php">'.
Display::return_icon('message_new.png', get_lang('ComposeMessage')).'</a>';
$actions .= '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.
Display::return_icon('inbox.png', get_lang('Inbox')).'</a>';
$actions .= '<a href="'.api_get_path(WEB_PATH).'main/messages/outbox.php">'.
Display::return_icon('outbox.png', get_lang('Outbox')).'</a>';
if ($allowSocial) {
} else {
$social_right_content .= '<div class=actions>';
if (api_get_setting('allow_message_tool') === 'true') {
$social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/new_message.php">'.
Display::return_icon('message_new.png', get_lang('ComposeMessage')).'</a>';
$social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">'.
Display::return_icon('inbox.png', get_lang('Inbox')).'</a>';
$social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/outbox.php">'.
Display::return_icon('outbox.png', get_lang('Outbox')).'</a>';
}
$social_right_content .= '</div>';
}
}
$show_message = null;
// LEFT COLUMN
$social_left_content = '';
if ($allowSocial) {
// Block Social Menu
$social_menu_block = SocialManager::show_social_menu('messages');
$social_right_content .= '<div class="row">';
$social_right_content .= '<div class="col-md-12">';
$social_right_content .= '<div class="actions">';
$social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">'.
Display::return_icon('back.png', get_lang('Back'), [], 32).'</a>';
$social_right_content .= '</div>';
$social_right_content .= '</div>';
$social_right_content .= '<div class="col-md-12">';
}
// MAIN CONTENT
if (!isset($_POST['compose'])) {
if (isset($_GET['re_id'])) {
$message_content .= show_compose_reply_to_message(
$social_right_content .= show_compose_reply_to_message(
$_GET['re_id'],
api_get_user_id(),
$tpl
);
} elseif (isset($_GET['send_to_user'])) {
$message_content .= show_compose_to_user($_GET['send_to_user'], $tpl);
$social_right_content .= show_compose_to_user($_GET['send_to_user'], $tpl);
} else {
$message_content .= show_compose_to_any($tpl);
$social_right_content .= show_compose_to_any($tpl);
}
} else {
$restrict = false;
@ -395,7 +411,7 @@ if (!isset($_POST['compose'])) {
// comes from a reply button
if (isset($_GET['re_id']) || isset($_GET['forward_id'])) {
$message_content .= manageForm($default, null, null, $tpl);
$social_right_content .= manageForm($default, null, null, $tpl);
} else {
// post
if ($restrict) {
@ -407,24 +423,29 @@ if (!isset($_POST['compose'])) {
if (isset($_POST['hidden_user'])) {
$default['users'] = [$_POST['hidden_user']];
}
$message_content .= manageForm($default, null, null, $tpl);
$social_right_content .= manageForm($default, null, null, $tpl);
} else {
$message_content .= Display::return_message(get_lang('ErrorSendingMessage'), 'error');
$social_right_content .= Display::return_message(get_lang('ErrorSendingMessage'), 'error');
}
}
}
MessageManager::cleanAudioMessage();
if ($actions) {
$tpl->assign(
'actions',
Display::toolbarAction('toolbar', [$actions])
);
if ($allowSocial) {
$social_right_content .= '</div>';
$social_right_content .= '</div>';
}
$tpl->assign('message', $show_message);
$tpl->assign('content_inbox', $message_content);
$social_layout = $tpl->get_template('message/inbox.html.twig');
$content = $tpl->fetch($social_layout);
$tpl->assign('content', $content);
$tpl->display_one_col_template();
// Block Social Avatar
SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'messages');
MessageManager::cleanAudioMessage();
if ($allowSocial) {
$tpl->assign('social_menu_block', $social_menu_block);
$tpl->assign('social_right_content', $social_right_content);
$social_layout = $tpl->get_template('social/inbox.tpl');
$tpl->display($social_layout);
} else {
$content = $social_right_content;
$tpl->assign('content', $content);
$tpl->display_one_col_template();
}

@ -15,16 +15,12 @@ if (api_get_setting('allow_message_tool') != 'true') {
$logInfo = [
'tool' => 'Messages',
'tool_id' => 0,
'tool_id_detail' => 0,
'action' => isset($_GET['action']) ? $_GET['action'] : 'outbox',
'action_details' => '',
];
Event::registerLog($logInfo);
$allowSocial = api_get_setting('allow_social_tool') == 'true';
$allowMessage = api_get_setting('allow_message_tool') == 'true';
$show_message = null;
if (isset($_GET['messages_page_nr'])) {
if ($allowSocial && $allowMessage) {
@ -49,41 +45,40 @@ $interbreadcrumb[] = [
'name' => get_lang('Messages'),
];
$actions = null;
$actions = '';
if ($allowMessage) {
$actionsLeft = '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php">'.
$actions .= '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php">'.
Display::return_icon('message_new.png', get_lang('ComposeMessage')).'</a>';
$actionsLeft .= '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.
$actions .= '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.
Display::return_icon('inbox.png', get_lang('Inbox')).'</a>';
$actionsLeft .= '<a href="'.api_get_path(WEB_PATH).'main/messages/outbox.php">'.
$actions .= '<a href="'.api_get_path(WEB_PATH).'main/messages/outbox.php">'.
Display::return_icon('outbox.png', get_lang('Outbox')).'</a>';
}
$action = null;
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
}
$keyword = '';
$form = MessageManager::getSearchForm(api_get_path(WEB_PATH).'main/messages/outbox.php');
if ($form->validate()) {
$values = $form->getSubmitValues();
$keyword = $values['keyword'];
$social_right_content = '';
if ($allowSocial) {
// Block Social Menu
$social_menu_block = SocialManager::show_social_menu('messages');
$actionsLeft = '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.
Display::return_icon('back.png', get_lang('Back'), [], 32).'</a>';
$form = MessageManager::getSearchForm(api_get_path(WEB_PATH).'main/messages/outbox.php');
if ($form->validate()) {
$values = $form->getSubmitValues();
$keyword = $values['keyword'];
}
$actionsRight = $form->returnForm();
$social_right_content .= Display::toolbarAction(
'toolbar',
[$actionsLeft, $actionsRight]
);
}
$actionsRight = $form->returnForm();
$actions .= Display::toolbarAction(
'toolbar',
[
$actionsLeft,
$actionsRight,
]
);
$message_content = null;
//MAIN CONTENT
if ($action == 'delete') {
$delete_list_id = [];
@ -100,29 +95,34 @@ if ($action == 'delete') {
);
}
$delete_list_id = [];
$message_content .= MessageManager::outbox_display($keyword);
$social_right_content .= MessageManager::outbox_display($keyword);
} elseif ($action == 'deleteone') {
$delete_list_id = [];
$id = Security::remove_XSS($_GET['id']);
MessageManager::delete_message_by_user_sender(api_get_user_id(), $id);
$delete_list_id = [];
$message_content .= MessageManager::outbox_display($keyword);
$social_right_content .= MessageManager::outbox_display($keyword);
} else {
$message_content .= MessageManager::outbox_display($keyword);
$social_right_content .= MessageManager::outbox_display($keyword);
}
$tpl = new Template(get_lang('Outbox'));
// Block Social Avatar
SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'messages');
if ($actions) {
$tpl->assign(
'actions',
$actions
);
if ($allowSocial) {
$tpl->assign('social_menu_block', $social_menu_block);
$tpl->assign('social_right_content', $social_right_content);
$social_layout = $tpl->get_template('social/inbox.tpl');
$tpl->display($social_layout);
} else {
$content = $social_right_content;
if ($actions) {
$tpl->assign(
'actions',
Display::toolbarAction('toolbar', [$actions])
);
}
$tpl->assign('content', $content);
$tpl->display_one_col_template();
}
$tpl->assign('content_inbox', $message_content);
$social_layout = $tpl->get_template('message/inbox.html.twig');
$content = $tpl->fetch($social_layout);
$tpl->assign('message', $show_message);
$tpl->assign('content', $content);
$tpl->display_one_col_template();

@ -49,8 +49,6 @@ $message = '';
$logInfo = [
'tool' => 'Messages',
'tool_id' => 0,
'tool_id_detail' => 0,
'action' => $source,
'action_details' => 'view-message',
];

@ -5,7 +5,6 @@ require_once __DIR__.'/../inc/global.inc.php';
api_block_anonymous_users();
// Access restrictions.
$is_allowedToTrack = api_is_platform_admin(true, true) ||
api_is_teacher() || api_is_course_tutor();
@ -24,34 +23,47 @@ if (empty($userInfo)) {
api_not_allowed(true);
}
$sessions = SessionManager::getSessionsFollowedByUser($userId,
null,
/**
* @param string $dateTime
* @param bool $showTime
*
* @return string
*/
function customDate($dateTime, $showTime = false)
{
$format = 'd/m/Y';
if ($showTime) {
$format = 'd/m/Y H:i:s';
}
$dateTime = api_get_local_time(
$dateTime,
null,
null,
true,
false,
false,
false,
'ORDER BY s.access_end_date'
true,
$format
);
return $dateTime;
}
$sessions = SessionManager::getSessionsFollowedByUser($userId,
null,
null,
null,
false,
false,
false,
'ORDER BY s.access_end_date'
);
$startDate = '';
$endDate = '';
if (!empty($sessions)) {
foreach ($sessions as $session) {
$startDate = api_get_local_time(
$session['access_start_date'],
null,
null,
true,
false
);
$endDate = api_get_local_time(
$session['access_end_date'],
null,
null,
true,
false
);
$startDate = customDate($session['access_start_date']);
$endDate = customDate($session['access_end_date']);
}
}
@ -62,28 +74,48 @@ $form = new FormValidator(
null,
['id' => 'myform']
);
$form->addElement('text', 'from', get_lang('From'), ['id' => 'date_from']);
$form->addElement('text', 'to', get_lang('Until'), ['id' => 'date_to']);
/*$form->addElement(
'select',
'type',
get_lang('Type'),
['day' => get_lang('Day'), 'month' => get_lang('Month')],
['id' => 'type']
);*/
$form->addElement('text', 'from', get_lang('From'));
$form->addElement('text', 'to', get_lang('Until'));
$form->addElement('hidden', 'user_id', $userId);
$form->addRule('from', get_lang('ThisFieldIsRequired'), 'required');
$form->addRule('from', get_lang('ThisFieldIsRequired').' dd/mm/yyyy', 'callback', 'validateDate');
$form->addRule('to', get_lang('ThisFieldIsRequired'), 'required');
$form->addRule('to', get_lang('ThisFieldIsRequired').' dd/mm/yyyy', 'callback', 'validateDate');
$form->addButtonSearch(get_lang('GenerateReport'));
/**
* @param string $value
*
* @return bool
*/
function validateDate($value)
{
$value = DateTime::createFromFormat('d/m/Y', $value);
if ($value === false) {
return false;
}
return true;
}
if ($form->validate()) {
$values = $form->getSubmitValues();
$from = $values['from'];
$to = $values['to'];
$sessionCategories = UserManager::get_sessions_by_category($userId, false);
$sessionCourseList = [];
$from = DateTime::createFromFormat('d/m/Y', $from);
$to = DateTime::createFromFormat('d/m/Y', $to);
$from = api_get_utc_datetime($from->format('Y-m-d'));
$to = api_get_utc_datetime($to->format('Y-m-d'));
$sessionCategories = UserManager::get_sessions_by_category($userId, false);
$report = [];
$minLogin = 0;
$maxLogin = 0;
$totalDuration = 0;
foreach ($sessionCategories as $category) {
foreach ($category['sessions'] as $session) {
$sessionId = $session['session_id'];
@ -92,21 +124,59 @@ if ($form->validate()) {
$courseInfo = api_get_course_info_by_id($course['real_id']);
$result = MySpace::get_connections_to_course_by_date(
$userId,
$course,
$courseInfo,
$sessionId,
$from,
$to
);
$partialMinLogin = 0;
$partialMaxLogin = 0;
$partialDuration = 0;
foreach ($result as $item) {
$record = [
$courseInfo['title'],
$session['session_name'],
api_get_local_time($item['login']),
api_get_local_time($item['logout']),
customDate($item['login'], true),
customDate($item['logout'], true),
api_format_time($item['duration'], 'js'),
];
$report[] = $record;
$totalDuration += $item['duration'];
if (empty($minLogin)) {
$minLogin = api_strtotime($item['login'], 'UTC');
}
if ($minLogin > api_strtotime($item['login'], 'UTC')) {
$minLogin = api_strtotime($item['login'], 'UTC');
}
if (api_strtotime($item['logout']) > $maxLogin) {
$maxLogin = api_strtotime($item['logout'], 'UTC');
}
// Partials
$partialDuration += $item['duration'];
if (empty($partialMinLogin)) {
$partialMinLogin = api_strtotime($item['login'], 'UTC');
}
if ($partialMinLogin > api_strtotime($item['login'], 'UTC')) {
$partialMinLogin = api_strtotime($item['login'], 'UTC');
}
if (api_strtotime($item['logout'], 'UTC') > $partialMaxLogin) {
$partialMaxLogin = api_strtotime($item['logout'], 'UTC');
}
$report[$sessionId]['courses'][$course['real_id']][] = $record;
$report[$sessionId]['name'][$course['real_id']] = $courseInfo['title'].'&nbsp; ('.$session['session_name'].')';
}
if (!empty($result)) {
$record = [
customDate($partialMinLogin, true),
customDate($partialMaxLogin, true),
api_format_time($partialDuration, 'js'),
];
$report[$sessionId]['courses'][$course['real_id']][] = $record;
$report[$sessionId]['name'][$course['real_id']] = $courseInfo['title'].'&nbsp; ('.$session['session_name'].')';
}
}
}
@ -124,25 +194,61 @@ if ($form->validate()) {
$to
);
$partialMinLogin = 0;
$partialMaxLogin = 0;
$partialDuration = 0;
foreach ($result as $item) {
$record = [
$course['title'],
'',
api_get_local_time($item['login']),
api_get_local_time($item['logout']),
customDate($item['login'], true),
customDate($item['logout'], true),
api_format_time($item['duration'], 'js'),
];
$report[] = $record;
$report[0]['courses'][$course['course_id']][] = $record;
$report[0]['name'][$course['course_id']] = $course['title'];
$totalDuration += $item['duration'];
if (empty($minLogin)) {
$minLogin = api_strtotime($item['login'], 'UTC');
}
if ($minLogin > api_strtotime($item['login'], 'UTC')) {
$minLogin = api_strtotime($item['login'], 'UTC');
}
if (api_strtotime($item['logout'], 'UTC') > $maxLogin) {
$maxLogin = api_strtotime($item['logout'], 'UTC');
}
// Partials
$partialDuration += $item['duration'];
if (empty($partialMinLogin)) {
$partialMinLogin = api_strtotime($item['login'], 'UTC');
}
if ($partialMinLogin > api_strtotime($item['login'], 'UTC')) {
$partialMinLogin = api_strtotime($item['login'], 'UTC');
}
if (api_strtotime($item['logout'], 'UTC') > $partialMaxLogin) {
$partialMaxLogin = api_strtotime($item['logout'], 'UTC');
}
}
if (!empty($result)) {
$record = [
customDate($partialMinLogin, true),
customDate($partialMaxLogin, true),
api_format_time($partialDuration, 'js'),
];
$report[0]['courses'][$course['course_id']][] = $record;
$report[0]['name'][$course['course_id']] = $course['title'];
}
}
$table = new HTML_Table(['class' => 'data_table']);
$headers = [
get_lang('Course'),
get_lang('Session'),
get_lang('StartDate'),
get_lang('EndDate'),
get_lang('Duration'),
get_lang('MinStartDate'),
get_lang('MaxEndDate'),
get_lang('TotalDuration'),
];
$row = 0;
$column = 0;
@ -151,18 +257,48 @@ if ($form->validate()) {
$column++;
}
$row++;
foreach ($report as $record) {
$column = 0;
foreach ($record as $item) {
$table->setCellContents($row, $column++, $item);
$column = 0;
$table->setCellContents($row, $column++, customDate($minLogin));
$table->setCellContents($row, $column++, customDate($maxLogin));
$table->setCellContents($row, $column++, api_format_time($totalDuration, 'js'));
$content = Display::page_subheader3(get_lang('Total')).$table->toHtml();
foreach ($report as $sessionId => $data) {
foreach ($data['courses'] as $courseId => $courseData) {
$content .= Display::page_subheader3($data['name'][$courseId]);
$table = new HTML_Table(['class' => 'data_table']);
$headers = [
get_lang('StartDate'),
get_lang('EndDate'),
get_lang('Duration'),
];
$row = 0;
$column = 0;
foreach ($headers as $header) {
$table->setHeaderContents($row, $column, $header);
$column++;
}
$row++;
$countData = count($courseData);
foreach ($courseData as $record) {
$column = 0;
foreach ($record as $item) {
$table->setCellContents($row, $column++, $item);
if ($row == $countData) {
$table->setRowAttributes($row, ['style' => 'font-weight:bold']);
}
}
$row++;
}
$content .= $table->toHtml();
}
$row++;
}
$tpl = new Template('', false, false, false, true, false, false);
$tpl->assign('title', get_lang('AttestationOfAttendance'));
$tpl->assign('student', $userInfo['complete_name']);
$tpl->assign('table_progress', $table->toHtml());
$tpl->assign('table_progress', $content);
$content = $tpl->fetch($tpl->get_template('my_space/pdf_export_student.tpl'));
$params = [
'pdf_title' => get_lang('Resume'),
@ -176,7 +312,7 @@ if ($form->validate()) {
'orientation' => 'P',
];
$pdf = new PDF('A4', $params['orientation'], $params);
@$pdf = new PDF('A4', $params['orientation'], $params);
$pdf->setBackground($tpl->theme);
@$pdf->content_to_pdf(

@ -1,7 +1,6 @@
<?php
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Entity\Message;
use Chamilo\CourseBundle\Entity\CLpCategory;
use ChamiloSession as Session;
@ -1338,7 +1337,7 @@ if (empty($details)) {
];
$timeCourse = null;
if (Tracking::minimunTimeAvailable($sessionId, $courseInfo['real_id'])) {
if (Tracking::minimumTimeAvailable($sessionId, $courseInfo['real_id'])) {
$timeCourse = Tracking::getCalculateTime($student_id, $courseInfo['real_id'], $sessionId);
}

@ -748,7 +748,7 @@ $newLinks .= Display::url(
class="form-control">
</select>
<br />
<button style="display:none" id="remove_user" name="remove_user" class="btn btn-primary" type="button"
<button style="display:none" id="remove_user" name="remove_user" class="btn btn-danger" type="button"
onclick="remove_item(document.getElementById('destination_users'))">
<?php echo get_lang('Remove'); ?> <em class="fa fa-trash"></em>
</button>

@ -21,7 +21,7 @@ $formSent = 0;
$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
$id = intval($_GET['id']);
$id = (int) $_GET['id'];
SessionManager::protectSession($id);
@ -51,11 +51,10 @@ if (!empty($sessionInfo['coach_access_end_date'])) {
$sessionInfo['coach_access_end_date'] = api_get_local_time($sessionInfo['coach_access_end_date']);
}
$id_coach = $sessionInfo['id_coach'];
$tool_name = get_lang('EditSession');
$interbreadcrumb[] = ['url' => "session_list.php", "name" => get_lang('SessionList')];
$interbreadcrumb[] = ['url' => "resume_session.php?id_session=".$id, "name" => get_lang('SessionOverview')];
$interbreadcrumb[] = ['url' => 'session_list.php', 'name' => get_lang('SessionList')];
$interbreadcrumb[] = ['url' => 'resume_session.php?id_session='.$id, 'name' => get_lang('SessionOverview')];
if (isset($_POST['formSent']) && $_POST['formSent']) {
$formSent = 1;
@ -206,7 +205,6 @@ $form->display();
<script>
$(function() {
<?php
if (!empty($sessionInfo['duration'])) {
echo 'accessSwitcher(0);';

@ -41,7 +41,7 @@ if (!empty($messageInfo['group_id'])) {
}
// Only process wall messages
if (!in_array($messageInfo['msg_status'], [MESSAGE_STATUS_WALL, MESSAGE_STATUS_WALL_POST])) {
if (!in_array($messageInfo['msg_status'], [MESSAGE_STATUS_WALL, MESSAGE_STATUS_WALL_POST, MESSAGE_STATUS_PROMOTED])) {
api_not_allowed();
}

@ -37,14 +37,13 @@ if (!empty($threadList)) {
$threadIdList = array_column($threadList, 'id');
}
// Social Post Wall
$posts = SocialManager::getMyWallMessages($user_id, 0, 10, $threadIdList);
$countPost = $posts['count'];
$posts = $posts['posts'];
SocialManager::getScrollJs($countPost, $htmlHeadXtra);
// Block Menu
$social_menu_block = SocialManager::show_social_menu('home');
$menu = SocialManager::show_social_menu('home');
$social_search_block = Display::panel(
UserManager::get_search_form(''),
@ -93,9 +92,9 @@ $htmlHeadXtra[] = SocialManager::getScriptToGetOpenGraph();
$tpl = new Template(get_lang('SocialNetwork'));
SocialManager::setSocialUserBlock($tpl, $user_id, 'home');
$tpl->assign('social_wall_block', $wallSocialAddPost);
$tpl->assign('social_post_wall_block', $posts);
$tpl->assign('social_menu_block', $social_menu_block);
$tpl->assign('add_post_form', $wallSocialAddPost);
$tpl->assign('posts', $posts);
$tpl->assign('social_menu_block', $menu);
$tpl->assign('social_auto_extend_link', $socialAutoExtendLink);
$tpl->assign('search_friends_form', $formSearch->returnForm());
$tpl->assign('social_friend_block', $friend_html);

@ -156,8 +156,8 @@ if (is_array($personal_course_list)) {
$course_list_code = array_unique_dimensional($course_list_code);
}
//Social Block Menu
$social_menu_block = SocialManager::show_social_menu(
// Social Block Menu
$menu = SocialManager::show_social_menu(
'shared_profile',
null,
$user_id,
@ -173,7 +173,7 @@ $sessionList = SessionManager::getSessionsFollowedByUser(
// My friends
$friend_html = SocialManager::listMyFriendsBlock($user_id, $link_shared);
$wallSocialAddPost = SocialManager::getWallForm(api_get_self());
$addPostForm = SocialManager::getWallForm(api_get_self());
$posts = SocialManager::getWallMessagesByUser($friendId);
$socialAutoExtendLink = SocialManager::getAutoExtendLink($user_id, $countPost);
@ -345,9 +345,9 @@ SocialManager::setSocialUserBlock(
);
$tpl->assign('social_friend_block', $friend_html);
$tpl->assign('social_menu_block', $social_menu_block);
$tpl->assign('social_wall_block', $wallSocialAddPost);
$tpl->assign('social_post_wall_block', $posts);
$tpl->assign('social_menu_block', $menu);
$tpl->assign('add_post_form', $addPostForm);
$tpl->assign('posts', $posts);
$tpl->assign('social_course_block', $social_course_block);
$tpl->assign('social_group_info_block', $social_group_info_block);
$tpl->assign('social_rss_block', $social_rss_block);

Loading…
Cancel
Save