/**
  * @param Request $request
  * @return null|RedirectResponse
  */
 public function onLogoutSuccess(Request $request)
 {
     // Chamilo logout
     $request->getSession()->remove('_locale');
     $request->getSession()->remove('_locale_user');
     if (api_is_global_chat_enabled()) {
         $chat = new \Chat();
         $chat->setUserStatus(0);
     }
     $userId = $this->storage->getToken()->getUser()->getId();
     $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
     $sql = "SELECT login_id, login_date\n                FROM {$tbl_track_login}\n                WHERE login_user_id = {$userId}\n                ORDER BY login_date DESC\n                LIMIT 0,1";
     $row = Database::query($sql);
     $loginId = null;
     if (Database::num_rows($row) > 0) {
         $loginId = Database::result($row, 0, "login_id");
     }
     $loginAs = $this->checker->isGranted('ROLE_PREVIOUS_ADMIN');
     if (!$loginAs) {
         $current_date = api_get_utc_datetime();
         $sql = "UPDATE {$tbl_track_login}\n                    SET logout_date='" . $current_date . "'\n        \t\t    WHERE login_id='{$loginId}'";
         Database::query($sql);
     }
     $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
     $query = "DELETE FROM " . $online_table . " WHERE login_user_id = {$userId}";
     Database::query($query);
     require_once api_get_path(SYS_PATH) . 'main/chat/chat_functions.lib.php';
     exit_of_chat($userId);
     $login = $this->router->generate('home');
     $response = new RedirectResponse($login);
     return $response;
 }
示例#2
0
 /**
  * Create a video chat
  * @param int $fromUser The sender user
  * @param int $toUser The receiver user
  * @return int The created video chat id. Otherwise return false
  */
 public static function createRoom($fromUser, $toUser)
 {
     $fromUserInfo = api_get_user_info($fromUser);
     $toUserInfo = api_get_user_info($toUser);
     $chatName = vsprintf(get_lang('VideoChatBetweenUserXAndUserY'), [$fromUserInfo['firstname'], $toUserInfo['firstname']]);
     return Database::insert(Database::get_main_table(TABLE_MAIN_CHAT_VIDEO), ['from_user' => intval($fromUser), 'to_user' => intval($toUser), 'room_name' => $chatName, 'datetime' => api_get_utc_datetime()]);
 }
示例#3
0
/**
 * Save the score for a HP quiz. Can be used by the learnpath tool as well
 * for HotPotatoes quizzes. When coming from the learning path, we
 * use the session variables telling us which item of the learning path has to
 * be updated (score-wise)
 * @param	string	File is the exercise name (the file name for a HP)
 * @param	integer	Score to save inside the tracking tables (HP and learnpath)
 * @return	void
 */
function save_scores($file, $score)
{
    global $origin;
    $TABLETRACK_HOTPOTATOES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
    $_user = api_get_user_info();
    // if tracking is disabled record nothing
    $weighting = 100;
    // 100%
    $date = api_get_utc_datetime();
    $c_id = api_get_course_int_id();
    if ($_user['user_id']) {
        $user_id = $_user['user_id'];
    } else {
        // anonymous
        $user_id = "NULL";
    }
    $params = ['exe_name' => $file, 'exe_user_id' => $user_id, 'exe_date' => $date, 'c_id' => $c_id, 'exe_result' => $score, 'exe_weighting' => $weighting];
    Database::insert($TABLETRACK_HOTPOTATOES, $params);
    if ($origin == 'learnpath') {
        //if we are in a learning path, save the score in the corresponding
        //table to get tracking in there as well
        global $jscript2run;
        //record the results in the learning path, using the SCORM interface (API)
        $jscript2run .= "<script>\n            \$(document).ready(function() {\n                //API_obj = window.frames.window.content.API;\n                //API_obj = \$('content_id').context.defaultView.content.API; //works only in FF\n                //API_obj = window.parent.frames.window.top.API;\n                API_obj = window.top.API;\n                API_obj.void_save_asset('{$score}', '{$weighting}', 0, 'completed');\n            });\n        </script>";
    }
}
示例#4
0
 /**
  * Updates an URL access
  * @author Julio Montoya <*****@*****.**>,
  *
  * @param	int 	$url_id The url id
  * @param	string 	$url
  * @param	string  $description The description of the site
  * @param	int		$active is active or not
  * @return 	boolean if success
  */
 public static function update($url_id, $url, $description, $active)
 {
     $url_id = intval($url_id);
     $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
     $sql = "UPDATE {$table}\n                SET url \t= '" . Database::escape_string($url) . "',\n                description = '" . Database::escape_string($description) . "',\n                active \t\t= '" . intval($active) . "',\n                created_by \t= '" . api_get_user_id() . "',\n                tms \t\t= '" . api_get_utc_datetime() . "'\n                WHERE id = '{$url_id}'";
     $result = Database::query($sql);
     return $result;
 }
 /**
  * Updates a group
  * @author Julio Montoya <*****@*****.**>,
  *
  * @param	int 	The id
  * @param	string  The description of the site
  * @param	int		is active or not
  * @param	int     the user_id of the owner
  * @return 	boolean if success
  */
 public static function update($group_id, $name, $description, $url, $visibility, $picture_uri)
 {
     $group_id = intval($group_id);
     $table = Database::get_main_table(TABLE_MAIN_GROUP);
     $now = api_get_utc_datetime();
     $sql = "UPDATE {$table}\n               \tSET name \t= '" . Database::escape_string($name) . "',\n                description = '" . Database::escape_string($description) . "',\n                picture_uri = '" . Database::escape_string($picture_uri) . "',\n                url \t\t= '" . Database::escape_string($url) . "',\n                visibility \t= '" . Database::escape_string($visibility) . "',\n                updated_on \t= '" . $now . "'\n                WHERE id = '{$group_id}'";
     $result = Database::query($sql);
     return $result;
 }
/**
 * Loads the data and injects it into the Dokeos database, using the Dokeos
 * internal functions.
 * @return  array  List of user IDs for the users that have just been inserted
 */
function fill_whoisonline()
{
    $table_e_online = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
    $max = 100;
    //Cleaning the table
    $sql = "TRUNCATE {$table_e_online}";
    $rs = Database::query($sql);
    //filling the table
    for ($i = 1; $i <= $max; $i++) {
        $date = api_get_utc_datetime();
        $sql = "INSERT INTO\t{$table_e_online} (login_id, login_user_id, login_date, login_ip, course, session_id, access_url_id)\n\t\t\t\tVALUES ('{$i}', '{$i}', '{$date}', '127.0.0.1', '', '0','1')";
        $rs = Database::query($sql);
    }
}
 /**
  * Updates a group
  * @author Julio Montoya <*****@*****.**>,
  *
  * @param int $group_id The id
  * @param string $name The description of the site
  * @param string $description
  * @param string $url
  * @param int $visibility
  * @param string $picture_uri
  * @param bool $allowMemberGroupToLeave
  * @return bool if success
  */
 public static function update($group_id, $name, $description, $url, $visibility, $picture_uri, $allowMemberGroupToLeave = null)
 {
     $group_id = intval($group_id);
     $table = Database::get_main_table(TABLE_MAIN_GROUP);
     $now = api_get_utc_datetime();
     $groupLeaveCondition = null;
     if (isset($allowMemberGroupToLeave)) {
         $allowMemberGroupToLeave = $allowMemberGroupToLeave == true ? 1 : 0;
         $groupLeaveCondition = " allow_members_leave_group = {$allowMemberGroupToLeave} , ";
     }
     $sql = "UPDATE {$table} SET\n                    name \t= '" . Database::escape_string($name) . "',\n                    description = '" . Database::escape_string($description) . "',\n                    picture_uri = '" . Database::escape_string($picture_uri) . "',\n                    url \t\t= '" . Database::escape_string($url) . "',\n                    visibility \t= '" . Database::escape_string($visibility) . "',\n                    {$groupLeaveCondition}\n                    updated_on \t= '" . $now . "'\n                WHERE id = '{$group_id}'";
     $result = Database::query($sql);
     return $result;
 }
 public function clean_parameters($params)
 {
     //Convert dates
     $params['display_start_date'] = isset($params['display_start_date']) ? api_get_utc_datetime($params['display_start_date'], true) : null;
     $params['display_end_date'] = isset($params['display_end_date']) ? api_get_utc_datetime($params['display_end_date'], true) : null;
     $params['access_start_date'] = isset($params['access_start_date']) ? api_get_utc_datetime($params['access_start_date'], true) : null;
     $params['access_end_date'] = isset($params['access_end_date']) ? api_get_utc_datetime($params['access_end_date'], true) : null;
     $params['coach_access_start_date'] = isset($params['coach_access_start_date']) ? api_get_utc_datetime($params['coach_access_start_date'], true) : null;
     $params['coach_access_end_date'] = isset($params['coach_access_end_date']) ? api_get_utc_datetime($params['coach_access_end_date'], true) : null;
     $params['id_coach'] = is_array($params['id_coach']) ? $params['id_coach'][0] : $params['id_coach'];
     if (empty($params['access_end_date'])) {
         $params['visibility'] = SessionManager::DEFAULT_VISIBILITY;
     }
     unset($params['submit']);
     return $params;
 }
