/** * Search for a list of available courses by title or code, based on * a given string * @param string String to search for * @param int Deprecated param * @return string A formatted, xajax answer block * @assert () === false */ function search_courses($needle, $id) { global $tbl_course; $xajax_response = new XajaxResponse(); $return = ''; if (!empty($needle)) { // xajax send utf8 datas... datas in db can be non-utf8 datas $charset = api_get_system_encoding(); $needle = api_convert_encoding($needle, $charset, 'utf-8'); $needle = Database::escape_string($needle); // search courses where username or firstname or lastname begins likes $needle $sql = 'SELECT code, title FROM ' . $tbl_course . ' u ' . ' WHERE (title LIKE "' . $needle . '%" ' . ' OR code LIKE "' . $needle . '%" ' . ' ) ' . ' ORDER BY title, code ' . ' LIMIT 11'; $rs = Database::query($sql); $i = 0; while ($course = Database::fetch_array($rs)) { $i++; if ($i <= 10) { $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_url(\'' . addslashes($course['code']) . '\',\'' . addslashes($course['title']) . ' (' . addslashes($course['code']) . ')' . '\')">' . $course['title'] . ' (' . $course['code'] . ')</a><br />'; } else { $return .= '...<br />'; } } } $xajax_response->addAssign('ajax_list_courses', 'innerHTML', api_utf8_encode($return)); return $xajax_response; }
function search_users($needle, $type) { global $_configuration, $tbl_access_url_rel_user, $tbl_user, $user_anonymous, $current_user_id, $user_id; $xajax_response = new XajaxResponse(); $return = ''; if (!empty($needle) && !empty($type)) { // xajax send utf8 datas... datas in db can be non-utf8 datas $charset = api_get_system_encoding(); $needle = api_convert_encoding($needle, $charset, 'utf-8'); $assigned_users_to_hrm = UserManager::get_users_followed_by_drh($user_id); $assigned_users_id = array_keys($assigned_users_to_hrm); $without_assigned_users = ''; if (count($assigned_users_id) > 0) { $without_assigned_users = " AND user.user_id NOT IN(" . implode(',', $assigned_users_id) . ")"; } if ($_configuration['multiple_access_urls']) { $sql = "SELECT user.user_id, username, lastname, firstname FROM {$tbl_user} user LEFT JOIN {$tbl_access_url_rel_user} au ON (au.user_id = user.user_id)\n\t\t\tWHERE " . (api_sort_by_first_name() ? 'firstname' : 'lastname') . " LIKE '{$needle}%' AND status NOT IN(" . DRH . ", " . SESSIONADMIN . ") AND user.user_id NOT IN ({$user_anonymous}, {$current_user_id}, {$user_id}) {$without_assigned_users} AND access_url_id = " . api_get_current_access_url_id() . ""; } else { $sql = "SELECT user_id, username, lastname, firstname FROM {$tbl_user} user\n\t\t\tWHERE " . (api_sort_by_first_name() ? 'firstname' : 'lastname') . " LIKE '{$needle}%' AND status NOT IN(" . DRH . ", " . SESSIONADMIN . ") AND user_id NOT IN ({$user_anonymous}, {$current_user_id}, {$user_id}) {$without_assigned_users}"; } $rs = Database::query($sql); $return .= '<select id="origin" name="NoAssignedUsersList[]" multiple="multiple" size="20" style="width:340px;">'; while ($user = Database::fetch_array($rs)) { $person_name = api_get_person_name($user['firstname'], $user['lastname']); $return .= '<option value="' . $user['user_id'] . '" title="' . htmlspecialchars($person_name, ENT_QUOTES) . '">' . $person_name . ' (' . $user['username'] . ')</option>'; } $return .= '</select>'; $xajax_response->addAssign('ajax_list_users_multiple', 'innerHTML', api_utf8_encode($return)); } return $xajax_response; }
public function sqlConnect() { if (!$this->connection_handler) { $this->connection_handler = @mysql_connect($this->connection['server'], $this->connection['login'], $this->connection['password'], true); // The system has not been designed to use special SQL modes that were introduced since MySQL 5 @mysql_query("set session sql_mode='';", $this->connection_handler); @mysql_select_db($this->connection['base'], $this->connection_handler); // Initialization of the database connection encoding to be used. // The internationalization library should be already initialized. @mysql_query("SET SESSION character_set_server='utf8';", $this->connection_handler); @mysql_query("SET SESSION collation_server='utf8_general_ci';", $this->connection_handler); $system_encoding = api_get_system_encoding(); if (api_is_utf8($system_encoding)) { // See Bug #1802: For UTF-8 systems we prefer to use "SET NAMES 'utf8'" statement in order to avoid a bizarre problem with Chinese language. @mysql_query("SET NAMES 'utf8';", $this->connection_handler); } else { @mysql_query("SET CHARACTER SET '" . Database::to_db_encoding($system_encoding) . "';", $this->connection_handler); } } return ($this->connection_handler) ? true : false; }
function search_sessions($needle, $type) { global $_configuration, $tbl_session_rel_access_url, $tbl_session, $user_id; $xajax_response = new XajaxResponse(); $return = ''; if (!empty($needle) && !empty($type)) { // xajax send utf8 datas... datas in db can be non-utf8 datas $charset = api_get_system_encoding(); $needle = api_convert_encoding($needle, $charset, 'utf-8'); $assigned_sessions_to_hrm = SessionManager::get_sessions_followed_by_drh($user_id); $assigned_sessions_id = array_keys($assigned_sessions_to_hrm); $without_assigned_sessions = ''; if (count($assigned_sessions_id) > 0) { $without_assigned_sessions = " AND s.id NOT IN(" . implode(',', $assigned_sessions_id) . ")"; } if ($_configuration['multiple_access_urls']) { $sql = " SELECT s.id, s.name FROM {$tbl_session} s LEFT JOIN {$tbl_session_rel_access_url} a ON (s.id = a.session_id)\n\t\t\t\t\t\tWHERE s.name LIKE '{$needle}%' {$without_assigned_sessions} AND access_url_id = " . api_get_current_access_url_id() . ""; } else { $sql = "SELECT s.id, s.name FROM {$tbl_session} s\n\t\t\t\tWHERE s.name LIKE '{$needle}%' {$without_assigned_sessions} "; } $rs = Database::query($sql); $return .= '<select id="origin" name="NoAssignedSessionsList[]" multiple="multiple" size="20" style="width:340px;">'; while ($session = Database::fetch_array($rs)) { $return .= '<option value="' . $session['id'] . '" title="' . htmlspecialchars($session['name'], ENT_QUOTES) . '">' . $session['name'] . '</option>'; } $return .= '</select>'; $xajax_response->addAssign('ajax_list_sessions_multiple', 'innerHTML', api_utf8_encode($return)); } return $xajax_response; }
function search_courses($needle, $type) { global $_configuration, $tbl_course, $tbl_course_rel_access_url, $user_id; $xajax_response = new XajaxResponse(); $return = ''; if (!empty($needle) && !empty($type)) { // xajax send utf8 datas... datas in db can be non-utf8 datas $charset = api_get_system_encoding(); $needle = api_convert_encoding($needle, $charset, 'utf-8'); $needle = Database::escape_string($needle); $assigned_courses_to_hrm = CourseManager::get_courses_followed_by_drh($user_id); $assigned_courses_code = array_keys($assigned_courses_to_hrm); foreach ($assigned_courses_code as &$value) { $value = "'" . $value . "'"; } $without_assigned_courses = ''; if (count($assigned_courses_code) > 0) { $without_assigned_courses = " AND c.code NOT IN(" . implode(',', $assigned_courses_code) . ")"; } if ($_configuration['multiple_access_urls']) { $sql = "SELECT c.code, c.title FROM {$tbl_course} c LEFT JOIN {$tbl_course_rel_access_url} a ON (a.course_code = c.code)\n WHERE c.code LIKE '{$needle}%' {$without_assigned_courses} AND access_url_id = " . api_get_current_access_url_id() . ""; } else { $sql = "SELECT c.code, c.title FROM {$tbl_course} c\n WHERE c.code LIKE '{$needle}%' {$without_assigned_courses} "; } $rs = Database::query($sql); $return .= '<select id="origin" name="NoAssignedCoursesList[]" multiple="multiple" size="20" style="width:340px;">'; while ($course = Database::fetch_array($rs)) { $return .= '<option value="' . $course['code'] . '" title="' . htmlspecialchars($course['title'], ENT_QUOTES) . '">' . $course['title'] . ' (' . $course['code'] . ')</option>'; } $return .= '</select>'; $xajax_response->addAssign('ajax_list_courses_multiple', 'innerHTML', api_utf8_encode($return)); } return $xajax_response; }
/** * Search users by username, firstname or lastname, based on the given * search string * @param string Search string * @param int Deprecated param * @return string Xajax response block * @assert () === false */ public static function search_users($needle, $id) { global $tbl_user, $tbl_access_url_rel_user; $xajax_response = new XajaxResponse(); $return = ''; if (!empty($needle)) { // xajax send utf8 datas... datas in db can be non-utf8 datas $charset = api_get_system_encoding(); $needle = api_convert_encoding($needle, $charset, 'utf-8'); $needle = Database::escape_string($needle); // search users where username or firstname or lastname begins likes $needle $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username'; $sql = 'SELECT u.user_id, username, lastname, firstname FROM ' . $tbl_user . ' u ' . ' WHERE (username LIKE "' . $needle . '%" ' . ' OR firstname LIKE "' . $needle . '%" ' . ' OR lastname LIKE "' . $needle . '%") ' . $order_clause . ' LIMIT 11'; $rs = Database::query($sql); $i = 0; while ($user = Database::fetch_array($rs)) { $i++; if ($i <= 10) { $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_url(\'' . addslashes($user['user_id']) . '\',\'' . api_get_person_name(addslashes($user['firstname']), addslashes($user['lastname'])) . ' (' . addslashes($user['username']) . ')' . '\')">' . api_get_person_name($user['firstname'], $user['lastname']) . ' (' . $user['username'] . ')</a><br />'; } else { $return .= '...<br />'; } } } $xajax_response->addAssign('ajax_list_users', 'innerHTML', api_utf8_encode($return)); return $xajax_response; }
/** * Search sessions by name, based on a search string * @param string Search string * @param int Deprecated param * @return string Xajax response block * @assert () === false */ function search_sessions($needle, $id) { global $tbl_session; $xajax_response = new XajaxResponse(); $return = ''; if (!empty($needle)) { // xajax send utf8 datas... datas in db can be non-utf8 datas $charset = api_get_system_encoding(); $needle = api_convert_encoding($needle, $charset, 'utf-8'); $needle = Database::escape_string($needle); // search sessiones where username or firstname or lastname begins likes $needle $sql = 'SELECT id, name FROM ' . $tbl_session . ' u WHERE (name LIKE "' . $needle . '%") ORDER BY name, id LIMIT 11'; $rs = Database::query($sql); $i = 0; while ($session = Database::fetch_array($rs)) { $i++; if ($i <= 10) { $return .= '<a href="#" onclick="add_user_to_url(\'' . addslashes($session['id']) . '\',\'' . addslashes($session['name']) . ' (' . addslashes($session['id']) . ')' . '\')">' . $session['name'] . ' </a><br />'; } else { $return .= '...<br />'; } } } $xajax_response->addAssign('ajax_list_courses', 'innerHTML', api_utf8_encode($return)); return $xajax_response; }
/** * Generates a course code from a course title * @todo Such a function might be useful in other places too. It might be moved in the CourseManager class. * @todo the function might be upgraded for avoiding code duplications (currently, it might suggest a code that is already in use) * @param string A course title * @param string The course title encoding (defaults to type defined globally) * @return string A proposed course code * @assert (null,null) === false * @assert ('ABC_DEF', null) === 'ABCDEF' * @assert ('ABC09*^[%A', null) === 'ABC09A' */ function generate_course_code($course_title, $encoding = null) { if (empty($encoding)) { $encoding = api_get_system_encoding(); } return substr(preg_replace('/[^A-Z0-9]/', '', strtoupper(api_transliterate($course_title, 'X', $encoding))), 0, CourseManager::MAX_COURSE_LENGTH_CODE); }
/** * Gets html pages and compose them into a learning path * @param array The files that will compose the generated learning path. Unused so far. * @return boolean False if file does not exit. Nothing otherwise. */ function make_lp($files = array()) { global $_course; // We get a content where ||page_break|| indicates where the page is broken. if (!file_exists($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html')) { return false; } $content = file_get_contents($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html'); unlink($this->base_work_dir.'/'.$this->file_path); unlink($this->base_work_dir.'/'.$this->created_dir.'/'.$this->file_name.'.html'); // The file is utf8 encoded and it seems to make problems with special quotes. // Then we htmlentities that, we replace these quotes and html_entity_decode that in good charset. $charset = api_get_system_encoding(); $content = api_htmlentities($content, ENT_COMPAT, $this->original_charset); $content = str_replace('’', '\'', $content); $content = api_convert_encoding($content, $charset, $this->original_charset); $content = str_replace($this->original_charset, $charset, $content); $content = api_html_entity_decode($content, ENT_COMPAT, $charset); // Set the path to pictures to absolute (so that it can be modified in fckeditor). $content = preg_replace("|src=\"([^\"]*)|i", "src=\"".api_get_path(REL_COURSE_PATH).$_course['path'].'/document'.$this->created_dir."/\\1", $content); list($header, $body) = explode('<BODY', $content); $body = '<BODY'.$body; // Remove font-family styles. $header = preg_replace("|font\-family[^;]*;|i", '', $header); // Chamilo styles. $my_style = api_get_setting('stylesheets'); if (empty($my_style)) { $my_style = 'chamilo'; } $style_to_import = "<style type=\"text/css\">\r\n"; $style_to_import .= '@import "'.api_get_path(WEB_CODE_PATH).'css/'.$my_style.'/default.css";'."\n"; $style_to_import .= "</style>\r\n"; $header = preg_replace("|</head>|i", "\r\n$style_to_import\r\n\\0", $header); // Line break before and after picture. $header = str_replace('p {', 'p {clear:both;', $header); $header = str_replace('absolute', 'relative', $header); switch ($this->split_steps) { case 'per_page': $this -> dealPerPage($header, $body); break; case 'per_chapter': $this -> dealPerChapter($header, $body); break; } }
function search_coachs($needle) { global $tbl_user; $xajax_response = new XajaxResponse(); $return = ''; if (!empty($needle)) { // xajax send utf8 datas... datas in db can be non-utf8 datas $charset = api_get_system_encoding(); $needle = api_convert_encoding($needle, $charset, 'utf-8'); $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username'; // search users where username or firstname or lastname begins likes $needle $sql = 'SELECT username, lastname, firstname FROM ' . $tbl_user . ' user WHERE (username LIKE "' . $needle . '%" OR firstname LIKE "' . $needle . '%" OR lastname LIKE "' . $needle . '%") AND status=1' . $order_clause . ' LIMIT 10'; if (api_is_multiple_url_enabled()) { $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { $sql = 'SELECT username, lastname, firstname FROM ' . $tbl_user . ' user INNER JOIN ' . $tbl_user_rel_access_url . ' url_user ON (url_user.user_id=user.user_id) WHERE access_url_id = ' . $access_url_id . ' AND (username LIKE "' . $needle . '%" OR firstname LIKE "' . $needle . '%" OR lastname LIKE "' . $needle . '%") AND status=1' . $order_clause . ' LIMIT 10'; } } $rs = Database::query($sql); while ($user = Database::fetch_array($rs)) { $return .= '<a href="javascript: void(0);" onclick="javascript: fill_coach_field(\'' . $user['username'] . '\')">' . api_get_person_name($user['firstname'], $user['lastname']) . ' (' . $user['username'] . ')</a><br />'; } } $xajax_response->addAssign('ajax_list_coachs', 'innerHTML', api_utf8_encode($return)); return $xajax_response; }
/** * Search for a session based on a given search string * @param string A search string * @param string A search box type (single or anything else) * @return string XajaxResponse * @assert ('abc','single') !== '' */ function search_courses($needle, $type) { global $tbl_session; $xajax_response = new XajaxResponse(); $return = ''; if (!empty($needle) && !empty($type)) { // xajax send utf8 datas... datas in db can be non-utf8 datas $charset = api_get_system_encoding(); $needle = api_convert_encoding($needle, $charset, 'utf-8'); $needle = Database::escape_string($needle); $sql = 'SELECT * FROM ' . $tbl_session . ' WHERE name LIKE "' . $needle . '%" ORDER BY id'; $rs = Database::query($sql); $course_list = array(); $return .= '<select id="origin" name="NoSessionCategoryList[]" multiple="multiple" size="20" style="width:340px;">'; while ($course = Database::fetch_array($rs)) { $course_list[] = $course['id']; $return .= '<option value="' . $course['id'] . '" title="' . htmlspecialchars($course['name'], ENT_QUOTES) . '">' . $course['name'] . '</option>'; } $return .= '</select>'; $xajax_response->addAssign('ajax_list_courses_multiple', 'innerHTML', api_utf8_encode($return)); } $_SESSION['course_list'] = $course_list; return $xajax_response; }
$msg = $_SESSION['oLP']->get_message(); error_log('New LP - Loaded lp_save : ' . $_SERVER['REQUEST_URI'] . ' from ' . $_SERVER['HTTP_REFERER'], 0); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo api_get_language_isocode(); ?> " lang="<?php echo api_get_language_isocode(); ?> "> <head> <meta http-equiv="Content-Type" content="text/html; charset=<?php echo api_get_system_encoding(); ?> " /> <script language='javascript'> <?php if ($_SESSION['oLP']->mode != 'fullscreen') { } ?> </script> </head> <body dir="<?php echo api_get_text_direction(); ?> "> </body></html>
/** * Creates a list with all the assignments in it * * @return string */ function get_student_publication() { global $charset; $table_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION); $table_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY); $sp_lang_var = api_convert_encoding(get_lang('LpAssignment'), $charset, api_get_system_encoding()); $return = '<a href="#" onclick="javascript:popup(\'popUpDiv5\');" class="big_button four_buttons rounded grey_border assignement_button">' . $sp_lang_var . '</a>'; $assignments_lang_var = api_convert_encoding(get_lang('Assignments'), $charset, api_get_system_encoding()); $close_lang_var = api_convert_encoding(get_lang('Close'), $charset, api_get_system_encoding()); $newassignment_lang_var = api_convert_encoding(get_lang('LpNewAssignment'), $charset, api_get_system_encoding()); $return .= '<div id="popUpDiv5" class="author_popup gradient rounded_10 grey_border" style="display:none;">' . '<span class="title">' . $assignments_lang_var . '</span>' . '<a href="#" class="close" onclick="javascript:popup(\'popUpDiv5\');">' . $close_lang_var . '</a>'; $return .= '<div id="resDoc" class="content">'; $sql = "SELECT id,url FROM {$table_work} s INNER JOIN {$table_item_property} i ON s.id = i.ref WHERE i.insert_user_id = '" . api_get_user_id() . "' AND session_id = '" . api_get_session_id() . "' AND filetype='folder' AND i.tool = 'work' AND i.visibility=1 "; $a_work = array(); $rs = Database::query($sql, __FILE__, __LINE__); while ($row = Database::fetch_array($rs)) { $a_work[] = $row; } foreach ($a_work as $work) { $return .= '<div class="lp_resource_element">'; if (!empty($work['id'])) { $return .= '<img alt="" src="../img/assignment_22.png" style="margin-right:5px;" title="" />'; $return .= '<a style="cursor:hand" style="vertical-align:middle"></a> <a href="' . api_get_self() . '?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&action=add_item&type=' . TOOL_STUDENTPUBLICATION . '&work_id=' . $work['id'] . '&lp_id=' . $this->lp_id . '" style="vertical-align:middle">' . api_convert_encoding(substr($work['url'], 1), $charset, api_get_system_encoding()) . '</a>'; } $return .= '</div>'; } $return .= '<div class="lp_resource_element">'; $return .= Display::return_icon('pixel.gif', '', array('class' => 'actionplaceholdericon actionnewlist', 'alt' => "' . {$newassignment_lang_var} . '", 'style' => 'margin-right:5px;', 'title' => "' . {$newassignment_lang_var} . '")); $return .= '<a href="../work/work.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&toolgroup=&curdirpath=/&createdir=1&origin=&gradebook=type=' . TOOL_STUDENTPUBLICATION . '&lp_id=' . $this->lp_id . '">' . $newassignment_lang_var . '</a>'; $return .= '</div>'; $return .= '</div>'; $return .= '</div>'; return $return; }
/** * @param $needle * @return xajaxResponse */ public static function searchUserGroupAjax($needle) { $response = new xajaxResponse(); $return = ''; if (!empty($needle)) { // xajax send utf8 datas... datas in db can be non-utf8 datas $charset = api_get_system_encoding(); $needle = api_convert_encoding($needle, $charset, 'utf-8'); $needle = Database::escape_string($needle); // search courses where username or firstname or lastname begins likes $needle $sql = 'SELECT id, name FROM ' . Database::get_main_table(TABLE_USERGROUP) . ' u WHERE name LIKE "' . $needle . '%" ORDER BY name LIMIT 11'; $result = Database::query($sql); $i = 0; while ($data = Database::fetch_array($result)) { $i++; if ($i <= 10) { $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_url(\'' . addslashes($data['id']) . '\',\'' . addslashes($data['name']) . ' \')">' . $data['name'] . ' </a><br />'; } else { $return .= '...<br />'; } } } $response->addAssign('ajax_list_courses', 'innerHTML', api_utf8_encode($return)); return $response; }
if ($key < $number_of_courses - 1) { ?> <a href="courses.php?action=<?php echo $action; ?>&move=down&course=<?php echo $course['code']; ?>&category=<?php echo $course['user_course_cat']; ?>&sec_token=<?php echo $stok; ?>"> <?php echo Display::display_icon('down.png', get_lang('Down'),'',22); ?> </a> <?php } else { echo Display::display_icon('down_na.png', get_lang('Down'),'',22); }?> </div> <div style="float:left; margin-right:10px;"> <!-- cancel subscrioption--> <?php if ($course['status'] != 1) { if ($course['unsubscr'] == 1) { ?> <!-- changed link to submit to avoid action by the search tool indexer --> <form action="<?php echo api_get_self(); ?>" method="post" onsubmit="javascript: if (!confirm('<?php echo addslashes(api_htmlentities(get_lang("ConfirmUnsubscribeFromCourse"), ENT_QUOTES, api_get_system_encoding())) ?>')) return false;"> <input type="hidden" name="sec_token" value="<?php echo $stok; ?>"> <input type="hidden" name="unsubscribe" value="<?php echo $course['code']; ?>" /> <button class="btn" value="<?php echo get_lang('Unsubscribe'); ?>" name="unsub"> <?php echo get_lang('Unsubscribe'); ?> </button> </form> </div> <?php } } ?> </td> </tr> <?php $key++; }
function search_users($needle, $type) { global $tbl_user, $tbl_session_rel_user, $id_session; $xajax_response = new XajaxResponse(); $return = ''; if (!empty($needle) && !empty($type)) { //normal behaviour if ($type == 'any_session' && $needle == 'false') { $type = 'multiple'; $needle = ''; } // xajax send utf8 datas... datas in db can be non-utf8 datas $charset = api_get_system_encoding(); $needle = Database::escape_string($needle); $needle = api_convert_encoding($needle, $charset, 'utf-8'); $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username'; $cond_user_id = ''; //Only for single & multiple if (in_array($type, array('single', 'multiple'))) { if (!empty($id_session)) { $id_session = intval($id_session); // check id_user from session_rel_user table $sql = 'SELECT id_user FROM ' . $tbl_session_rel_user . ' WHERE id_session ="' . $id_session . '" AND relation_type<>' . SESSION_RELATION_TYPE_RRHH . ' '; $res = Database::query($sql); $user_ids = array(); if (Database::num_rows($res) > 0) { while ($row = Database::fetch_row($res)) { $user_ids[] = (int) $row[0]; } } if (count($user_ids) > 0) { $cond_user_id = ' AND user.user_id NOT IN(' . implode(",", $user_ids) . ')'; } } } switch ($type) { case 'single': // search users where username or firstname or lastname begins likes $needle $sql = 'SELECT user.user_id, username, lastname, firstname, official_code FROM ' . $tbl_user . ' user WHERE (username LIKE "' . $needle . '%" OR firstname LIKE "' . $needle . '%" OR lastname LIKE "' . $needle . '%") AND user.status<>6 AND user.status<>' . DRH . '' . $order_clause . ' LIMIT 11'; break; case 'multiple': $sql = 'SELECT user.user_id, username, lastname, firstname, official_code FROM ' . $tbl_user . ' user WHERE ' . (api_sort_by_first_name() ? 'firstname' : 'lastname') . ' LIKE "' . $needle . '%" AND user.status<>' . DRH . ' AND user.status<>6 ' . $cond_user_id . $order_clause; break; case 'any_session': $sql = 'SELECT DISTINCT user.user_id, username, lastname, firstname, official_code FROM ' . $tbl_user . ' user LEFT OUTER JOIN ' . $tbl_session_rel_user . ' s ON (s.id_user = user.user_id) WHERE s.id_user IS null AND user.status<>' . DRH . ' AND user.status<>6 ' . $cond_user_id . $order_clause; break; } if (api_is_multiple_url_enabled()) { $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { switch ($type) { case 'single': $sql = 'SELECT user.user_id, username, lastname, firstname, official_code FROM ' . $tbl_user . ' user INNER JOIN ' . $tbl_user_rel_access_url . ' url_user ON (url_user.user_id=user.user_id) WHERE access_url_id = ' . $access_url_id . ' AND (username LIKE "' . $needle . '%" OR firstname LIKE "' . $needle . '%" OR lastname LIKE "' . $needle . '%") AND user.status<>6 AND user.status<>' . DRH . ' ' . $order_clause . ' LIMIT 11'; break; case 'multiple': $sql = 'SELECT user.user_id, username, lastname, firstname , official_code FROM ' . $tbl_user . ' user INNER JOIN ' . $tbl_user_rel_access_url . ' url_user ON (url_user.user_id=user.user_id) WHERE access_url_id = ' . $access_url_id . ' AND ' . (api_sort_by_first_name() ? 'firstname' : 'lastname') . ' LIKE "' . $needle . '%" AND user.status<>' . DRH . ' AND user.status<>6 ' . $cond_user_id . $order_clause; break; case 'any_session': $sql = 'SELECT DISTINCT user.user_id, username, lastname, firstname, official_code FROM ' . $tbl_user . ' user LEFT OUTER JOIN ' . $tbl_session_rel_user . ' s ON (s.id_user = user.user_id) INNER JOIN ' . $tbl_user_rel_access_url . ' url_user ON (url_user.user_id=user.user_id) WHERE access_url_id = ' . $access_url_id . ' AND s.id_user IS null AND user.status<>' . DRH . ' AND user.status<>6 ' . $cond_user_id . $order_clause; break; } } } $rs = Database::query($sql); $i = 0; if ($type == 'single') { while ($user = Database::fetch_array($rs)) { $i++; if ($i <= 10) { $person_name = api_get_person_name($user['firstname'], $user['lastname']) . ' (' . $user['username'] . ') ' . $user['official_code']; $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_session(\'' . $user['user_id'] . '\',\'' . $person_name . ' ' . '\')">' . $person_name . ' </a><br />'; } else { $return .= '...<br />'; } } $xajax_response->addAssign('ajax_list_users_single', 'innerHTML', api_utf8_encode($return)); } else { global $nosessionUsersList; $return .= '<select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;">'; while ($user = Database::fetch_array($rs)) { $person_name = api_get_person_name($user['firstname'], $user['lastname']) . ' (' . $user['username'] . ') ' . $user['official_code']; $return .= '<option value="' . $user['user_id'] . '">' . $person_name . ' </option>'; } $return .= '</select>'; $xajax_response->addAssign('ajax_list_users_multiple', 'innerHTML', api_utf8_encode($return)); } } return $xajax_response; }
/** * Static function to parse AICC ini files. * Based on work by sinedeo at gmail dot com published on php.net (parse_ini_file()) * @param string File path * @return array Structured array */ function parse_ini_file_quotes_safe($f) { $null = ""; $r = $null; $sec = $null; $f = @file($f); for ($i = 0; $i < @count($f); $i++) { $newsec = 0; $w = @trim($f[$i]); if ($w) { if ($w[0] == ';') { continue; } if (!$r or $sec) { if (@substr($w, 0, 1) == "[" and @substr($w, -1, 1) == "]") { $sec = @substr($w, 1, @strlen($w) - 2); $newsec = 1; } } if (!$newsec) { $w = @explode("=", $w); $k = @trim($w[0]); unset($w[0]); $v = @trim(@implode("=", $w)); $v = api_convert_encoding($v, api_get_system_encoding(), mb_detect_encoding($v)); if (@substr($v, 0, 1) == "\"" and @substr($v, -1, 1) == "\"") { $v = @substr($v, 1, @strlen($v) - 2); } if ($sec) { if (strtolower($sec) == 'course_description') { //special case $r[strtolower($sec)] = $k; } else { $r[strtolower($sec)][strtolower($k)] = $v; } } else { $r[strtolower($k)] = $v; } } } } return $r; }
/** * stores the user course category in the chamilo_user database * @param string Category title * @return bool True if it success */ public function store_course_category($category_title) { $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY); // protect data $current_user_id = api_get_user_id(); $category_title = Database::escape_string($category_title); $result = false; // step 1: we determine the max value of the user defined course categories $sql = "SELECT sort FROM {$tucc} WHERE user_id='" . $current_user_id . "' ORDER BY sort DESC"; $rs_sort = Database::query($sql); $maxsort = Database::fetch_array($rs_sort); $nextsort = $maxsort['sort'] + 1; // step 2: we check if there is already a category with this name, if not we store it, else we give an error. $sql = "SELECT * FROM {$tucc} WHERE user_id='" . $current_user_id . "' AND title='" . $category_title . "'ORDER BY sort DESC"; $rs = Database::query($sql); if (Database::num_rows($rs) == 0) { $sql_insert = "INSERT INTO {$tucc} (user_id, title,sort)\n VALUES ('" . $current_user_id . "', '" . api_htmlentities($category_title, ENT_QUOTES, api_get_system_encoding()) . "', '" . $nextsort . "')"; $resultQuery = Database::query($sql_insert); if (Database::affected_rows($resultQuery)) { $result = true; } } else { $result = false; } return $result; }
/** * Manages chapter splitting * @param string Chapter header * @param string Content * @return void */ function dealPerChapter($header, $content) { $_course = api_get_course_info(); $content = str_replace('||page_break||', '', $content); // Get all the h1. preg_match_all("|<h1[^>]*>([^(h1)+]*)</h1>|is", $content, $matches_temp); // Empty the fake chapters. $new_index = 0; for ($i = 0; $i < count($matches_temp[0]); $i++) { if (trim($matches_temp[1][$i]) !== '') { $matches[0][$new_index] = $matches_temp[0][$i]; $matches[1][$new_index] = $matches_temp[1][$i]; $new_index++; } } // Add intro item. $intro_content = api_substr($content, 0, api_strpos($content, $matches[0][0])); $items_to_create[get_lang('Introduction')] = $intro_content; for ($i = 0; $i < count($matches[0]); $i++) { if (empty($matches[1][$i])) { continue; } $content = api_strstr($content, $matches[0][$i]); if ($i + 1 !== count($matches[0])) { $chapter_content = api_substr($content, 0, api_strpos($content, $matches[0][$i + 1])); } else { $chapter_content = $content; } $items_to_create[$matches[1][$i]] = $chapter_content; } $i = 0; foreach ($items_to_create as $item_title => $item_content) { $i++; $page_content = $this->format_page_content($header, $item_content); $html_file = $this->created_dir . '-' . $i . '.html'; $handle = fopen($this->base_work_dir . $this->created_dir . '/' . $html_file, 'w+'); fwrite($handle, $page_content); fclose($handle); $document_id = add_document($_course, $this->created_dir . '/' . $html_file, 'file', filesize($this->base_work_dir . $this->created_dir . '/' . $html_file), $html_file); if ($document_id) { // Put the document in item_property update. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_SESSION['_uid'], 0, 0, null, null, api_get_session_id()); $infos = pathinfo($this->filepath); $slide_name = strip_tags(nl2br($item_title)); $slide_name = str_replace(array("\r\n", "\r", "\n"), '', $slide_name); $slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_system_encoding()); $previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, ''); if ($this->first_item == 0) { $this->first_item = $previous; } } } }
/** * @param array $courseInfo * @param $file * @return array|bool|string */ public function importEventFile($courseInfo, $file) { $charset = api_get_system_encoding(); $filepath = api_get_path(SYS_ARCHIVE_PATH) . $file['name']; $messages = array(); if (!@move_uploaded_file($file['tmp_name'], $filepath)) { error_log('Problem moving uploaded file: ' . $file['error'] . ' in ' . __FILE__ . ' line ' . __LINE__); return false; } $data = file_get_contents($filepath); $trans = array('DAILY' => 'daily', 'WEEKLY' => 'weekly', 'MONTHLY' => 'monthlyByDate', 'YEARLY' => 'yearly'); $sentTo = array('everyone' => true); $calendar = Sabre\VObject\Reader::read($data); $currentTimeZone = _api_get_timezone(); if (!empty($calendar->VEVENT)) { foreach ($calendar->VEVENT as $event) { $start = $event->DTSTART->getDateTime(); $end = $event->DTEND->getDateTime(); //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz) $startDateTime = api_get_local_time($start->format('Y-m-d H:i:s'), $currentTimeZone, $start->format('e')); $endDateTime = api_get_local_time($end->format('Y-m-d H:i'), $currentTimeZone, $end->format('e')); $title = api_convert_encoding((string) $event->summary, $charset, 'UTF-8'); $description = api_convert_encoding((string) $event->description, $charset, 'UTF-8'); $id = $this->addEvent($startDateTime, $endDateTime, 'false', $title, $description, $sentTo); $messages[] = " {$title} - " . $startDateTime . " - " . $endDateTime; //$attendee = (string)$event->attendee; /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */ $repeat = $event->RRULE; if ($id && !empty($repeat)) { $repeat = $repeat->getParts(); $freq = $trans[$repeat['FREQ']]; if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) { // Check if datetime or just date (strlen == 8) if (strlen($repeat['UNTIL']) == 8) { // Fix the datetime format to avoid exception in the next step $repeat['UNTIL'] .= 'T000000'; } $until = Sabre\VObject\DateTimeParser::parseDateTime($repeat['UNTIL'], new DateTimeZone($currentTimeZone)); $until = $until->format('Y-m-d H:i'); //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $until, $attendee); $this->addRepeatedItem($id, $freq, $until, $sentTo); } if (!empty($repeat['COUNT'])) { /*$count = $repeat['COUNT']; $interval = $repeat['INTERVAL']; $endDate = null; switch($freq) { case 'daily': $start = api_strtotime($startDateTime); $date = new DateTime($startDateTime); $days = $count * $interval; var_dump($days); $date->add(new DateInterval("P".$days."D")); $endDate = $date->format('Y-m-d H:i'); //$endDate = $count * for ($i = 0; $i < $count; $i++) { $days = 86400 * 7 } } }*/ //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $count, $attendee); /*$this->addRepeatedItem( $id, $freq, $endDate, $sentTo );*/ } } } } if (!empty($messages)) { $messages = implode('<br /> ', $messages); } else { $messages = get_lang('NoAgendaItems'); } return $messages; }
} if ($debug > 0) { error_log('Videoconf upload path: ' . VIDEOCONF_UPLOAD_PATH); } /* $canDelete = ($canDelete && $isBellowVideoConfUploadPath); */ $can_delete = $is_manager && $is_below_videoconf_dir; // get files list $files = DocumentManager::get_all_document_data($_course, $cwd, 0, null, false); printf("<dokeosobject><fileListMeta></fileListMeta><fileList>"); printf("<folders>"); // title filter if (is_array($files)) { foreach (array_keys($files) as $k) { // converting to UTF-8 $files[$k]['title'] = api_convert_encoding(api_strlen($files[$k]['title']) > 32 ? api_substr($files[$k]['title'], 0, 32) . "..." : $files[$k]['title'], 'utf-8', api_get_system_encoding()); // removing '<', '>' and '_' $files[$k]['title'] = str_replace(array('<', '>', '_'), ' ', $files[$k]['title']); } } if (is_array($files)) { foreach ($files as $i) { if ($i["filetype"] == "folder") { printf('<folder><path>%s</path><title>%s</title><canDelete>%s</canDelete></folder>', $i['path'], $i['title'], $can_delete ? 'true' : 'false'); } } } printf("</folders><files>"); if (is_array($files)) { foreach ($files as $i) { $extension = strrpos($i['path'], '.') > 0 ? substr($i['path'], strrpos($i['path'], '.'), 10) : '';
function add_docs_to_visio($files = array()) { global $_course; foreach ($files as $file) { list($slide_name,$file_name) = explode('||',$file); // '||' is used as separator between slide name (with accents) and file name (without accents). $slide_name = api_htmlentities($slide_name, ENT_COMPAT, $this->original_charset); $slide_name = str_replace('’', '\'', $slide_name); $slide_name = api_convert_encoding($slide_name, api_get_system_encoding(), $this->original_charset); $slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_system_encoding()); $did = add_document($_course, $this->created_dir.'/'.urlencode($file_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$file_name), $slide_name); if ($did) { api_item_property_update($_course, TOOL_DOCUMENT, $did, 'DocumentAdded', $_SESSION['_uid'], 0, null, null, null, api_get_session_id()); } } }
echo '<input type="submit" value="' . get_lang('Submit') . '">'; echo '</form>'; echo '</div>'; } elseif (!empty($annee) && empty($id_session)) { Display::display_header($tool_name); echo '<div style="align:center">'; echo Display::return_icon('course.gif', get_lang('SelectSessionToImportUsersTo')) . ' ' . get_lang('SelectSessionToImportUsersTo') . '<br />'; echo '<form method="post" action="' . api_get_self() . '?annee=' . Security::remove_XSS($annee) . '"><br />'; echo '<select name="id_session">'; $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION); $sql = "SELECT id,name,nbr_courses,date_start,date_end " . " FROM {$tbl_session} " . " ORDER BY name"; $result = Database::query($sql); $sessions = Database::store_result($result); $nbr_results = count($sessions); foreach ($sessions as $row) { echo '<option value="' . $row['id'] . '">' . api_htmlentities($row['name'], ENT_COMPAT, api_get_system_encoding()) . ' (' . $row['date_start'] . ' - ' . $row['date_end'] . ')</option>'; } echo '</select>'; echo '<input type="submit" value="' . get_lang('Submit') . '">'; echo '</form>'; echo '</div>'; } elseif (!empty($annee) && !empty($id_session) && empty($_POST['confirmed'])) { Display::display_header($tool_name); echo '<div style="align: center;">'; echo '<br />'; echo '<br />'; echo '<h3>' . Display::return_icon('group.gif', get_lang('SelectStudents')) . ' ' . get_lang('SelectStudents') . '</h3>'; //echo "Connection ..."; $ds = ldap_connect($ldap_host, $ldap_port) or die(get_lang('LDAPConnectionError')); ldap_set_version($ds); if ($ds) {
function search($needle, $type) { global $tbl_user, $elements_in; $xajax_response = new XajaxResponse(); $return = ''; if (!empty($needle) && !empty($type)) { // xajax send utf8 datas... datas in db can be non-utf8 datas $charset = api_get_system_encoding(); $needle = Database::escape_string($needle); $needle = api_convert_encoding($needle, $charset, 'utf-8'); if ($type == 'single') { // search users where username or firstname or lastname begins likes $needle /* $sql = 'SELECT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user WHERE (username LIKE "'.$needle.'%" OR firstname LIKE "'.$needle.'%" OR lastname LIKE "'.$needle.'%") AND user.user_id<>"'.$user_anonymous.'" AND user.status<>'.DRH.''. $order_clause. ' LIMIT 11';*/ } else { $list = CourseManager::get_courses_list(0, 0, 2, 'ASC', -1, $needle); } $i = 0; if ($type == 'single') { /* while ($user = Database :: fetch_array($rs)) { $i++; if ($i<=10) { $person_name = api_get_person_name($user['firstname'], $user['lastname']); $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_session(\''.$user['user_id'].'\',\''.$person_name.' ('.$user['username'].')'.'\')">'.$person_name.' ('.$user['username'].')</a><br />'; } else { $return .= '...<br />'; } } $xajax_response -> addAssign('ajax_list_users_single','innerHTML',api_utf8_encode($return));*/ } else { $return .= '<select id="elements_not_in" name="elements_not_in_name[]" multiple="multiple" size="15" style="width:360px;">'; foreach ($list as $row) { if (!in_array($row['id'], array_keys($elements_in))) { $return .= '<option value="' . $row['id'] . '">' . $row['title'] . ' (' . $row['visual_code'] . ')</option>'; } } $return .= '</select>'; $xajax_response->addAssign('ajax_list_multiple', 'innerHTML', api_utf8_encode($return)); } } return $xajax_response; }
/** * Set header parameters */ private function set_header_parameters() { global $httpHeadXtra, $_course, $interbreadcrumb, $language_file, $noPHP_SELF, $_configuration, $this_section; $help = $this->help; $nameTools = $this->title; $navigation = return_navigation_array(); $this->menu_navigation = $navigation['menu_navigation']; $this->assign('system_charset', api_get_system_encoding()); if (isset($httpHeadXtra) && $httpHeadXtra) { foreach ($httpHeadXtra as & $thisHttpHead) { header($thisHttpHead); } } $this->assign('online_button', Display::return_icon('online.png')); $this->assign('offline_button',Display::return_icon('offline.png')); // Get language iso-code for this page - ignore errors $this->assign('document_language', api_get_language_isocode()); $course_title = isset($_course['name']) ? $_course['name'] : null; $title_list = array(); $title_list[] = api_get_setting('Institution'); $title_list[] = api_get_setting('siteName'); if (!empty($course_title)) { $title_list[] = $course_title; } if ($nameTools != '') { $title_list[] = $nameTools; } $title_string = ''; for ($i = 0; $i < count($title_list); $i++) { $title_string .= $title_list[$i]; if (isset($title_list[$i + 1])) { $item = trim($title_list[$i + 1]); if (!empty($item)) { $title_string .= ' - '; } } } $this->assign('title_string', $title_string); //Setting the theme and CSS files $this->set_css_files(); $this->set_js_files(); //$this->set_js_files_post(); $browser = api_browser_support('check_browser'); if ($browser[0] == 'Internet Explorer' && $browser[1] >= '11') { $browser_head = '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />'; $this->assign('browser_specific_head', $browser_head); } // Implementation of prefetch. // See http://cdn.chamilo.org/main/img/online.png for details $prefetch = ''; if (!empty($_configuration['cdn_enable'])) { $prefetch .= '<meta http-equiv="x-dns-prefetch-control" content="on">'; foreach ($_configuration['cdn'] as $host => $exts) { $prefetch .= '<link rel="dns-prefetch" href="'.$host.'">'; } } $this->assign('prefetch', $prefetch); $this->assign('text_direction', api_get_text_direction()); $this->assign('section_name', 'section-'.$this_section); $favico = '<link rel="shortcut icon" href="'.api_get_path(WEB_PATH).'favicon.ico" type="image/x-icon" />'; if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) { $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { $url_info = api_get_access_url($access_url_id); $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url'])); $clean_url = replace_dangerous_char($url); $clean_url = str_replace('/', '-', $clean_url); $clean_url .= '/'; $homep = api_get_path(REL_PATH).'home/'.$clean_url; //homep for Home Path $icon_real_homep = api_get_path(SYS_PATH).'home/'.$clean_url; //we create the new dir for the new sites if (is_file($icon_real_homep.'favicon.ico')) { $favico = '<link rel="shortcut icon" href="'.$homep.'favicon.ico" type="image/x-icon" />'; } } } $this->assign('favico', $favico); $this->set_help(); //@todo move this in the template $bug_notification_link = ''; if (api_get_setting('show_link_bug_notification') == 'true' && $this->user_is_logged_in) { $bug_notification_link = '<li class="report"> <a href="http://support.chamilo.org/projects/chamilo-18/wiki/How_to_report_bugs" target="_blank"> <img src="'.api_get_path(WEB_IMG_PATH).'bug.large.png" style="vertical-align: middle;" alt="'.get_lang('ReportABug').'" title="'.get_lang( 'ReportABug' ).'"/></a> </li>'; } $this->assign('bug_notification_link', $bug_notification_link); $notification = return_notification_menu(); $this->assign('notification_menu', $notification); //Preparing values for the menu //Logout link if (isset($_configuration['hide_logout_button']) && $_configuration['hide_logout_button'] == 'true') { $this->assign('logout_link', null); } else { $this->assign('logout_link', api_get_path(WEB_PATH).'index.php?logout=logout&uid='.api_get_user_id()); } //Profile link if (api_get_setting('allow_social_tool') == 'true') { $profile_url = api_get_path(WEB_CODE_PATH).'social/home.php'; $profile_link = Display::url(get_lang('Profile'), $profile_url); } else { $profile_url = api_get_path(WEB_CODE_PATH).'auth/profile.php'; $profile_link = Display::url(get_lang('Profile'), $profile_url); } $this->assign('profile_link', $profile_link); $this->assign('profile_url', $profile_url); //Message link $message_link = null; $message_url = null; if (api_get_setting('allow_message_tool') == 'true') { $message_url = api_get_path(WEB_CODE_PATH).'messages/inbox.php'; $message_link = '<a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">'.get_lang('Inbox').'</a>'; } $this->assign('message_link', $message_link); $this->assign('message_url', $message_url); $institution = api_get_setting('Institution'); $portal_name = empty($institution) ? api_get_setting('siteName') : $institution; $this->assign('portal_name', $portal_name); //Menu $menu = return_menu(); $this->assign('menu', $menu); //Setting notifications $count_unread_message = 0; if (api_get_setting('allow_message_tool') == 'true') { // get count unread message and total invitations $count_unread_message = MessageManager::get_number_of_messages(true); } $total_invitations = 0; if (api_get_setting('allow_social_tool') == 'true') { $number_of_new_messages_of_friend = SocialManager::get_message_number_invitation_by_user_id( api_get_user_id() ); $group_pending_invitations = GroupPortalManager::get_groups_by_user( api_get_user_id(), GROUP_USER_PERMISSION_PENDING_INVITATION, false ); $group_pending_invitations = 0; if (!empty($group_pending_invitations)) { $group_pending_invitations = count($group_pending_invitations); } $total_invitations = intval($number_of_new_messages_of_friend) + $group_pending_invitations + intval( $count_unread_message ); } $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : null); $this->assign('user_notifications', $total_invitations); //Breadcrumb $breadcrumb = return_breadcrumb($interbreadcrumb, $language_file, $nameTools); $this->assign('breadcrumb', $breadcrumb); //Extra content $extra_header = null; if (!api_is_platform_admin()) { $extra_header = trim(api_get_setting('header_extra_content')); } $this->assign('header_extra_content', $extra_header); //if ($this->show_header == 1) { header('Content-Type: text/html; charset='.api_get_system_encoding()); header( 'X-Powered-By: '.$_configuration['software_name'].' '.substr($_configuration['system_version'], 0, 1) ); //} }
?> :</p> <pre> <b>id</b>;<b>parent_id</b>;<b>name</b>;<b>description</b> <b>2</b>;<b>1</b>;<b>Chamilo Expert</b>;Chamilo is an open source LMS;<br /> </pre> <!--p><?php echo get_lang('XMLMustLookLike') . ' (' . get_lang('MandatoryFields') . ')'; ?> :</p> <blockquote> <pre> <?xml version="1.0" encoding="<?php echo api_refine_encoding_id(api_get_system_encoding()); ?> "?> <Skills> <Skill> <b><id>n</id></b> <b><parent_id>n</parent_id></b> <b><name>xxx</name></b> <description>xxx</description> </Skill> </Skills> </pre> </blockquote--> <?php Display::display_footer();
/** * Handles a given Excel spreadsheets as in the template provided */ function lp_upload_quiz_action_handling() { global $debug; $_course = api_get_course_info(); $courseId = $_course['real_id']; if (!isset($_POST['submit_upload_quiz'])) { return; } // Get the extension of the document. $path_info = pathinfo($_FILES['user_upload_quiz']['name']); // Check if the document is an Excel document if ($path_info['extension'] != 'xls') { return; } // Read the Excel document $data = new Spreadsheet_Excel_Reader(); // Set output Encoding. $data->setOutputEncoding(api_get_system_encoding()); // Reading the xls document. $data->read($_FILES['user_upload_quiz']['tmp_name']); $correctScore = isset($_POST['correct_score']) ? $_POST['correct_score'] : null; $incorrectScore = isset($_POST['incorrect_score']) ? $_POST['incorrect_score'] : null; $useCustomScore = isset($_POST['user_custom_score']) ? true : false; $propagateNegative = 0; if ($useCustomScore && !empty($incorrectScore)) { if ($incorrectScore < 0) { $propagateNegative = 1; } } // Variables $quiz_index = 0; $question_title_index = array(); $question_name_index_init = array(); $question_name_index_end = array(); $score_index = array(); $feedback_true_index = array(); $feedback_false_index = array(); $number_questions = 0; $question_description_index = array(); // Reading all the first column items sequentially to create breakpoints for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) { if ($data->sheets[0]['cells'][$i][1] == 'Quiz' && $i == 1) { $quiz_index = $i; // Quiz title position, only occurs once } elseif ($data->sheets[0]['cells'][$i][1] == 'Question') { $question_title_index[] = $i; // Question title position line $question_name_index_init[] = $i + 1; // Questions name 1st position line $number_questions++; } elseif ($data->sheets[0]['cells'][$i][1] == 'Score') { $question_name_index_end[] = $i - 1; // Question name position $score_index[] = $i; // Question score position } elseif ($data->sheets[0]['cells'][$i][1] == 'FeedbackTrue') { $feedback_true_index[] = $i; // FeedbackTrue position (line) } elseif ($data->sheets[0]['cells'][$i][1] == 'FeedbackFalse') { $feedback_false_index[] = $i; // FeedbackFalse position (line) } elseif ($data->sheets[0]['cells'][$i][1] == 'EnrichQuestion') { $question_description_index[] = $i; } } // Variables $quiz = array(); $question = array(); $new_answer = array(); $score_list = array(); $feedback_true_list = array(); $feedback_false_list = array(); $question_description = array(); // Getting questions. $k = $z = $q = $l = $m = 0; for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) { if (is_array($data->sheets[0]['cells'][$i])) { $column_data = $data->sheets[0]['cells'][$i]; // Fill all column with data to have a full array for ($x = 1; $x <= $data->sheets[0]['numCols']; $x++) { if (empty($column_data[$x])) { $data->sheets[0]['cells'][$i][$x] = ''; } } // Array filled with data $column_data = $data->sheets[0]['cells'][$i]; } else { $column_data = ''; } // Fill quiz data if ($quiz_index == $i) { // The title always in the first position $quiz = $column_data; } elseif (in_array($i, $question_title_index)) { //a complete line where 1st column is 'Question' $question[$k] = $column_data; $k++; } elseif (in_array($i, $score_index)) { //a complete line where 1st column is 'Score' $score_list[$z] = $column_data; $z++; } elseif (in_array($i, $feedback_true_index)) { //a complete line where 1st column is 'FeedbackTrue' $feedback_true_list[$q] = $column_data; $q++; } elseif (in_array($i, $feedback_false_index)) { //a complete line where 1st column is 'FeedbackFalse' for wrong answers $feedback_false_list[$l] = $column_data; $l++; } elseif (in_array($i, $question_description_index)) { //a complete line where 1st column is 'EnrichQuestion' $question_description[$m] = $column_data; $m++; } } // Get answers for ($i = 0; $i < count($question_name_index_init); $i++) { for ($j = $question_name_index_init[$i]; $j <= $question_name_index_end[$i]; $j++) { if (is_array($data->sheets[0]['cells'][$j])) { $column_data = $data->sheets[0]['cells'][$j]; // Fill all column with data for ($x = 1; $x <= $data->sheets[0]['numCols']; $x++) { if (empty($column_data[$x])) { $data->sheets[0]['cells'][$j][$x] = ''; } } $column_data = $data->sheets[0]['cells'][$j]; // Array filled of data if (is_array($data->sheets[0]['cells'][$j]) && count($data->sheets[0]['cells'][$j]) > 0) { $new_answer[$i][$j] = $data->sheets[0]['cells'][$j]; } } } } // Quiz title. $quiz_title = $quiz[2]; if ($quiz_title != '') { // Variables $type = 2; $random = $active = $results = $max_attempt = $expired_time = 0; // Make sure feedback is enabled (3 to disable), otherwise the fields // added to the XLS are not shown, which is confusing $feedback = 0; // Quiz object $exercise = new Exercise(); // $quiz_id = $exercise->createExercise($quiz_title, $expired_time, $type, $random, $active, $results, $max_attempt, $feedback, $propagateNegative); if ($quiz_id) { // insert into the item_property table api_item_property_update($_course, TOOL_QUIZ, $quiz_id, 'QuizAdded', api_get_user_id()); // Import questions. for ($i = 0; $i < $number_questions; $i++) { // Question name $question_title = $question[$i][2]; $question_description_text = "<p></p>"; if (isset($question_description[$i][2])) { // Question description. $question_description_text = "<p>" . $question_description[$i][2] . "</p>"; } // Unique answers are the only question types available for now // through xls-format import $question_id = null; $detectQuestionType = detectQuestionType($new_answer[$i], $score_list); /** @var Question $answer */ switch ($detectQuestionType) { case FREE_ANSWER: $answer = new FreeAnswer(); break; case GLOBAL_MULTIPLE_ANSWER: $answer = new GlobalMultipleAnswer(); break; case MULTIPLE_ANSWER: $answer = new MultipleAnswer(); break; case UNIQUE_ANSWER: default: $answer = new UniqueAnswer(); break; } if ($question_title != '') { $question_id = $answer->create_question($quiz_id, $question_title, $question_description_text, 0, $answer->type); } $total = 0; if (is_array($new_answer[$i]) && !empty($question_id)) { $id = 1; $answers_data = $new_answer[$i]; $globalScore = null; $objAnswer = new Answer($question_id, $courseId); $globalScore = $score_list[$i][3]; // Calculate the number of correct answers to divide the // score between them when importing from CSV $numberRightAnswers = 0; foreach ($answers_data as $answer_data) { if (strtolower($answer_data[3]) == 'x') { $numberRightAnswers++; } } foreach ($answers_data as $answer_data) { $answerValue = $answer_data[2]; $correct = 0; $score = 0; if (strtolower($answer_data[3]) == 'x') { $correct = 1; $score = $score_list[$i][3]; $comment = $feedback_true_list[$i][2]; } else { $comment = $feedback_false_list[$i][2]; $floatVal = (double) $answer_data[3]; if (is_numeric($floatVal)) { $score = $answer_data[3]; } } if ($useCustomScore) { if ($correct) { $score = $correctScore; } else { $score = $incorrectScore; } } // Fixing scores: switch ($detectQuestionType) { case GLOBAL_MULTIPLE_ANSWER: $score /= $numberRightAnswers; break; case UNIQUE_ANSWER: break; case MULTIPLE_ANSWER: if (!$correct) { //$total = $total - $score; } break; } $objAnswer->createAnswer($answerValue, $correct, $comment, $score, $id); $total += $score; $id++; } $objAnswer->save(); $questionObj = Question::read($question_id, $courseId); switch ($detectQuestionType) { case GLOBAL_MULTIPLE_ANSWER: $questionObj->updateWeighting($globalScore); break; case UNIQUE_ANSWER: case MULTIPLE_ANSWER: default: $questionObj->updateWeighting($total); break; } $questionObj->save(); } else { if ($detectQuestionType === FREE_ANSWER) { $questionObj = Question::read($question_id, $courseId); $globalScore = $score_list[$i][3]; $questionObj->updateWeighting($globalScore); $questionObj->save(); } } } } if (isset($_SESSION['lpobject'])) { if ($debug > 0) { error_log('New LP - SESSION[lpobject] is defined', 0); } $oLP = unserialize($_SESSION['lpobject']); if (is_object($oLP)) { if ($debug > 0) { error_log('New LP - oLP is object', 0); } if (empty($oLP->cc) or $oLP->cc != api_get_course_id()) { if ($debug > 0) { error_log('New LP - Course has changed, discard lp object', 0); } $oLP = null; Session::erase('oLP'); Session::erase('lpobject'); } else { $_SESSION['oLP'] = $oLP; } } } if (isset($_SESSION['oLP']) && isset($_GET['lp_id'])) { $previous = $_SESSION['oLP']->select_previous_item_id(); $parent = 0; // Add a Quiz as Lp Item $_SESSION['oLP']->add_item($parent, $previous, TOOL_QUIZ, $quiz_id, $quiz_title, ''); // Redirect to home page for add more content header('location: ../newscorm/lp_controller.php?' . api_get_cidreq() . '&action=add_item&type=step&lp_id=' . Security::remove_XSS($_GET['lp_id'])); exit; } else { // header('location: exercise.php?' . api_get_cidreq()); echo '<script>window.location.href = "' . api_get_path(WEB_CODE_PATH) . 'exercice/admin.php?' . api_get_cidReq() . '&exerciseId=' . $quiz_id . '&session_id=' . api_get_session_id() . '"</script>'; } } }
/** * // TODO: The output encoding should be equal to the system encoding. * * Exports the learning path as a SCORM package. This is the main function that * gathers the content, transforms it, writes the imsmanifest.xml file, zips the * whole thing and returns the zip. * * This method needs to be called in PHP5, as it will fail with non-adequate * XML package (like the ones for PHP4), and it is *not* a static method, so * you need to call it on a learnpath object. * @TODO The method might be redefined later on in the scorm class itself to avoid * creating a SCORM structure if there is one already. However, if the initial SCORM * path has been modified, it should use the generic method here below. * @TODO link this function with the export_lp() function in the same class * @param string Optional name of zip file. If none, title of learnpath is * domesticated and trailed with ".zip" * @return string Returns the zip package string, or null if error */ public function scorm_export() { $_course = api_get_course_info(); $course_id = api_get_course_int_id(); $links_to_create = null; // Remove memory and time limits as much as possible as this might be a long process... if (function_exists('ini_set')) { api_set_memory_limit('128M'); ini_set('max_execution_time', 600); } // Create the zip handler (this will remain available throughout the method). $archive_path = api_get_path(SYS_ARCHIVE_PATH); $sys_course_path = api_get_path(SYS_COURSE_PATH); $temp_dir_short = uniqid(); $temp_zip_dir = $archive_path . '/' . $temp_dir_short; $temp_zip_file = $temp_zip_dir . '/' . md5(time()) . '.zip'; $zip_folder = new PclZip($temp_zip_file); $current_course_path = api_get_path(SYS_COURSE_PATH) . api_get_course_path(); $root_path = $main_path = api_get_path(SYS_PATH); $files_cleanup = array(); // Place to temporarily stash the zipfiles. // create the temp dir if it doesn't exist // or do a cleanup befor creating the zipfile. if (!is_dir($temp_zip_dir)) { mkdir($temp_zip_dir, api_get_permissions_for_new_directories()); } else { // Cleanup: Check the temp dir for old files and delete them. $handle = opendir($temp_zip_dir); while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..') { unlink("{$temp_zip_dir}/{$file}"); } } closedir($handle); } $zip_files = $zip_files_abs = $zip_files_dist = array(); if (is_dir($current_course_path . '/scorm/' . $this->path) && is_file($current_course_path . '/scorm/' . $this->path . '/imsmanifest.xml')) { // Remove the possible . at the end of the path. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path; $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir . '/scorm/' . $dest_path_to_lp); mkdir($dest_path_to_scorm_folder, api_get_permissions_for_new_directories(), true); $zip_files_dist = api_copyr($current_course_path . '/scorm/' . $this->path, $dest_path_to_scorm_folder, array('imsmanifest'), $zip_files); } // Build a dummy imsmanifest structure. Do not add to the zip yet (we still need it). // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content // Aggregation Model official document, secion "2.3 Content Packaging". $xmldoc = new DOMDocument('1.0'); // We are going to build a UTF-8 encoded manifest. Later we will recode it to the desired (and supported) encoding. $root = $xmldoc->createElement('manifest'); $root->setAttribute('identifier', 'SingleCourseManifest'); $root->setAttribute('version', '1.1'); $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2'); $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2'); $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $root->setAttribute('xsi:schemaLocation', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd'); // Build mandatory sub-root container elements. $metadata = $xmldoc->createElement('metadata'); $md_schema = $xmldoc->createElement('schema', 'ADL SCORM'); $metadata->appendChild($md_schema); $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2'); $metadata->appendChild($md_schemaversion); $root->appendChild($metadata); $organizations = $xmldoc->createElement('organizations'); $resources = $xmldoc->createElement('resources'); // Build the only organization we will use in building our learnpaths. $organizations->setAttribute('default', 'chamilo_scorm_export'); $organization = $xmldoc->createElement('organization'); $organization->setAttribute('identifier', 'chamilo_scorm_export'); // To set the title of the SCORM entity (=organization), we take the name given // in Chamilo and convert it to HTML entities using the Chamilo charset (not the // learning path charset) as it is the encoding that defines how it is stored // in the database. Then we convert it to HTML entities again as the "&" character // alone is not authorized in XML (must be &). // The title is then decoded twice when extracting (see scorm::parse_manifest). $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name())); $organization->appendChild($org_title); $folder_name = 'document'; // Removes the learning_path/scorm_folder path when exporting see #4841 $path_to_remove = null; $result = $this->generate_lp_folder($_course); if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) { $path_to_remove = 'document' . $result['dir']; $path_to_replace = $folder_name . '/'; } //Fixes chamilo scorm exports if ($this->ref == 'chamilo_scorm_export') { $path_to_remove = 'scorm/' . $this->path . '/document/'; } // For each element, add it to the imsmanifest structure, then add it to the zip. // Always call the learnpathItem->scorm_export() method to change it to the SCORM format. $link_updates = array(); foreach ($this->items as $index => $item) { if (!in_array($item->type, array(TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION))) { // Get included documents from this item. if ($item->type == 'sco') { $inc_docs = $item->get_resources_from_source(null, api_get_path(SYS_COURSE_PATH) . api_get_course_path() . '/' . 'scorm/' . $this->path . '/' . $item->get_path()); } else { $inc_docs = $item->get_resources_from_source(); } // Give a child element <item> to the <organization> element. $my_item_id = $item->get_id(); $my_item = $xmldoc->createElement('item'); $my_item->setAttribute('identifier', 'ITEM_' . $my_item_id); $my_item->setAttribute('identifierref', 'RESOURCE_' . $my_item_id); $my_item->setAttribute('isvisible', 'true'); // Give a child element <title> to the <item> element. $my_title = $xmldoc->createElement('title', htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8')); $my_item->appendChild($my_title); // Give a child element <adlcp:prerequisites> to the <item> element. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $this->get_scorm_prereq_string($my_item_id)); $my_prereqs->setAttribute('type', 'aicc_script'); $my_item->appendChild($my_prereqs); // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported. //$xmldoc->createElement('adlcp:maxtimeallowed',''); // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported. //$xmldoc->createElement('adlcp:timelimitaction',''); // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported. //$xmldoc->createElement('adlcp:datafromlms',''); // Give a child element <adlcp:masteryscore> to the <item> element. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score()); $my_item->appendChild($my_masteryscore); // Attach this item to the organization element or hits parent if there is one. if (!empty($item->parent) && $item->parent != 0) { $children = $organization->childNodes; $possible_parent =& $this->get_scorm_xml_node($children, 'ITEM_' . $item->parent); if (is_object($possible_parent)) { $possible_parent->appendChild($my_item); } else { if ($this->debug > 0) { error_log('Parent ITEM_' . $item->parent . ' of item ITEM_' . $my_item_id . ' not found'); } } } else { if ($this->debug > 0) { error_log('No parent'); } $organization->appendChild($my_item); } // Get the path of the file(s) from the course directory root. $my_file_path = $item->get_file_path('scorm/' . $this->path . '/'); if (!empty($path_to_remove)) { //From docs $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path); //From quiz if ($this->ref == 'chamilo_scorm_export') { $path_to_remove = 'scorm/' . $this->path . '/'; $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path); } } else { $my_xml_file_path = $my_file_path; } $my_sub_dir = dirname($my_file_path); $my_sub_dir = str_replace('\\', '/', $my_sub_dir); //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_QUOTES, 'UTF-8'); $my_xml_sub_dir = $my_sub_dir; // Give a <resource> child to the <resources> element $my_resource = $xmldoc->createElement('resource'); $my_resource->setAttribute('identifier', 'RESOURCE_' . $item->get_id()); $my_resource->setAttribute('type', 'webcontent'); $my_resource->setAttribute('href', $my_xml_file_path); // adlcp:scormtype can be either 'sco' or 'asset'. if ($item->type == 'sco') { $my_resource->setAttribute('adlcp:scormtype', 'sco'); } else { $my_resource->setAttribute('adlcp:scormtype', 'asset'); } // xml:base is the base directory to find the files declared in this resource. $my_resource->setAttribute('xml:base', ''); // Give a <file> child to the <resource> element. $my_file = $xmldoc->createElement('file'); $my_file->setAttribute('href', $my_xml_file_path); $my_resource->appendChild($my_file); // Dependency to other files - not yet supported. $i = 1; foreach ($inc_docs as $doc_info) { if (count($doc_info) < 1 || empty($doc_info[0])) { continue; } $my_dep = $xmldoc->createElement('resource'); $res_id = 'RESOURCE_' . $item->get_id() . '_' . $i; $my_dep->setAttribute('identifier', $res_id); $my_dep->setAttribute('type', 'webcontent'); $my_dep->setAttribute('adlcp:scormtype', 'asset'); $my_dep_file = $xmldoc->createElement('file'); // Check type of URL. //error_log(__LINE__.'Now dealing with '.$doc_info[0].' of type '.$doc_info[1].'-'.$doc_info[2], 0); if ($doc_info[1] == 'remote') { // Remote file. Save url as is. $my_dep_file->setAttribute('href', $doc_info[0]); $my_dep->setAttribute('xml:base', ''); } elseif ($doc_info[1] == 'local') { switch ($doc_info[2]) { case 'url': // Local URL - save path as url for now, don't zip file. $abs_path = api_get_path(SYS_PATH) . str_replace(api_get_path(WEB_PATH), '', $doc_info[0]); $current_dir = dirname($abs_path); $current_dir = str_replace('\\', '/', $current_dir); $file_path = realpath($abs_path); $file_path = str_replace('\\', '/', $file_path); $my_dep_file->setAttribute('href', $file_path); $my_dep->setAttribute('xml:base', ''); if (strstr($file_path, $main_path) !== false) { // The calculated real path is really inside Chamilo's root path. // Reduce file path to what's under the DocumentRoot. $file_path = substr($file_path, strlen($root_path) - 1); //echo $file_path;echo '<br /><br />'; //error_log(__LINE__.'Reduced url path: '.$file_path, 0); $zip_files_abs[] = $file_path; $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path); $my_dep_file->setAttribute('href', $file_path); $my_dep->setAttribute('xml:base', ''); } elseif (empty($file_path)) { /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH))); if (strpos($document_root, -1) == '/') { $document_root = substr(0, -1, $document_root); }*/ $file_path = $_SERVER['DOCUMENT_ROOT'] . $abs_path; $file_path = str_replace('//', '/', $file_path); if (file_exists($file_path)) { $file_path = substr($file_path, strlen($current_dir)); // We get the relative path. $zip_files[] = $my_sub_dir . '/' . $file_path; $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path); $my_dep_file->setAttribute('href', $file_path); $my_dep->setAttribute('xml:base', ''); } } break; case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip. $my_dep_file->setAttribute('href', $doc_info[0]); $my_dep->setAttribute('xml:base', ''); //$current_dir = str_replace('\\', '/', dirname($current_course_path.'/'.$item->get_file_path())).'/'; // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar $abs_img_path_without_subdir = $doc_info[0]; $relp = api_get_path(REL_PATH); // The url-append config param. $pos = strpos($abs_img_path_without_subdir, $relp); if ($pos === 0) { $abs_img_path_without_subdir = '/' . substr($abs_img_path_without_subdir, strlen($relp)); } //$file_path = realpath(api_get_path(SYS_PATH).$doc_info[0]); $file_path = realpath(api_get_path(SYS_PATH) . $abs_img_path_without_subdir); $file_path = str_replace('\\', '/', $file_path); $file_path = str_replace('//', '/', $file_path); //error_log(__LINE__.'Abs path: '.$file_path, 0); // Prepare the current directory path (until just under 'document') with a trailing slash. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path . '/'; // Check if the current document is in that path. if (strstr($file_path, $cur_path) !== false) { // The document is in that path, now get the relative path // to the containing document. $orig_file_path = dirname($cur_path . $my_file_path) . '/'; $orig_file_path = str_replace('\\', '/', $orig_file_path); $relative_path = ''; if (strstr($file_path, $cur_path) !== false) { $relative_path = substr($file_path, strlen($orig_file_path)); $file_path = substr($file_path, strlen($cur_path)); } else { // This case is still a problem as it's difficult to calculate a relative path easily // might still generate wrong links. //$file_path = substr($file_path,strlen($cur_path)); // Calculate the directory path to the current file (without trailing slash). $my_relative_path = dirname($file_path); $my_relative_path = str_replace('\\', '/', $my_relative_path); $my_relative_file = basename($file_path); // Calculate the directory path to the containing file (without trailing slash). $my_orig_file_path = substr($orig_file_path, 0, -1); $dotdot = ''; $subdir = ''; while (strstr($my_relative_path, $my_orig_file_path) === false && strlen($my_orig_file_path) > 1 && strlen($my_relative_path) > 1) { $my_relative_path2 = dirname($my_relative_path); $my_relative_path2 = str_replace('\\', '/', $my_relative_path2); $my_orig_file_path = dirname($my_orig_file_path); $my_orig_file_path = str_replace('\\', '/', $my_orig_file_path); $subdir = substr($my_relative_path, strlen($my_relative_path2) + 1) . '/' . $subdir; $dotdot += '../'; $my_relative_path = $my_relative_path2; } $relative_path = $dotdot . $subdir . $my_relative_file; } // Put the current document in the zip (this array is the array // that will manage documents already in the course folder - relative). $zip_files[] = $file_path; // Update the links to the current document in the containing document (make them relative). $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $relative_path); $my_dep_file->setAttribute('href', $file_path); $my_dep->setAttribute('xml:base', ''); } elseif (strstr($file_path, $main_path) !== false) { // The calculated real path is really inside Chamilo's root path. // Reduce file path to what's under the DocumentRoot. $file_path = substr($file_path, strlen($root_path)); //echo $file_path;echo '<br /><br />'; //error_log('Reduced path: '.$file_path, 0); $zip_files_abs[] = $file_path; $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path); $my_dep_file->setAttribute('href', 'document/' . $file_path); $my_dep->setAttribute('xml:base', ''); } elseif (empty($file_path)) { /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH))); if(strpos($document_root,-1) == '/') { $document_root = substr(0, -1, $document_root); }*/ $file_path = $_SERVER['DOCUMENT_ROOT'] . $doc_info[0]; $file_path = str_replace('//', '/', $file_path); if (file_exists($file_path)) { $file_path = substr($file_path, strlen($current_dir)); // We get the relative path. $zip_files[] = $my_sub_dir . '/' . $file_path; $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path); $my_dep_file->setAttribute('href', 'document/' . $file_path); $my_dep->setAttribute('xml:base', ''); } } break; case 'rel': // Path relative to the current document. Save xml:base as current document's directory and save file in zip as subdir.file_path if (substr($doc_info[0], 0, 2) == '..') { // Relative path going up. $current_dir = dirname($current_course_path . '/' . $item->get_file_path()) . '/'; $current_dir = str_replace('\\', '/', $current_dir); $file_path = realpath($current_dir . $doc_info[0]); $file_path = str_replace('\\', '/', $file_path); //error_log($file_path.' <-> '.$main_path,0); if (strstr($file_path, $main_path) !== false) { // The calculated real path is really inside Chamilo's root path. // Reduce file path to what's under the DocumentRoot. $file_path = substr($file_path, strlen($root_path)); //error_log('Reduced path: '.$file_path, 0); $zip_files_abs[] = $file_path; $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path); $my_dep_file->setAttribute('href', 'document/' . $file_path); $my_dep->setAttribute('xml:base', ''); } } else { $zip_files[] = $my_sub_dir . '/' . $doc_info[0]; $my_dep_file->setAttribute('href', $doc_info[0]); $my_dep->setAttribute('xml:base', $my_xml_sub_dir); } break; default: $my_dep_file->setAttribute('href', $doc_info[0]); $my_dep->setAttribute('xml:base', ''); break; } } $my_dep->appendChild($my_dep_file); $resources->appendChild($my_dep); $dependency = $xmldoc->createElement('dependency'); $dependency->setAttribute('identifierref', $res_id); $my_resource->appendChild($dependency); $i++; } //$my_dependency = $xmldoc->createElement('dependency'); //$my_dependency->setAttribute('identifierref', ''); $resources->appendChild($my_resource); $zip_files[] = $my_file_path; //error_log('File '.$my_file_path. ' added to $zip_files', 0); } else { // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it. switch ($item->type) { case TOOL_LINK: $my_item = $xmldoc->createElement('item'); $my_item->setAttribute('identifier', 'ITEM_' . $item->get_id()); $my_item->setAttribute('identifierref', 'RESOURCE_' . $item->get_id()); $my_item->setAttribute('isvisible', 'true'); // Give a child element <title> to the <item> element. $my_title = $xmldoc->createElement('title', htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8')); $my_item->appendChild($my_title); // Give a child element <adlcp:prerequisites> to the <item> element. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string()); $my_prereqs->setAttribute('type', 'aicc_script'); $my_item->appendChild($my_prereqs); // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported. //$xmldoc->createElement('adlcp:maxtimeallowed', ''); // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported. //$xmldoc->createElement('adlcp:timelimitaction', ''); // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported. //$xmldoc->createElement('adlcp:datafromlms', ''); // Give a child element <adlcp:masteryscore> to the <item> element. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score()); $my_item->appendChild($my_masteryscore); // Attach this item to the organization element or its parent if there is one. if (!empty($item->parent) && $item->parent != 0) { $children = $organization->childNodes; for ($i = 0; $i < $children->length; $i++) { $item_temp = $children->item($i); if ($item_temp->nodeName == 'item') { if ($item_temp->getAttribute('identifier') == 'ITEM_' . $item->parent) { $item_temp->appendChild($my_item); } } } } else { $organization->appendChild($my_item); } $my_file_path = 'link_' . $item->get_id() . '.html'; $sql = 'SELECT url, title FROM ' . Database::get_course_table(TABLE_LINK) . ' WHERE c_id = ' . $course_id . ' AND id=' . $item->path; $rs = Database::query($sql); if ($link = Database::fetch_array($rs)) { $url = $link['url']; $title = stripslashes($link['title']); $links_to_create[$my_file_path] = array('title' => $title, 'url' => $url); //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_QUOTES, 'UTF-8'); $my_xml_file_path = $my_file_path; $my_sub_dir = dirname($my_file_path); $my_sub_dir = str_replace('\\', '/', $my_sub_dir); //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_QUOTES, 'UTF-8'); $my_xml_sub_dir = $my_sub_dir; // Give a <resource> child to the <resources> element. $my_resource = $xmldoc->createElement('resource'); $my_resource->setAttribute('identifier', 'RESOURCE_' . $item->get_id()); $my_resource->setAttribute('type', 'webcontent'); $my_resource->setAttribute('href', $my_xml_file_path); // adlcp:scormtype can be either 'sco' or 'asset'. $my_resource->setAttribute('adlcp:scormtype', 'asset'); // xml:base is the base directory to find the files declared in this resource. $my_resource->setAttribute('xml:base', ''); // give a <file> child to the <resource> element. $my_file = $xmldoc->createElement('file'); $my_file->setAttribute('href', $my_xml_file_path); $my_resource->appendChild($my_file); $resources->appendChild($my_resource); } break; case TOOL_QUIZ: require_once api_get_path(SYS_CODE_PATH) . 'exercice/exercise.class.php'; $exe_id = $item->path; // Should be using ref when everything will be cleaned up in this regard. $exe = new Exercise(); $exe->read($exe_id); $my_item = $xmldoc->createElement('item'); $my_item->setAttribute('identifier', 'ITEM_' . $item->get_id()); $my_item->setAttribute('identifierref', 'RESOURCE_' . $item->get_id()); $my_item->setAttribute('isvisible', 'true'); // Give a child element <title> to the <item> element. $my_title = $xmldoc->createElement('title', htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8')); $my_item->appendChild($my_title); $my_max_score = $xmldoc->createElement('max_score', $item->get_max()); //$my_item->appendChild($my_max_score); // Give a child element <adlcp:prerequisites> to the <item> element. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string()); $my_prereqs->setAttribute('type', 'aicc_script'); $my_item->appendChild($my_prereqs); // Give a child element <adlcp:masteryscore> to the <item> element. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score()); $my_item->appendChild($my_masteryscore); // Attach this item to the organization element or hits parent if there is one. if (!empty($item->parent) && $item->parent != 0) { $children = $organization->childNodes; for ($i = 0; $i < $children->length; $i++) { $item_temp = $children->item($i); if ($item_temp->nodeName == 'item') { if ($item_temp->getAttribute('identifier') == 'ITEM_' . $item->parent) { $item_temp->appendChild($my_item); } } } } else { $organization->appendChild($my_item); } // Include export scripts. require_once api_get_path(SYS_CODE_PATH) . 'exercice/export/scorm/scorm_export.php'; // Get the path of the file(s) from the course directory root //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/'); $my_file_path = 'quiz_' . $item->get_id() . '.html'; // Write the contents of the exported exercise into a (big) html file // to later pack it into the exported SCORM. The file will be removed afterwards. $contents = export_exercise($exe_id, true); $tmp_file_path = $archive_path . $temp_dir_short . '/' . $my_file_path; $res = file_put_contents($tmp_file_path, $contents); if ($res === false) { error_log('Could not write into file ' . $tmp_file_path . ' ' . __FILE__ . ' ' . __LINE__, 0); } $files_cleanup[] = $tmp_file_path; //error_log($tmp_path); die(); //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_QUOTES, 'UTF-8'); $my_xml_file_path = $my_file_path; $my_sub_dir = dirname($my_file_path); $my_sub_dir = str_replace('\\', '/', $my_sub_dir); //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_QUOTES, 'UTF-8'); $my_xml_sub_dir = $my_sub_dir; // Give a <resource> child to the <resources> element. $my_resource = $xmldoc->createElement('resource'); $my_resource->setAttribute('identifier', 'RESOURCE_' . $item->get_id()); $my_resource->setAttribute('type', 'webcontent'); $my_resource->setAttribute('href', $my_xml_file_path); // adlcp:scormtype can be either 'sco' or 'asset'. $my_resource->setAttribute('adlcp:scormtype', 'sco'); // xml:base is the base directory to find the files declared in this resource. $my_resource->setAttribute('xml:base', ''); // Give a <file> child to the <resource> element. $my_file = $xmldoc->createElement('file'); $my_file->setAttribute('href', $my_xml_file_path); $my_resource->appendChild($my_file); // Get included docs. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path); // Dependency to other files - not yet supported. $i = 1; foreach ($inc_docs as $doc_info) { if (count($doc_info) < 1 || empty($doc_info[0])) { continue; } $my_dep = $xmldoc->createElement('resource'); $res_id = 'RESOURCE_' . $item->get_id() . '_' . $i; $my_dep->setAttribute('identifier', $res_id); $my_dep->setAttribute('type', 'webcontent'); $my_dep->setAttribute('adlcp:scormtype', 'asset'); $my_dep_file = $xmldoc->createElement('file'); // Check type of URL. //error_log(__LINE__.'Now dealing with '.$doc_info[0].' of type '.$doc_info[1].'-'.$doc_info[2], 0); if ($doc_info[1] == 'remote') { // Remote file. Save url as is. $my_dep_file->setAttribute('href', $doc_info[0]); $my_dep->setAttribute('xml:base', ''); } elseif ($doc_info[1] == 'local') { switch ($doc_info[2]) { case 'url': // Local URL - save path as url for now, don't zip file. // Save file but as local file (retrieve from URL). $abs_path = api_get_path(SYS_PATH) . str_replace(api_get_path(WEB_PATH), '', $doc_info[0]); $current_dir = dirname($abs_path); $current_dir = str_replace('\\', '/', $current_dir); $file_path = realpath($abs_path); $file_path = str_replace('\\', '/', $file_path); $my_dep_file->setAttribute('href', 'document/' . $file_path); $my_dep->setAttribute('xml:base', ''); if (strstr($file_path, $main_path) !== false) { // The calculated real path is really inside the chamilo root path. // Reduce file path to what's under the DocumentRoot. $file_path = substr($file_path, strlen($root_path)); //echo $file_path;echo '<br /><br />'; //error_log('Reduced path: '.$file_path, 0); $zip_files_abs[] = $file_path; $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => 'document/' . $file_path); $my_dep_file->setAttribute('href', 'document/' . $file_path); $my_dep->setAttribute('xml:base', ''); } elseif (empty($file_path)) { /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH),api_get_path(REL_PATH))); if (strpos($document_root,-1) == '/') { $document_root = substr(0, -1, $document_root); }*/ $file_path = $_SERVER['DOCUMENT_ROOT'] . $abs_path; $file_path = str_replace('//', '/', $file_path); if (file_exists($file_path)) { $file_path = substr($file_path, strlen($current_dir)); // We get the relative path. $zip_files[] = $my_sub_dir . '/' . $file_path; $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => 'document/' . $file_path); $my_dep_file->setAttribute('href', 'document/' . $file_path); $my_dep->setAttribute('xml:base', ''); } } break; case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip. $current_dir = dirname($current_course_path . '/' . $item->get_file_path()) . '/'; $current_dir = str_replace('\\', '/', $current_dir); $file_path = realpath($doc_info[0]); $file_path = str_replace('\\', '/', $file_path); $my_dep_file->setAttribute('href', $file_path); $my_dep->setAttribute('xml:base', ''); if (strstr($file_path, $main_path) !== false) { // The calculated real path is really inside the chamilo root path. // Reduce file path to what's under the DocumentRoot. $file_path = substr($file_path, strlen($root_path)); //echo $file_path;echo '<br /><br />'; //error_log('Reduced path: '.$file_path, 0); $zip_files_abs[] = $file_path; $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path); $my_dep_file->setAttribute('href', 'document/' . $file_path); $my_dep->setAttribute('xml:base', ''); } elseif (empty($file_path)) { /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH))); if (strpos($document_root,-1) == '/') { $document_root = substr(0, -1, $document_root); }*/ $file_path = $_SERVER['DOCUMENT_ROOT'] . $doc_info[0]; $file_path = str_replace('//', '/', $file_path); if (file_exists($file_path)) { $file_path = substr($file_path, strlen($current_dir)); // We get the relative path. $zip_files[] = $my_sub_dir . '/' . $file_path; $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path); $my_dep_file->setAttribute('href', 'document/' . $file_path); $my_dep->setAttribute('xml:base', ''); } } break; case 'rel': // Path relative to the current document. Save xml:base as current document's directory and save file in zip as subdir.file_path if (substr($doc_info[0], 0, 2) == '..') { // Relative path going up. $current_dir = dirname($current_course_path . '/' . $item->get_file_path()) . '/'; $current_dir = str_replace('\\', '/', $current_dir); $file_path = realpath($current_dir . $doc_info[0]); $file_path = str_replace('\\', '/', $file_path); //error_log($file_path.' <-> '.$main_path, 0); if (strstr($file_path, $main_path) !== false) { // The calculated real path is really inside Chamilo's root path. // Reduce file path to what's under the DocumentRoot. $file_path = substr($file_path, strlen($root_path)); $file_path_dest = $file_path; // File path is courses/CHAMILO/document/.... $info_file_path = explode('/', $file_path); if ($info_file_path[0] == 'courses') { // Add character "/" in file path. $file_path_dest = 'document/' . $file_path; } //error_log('Reduced path: '.$file_path, 0); $zip_files_abs[] = $file_path; $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path_dest); $my_dep_file->setAttribute('href', 'document/' . $file_path); $my_dep->setAttribute('xml:base', ''); } } else { $zip_files[] = $my_sub_dir . '/' . $doc_info[0]; $my_dep_file->setAttribute('href', $doc_info[0]); $my_dep->setAttribute('xml:base', $my_xml_sub_dir); } break; default: $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/ $my_dep->setAttribute('xml:base', ''); break; } } $my_dep->appendChild($my_dep_file); $resources->appendChild($my_dep); $dependency = $xmldoc->createElement('dependency'); $dependency->setAttribute('identifierref', $res_id); $my_resource->appendChild($dependency); $i++; } $resources->appendChild($my_resource); $zip_files[] = $my_file_path; break; default: // Get the path of the file(s) from the course directory root $my_file_path = 'non_exportable.html'; //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8'); $my_xml_file_path = $my_file_path; $my_sub_dir = dirname($my_file_path); $my_sub_dir = str_replace('\\', '/', $my_sub_dir); //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8'); $my_xml_sub_dir = $my_sub_dir; // Give a <resource> child to the <resources> element. $my_resource = $xmldoc->createElement('resource'); $my_resource->setAttribute('identifier', 'RESOURCE_' . $item->get_id()); $my_resource->setAttribute('type', 'webcontent'); $my_resource->setAttribute('href', $folder_name . '/' . $my_xml_file_path); // adlcp:scormtype can be either 'sco' or 'asset'. $my_resource->setAttribute('adlcp:scormtype', 'asset'); // xml:base is the base directory to find the files declared in this resource. $my_resource->setAttribute('xml:base', ''); // Give a <file> child to the <resource> element. $my_file = $xmldoc->createElement('file'); $my_file->setAttribute('href', 'document/' . $my_xml_file_path); $my_resource->appendChild($my_file); $resources->appendChild($my_resource); break; } } } $organizations->appendChild($organization); $root->appendChild($organizations); $root->appendChild($resources); $xmldoc->appendChild($root); // TODO: Add a readme file here, with a short description and a link to the Reload player // then add the file to the zip, then destroy the file (this is done automatically). // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138 //error_log(print_r($zip_files,true), 0); foreach ($zip_files as $file_path) { if (empty($file_path)) { continue; } //error_log(__LINE__.'getting document from '.$sys_course_path.$_course['path'].'/'.$file_path.' removing '.$sys_course_path.$_course['path'].'/',0); $dest_file = $archive_path . $temp_dir_short . '/' . $file_path; $this->create_path($dest_file); //error_log('copy '.api_get_path(SYS_COURSE_PATH).$_course['path'].'/'.$file_path.' to '.api_get_path(SYS_ARCHIVE_PATH).$temp_dir_short.'/'.$file_path,0); //echo $main_path.$file_path.'<br />'; @copy($sys_course_path . $_course['path'] . '/' . $file_path, $dest_file); // Check if the file needs a link update. if (in_array($file_path, array_keys($link_updates))) { $string = file_get_contents($dest_file); unlink($dest_file); foreach ($link_updates[$file_path] as $old_new) { //error_log('Replacing '.$old_new['orig'].' by '.$old_new['dest'].' in '.$file_path, 0); // This is an ugly hack that allows .flv files to be found by the flv player that // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs // to find the flv to play in document/main/, so we replace main/ in the flv path by // ../../.. to return from inc/lib/flv_player to the document/main path. if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') { $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']); } elseif (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 6) == 'video/') { $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']); } //Fix to avoid problems with default_course_document if (strpos("main/default_course_document", $old_new['dest'] === false)) { $new_dest = str_replace('document/', $mult . 'document/', $old_new['dest']); } else { //$new_dest = str_replace('main/default_course_document', $mult.'document/main/default_course_document', $old_new['dest']); $new_dest = $old_new['dest']; } //$string = str_replace($old_new['orig'], $old_new['dest'], $string); $string = str_replace($old_new['orig'], $new_dest, $string); //Add files inside the HTMLs $new_path = str_replace('/courses/', '', $old_new['orig']); //var_dump($sys_course_path.$new_path); var_dump($archive_path.$temp_dir_short.'/'.$old_new['dest']); echo '---'; if (file_exists($sys_course_path . $new_path)) { copy($sys_course_path . $new_path, $archive_path . $temp_dir_short . '/' . $old_new['dest']); } } file_put_contents($dest_file, $string); } } foreach ($zip_files_abs as $file_path) { if (empty($file_path)) { continue; } //error_log(__LINE__.'checking existence of '.$main_path.$file_path.'', 0); if (!is_file($main_path . $file_path) || !is_readable($main_path . $file_path)) { continue; } //error_log(__LINE__.'getting document from '.$main_path.$file_path.' removing '.api_get_path(SYS_COURSE_PATH).$_course['path'].'/', 0); $dest_file = $archive_path . $temp_dir_short . '/document/' . $file_path; $this->create_path($dest_file); //error_log('Created path '.api_get_path(SYS_ARCHIVE_PATH).$temp_dir_short.'/document/'.$file_path, 0); //error_log('copy '.api_get_path(SYS_COURSE_PATH).$_course['path'].'/'.$file_path.' to '.api_get_path(SYS_ARCHIVE_PATH).$temp_dir_short.'/'.$file_path, 0); //echo $main_path.$file_path.' - '.$dest_file.'<br />'; copy($main_path . $file_path, $dest_file); // Check if the file needs a link update. if (in_array($file_path, array_keys($link_updates))) { $string = file_get_contents($dest_file); unlink($dest_file); foreach ($link_updates[$file_path] as $old_new) { //error_log('Replacing '.$old_new['orig'].' by '.$old_new['dest'].' in '.$file_path, 0); // This is an ugly hack that allows .flv files to be found by the flv player that // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs // to find the flv to play in document/main/, so we replace main/ in the flv path by // ../../.. to return from inc/lib/flv_player to the document/main path. if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') { $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']); } $string = str_replace($old_new['orig'], $old_new['dest'], $string); } file_put_contents($dest_file, $string); } } if (is_array($links_to_create)) { foreach ($links_to_create as $file => $link) { $file_content = '<!DOCTYPE html> <head> <meta charset="' . api_get_language_isocode() . '" /> <title>' . $link['title'] . '</title> </head> <body dir="' . api_get_text_direction() . '"> <div style="text-align:center"> <a href="' . $link['url'] . '">' . $link['title'] . '</a></div> </body> </html>'; file_put_contents($archive_path . $temp_dir_short . '/' . $file, $file_content); } } // Add non exportable message explanation. $lang_not_exportable = get_lang('ThisItemIsNotExportable'); $file_content = '<!DOCTYPE html> <head> <meta charset="' . api_get_language_isocode() . '" /> <title>' . $lang_not_exportable . '</title> <meta http-equiv="Content-Type" content="text/html; charset=' . api_get_system_encoding() . '" /> </head> <body dir="' . api_get_text_direction() . '">'; $file_content .= <<<EOD <style> .error-message { font-family: arial, verdana, helvetica, sans-serif; border-width: 1px; border-style: solid; left: 50%; margin: 10px auto; min-height: 30px; padding: 5px; right: 50%; width: 500px; background-color: #FFD1D1; border-color: #FF0000; color: #000; } </style> <body> <div class="error-message"> {$lang_not_exportable} </div> </body> </html> EOD; if (!is_dir($archive_path . $temp_dir_short . '/document')) { @mkdir($archive_path . $temp_dir_short . '/document', api_get_permissions_for_new_directories()); } file_put_contents($archive_path . $temp_dir_short . '/document/non_exportable.html', $file_content); // Add the extra files that go along with a SCORM package. $main_code_path = api_get_path(SYS_CODE_PATH) . 'newscorm/packaging/'; $extra_files = scandir($main_code_path); foreach ($extra_files as $extra_file) { if (strpos($extra_file, '.') === 0) { continue; } else { $dest_file = $archive_path . $temp_dir_short . '/' . $extra_file; $this->create_path($dest_file); copy($main_code_path . $extra_file, $dest_file); } } // Finalize the imsmanifest structure, add to the zip, then return the zip. $manifest = @$xmldoc->saveXML(); $manifest = Text::api_utf8_decode_xml($manifest); // The manifest gets the system encoding now. file_put_contents($archive_path . '/' . $temp_dir_short . '/imsmanifest.xml', $manifest); $zip_folder->add($archive_path . '/' . $temp_dir_short, PCLZIP_OPT_REMOVE_PATH, $archive_path . '/' . $temp_dir_short . '/'); // Clean possible temporary files. foreach ($files_cleanup as $file) { $res = unlink($file); if ($res === false) { error_log('Could not delete temp file ' . $file . ' ' . __FILE__ . ' ' . __LINE__, 0); } } // Send file to client $name = api_replace_dangerous_char($this->get_name()) . '.zip'; DocumentManager::file_send_for_download($temp_zip_file, true, $name); }
/** * Truncates a string. * * @author Brouckaert Olivier * @param string $text The text to truncate. * @param integer $length The approximate desired length. The length of the suffix below is to be added to have the total length of the result string. * @param string $suffix A suffix to be added as a replacement. * @param string $encoding (optional) The encoding to be used. If it is omitted, the platform character set will be used by default. * @param boolean $middle If this parameter is true, truncation is done in the middle of the string. * @return string Truncated string, decorated with the given suffix (replacement). */ function api_trunc_str($text, $length = 30, $suffix = '...', $middle = false, $encoding = null) { if (empty($encoding)) { $encoding = api_get_system_encoding(); } $text_length = api_strlen($text, $encoding); if ($text_length <= $length) { return $text; } if ($middle) { return rtrim(api_substr($text, 0, round($length / 2), $encoding)) . $suffix . ltrim(api_substr($text, -round($length / 2), $text_length, $encoding)); } return rtrim(api_substr($text, 0, $length, $encoding)) . $suffix; }
/** * Adds a user to the Dokeos database or updates its data * @param string username (and uid inside LDAP) * @author Mustapha Alouani */ function ldap_add_user($login) { global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass; $ds = ldap_connect($ldap_host, $ldap_port); ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($ds, LDAP_OPT_REFERRALS, 0); if ($ds) { $str_query = "(uid=" . $login . ")"; $r = false; $res = ldap_handle_bind($ds, $r); $sr = ldap_search($ds, $ldap_basedn, $str_query); //echo "Le nombre de resultats est : ".ldap_count_entries($ds,$sr)."<p>"; $info = ldap_get_entries($ds, $sr); for ($key = 0; $key < $info['count']; $key++) { $lastname = api_convert_encoding($info[$key]['sn'][0], api_get_system_encoding(), 'UTF-8'); $firstname = api_convert_encoding($info[$key]['givenname'][0], api_get_system_encoding(), 'UTF-8'); $email = $info[$key]['mail'][0]; // Get uid from dn $dn_array = ldap_explode_dn($info[$key]['dn'], 1); $username = $dn_array[0]; // uid is first key $outab[] = $info[$key]['edupersonprimaryaffiliation'][0]; // Ici "student" //$val = ldap_get_values_len($ds, $entry, "userPassword"); //$val = ldap_get_values_len($ds, $info[$key], "userPassword"); //$password = $val[0]; // TODO the password, if encrypted at the source, will be encrypted twice, which makes it useless. Try to fix that. $password = $info[$key]['userPassword'][0]; $structure = $info[$key]['edupersonprimaryorgunitdn'][0]; $array_structure = explode(",", $structure); $array_val = explode("=", $array_structure[0]); $etape = $array_val[1]; $array_val = explode("=", $array_structure[1]); $annee = $array_val[1]; // Pour faciliter la gestion on ajoute le code "etape-annee" $official_code = $etape . "-" . $annee; $auth_source = 'ldap'; // Pas de date d'expiration d'etudiant (a recuperer par rapport au shadow expire LDAP) $expiration_date = '0000-00-00 00:00:00'; $active = 1; if (empty($status)) { $status = 5; } if (empty($phone)) { $phone = ''; } if (empty($picture_uri)) { $picture_uri = ''; } // Ajout de l'utilisateur if (UserManager::is_username_available($username)) { $user_id = UserManager::create_user($firstname, $lastname, $status, $email, $username, $password, $official_code, api_get_setting('platformLanguage'), $phone, $picture_uri, $auth_source, $expiration_date, $active); } else { $user = UserManager::get_user_info($username); $user_id = $user['user_id']; UserManager::update_user($user_id, $firstname, $lastname, $username, null, null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active); } } } else { Display::display_error_message(get_lang('LDAPConnectionError')); } return $user_id; }