示例#9
0
/**
 * Save the score for a HP quiz. Can be used by the learnpath tool as well
 * for HotPotatoes quizzes. When coming from the learning path, we
 * use the session variables telling us which item of the learning path has to
 * be updated (score-wise)
 * @param    string    File is the exercise name (the file name for a HP)
 * @param    integer    Score to save inside the tracking tables (HP and learnpath)
 * @return    void
 */
function save_scores($file, $score)
{
    global $origin, $_user, $TABLETRACK_HOTPOTATOES;
    $weighting = 100;
    // 100%
    $date = api_get_utc_datetime();
    if ($_user['user_id']) {
        $user_id = $_user['user_id'];
    } else {
        // anonymous
        $user_id = "NULL";
    }
    $sql = "INSERT INTO {$TABLETRACK_HOTPOTATOES} (exe_name, exe_user_id, exe_date, c_id, exe_result, exe_weighting) VALUES (\n\t\t\t'" . Database::escape_string($file) . "',\n\t\t\t'" . Database::escape_string($user_id) . "',\n\t\t\t'" . Database::escape_string($date) . "',\n\t\t\t'" . api_get_course_int_id() . "',\n\t\t\t'" . Database::escape_string($score) . "',\n\t\t\t'" . Database::escape_string($weighting) . "')";
    Database::query($sql);
    if ($origin == 'learnpath') {
        //if we are in a learning path, save the score in the corresponding
        //table to get tracking in there as well
        global $jscript2run;
        //record the results in the learning path, using the SCORM interface (API)
        $jscript2run .= "<script>\n            \$(document).ready(function() {\n                //API_obj = window.frames.window.content.API;\n                //API_obj = \$('content_id').context.defaultView.content.API; //works only in FF\n                //API_obj = window.parent.frames.window.top.API;\n                API_obj = window.top.API;\n                API_obj.void_save_asset('{$score}', '{$weighting}', 0, 'completed');\n            });\n        </script>";
    }
}
示例#10
0
 /**
  * Creates a new url access
  *
  * @author Julio Montoya <*****@*****.**>,
  *
  * @param string The URL of the site
  * @param string The description of the site
  * @param int is active or not
  * @param int the user_id of the owner
  * @param int The type of URL (1=multiple-access-url, 2=sincro-server, 3=sincro-client)
  * @param array If the type is different than 1, then there might be extra URL parameters to take into account
  * @return boolean if success
  */
 public static function add($url, $description, $active, $type = 1, $extra_params)
 {
     $tms = time();
     $type = intval($type);
     $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
     $u = api_get_user_id();
     if ($u == 0) {
         $u = api_get_anonymous_id();
     }
     if ($type > 1) {
         $active = 0;
     }
     $sql = "INSERT INTO {$table_access_url} " . " SET url \t= '" . Database::escape_string($url) . "', " . " description = '" . Database::escape_string($description) . "', " . " active \t\t= {$active}, " . " created_by \t= {$u}, " . " url_type        = {$type}, " . " tms = FROM_UNIXTIME(" . $tms . ")";
     $result = Database::query($sql);
     $id = Database::insert_id();
     if ($result !== false && $type == 3 && count($extra_params) > 0) {
         // Register extra parameters in the branch_sync table
         $t = Database::get_main_table(TABLE_BRANCH_SYNC);
         $sql = "INSERT INTO {$t} SET " . " access_url_id = {$id} " . (!empty($extra_params['ip']) ? ", branch_ip = '" . Database::escape_string($extra_params['ip']) . "'" : "") . (!empty($extra_params['name']) ? ", branch_name = '" . Database::escape_string($extra_params['name']) . "'" : "") . (!empty($extra_params['last_sync']) ? ", last_sync_trans_id = '" . Database::escape_string($extra_params['last_sync']) . "'" : "") . (!empty($extra_params['dwn_speed']) ? ", dwn_speed = '" . Database::escape_string($extra_params['dwn_speed']) . "'" : "") . (!empty($extra_params['up_speed']) ? ", up_speed = '" . Database::escape_string($extra_params['up_speed']) . "'" : "") . (!empty($extra_params['delay']) ? ", delay = '" . Database::escape_string($extra_params['delay']) . "'" : "") . (!empty($extra_params['admin_mail']) ? ", admin_mail = '" . Database::escape_string($extra_params['admin_mail']) . "'" : "") . (!empty($extra_params['admin_name']) ? ", admin_name = '" . Database::escape_string($extra_params['admin_name']) . "'" : "") . (!empty($extra_params['admin_phone']) ? ", admin_phone = '" . Database::escape_string($extra_params['admin_phone']) . "'" : "") . (!empty($extra_params['latitude']) ? ", latitude = '" . Database::escape_string($extra_params['latitude']) . "'" : "") . (!empty($extra_params['longitude']) ? ", longitude = '" . Database::escape_string($extra_params['longitude']) . "'" : "") . ", last_sync_trans_date = '" . api_get_utc_datetime() . "'";
         $result = $result && Database::query($sql);
     }
     return $result;
 }
示例#11
0
 /**
  * Export the given HTML to PDF, using a global template
  * @param string the HTML content
  * @uses export/table_pdf.tpl
  */
 function html_to_pdf_with_template($content)
 {
     Display::display_no_header();
     //Assignments
     Display::$global_template->assign('pdf_content', $content);
     $organization = api_get_setting('Institution');
     $img = api_get_path(SYS_CODE_PATH) . 'css/' . api_get_visual_theme() . '/images/header-logo.png';
     if (file_exists($img)) {
         $img = api_get_path(WEB_CODE_PATH) . 'css/' . api_get_visual_theme() . '/images/header-logo.png';
         $organization = "<img src='{$img}'>";
     } else {
         if (!empty($organization)) {
             $organization = '<h2 align="left">' . $organization . '</h2>';
         }
     }
     Display::$global_template->assign('organization', $organization);
     //Showing only the current teacher/admin instead the all teacherlist name see BT#4080
     $user_info = api_get_user_info();
     $teacher_list = $user_info['complete_name'];
     $session_name = api_get_session_name(api_get_session_id());
     if (!empty($session_name)) {
         Display::$global_template->assign('pdf_session', $session_name);
     }
     Display::$global_template->assign('pdf_course', $this->params['course_code']);
     Display::$global_template->assign('pdf_date', api_format_date(api_get_utc_datetime(), DATE_TIME_FORMAT_LONG));
     Display::$global_template->assign('pdf_teachers', $teacher_list);
     Display::$global_template->assign('pdf_title', $this->params['pdf_title']);
     Display::$global_template->assign('add_signatures', $this->params['add_signatures']);
     //Getting template
     $tpl = Display::$global_template->get_template('export/table_pdf.tpl');
     $html = Display::$global_template->fetch($tpl);
     $html = api_utf8_encode($html);
     $css_file = api_get_path(TO_SYS, WEB_CSS_PATH) . '/print.css';
     $css = file_exists($css_file) ? @file_get_contents($css_file) : '';
     self::content_to_pdf($html, $css, $this->params['filename'], $this->params['course_code']);
 }
示例#12
0
 $sql = "SELECT * FROM {$TBL_STUDENT_PUBLICATION}\n                            \t\tWHERE description like '%{$search_this}%' AND url LIKE '%{$search_this2}%' AND session_id = {$new_session_id} AND c_id = {$course_id}\n                            \t\tORDER BY id desc  LIMIT 1";
 if ($debug) {
     echo $sql;
 }
 $sub_res = Database::query($sql);
 $num_rows = Database::num_rows($sub_res);
 if ($num_rows > 0) {
     $new_result = Database::fetch_array($sub_res, 'ASSOC');
     $created_dir = $new_result['url'];
     $new_parent_id = $new_result['id'];
 } else {
     if ($update_database) {
         $dir_name = substr($parent_data['url'], 1);
         $created_dir = create_unexisting_work_directory($base_work_dir, $dir_name);
         $created_dir = '/' . $created_dir;
         $now = api_get_utc_datetime();
         //Creating directory
         $sql_add_publication = "INSERT INTO " . $TBL_STUDENT_PUBLICATION . " SET\n                                           url         = '" . $created_dir . "',\n\t                                       c_id        = {$course_id},\n\t                                       title        = '" . $parent_data['title'] . "',\n\t                                       description  = '" . $parent_data['description'] . " folder_moved_from_session_id_{$origin_session_id} ',\n\t                                       author       = '',\n\t                                       active       = '0',\n\t                                       accepted     = '1',\n\t                                       filetype     = 'folder',\n\t                                       sent_date    = '" . $now . "',\n\t                                       qualification    = '" . $parent_data['qualification'] . "',\n\t                                       parent_id    = '',\n\t                                       qualificator_id  = '',\n\t                                       date_of_qualification    = '0000-00-00 00:00:00',\n\t                                       session_id   = " . $new_session_id;
         $rest_insert = Database::query($sql_add_publication);
         if ($debug) {
             echo $sql_add_publication;
         }
         // add the directory
         $id = Database::insert_id();
         //Folder created
         api_item_property_update($course_info, 'work', $id, 'DirectoryCreated', api_get_user_id());
         if ($debug) {
             var_dump($rest_insert);
         }
         $new_parent_id = $id;
         $result_message[$TBL_STUDENT_PUBLICATION . ' - new folder created called: ' . $created_dir]++;
示例#13
0
 /**
  * @param string $file
  * @param bool $moveFile
  */
 private function importStudents($file, $moveFile = true)
 {
     $data = Import::csv_to_array($file);
     /*
     * Another users import.
             Unique identifier: official code and username . ok
             Password should never get updated. ok
             If an update should need to occur (because it changed in the .csv),
             we’ll want that logged. We will handle this manually in that case.
             All other fields should be updateable, though passwords should of course not get updated. ok
             If a user gets deleted (not there anymore),
             He should be set inactive one year after the current date.
             So I presume you’ll just update the expiration date.
             We want to grant access to courses up to a year after deletion.
     */
     if (!empty($data)) {
         $language = $this->defaultLanguage;
         $this->logger->addInfo(count($data) . " records found.");
         foreach ($data as $row) {
             $row = $this->cleanUserRow($row);
             $user_id = UserManager::get_user_id_from_original_id($row['extra_' . $this->extraFieldIdNameList['user']], $this->extraFieldIdNameList['user']);
             $userInfo = array();
             $userInfoByOfficialCode = null;
             if (!empty($user_id)) {
                 $userInfo = api_get_user_info($user_id);
                 $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
             }
             $expirationDate = api_get_utc_datetime(strtotime("+" . intval($this->expirationDateInUserCreation) . "years"));
             if (empty($userInfo) && empty($userInfoByOfficialCode)) {
                 // Create user
                 $result = UserManager::create_user($row['firstname'], $row['lastname'], STUDENT, $row['email'], $row['username'], $row['password'], $row['official_code'], $language, $row['phone'], null, $row['auth_source'], $expirationDate, 1, 0, null, null, false);
                 if ($result) {
                     foreach ($row as $key => $value) {
                         if (substr($key, 0, 6) == 'extra_') {
                             //an extra field
                             UserManager::update_extra_field_value($result, substr($key, 6), $value);
                         }
                     }
                     $this->logger->addInfo("Students - User created: " . $row['username']);
                 } else {
                     $this->logger->addError("Students - User NOT created: " . $row['username'] . " " . $row['firstname'] . " " . $row['lastname']);
                 }
             } else {
                 if (empty($userInfo)) {
                     $this->logger->addError("Students - Can't update user :"******"Students - User email is not updated : " . $row['username'] . " because the avoid conditions (email).");
                             // Do not change email keep the old email.
                             $email = $userInfo['email'];
                         }
                         // 2. Condition
                         if (!in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
                             $email = $userInfo['email'];
                         }
                         // 3. Condition
                         if (in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
                             $email = $row['email'];
                         }
                         // Blocking password update
                         $avoidUsersWithPassword = $this->conditions['importStudents']['update']['avoid']['password'];
                         if ($userInfo['password'] != api_get_encrypted_password($row['password']) && in_array($row['password'], $avoidUsersWithPassword)) {
                             $this->logger->addInfo("Students - User password is not updated: " . $row['username'] . " because the avoid conditions (password).");
                             $password = null;
                             $resetPassword = 0;
                             // disallow password change
                         }
                     }
                 }
                 $expirationDate = api_get_utc_datetime(strtotime("+" . intval($this->expirationDateInUserUpdate) . "years"));
                 // Update user
                 $result = UserManager::update_user($userInfo['user_id'], $row['firstname'], $row['lastname'], $row['username'], $password, $row['auth_source'], $email, STUDENT, $userInfo['official_code'], $userInfo['phone'], $userInfo['picture_uri'], $expirationDate, $userInfo['active'], null, 0, null, null, null, false, $resetPassword);
                 if ($result) {
                     if ($row['username'] != $userInfo['username']) {
                         $this->logger->addInfo("Students - Username was changes from '" . $userInfo['username'] . "' to '" . $row['username'] . "' ");
                     }
                     foreach ($row as $key => $value) {
                         if (substr($key, 0, 6) == 'extra_') {
                             //an extra field
                             UserManager::update_extra_field_value($userInfo['user_id'], substr($key, 6), $value);
                         }
                     }
                     $this->logger->addInfo("Students - User updated: " . $row['username']);
                 } else {
                     $this->logger->addError("Students - User NOT updated: " . $row['username'] . " " . $row['firstname'] . " " . $row['lastname']);
                 }
             }
         }
     }
     if ($moveFile) {
         $this->moveFile($file);
     }
 }
 /**
  * Creates a new course request within the database.
  * @param string $wanted_code       The code for the created in the future course.
  * @param string $title
  * @param string $description
  * @param string $category_code
  * @param string $course_language
  * @param string $objetives
  * @param string $target_audience
  * @param int/string $user_id
  * @return int/bool The database id of the newly created course request or FALSE on failure.
  */
 public static function create_course_request($wanted_code, $title, $description, $category_code, $course_language, $objetives, $target_audience, $user_id, $exemplary_content)
 {
     $wanted_code = trim($wanted_code);
     $user_id = (int) $user_id;
     $exemplary_content = (bool) $exemplary_content ? 1 : 0;
     if ($wanted_code == '') {
         return false;
     }
     if (self::course_code_exists($wanted_code)) {
         return false;
     }
     if ($user_id <= 0) {
         return false;
     }
     $user_info = api_get_user_info($user_id);
     if (!is_array($user_info)) {
         return false;
     }
     $tutor_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $course_language);
     $request_date = api_get_utc_datetime();
     $status = COURSE_REQUEST_PENDING;
     $info = 0;
     $keys = AddCourse::define_course_keys($wanted_code, '');
     if (!count($keys)) {
         return false;
     }
     $visual_code = $keys['currentCourseCode'];
     $code = $keys['currentCourseId'];
     $db_name = isset($keys['currentCourseDbName']) ? $keys['currentCourseDbName'] : null;
     $directory = $keys['currentCourseRepository'];
     $sql = sprintf('INSERT INTO %s (
             code, user_id, directory, db_name,
             course_language, title, description, category_code,
             tutor_name, visual_code, request_date,
             objetives, target_audience, status, info, exemplary_content)
         VALUES (
             "%s", "%s", "%s", "%s",
             "%s", "%s", "%s", "%s",
             "%s", "%s", "%s",
             "%s", "%s", "%s", "%s", "%s");', Database::get_main_table(TABLE_MAIN_COURSE_REQUEST), Database::escape_string($code), Database::escape_string($user_id), Database::escape_string($directory), Database::escape_string($db_name), Database::escape_string($course_language), Database::escape_string($title), Database::escape_string($description), Database::escape_string($category_code), Database::escape_string($tutor_name), Database::escape_string($visual_code), Database::escape_string($request_date), Database::escape_string($objetives), Database::escape_string($target_audience), Database::escape_string($status), Database::escape_string($info), Database::escape_string($exemplary_content));
     $result_sql = Database::query($sql);
     if (!$result_sql) {
         return false;
     }
     $last_insert_id = Database::insert_id();
     // E-mail notifications.
     // E-mail language: The platform language seems to be the best choice.
     $email_language = api_get_setting('platformLanguage');
     $email_subject = sprintf(get_lang('CourseRequestEmailSubject', null, $email_language), '[' . api_get_setting('siteName') . ']', $code);
     $email_body = get_lang('CourseRequestMailOpening', null, $email_language) . "\n\n";
     $email_body .= get_lang('CourseName', null, $email_language) . ': ' . $title . "\n";
     $email_body .= get_lang('Fac', null, $email_language) . ': ' . $category_code . "\n";
     $email_body .= get_lang('CourseCode', null, $email_language) . ': ' . $code . "\n";
     $email_body .= get_lang('Professor', null, $email_language) . ': ' . api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $email_language) . "\n";
     $email_body .= get_lang('Email', null, $email_language) . ': ' . $user_info['mail'] . "\n";
     $email_body .= get_lang('Description', null, $email_language) . ': ' . $description . "\n";
     $email_body .= get_lang('Objectives', null, $email_language) . ': ' . $objetives . "\n";
     $email_body .= get_lang('TargetAudience', null, $email_language) . ': ' . $target_audience . "\n";
     $email_body .= get_lang('Ln', null, $email_language) . ': ' . $course_language . "\n";
     $email_body .= get_lang('FillWithExemplaryContent', null, $email_language) . ': ' . ($exemplary_content ? get_lang('Yes', null, $email_language) : get_lang('No', null, $email_language)) . "\n";
     // Sending an e-mail to the platform administrator.
     $email_body_admin = $email_body;
     $email_body_admin .= "\n" . get_lang('CourseRequestPageForApproval', null, $email_language) . ' ' . api_get_path(WEB_CODE_PATH) . 'admin/course_request_edit.php?id=' . $last_insert_id . "\n";
     $email_body_admin .= "\n" . get_lang('CourseRequestLegalNote', null, $email_language) . "\n";
     $sender_name_teacher = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
     $sender_email_teacher = $user_info['mail'];
     $recipient_name_admin = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
     $recipient_email_admin = api_get_setting('emailAdministrator');
     $userInfo = api_get_user_info($user_id);
     $additionalParameters = array('smsType' => SmsPlugin::NEW_COURSE_SUGGESTED_TEACHER, 'userId' => $user_id, 'userUsername' => $userInfo['username']);
     api_mail_html($recipient_name_admin, $recipient_email_admin, $email_subject, $email_body_admin, $sender_name_teacher, $sender_email_teacher, null, null, null, $additionalParameters);
     // Sending an e-mail to the requestor.
     $email_body_teacher = get_lang('Dear', null, $email_language) . ' ';
     $email_body_teacher .= api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $email_language) . ",\n\n";
     $email_body_teacher .= $email_body;
     $email_body_teacher .= "\n" . get_lang('Formula', null, $email_language) . "\n";
     $email_body_teacher .= api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, null, $email_language) . "\n";
     $email_body_teacher .= get_lang('Manager', null, $email_language) . ' ' . api_get_setting('siteName') . "\n";
     $email_body_teacher .= get_lang('Phone', null, $email_language) . ': ' . api_get_setting('administratorTelephone') . "\n";
     $email_body_teacher .= get_lang('Email', null, $email_language) . ': ' . api_get_setting('emailAdministrator', null, $email_language) . "\n";
     $email_body_teacher .= "\n" . get_lang('CourseRequestLegalNote', null, $email_language) . "\n";
     // Swap the sender and the recipient.
     $sender_name_admin = $recipient_name_admin;
     $sender_email_admin = $recipient_email_admin;
     $recipient_name_teacher = $sender_name_teacher;
     $recipient_email_teacher = $sender_email_teacher;
     $additionalParameters = array('smsType' => SmsPlugin::COURSE_OPENING_REQUEST_CODE_REGISTERED, 'userId' => $user_info['user_id'], 'courseCode' => $wanted_code);
     api_mail_html($recipient_name_teacher, $recipient_email_teacher, $email_subject, $email_body_teacher, $sender_name_admin, $sender_email_admin, null, null, null, $additionalParameters);
     return $last_insert_id;
 }
function WSUnsuscribeCoursesFromSession($params)
{
    if (!WSHelperVerifyKey($params)) {
        return return_error(WS_ERROR_SECRET_KEY);
    }
    // Initialisation
    $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
    $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
    $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
    $coursessessions_params = $params['coursessessions'];
    $results = array();
    $orig_course_id_value = array();
    $orig_session_id_value = array();
    foreach ($coursessessions_params as $coursesession_param) {
        $original_session_id_value = $coursesession_param['original_session_id_value'];
        $original_session_id_name = $coursesession_param['original_session_id_name'];
        $original_course_id_name = $coursesession_param['original_course_id_name'];
        $original_course_id_values = $coursesession_param['original_course_id_values'];
        $orig_session_id_value[] = $original_session_id_value;
        $id_session = SessionManager::getSessionIdFromOriginalId($original_session_id_value, $original_session_id_name);
        if (empty($id_session)) {
            $results[] = 0;
            continue;
        }
        // Get courses list from row_original_course_id_values
        $course_list = array();
        $courseIdList = [];
        foreach ($original_course_id_values as $row_original_course_list) {
            $course_code = Database::escape_string($row_original_course_list['course_code']);
            // Check whether exits $x_course_code into user_field_values table.
            $courseInfo = CourseManager::getCourseInfoFromOriginalId($row_original_course_list['course_code'], $original_course_id_name);
            if (empty($courseInfo) || isset($courseInfo) && $courseInfo['visibility'] == 0) {
                continue;
                // Course_code doesn't exist'
            }
            $course_list[] = $courseInfo['code'];
            $courseIdList[] = $courseInfo['real_id'];
        }
        if (empty($course_list)) {
            $results[] = 0;
            continue;
        }
        $orig_course_id_value[] = implode(',', $course_list);
        foreach ($courseIdList as $courseId) {
            $courseId = intval($courseId);
            Database::query("DELETE FROM {$tbl_session_rel_course}\n                            WHERE c_id ='{$courseId}' AND session_id='{$id_session}'");
            $result = Database::query("DELETE FROM {$tbl_session_rel_course_rel_user} WHERE c_id='{$courseId}' AND session_id = '{$id_session}'");
            Event::addEvent(LOG_SESSION_DELETE_COURSE, LOG_COURSE_ID, $courseId, api_get_utc_datetime(), api_get_user_id(), $courseId, $id_session);
            $return = Database::affected_rows($result);
        }
        $nbr_courses = 0;
        $sql = "SELECT nbr_courses FROM {$tbl_session} WHERE id = '{$id_session}'";
        $res_nbr_courses = Database::query($sql);
        $row_nbr_courses = Database::fetch_row($res_nbr_courses);
        if (Database::num_rows($res_nbr_courses) > 0) {
            $nbr_users = $row_nbr_courses[0] - $return;
        }
        // Update number of users in the session.
        $update_sql = "UPDATE {$tbl_session} SET nbr_courses= {$nbr_courses} WHERE id='{$id_session}' ";
        Database::query($update_sql);
        $results[] = 1;
        continue;
    }
    $count_results = count($results);
    $output = array();
    for ($i = 0; $i < $count_results; $i++) {
        $output[] = array('original_course_id_values' => $orig_course_id_value[$i], 'original_session_id_value' => $orig_session_id_value[$i], 'result' => $results[$i]);
    }
    return $output;
}
示例#16
0
 /**
  * @inheritdoc
  */
 public function update($values)
 {
     $values['updated_on'] = api_get_utc_datetime();
     $values['group_type'] = isset($values['group_type']) ? self::SOCIAL_CLASS : self::NORMAL_CLASS;
     if (isset($values['id'])) {
         $picture = isset($_FILES['picture']) ? $_FILES['picture'] : null;
         if (!empty($picture)) {
             $picture = $this->manageFileUpload($values['id'], $picture);
             if ($picture) {
                 $values['picture'] = $picture;
             }
         }
         if (isset($values['delete_picture'])) {
             $values['picture'] = null;
         }
     }
     parent::update($values);
     if (isset($values['delete_picture'])) {
         $this->delete_group_picture($values['id']);
     }
     return true;
 }
示例#17
0
         }
     } else {
         //only my contacts
         if ($access_url_id != 0) {
             $sql = "SELECT DISTINCT u.user_id as id, u.firstname, u.lastname, u.email\n                            FROM {$tbl_access_url_rel_user} r, {$tbl_my_user_friend} uf\n                            INNER JOIN {$tbl_my_user} AS u\n                            ON uf.friend_user_id = u.user_id\n                            WHERE\n                                u.status <> 6 AND\n                                relation_type NOT IN(" . USER_RELATION_TYPE_DELETED . ", " . USER_RELATION_TYPE_RRHH . ") AND\n                                uf.user_id = {$user_id} AND\n                                friend_user_id <> {$user_id} AND\n                                u.user_id = r.user_id AND\n                                r.access_url_id = {$access_url_id}\n                                {$likeCondition}";
         } else {
             $sql = "SELECT DISTINCT u.user_id as id, u.firstname, u.lastname, u.email\n                            FROM {$tbl_my_user_friend} uf\n                            INNER JOIN {$tbl_my_user} AS u\n                            ON uf.friend_user_id = u.user_id\n         \t                WHERE\n                                u.status <> 6 AND\n                                relation_type NOT IN(" . USER_RELATION_TYPE_DELETED . ", " . USER_RELATION_TYPE_RRHH . ") AND\n                                uf.user_id = {$user_id} AND\n                                friend_user_id <> {$user_id}\n                                {$likeCondition}";
         }
     }
 } elseif (api_get_setting('social.allow_social_tool') == 'false' && api_get_setting('message.allow_message_tool') == 'true') {
     if (api_get_setting('message.allow_send_message_to_all_platform_users') == 'true') {
         $sql = "SELECT DISTINCT u.user_id as id, u.firstname, u.lastname, u.email\n                        FROM {$tbl_user} u LEFT JOIN {$tbl_access_url_rel_user} r ON u.user_id = r.user_id\n                        WHERE\n                            u.status <> 6  AND\n                            u.user_id <> {$user_id} AND\n                            r.access_url_id = {$access_url_id}\n                            {$likeCondition} ";
     } else {
         $time_limit = api_get_setting('display.time_limit_whosonline');
         $online_time = time() - $time_limit * 60;
         $limit_date = api_get_utc_datetime($online_time);
         $sql = "SELECT SELECT DISTINCT u.user_id as id, u.firstname, u.lastname, u.email\n                        FROM {$tbl_my_user} u INNER JOIN {$track_online_table} t\n                        ON u.user_id=t.login_user_id\n                        WHERE login_date >= '" . $limit_date . "' AND\n                        {$likeCondition}";
     }
 }
 $sql .= ' LIMIT 20';
 $result = Database::query($sql);
 $showEmail = api_get_setting('display.show_email_addresses');
 $return = array();
 if (Database::num_rows($result) > 0) {
     while ($row = Database::fetch_array($result, 'ASSOC')) {
         $name = api_get_person_name($row['firstname'], $row['lastname']);
         if ($showEmail == 'true') {
             $name .= ' (' . $row['email'] . ')';
         }
         $return['items'][] = array('text' => $name, 'id' => $row['id']);
     }
 /**
  * @param string $category_code
  * @param int $random_value
  * @param array $limit will be used if $random_value is not set.
  * This array should contains 'start' and 'length' keys
  * @return array
  */
 function browseCoursesInCategory($category_code, $random_value = null, $limit = array())
 {
     $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
     $specialCourseList = CourseManager::get_special_course_list();
     $without_special_courses = '';
     if (!empty($specialCourseList)) {
         $without_special_courses = ' AND course.code NOT IN (' . implode(',', $specialCourseList) . ')';
     }
     $visibilityCondition = null;
     $hidePrivate = api_get_setting('platform.course_catalog_hide_private');
     if ($hidePrivate === 'true') {
         $courseInfo = api_get_course_info();
         $courseVisibility = $courseInfo['visibility'];
         $visibilityCondition = ' AND course.visibility <> 1';
     }
     if (!empty($random_value)) {
         $random_value = intval($random_value);
         $sql = "SELECT COUNT(*) FROM {$tbl_course}";
         $result = Database::query($sql);
         list($num_records) = Database::fetch_row($result);
         if (api_is_multiple_url_enabled()) {
             $url_access_id = api_get_current_access_url_id();
             $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
             $sql = "SELECT COUNT(*) FROM {$tbl_course} course\n                        INNER JOIN {$tbl_url_rel_course} as url_rel_course\n                        ON (url_rel_course.c_id = course.id)\n                        WHERE access_url_id = {$url_access_id} ";
             $result = Database::query($sql);
             list($num_records) = Database::fetch_row($result);
             $sql = "SELECT course.id FROM {$tbl_course} course\n                        INNER JOIN {$tbl_url_rel_course} as url_rel_course\n                        ON (url_rel_course.c_id = course.id)\n                        WHERE\n                            access_url_id = {$url_access_id} AND\n                            RAND()*{$num_records}< {$random_value}\n                            {$without_special_courses} {$visibilityCondition}\n                        ORDER BY RAND()\n                        LIMIT 0, {$random_value}";
         } else {
             $sql = "SELECT id FROM {$tbl_course} course\n                        WHERE RAND()*{$num_records}< {$random_value} {$without_special_courses} {$visibilityCondition}\n                        ORDER BY RAND()\n                        LIMIT 0, {$random_value}";
         }
         $result = Database::query($sql);
         $id_in = null;
         while (list($id) = Database::fetch_row($result)) {
             if ($id_in) {
                 $id_in .= ",{$id}";
             } else {
                 $id_in = "{$id}";
             }
         }
         if ($id_in === null) {
             return array();
         }
         $sql = "SELECT * FROM {$tbl_course} WHERE id IN({$id_in})";
     } else {
         $limitFilter = self::getLimitFilterFromArray($limit);
         $category_code = Database::escape_string($category_code);
         if (empty($category_code) || $category_code == "ALL") {
             $sql = "SELECT * FROM {$tbl_course}\n                        WHERE\n                            1=1\n                            {$without_special_courses}\n                            {$visibilityCondition}\n                        ORDER BY title {$limitFilter} ";
         } else {
             if ($category_code == 'NONE') {
                 $category_code = '';
             }
             $sql = "SELECT * FROM {$tbl_course}\n                        WHERE\n                            category_code='{$category_code}'\n                            {$without_special_courses}\n                            {$visibilityCondition}\n                        ORDER BY title {$limitFilter} ";
         }
         //showing only the courses of the current Chamilo access_url_id
         if (api_is_multiple_url_enabled()) {
             $url_access_id = api_get_current_access_url_id();
             $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
             if ($category_code != "ALL") {
                 $sql = "SELECT * FROM {$tbl_course} as course\n                            INNER JOIN {$tbl_url_rel_course} as url_rel_course\n                            ON (url_rel_course.c_id = course.id)\n                            WHERE\n                                access_url_id = {$url_access_id} AND\n                                category_code='{$category_code}'\n                                {$without_special_courses}\n                                {$visibilityCondition}\n                            ORDER BY title {$limitFilter}";
             } else {
                 $sql = "SELECT * FROM {$tbl_course} as course\n                            INNER JOIN {$tbl_url_rel_course} as url_rel_course\n                            ON (url_rel_course.c_id = course.id)\n                            WHERE\n                                access_url_id = {$url_access_id}\n                                {$without_special_courses}\n                                {$visibilityCondition}\n                            ORDER BY title {$limitFilter}";
             }
         }
     }
     $result = Database::query($sql);
     $courses = array();
     while ($row = Database::fetch_array($result)) {
         $row['registration_code'] = !empty($row['registration_code']);
         $count_users = CourseManager::get_users_count_in_course($row['code']);
         $count_connections_last_month = Tracking::get_course_connections_count($row['id'], 0, api_get_utc_datetime(time() - 30 * 86400));
         if ($row['tutor_name'] == '0') {
             $row['tutor_name'] = get_lang('NoManager');
         }
         $point_info = CourseManager::get_course_ranking($row['id'], 0);
         $courses[] = array('real_id' => $row['id'], 'point_info' => $point_info, 'code' => $row['code'], 'directory' => $row['directory'], 'visual_code' => $row['visual_code'], 'title' => $row['title'], 'tutor' => $row['tutor_name'], 'subscribe' => $row['subscribe'], 'unsubscribe' => $row['unsubscribe'], 'registration_code' => $row['registration_code'], 'creation_date' => $row['creation_date'], 'visibility' => $row['visibility'], 'count_users' => $count_users, 'count_connections' => $count_connections_last_month);
     }
     return $courses;
 }
示例#19
0
 /**
  * Print the number of users that didn't login for a certain period of time
  */
 public static function printUsersNotLoggedInStats()
 {
     $totalLogin = array();
     $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
     $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
     $current_url_id = api_get_current_access_url_id();
     $total = self::countUsers();
     if (api_is_multiple_url_enabled()) {
         $table_url = ", {$access_url_rel_user_table}";
         $where_url = " AND login_user_id=user_id AND access_url_id='" . $current_url_id . "'";
     } else {
         $table_url = '';
         $where_url = '';
     }
     $now = api_get_utc_datetime();
     $sql[get_lang('ThisDay')] = "SELECT count(distinct(login_user_id)) AS number " . " FROM {$table} {$table_url} " . " WHERE DATE_ADD(login_date, INTERVAL 1 DAY) >= '{$now}' {$where_url}";
     $sql[get_lang('Last7days')] = "SELECT count(distinct(login_user_id)) AS number " . " FROM {$table} {$table_url} " . " WHERE DATE_ADD(login_date, INTERVAL 7 DAY) >= '{$now}' {$where_url}";
     $sql[get_lang('Last31days')] = "SELECT count(distinct(login_user_id)) AS number " . " FROM {$table} {$table_url} " . " WHERE DATE_ADD(login_date, INTERVAL 31 DAY) >= '{$now}' {$where_url}";
     $sql[sprintf(get_lang('LastXMonths'), 6)] = "SELECT count(distinct(login_user_id)) AS number " . " FROM {$table} {$table_url} " . " WHERE DATE_ADD(login_date, INTERVAL 6 MONTH) >= '{$now}' {$where_url}";
     $sql[get_lang('NeverConnected')] = "SELECT count(distinct(login_user_id)) AS number " . " FROM {$table} {$table_url} WHERE 1=1 {$where_url}";
     foreach ($sql as $index => $query) {
         $res = Database::query($query);
         $obj = Database::fetch_object($res);
         $r = $total - $obj->number;
         $totalLogin[$index] = $r < 0 ? 0 : $r;
     }
     Statistics::printStats(get_lang('StatsUsersDidNotLoginInLastPeriods'), $totalLogin, false);
 }
 /**
  *
  * @param ItemProperty $item 
  */
 public function update($item)
 {
     $this->defaults($item);
     $user_id = api_get_user_id();
     $item->set_insert_user_id($user_id);
     $c_id = $item->get_c_id();
     $id = $item->get_id();
     //$tool = Database::escape_string($item->get_tool());
     //$insert_user_id = $item->get_insert_user_id();
     //$insert_date = api_get_utc_datetime($item->get_insert_date());
     $lastedit_date = api_get_utc_datetime($item->get_lastedit_date());
     //$ref = $item->get_ref();
     $lastedit_type = Database::escape_string($item->get_lastedit_type());
     $last_edit_user_id = $item->get_lastedit_user_id();
     $to_group_id = $item->get_to_group_id();
     $to_group_id = empty($to_group_id) ? '0' : $to_group_id;
     $to_user_id = $item->get_to_user_id();
     $to_user_id = empty($to_user_id) ? '0' : $to_user_id;
     $visibility = $item->get_visibility();
     $visibility = $visibility ? $visibility : '0';
     $start_visible = $item->get_start_visible();
     $start_visible = empty($start_visible) ? '0000-00-00 00:00:00' : api_get_utc_datetime($start_visible);
     $end_visible = $item->get_end_visible();
     $end_visible = empty($end_visible) ? '0000-00-00 00:00:00' : api_get_utc_datetime($end_visible);
     $session_id = $item->get_id_session();
     $TABLE = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $sql = "UPDATE \n                    {$TABLE}\n                SET \n                    lastedit_date\t\t= '{$lastedit_date}',\n                    lastedit_type\t\t= '{$lastedit_type}',\n                    lastedit_user_id\t= {$last_edit_user_id},\n                    to_group_id         = {$to_group_id},\n                    to_user_id          = {$to_user_id},\n                    visibility\t\t\t= {$visibility},\n                    start_visible       = '{$start_visible}',\n                    end_visible         = '{$end_visible}',\n                    id_session \t\t\t= {$session_id}\n                WHERE \n                    c_id =  {$c_id} AND\n                    id = {$id}";
     $result = Database::query($sql);
     return (bool) $result;
 }
示例#21
0
 /**
  * Sends a message from one user to another user
  * @param int $from_user_id The ID of the user sending the message
  * @param int $to_user_id The ID of the user receiving the message
  * @param string $message Message
  * @param boolean $printResult Optional. Whether print the result
  * @param boolean $sanitize Optional. Whether sanitize the message
  * @return void Prints "1"
  */
 public function send($from_user_id, $to_user_id, $message, $printResult = true, $sanitize = true)
 {
     $user_friend_relation = SocialManager::get_relation_between_contacts($from_user_id, $to_user_id);
     if ($user_friend_relation == USER_RELATION_TYPE_FRIEND) {
         $user_info = api_get_user_info($to_user_id, true);
         $this->save_window($to_user_id);
         $_SESSION['openChatBoxes'][$to_user_id] = api_get_utc_datetime();
         if ($sanitize) {
             $messagesan = self::sanitize($message);
         } else {
             $messagesan = $message;
         }
         error_log(print_r($sanitize) . '----' . $messagesan);
         if (!isset($_SESSION['chatHistory'][$to_user_id])) {
             $_SESSION['chatHistory'][$to_user_id] = array();
         }
         $item = array("s" => "1", "f" => $from_user_id, "m" => $messagesan, "username" => get_lang('Me'));
         $_SESSION['chatHistory'][$to_user_id]['items'][] = $item;
         $_SESSION['chatHistory'][$to_user_id]['user_info']['user_name'] = $user_info['complete_name'];
         $_SESSION['chatHistory'][$to_user_id]['user_info']['online'] = $user_info['user_is_online'];
         $_SESSION['chatHistory'][$to_user_id]['user_info']['avatar'] = $user_info['avatar_small'];
         unset($_SESSION['tsChatBoxes'][$to_user_id]);
         $params = array();
         $params['from_user'] = intval($from_user_id);
         $params['to_user'] = intval($to_user_id);
         $params['message'] = $message;
         $params['sent'] = api_get_utc_datetime();
         if (!empty($from_user_id) && !empty($to_user_id)) {
             $this->save($params);
         }
         if ($printResult) {
             echo "1";
             exit;
         }
     } else {
         if ($printResult) {
             echo "0";
             exit;
         }
     }
 }
 /**
  * It's used for controlling attendace calendar (list, add, edit, delete),
  * render to attendance_calendar view
  * @param string action (optional, by default 'calendar_list')
  * @param int	 attendance id (optional)
  * @param int	 calendar id (optional)
  */
 public function attendance_calendar($action = 'calendar_list', $attendance_id = 0, $calendar_id = 0)
 {
     $attendance = new Attendance();
     $calendar_id = intval($calendar_id);
     $data = array();
     $data['attendance_id'] = $attendance_id;
     $attendance_id = intval($attendance_id);
     if ($action == 'calendar_add') {
         if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST") {
             if (!isset($_POST['cancel'])) {
                 if (isset($_POST['repeat'])) {
                     //@todo  check this error_logs
                     $start_datetime = api_strtotime(api_get_utc_datetime($attendance->build_datetime_from_array($_POST['date_time'])), 'UTC');
                     //error_log('$start_datetime '.$start_datetime);
                     $_POST['end_date_time']['H'] = $_POST['date_time']['H'];
                     $_POST['end_date_time']['i'] = $_POST['date_time']['i'];
                     //error_log($attendance->build_datetime_from_array($_POST['end_date_time']));
                     $end_datetime = api_strtotime(api_get_utc_datetime($attendance->build_datetime_from_array($_POST['end_date_time'])), 'UTC');
                     //error_log('$end_datetime '.$end_datetime);
                     $checkdate = checkdate($_POST['end_date_time']['F'], $_POST['end_date_time']['d'], $_POST['end_date_time']['Y']);
                     $repeat_type = $_POST['repeat_type'];
                     if ($end_datetime > $start_datetime && $checkdate) {
                         $affected_rows = $attendance->attendance_repeat_calendar_add($attendance_id, $start_datetime, $end_datetime, $repeat_type);
                         $action = 'calendar_list';
                     } else {
                         if (!$checkdate) {
                             $data['error_checkdate'] = true;
                         } else {
                             $data['error_repeat_date'] = true;
                         }
                         $data['repeat'] = true;
                         $action = 'calendar_add';
                     }
                 } else {
                     $datetime = $attendance->build_datetime_from_array($_POST['date_time']);
                     $datetimezone = api_get_utc_datetime($datetime);
                     if (!empty($datetime)) {
                         $attendance->set_date_time($datetimezone);
                         $affected_rows = $attendance->attendance_calendar_add($attendance_id);
                         $action = 'calendar_list';
                     } else {
                         $data['error_date'] = true;
                         $action = 'calendar_add';
                     }
                 }
             } else {
                 $action = 'calendar_list';
             }
         }
     } else {
         if ($action == 'calendar_edit') {
             $data['calendar_id'] = $calendar_id;
             if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST") {
                 if (!isset($_POST['cancel'])) {
                     $datetime = $attendance->build_datetime_from_array($_POST['date_time']);
                     $datetimezone = api_get_utc_datetime($datetime);
                     $attendance->set_date_time($datetimezone);
                     $affected_rows = $attendance->attendance_calendar_edit($calendar_id, $attendance_id);
                     $data['calendar_id'] = 0;
                     $action = 'calendar_list';
                 } else {
                     $action = 'calendar_list';
                 }
             }
         } else {
             if ($action == 'calendar_delete') {
                 $affected_rows = $attendance->attendance_calendar_delete($calendar_id, $attendance_id);
                 $action = 'calendar_list';
             } else {
                 if ($action == 'calendar_all_delete') {
                     $affected_rows = $attendance->attendance_calendar_delete(0, $attendance_id, true);
                     $action = 'calendar_list';
                 }
             }
         }
     }
     $data['action'] = $action;
     $data['attendance_calendar'] = $attendance->get_attendance_calendar($attendance_id);
     $data['is_locked_attendance'] = $attendance->is_locked_attendance($attendance_id);
     // render to the view
     $this->view->set_data($data);
     $this->view->set_layout('layout');
     $this->view->set_template('attendance_calendar');
     $this->view->render();
 }
 /**
  * Save values in the *_field_values table
  * @param array $params Structured array with the values to save
  * @param boolean $show_query Whether to show the insert query (passed to the parent save() method)
  * @result mixed The result sent from the parent method
  * @assert (array()) === false
  */
 public function save($params, $show_query = false)
 {
     $extra_field = $this->getExtraField();
     // Setting value to insert.
     $value = $params['value'];
     $value_to_insert = null;
     if (is_array($value)) {
         $value_to_insert = implode(';', $value);
     } else {
         $value_to_insert = Database::escape_string($value);
     }
     $params['value'] = $value_to_insert;
     // If field id exists
     if (isset($params['field_id'])) {
         $extraFieldInfo = $extra_field->get($params['field_id']);
     } else {
         // Try the variable
         $extraFieldInfo = $extra_field->get_handler_field_info_by_field_variable($params['variable']);
         $params['field_id'] = $extraFieldInfo['id'];
     }
     if ($extraFieldInfo) {
         switch ($extraFieldInfo['field_type']) {
             case ExtraField::FIELD_TYPE_RADIO:
             case ExtraField::FIELD_TYPE_SELECT:
                 break;
             case ExtraField::FIELD_TYPE_SELECT_MULTIPLE:
                 //$field_options = $session_field_option->get_field_options_by_field($params['field_id']);
                 //$params['field_value'] = split(';', $value_to_insert);
                 /*
                                         if ($field_options) {
                                             $check = false;
                                             foreach ($field_options as $option) {
                                                 if (in_array($option['option_value'], $values)) {
                                                     $check = true;
                                                     break;
                                                 }
                                            }
                                            if (!$check) {
                                                return false; //option value not found
                                            }
                                        } else {
                                            return false; //enumerated type but no option found
                                        }*/
                 break;
             case ExtraField::FIELD_TYPE_TEXT:
             case ExtraField::FIELD_TYPE_TEXTAREA:
                 break;
             case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
                 if (is_array($value)) {
                     if (isset($value['extra_' . $extraFieldInfo['variable']]) && isset($value['extra_' . $extraFieldInfo['variable'] . '_second'])) {
                         $value_to_insert = $value['extra_' . $extraFieldInfo['variable']] . '::' . $value['extra_' . $extraFieldInfo['variable'] . '_second'];
                     } else {
                         $value_to_insert = null;
                     }
                 }
                 break;
             default:
                 break;
         }
         if ($extraFieldInfo['field_type'] == ExtraField::FIELD_TYPE_TAG) {
             $field_values = self::getAllValuesByItemAndFieldAndValue($params['item_id'], $params['field_id'], $value);
         } else {
             $field_values = self::get_values_by_handler_and_field_id($params['item_id'], $params['field_id']);
         }
         $params['value'] = $value_to_insert;
         $params['author_id'] = api_get_user_id();
         // Insert
         if (empty($field_values)) {
             /* Enable this when field_loggeable is introduced as a table field (2.0)
                if ($extraFieldInfo['field_loggeable'] == 1) {
                */
             if (false) {
                 global $app;
                 switch ($this->type) {
                     case 'question':
                         $extraFieldValue = new ChamiloLMS\Entity\QuestionFieldValues();
                         $extraFieldValue->setUserId(api_get_user_id());
                         $extraFieldValue->setQuestionId($params[$this->handler_id]);
                         break;
                     case 'course':
                         $extraFieldValue = new ChamiloLMS\Entity\CourseFieldValues();
                         $extraFieldValue->setUserId(api_get_user_id());
                         $extraFieldValue->setQuestionId($params[$this->handler_id]);
                         break;
                     case 'user':
                         $extraFieldValue = new ChamiloLMS\Entity\UserFieldValues();
                         $extraFieldValue->setUserId($params[$this->handler_id]);
                         $extraFieldValue->setAuthorId(api_get_user_id());
                         break;
                     case 'session':
                         $extraFieldValue = new ChamiloLMS\Entity\SessionFieldValues();
                         $extraFieldValue->setUserId(api_get_user_id());
                         $extraFieldValue->setSessionId($params[$this->handler_id]);
                         break;
                 }
                 if (isset($extraFieldValue)) {
                     if (!empty($params['value'])) {
                         $extraFieldValue->setComment($params['comment']);
                         $extraFieldValue->setFieldValue($params['value']);
                         $extraFieldValue->setFieldId($params['field_id']);
                         $extraFieldValue->setTms(api_get_utc_datetime(null, false, true));
                         $app['orm.ems']['db_write']->persist($extraFieldValue);
                         $app['orm.ems']['db_write']->flush();
                     }
                 }
             } else {
                 if ($extraFieldInfo['field_type'] == ExtraField::FIELD_TYPE_TAG) {
                     $option = new ExtraFieldOption($this->type);
                     $optionExists = $option->get($params['value']);
                     if (empty($optionExists)) {
                         $optionParams = array('field_id' => $params['field_id'], 'option_value' => $params['value']);
                         $optionId = $option->saveOptions($optionParams);
                     } else {
                         $optionId = $optionExists['id'];
                     }
                     $params['value'] = $optionId;
                     if ($optionId) {
                         return parent::save($params, $show_query);
                     }
                 } else {
                     return parent::save($params, $show_query);
                 }
             }
         } else {
             // Update
             /* Enable this when field_loggeable is introduced as a table field (2.0)
                if ($extraFieldInfo['field_loggeable'] == 1) {
                */
             if (false) {
                 global $app;
                 switch ($this->type) {
                     case 'question':
                         $extraFieldValue = $app['orm.ems']['db_write']->getRepository('ChamiloLMS\\Entity\\QuestionFieldValues')->find($field_values['id']);
                         $extraFieldValue->setUserId(api_get_user_id());
                         $extraFieldValue->setQuestionId($params[$this->handler_id]);
                         break;
                     case 'course':
                         $extraFieldValue = $app['orm.ems']['db_write']->getRepository('ChamiloLMS\\Entity\\CourseFieldValues')->find($field_values['id']);
                         $extraFieldValue->setUserId(api_get_user_id());
                         $extraFieldValue->setCourseCode($params[$this->handler_id]);
                         break;
                     case 'user':
                         $extraFieldValue = $app['orm.ems']['db_write']->getRepository('ChamiloLMS\\Entity\\UserFieldValues')->find($field_values['id']);
                         $extraFieldValue->setUserId(api_get_user_id());
                         $extraFieldValue->setAuthorId(api_get_user_id());
                         break;
                     case 'session':
                         $extraFieldValue = $app['orm.ems']['db_write']->getRepository('ChamiloLMS\\Entity\\SessionFieldValues')->find($field_values['id']);
                         $extraFieldValue->setUserId(api_get_user_id());
                         $extraFieldValue->setSessionId($params[$this->handler_id]);
                         break;
                 }
                 if (isset($extraFieldValue)) {
                     if (!empty($params['value'])) {
                         /*
                          *  If the field value is similar to the previous value then the comment will be the same
                             in order to no save in the log an empty record
                         */
                         if ($extraFieldValue->getFieldValue() == $params['value']) {
                             if (empty($params['comment'])) {
                                 $params['comment'] = $extraFieldValue->getComment();
                             }
                         }
                         $extraFieldValue->setComment($params['comment']);
                         $extraFieldValue->setFieldValue($params['value']);
                         $extraFieldValue->setFieldId($params['field_id']);
                         $extraFieldValue->setTms(api_get_utc_datetime(null, false, true));
                         $app['orm.ems']['db_write']->persist($extraFieldValue);
                         $app['orm.ems']['db_write']->flush();
                     }
                 }
             } else {
                 $params['id'] = $field_values['id'];
                 return parent::update($params, $show_query);
             }
         }
     }
 }
示例#24
0
    /**
     * insert log result
     */
    public function add_result__log($userid, $evaluationid)
    {
        if (isset($userid) && isset($evaluationid)) {
            $tbl_grade_results_log = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT_LOG);
            $result = new Result();
            $arr_result = $result->load(null, $userid, $evaluationid);
            $arr = get_object_vars($arr_result[0]);
            $sql = 'INSERT INTO ' . $tbl_grade_results_log . ' (id_result,user_id, evaluation_id,created_at';
            if (isset($arr['score'])) {
                $sql .= ',score';
            }
            $sql .= ') VALUES
					(' . (int) $arr['id'] . ',' . (int) $arr['user_id'] . ', ' . (int) $arr['evaluation'] . ", '" . api_get_utc_datetime() . "'";
            if (isset($arr['score'])) {
                $sql .= ', ' . $arr['score'];
            }
            $sql .= ')';
            Database::query($sql);
        } else {
            die('Error in Result add: required field empty');
        }
    }
示例#25
0
     $array_content_id_exe = array_slice($post_content_id, $loop_in_track);
 } else {
     $array_content_id_exe = $post_content_id;
 }
 for ($i = 0; $i < $loop_in_track; $i++) {
     $my_marks = $_POST['marks_' . $array_content_id_exe[$i]];
     $contain_comments = $_POST['comments_' . $array_content_id_exe[$i]];
     if (isset($contain_comments)) {
         $my_comments = $_POST['comments_' . $array_content_id_exe[$i]];
     } else {
         $my_comments = '';
     }
     $my_questionid = intval($array_content_id_exe[$i]);
     $params = ['marks' => $my_marks, 'teacher_comment' => $my_comments];
     Database::update($TBL_TRACK_ATTEMPT, $params, ['question_id = ? AND exe_id = ?' => [$my_questionid, $id]]);
     $params = ['exe_id' => $id, 'question_id' => $my_questionid, 'marks' => $my_marks, 'insert_date' => api_get_utc_datetime(), 'author' => api_get_user_id(), 'teacher_comment' => $my_comments];
     Database::insert($TBL_TRACK_ATTEMPT_RECORDING, $params);
 }
 $qry = 'SELECT DISTINCT question_id, marks
         FROM ' . $TBL_TRACK_ATTEMPT . ' WHERE exe_id = ' . $id . '
         GROUP BY question_id';
 $res = Database::query($qry);
 $tot = 0;
 while ($row = Database::fetch_array($res, 'ASSOC')) {
     $tot += $row['marks'];
 }
 $sql = "UPDATE {$TBL_TRACK_EXERCISES}\n            SET exe_result = '" . floatval($tot) . "'\n            WHERE exe_id = " . $id;
 Database::query($sql);
 if (isset($_POST['send_notification'])) {
     //@todo move this somewhere else
     $subject = get_lang('ExamSheetVCC');
示例#26
0
 public static function who_is_online_in_this_course_count($uid, $time_limit, $coursecode = null)
 {
     if (empty($coursecode)) {
         return false;
     }
     $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
     $coursecode = Database::escape_string($coursecode);
     $time_limit = Database::escape_string($time_limit);
     $online_time = time() - $time_limit * 60;
     $current_date = api_get_utc_datetime($online_time);
     $query = "SELECT count(login_user_id) as count FROM " . $track_online_table . "\n                  WHERE login_user_id <> 2 AND course='" . $coursecode . "' AND login_date >= '{$current_date}' ";
     $result = Database::query($query);
     if (Database::num_rows($result) > 0) {
         $row = Database::fetch_array($result);
         return $row['count'];
     } else {
         return false;
     }
 }
示例#27
0
/**
 * This function retrieves all the personal agenda items and add them to the agenda items found by the other functions.
 */
function get_personal_agenda_items($user_id, $agendaitems, $day = "", $month = "", $year = "", $week = "", $type)
{
    $tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
    $user_id = intval($user_id);
    // 1. creating the SQL statement for getting the personal agenda items in MONTH view
    if ($type == "month_view" or $type == "") {
        // we are in month view
        $sql = "SELECT * FROM " . $tbl_personal_agenda . " WHERE user='******' and MONTH(date)='" . $month . "' AND YEAR(date) = '" . $year . "'  ORDER BY date ASC";
    }
    // 2. creating the SQL statement for getting the personal agenda items in WEEK view
    // we are in week view
    if ($type == "week_view") {
        $start_end_day_of_week = calculate_start_end_of_week($week, $year);
        $start_day = $start_end_day_of_week['start']['day'];
        $start_month = $start_end_day_of_week['start']['month'];
        $start_year = $start_end_day_of_week['start']['year'];
        $end_day = $start_end_day_of_week['end']['day'];
        $end_month = $start_end_day_of_week['end']['month'];
        $end_year = $start_end_day_of_week['end']['year'];
        // in sql statements you have to use year-month-day for date calculations
        $start_filter = $start_year . "-" . $start_month . "-" . $start_day . " 00:00:00";
        $start_filter = api_get_utc_datetime($start_filter);
        $end_filter = $end_year . "-" . $end_month . "-" . $end_day . " 23:59:59";
        $end_filter = api_get_utc_datetime($end_filter);
        $sql = " SELECT * FROM " . $tbl_personal_agenda . " WHERE user='******' AND date>='" . $start_filter . "' AND date<='" . $end_filter . "'";
    }
    // 3. creating the SQL statement for getting the personal agenda items in DAY view
    if ($type == "day_view") {
        // we are in day view
        // we could use mysql date() function but this is only available from 4.1 and higher
        $start_filter = $year . "-" . $month . "-" . $day . " 00:00:00";
        $start_filter = api_get_utc_datetime($start_filter);
        $end_filter = $year . "-" . $month . "-" . $day . " 23:59:59";
        $end_filter = api_get_utc_datetime($end_filter);
        $sql = " SELECT * FROM " . $tbl_personal_agenda . " WHERE user='******' AND date>='" . $start_filter . "' AND date<='" . $end_filter . "'";
    }
    $result = Database::query($sql);
    while ($item = Database::fetch_array($result, 'ASSOC')) {
        $time_minute = api_convert_and_format_date($item['date'], TIME_NO_SEC_FORMAT);
        $item['date'] = api_get_local_time($item['date']);
        $item['start_date_tms'] = api_strtotime($item['date']);
        $item['content'] = $item['text'];
        // we break the date field in the database into a date and a time part
        $agenda_db_date = explode(" ", $item['date']);
        $date = $agenda_db_date[0];
        $time = $agenda_db_date[1];
        // we divide the date part into a day, a month and a year
        $agendadate = explode("-", $item['date']);
        $year = intval($agendadate[0]);
        $month = intval($agendadate[1]);
        $day = intval($agendadate[2]);
        // we divide the time part into hour, minutes, seconds
        $agendatime = explode(":", $time);
        $hour = $agendatime[0];
        $minute = $agendatime[1];
        $second = $agendatime[2];
        if ($type == 'month_view') {
            $item['calendar_type'] = 'personal';
            $item['start_date'] = $item['date'];
            $agendaitems[$day][] = $item;
            continue;
        }
        // if the student has specified a course we a add a link to that course
        if ($item['course'] != "") {
            $url = api_get_path(WEB_CODE_PATH) . "calendar/agenda.php?cidReq=" . urlencode($item['course']) . "&amp;day={$day}&amp;month={$month}&amp;year={$year}#{$day}";
            // RH  //Patrick Cool: to highlight the relevant agenda item
            $course_link = "<a href=\"{$url}\" title=\"" . $item['course'] . "\">" . $item['course'] . "</a>";
        } else {
            $course_link = "";
        }
        // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
        // if we have a day_view we use a half hour as index => key 33 = 16h30
        if ($type !== "day_view") {
            // This is the array construction for the WEEK or MONTH view
            //Display events in agenda
            $agendaitems[$day] .= "<div><i>{$time_minute}</i> {$course_link} <a href=\"myagenda.php?action=view&amp;view=personal&amp;day={$day}&amp;month={$month}&amp;year={$year}&amp;id=" . $item['id'] . "#" . $item['id'] . "\" class=\"personal_agenda\">" . $item['title'] . "</a></div><br />";
        } else {
            // this is the array construction for the DAY view
            $halfhour = 2 * $agendatime['0'];
            if ($agendatime['1'] >= '30') {
                $halfhour = $halfhour + 1;
            }
            //Display events by list
            $agendaitems[$halfhour] .= "<div><i>{$time_minute}</i> {$course_link} <a href=\"myagenda.php?action=view&amp;view=personal&amp;day={$day}&amp;month={$month}&amp;year={$year}&amp;id=" . $item['id'] . "#" . $item['id'] . "\" class=\"personal_agenda\">" . $item['title'] . "</a></div>";
        }
    }
    return $agendaitems;
}
 /**
  * @param int $idevaluation
  */
 public function add_evaluation_log($idevaluation)
 {
     if (!empty($idevaluation)) {
         $tbl_grade_evaluations = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
         $tbl_grade_linkeval_log = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG);
         $eval = new Evaluation();
         $dateobject = $eval->load($idevaluation, null, null, null, null);
         $arreval = get_object_vars($dateobject[0]);
         if (!empty($arreval['id'])) {
             $sql = 'SELECT weight from ' . $tbl_grade_evaluations . '
                     WHERE id=' . $arreval['id'];
             $rs = Database::query($sql);
             $row_old_weight = Database::fetch_array($rs, 'ASSOC');
             $current_date = api_get_utc_datetime();
             $params = ['id_linkeval_log' => $arreval['id'], 'name' => $arreval['name'], 'description' => $arreval['description'], 'created_at' => $current_date, 'weight' => $row_old_weight['weight'], 'visible' => $arreval['visible'], 'type' => 'evaluation', 'user_id_log' => api_get_user_id()];
             Database::insert($tbl_grade_linkeval_log, $params);
         }
     }
 }
 /**
  * @param string $link
  * @param int $userId
  * @param int $courseId
  * @param int $sessionId
  *
  * @return bool
  */
 public function saveUserMailLegal($link, $userId, $courseId, $sessionId)
 {
     $data = $this->getUserAcceptedLegal($userId, $courseId, $sessionId);
     if (empty($data)) {
         return null;
     }
     if ($data['mail_agreement_link'] == $link) {
         $table = Database::get_main_table('session_rel_course_rel_user_legal');
         $id = $data['id'];
         $values = array('mail_agreement' => 1, 'mail_agreement_date' => api_get_utc_datetime());
         Database::update($table, $values, array('id = ?' => array($id)));
     }
 }
示例#30
0
 /**
  * Closes a meeting (usually when the user click on the close button from
  * the conferences listing.
  * @param string The internal ID of the meeting (id field for this meeting)
  * @return void
  * @assert (0) === false
  */
 public function endMeeting($id)
 {
     if (empty($id)) {
         return false;
     }
     $meetingData = Database::select('*', $this->table, array('where' => array('id = ?' => array($id))), 'first');
     $pass = $this->getUserMeetingPassword();
     $endParams = array('meetingId' => $meetingData['remote_id'], 'password' => $pass);
     $this->api->endMeetingWithXmlResponseArray($endParams);
     Database::update($this->table, array('status' => 0, 'closed_at' => api_get_utc_datetime()), array('id = ? ' => $id));
 }