/** * @param $exerciseId * @param bool $addQs * @param bool $rmQs */ public function search_engine_edit($exerciseId, $addQs = false, $rmQs = false) { // update search engine and its values table if enabled if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) { $course_id = api_get_course_id(); // get search_did $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); if ($addQs || $rmQs) { //there's only one row per question on normal db and one document per question on search engine db $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1'; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id); } else { $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%s LIMIT 1'; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id); } $res = Database::query($sql); if (Database::num_rows($res) > 0 || $addQs) { require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php'; require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php'; $di = new ChamiloIndexer(); if ($addQs) { $question_exercises = array((int) $exerciseId); } else { $question_exercises = array(); } isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english'); $di->connectDb(null, null, $lang); // retrieve others exercise ids $se_ref = Database::fetch_array($res); $se_doc = $di->get_document((int) $se_ref['search_did']); if ($se_doc !== false) { if (($se_doc_data = $di->get_document_data($se_doc)) !== false) { $se_doc_data = unserialize($se_doc_data); if (isset($se_doc_data[SE_DATA]['type']) && $se_doc_data[SE_DATA]['type'] == SE_DOCTYPE_EXERCISE_QUESTION) { if (isset($se_doc_data[SE_DATA]['exercise_ids']) && is_array($se_doc_data[SE_DATA]['exercise_ids'])) { foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) { if (!in_array($old_value, $question_exercises)) { $question_exercises[] = $old_value; } } } } } } if ($rmQs) { while (($key = array_search($exerciseId, $question_exercises)) !== false) { unset($question_exercises[$key]); } } // build the chunk to index $ic_slide = new IndexableChunk(); $ic_slide->addValue("title", $this->question); $ic_slide->addCourseId($course_id); $ic_slide->addToolId(TOOL_QUIZ); $xapian_data = array(SE_COURSE_ID => $course_id, SE_TOOL_ID => TOOL_QUIZ, SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_QUESTION, 'exercise_ids' => $question_exercises, 'question_id' => (int) $this->id), SE_USER => (int) api_get_user_id()); $ic_slide->xapian_data = serialize($xapian_data); $ic_slide->addValue("content", $this->description); //TODO: index answers, see also form validation on question_admin.inc.php $di->remove_document((int) $se_ref['search_did']); $di->addChunk($ic_slide); //index and return search engine document id if (!empty($question_exercises)) { // if empty there is nothing to index $did = $di->index(); unset($di); } if ($did || $rmQs) { // save it to db if ($addQs || $rmQs) { $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=\'%s\''; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id); } else { $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\' AND ref_id_second_level=\'%s\''; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id); } Database::query($sql); if ($rmQs) { if (!empty($question_exercises)) { $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did) VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)'; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, array_shift($question_exercises), $this->id, $did); Database::query($sql); } } else { $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did) VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)'; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id, $did); Database::query($sql); } } } } }
/** * Manages page splitting * @param string Page header * @param string Page body * @return void */ function dealPerPage($header, $body) { $_course = api_get_course_info(); // Split document to pages. $pages = explode('||page_break||', $body); $first_item = 0; foreach ($pages as $key => $page_content) { // For every pages, we create a new file. $key += 1; $page_content = $this->format_page_content($header, $page_content, $this->base_work_dir . $this->created_dir); $html_file = $this->created_dir . '-' . $key . '.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); $slide_name = ''; 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 = 'Page ' . str_repeat('0', 2 - strlen($key)) . $key; $previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, ''); if ($this->first_item == 0) { $this->first_item = $previous; } // Code for text indexing. if (isset($_POST['index_document']) && $_POST['index_document']) { //Display::display_normal_message(print_r($_POST)); $di = new ChamiloIndexer(); isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english'); $di->connectDb(NULL, NULL, $lang); $ic_slide = new IndexableChunk(); $ic_slide->addValue('title', $slide_name); $specific_fields = get_specific_field_list(); $all_specific_terms = ''; foreach ($specific_fields as $specific_field) { if (isset($_REQUEST[$specific_field['code']])) { $sterms = trim($_REQUEST[$specific_field['code']]); $all_specific_terms .= ' ' . $sterms; if (!empty($sterms)) { $sterms = explode(',', $sterms); foreach ($sterms as $sterm) { $ic_slide->addTerm(trim($sterm), $specific_field['code']); } } } } $page_content = $all_specific_terms . ' ' . $page_content; $ic_slide->addValue('content', $page_content); // Add a comment to say terms separated by commas. $courseid = api_get_course_id(); $ic_slide->addCourseId($courseid); $ic_slide->addToolId(TOOL_LEARNPATH); $lp_id = $this->lp_id; $xapian_data = array(SE_COURSE_ID => $courseid, SE_TOOL_ID => TOOL_LEARNPATH, SE_DATA => array('lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => $document_id), SE_USER => (int) api_get_user_id()); $ic_slide->xapian_data = serialize($xapian_data); $di->addChunk($ic_slide); // Index and return search engine document id. $did = $di->index(); if ($did) { // Save it to db. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did) VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)'; $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did); Database::query($sql); } } } } }
public function make_lp($files = array()) { global $_course; $previous = 0; $i = 0; if (!is_dir($this->base_work_dir.$this->created_dir)) return false; foreach ($files as $file) { /* '||' is used as separator between fields: slide name (with accents) || file name (without accents) || all slide text (to be indexed). */ list($slide_name, $file_name, $slide_body) = explode('||', $file); // Filename is utf8 encoded, but when we decode, some chars are not translated (like quote ’). // so we remove these chars by translating it in htmlentities and the reconvert it in want charset. $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()); if ($this->take_slide_name === true) { $slide_name = str_replace('_', ' ', $slide_name); $slide_name = api_ucfirst($slide_name); } else { $slide_name = 'slide'.str_repeat('0', 2 - strlen($i)).$i; } $i++; // Add the png to documents. $document_id = add_document( $_course, $this->created_dir.'/'.urlencode($file_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$file_name), $slide_name ); api_item_property_update( $_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id(), 0, 0, null, null, api_get_session_id() ); // Generating the thumbnail. $image = $this->base_work_dir.$this->created_dir .'/'. $file_name; $pattern = '/(\w+)\.png$/'; $replacement = '${1}_thumb.png'; $thumb_name = preg_replace($pattern, $replacement, $file_name); // Calculate thumbnail size. $image_size = api_getimagesize($image); $width = $image_size['width']; $height = $image_size['height']; $thumb_width = 300; $thumb_height = floor($height * ($thumb_width / $width)); $my_new_image = new Image($image); $my_new_image->resize($thumb_width, $thumb_height); $my_new_image->send_image($this->base_work_dir.$this->created_dir .'/'. $thumb_name, -1, 'png'); // Adding the thumbnail to documents. $document_id_thumb = add_document( $_course, $this->created_dir.'/'.urlencode($thumb_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$thumb_name), $slide_name ); api_item_property_update($_course, TOOL_THUMBNAIL, $document_id_thumb, 'DocumentAdded', api_get_user_id(), 0, 0); // Create an html file. $html_file = $file_name.'.html'; $fp = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file, 'w+'); $slide_src = api_get_path(REL_COURSE_PATH).$_course['path'].'/document/'.$this->created_dir.'/'.utf8_encode($file_name); $slide_src = str_replace('//', '/', $slide_src); fwrite($fp, '<html> <head> </head> <body> <img src="'.$slide_src.'" /> </body> </html>'); // This indentation is to make the generated html files to look well. fclose($fp); $document_id = add_document( $_course, $this->created_dir.'/'.urlencode($html_file), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$html_file), $slide_name ); if ($document_id) { // Put the document in item_property update. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id(), 0, 0, null, null, api_get_session_id()); $previous = $this->add_item(0, $previous, 'document', $document_id, $slide_name, ''); if ($this->first_item == 0) { $this->first_item = $previous; } } // Code for text indexing. if (api_get_setting('search_enabled') == 'true') { if (isset($_POST['index_document']) && $_POST['index_document']) { $di = new ChamiloIndexer(); isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english'; $di->connectDb(NULL, NULL, $lang); $ic_slide = new IndexableChunk(); $ic_slide->addValue('title', $slide_name); $specific_fields = get_specific_field_list(); $all_specific_terms = ''; foreach ($specific_fields as $specific_field) { if (isset($_REQUEST[$specific_field['code']])) { $sterms = trim($_REQUEST[$specific_field['code']]); $all_specific_terms .= ' '. $sterms; if (!empty($sterms)) { $sterms = explode(',', $sterms); foreach ($sterms as $sterm) { $ic_slide->addTerm(trim($sterm), $specific_field['code']); } } } } $slide_body = $all_specific_terms .' '. $slide_body; $ic_slide->addValue('content', $slide_body); /* FIXME: cidReq:lp_id:doc_id al indexar */ // Add a comment to say terms separated by commas. $courseid = api_get_course_id(); $ic_slide->addCourseId($courseid); $ic_slide->addToolId(TOOL_LEARNPATH); $lp_id = $this->lp_id; $xapian_data = array( SE_COURSE_ID => $courseid, SE_TOOL_ID => TOOL_LEARNPATH, SE_DATA => array('lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => $document_id), SE_USER => (int)api_get_user_id(), ); $ic_slide->xapian_data = serialize($xapian_data); $di->addChunk($ic_slide); // Index and return search engine document id. $did = $di->index(); if ($did) { // Save it to db. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did) VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)'; $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did); Database::query($sql); } } } } }
/** * Index a given document. * @param int Document ID inside its corresponding course * @param string Course code * @param int Session ID (not used yet) * @param string Language of document's content (defaults to course language) * @param array Array of specific fields (['code'=>'value',...]) * @param string What to do if the file already exists (default or overwrite) * @param bool When set to true, this runs the indexer without actually saving anything to any database * @return bool Returns true on presumed success, false on failure */ public static function index_document($docid, $course_code, $session_id = 0, $lang = 'english', $specific_fields_values = array(), $if_exists = '', $simulation = false) { if (api_get_setting('search.search_enabled') !== 'true') { return false; } if (empty($docid) or $docid != intval($docid)) { return false; } if (empty($session_id)) { $session_id = api_get_session_id(); } $course_info = api_get_course_info($course_code); $course_dir = $course_info['path'] . '/document'; $sys_course_path = api_get_path(SYS_COURSE_PATH); $base_work_dir = $sys_course_path . $course_dir; $course_id = $course_info['real_id']; $table_document = Database::get_course_table(TABLE_DOCUMENT); $qry = "SELECT path, title FROM {$table_document} WHERE c_id = {$course_id} AND id = '{$docid}' LIMIT 1"; $result = Database::query($qry); if (Database::num_rows($result) == 1) { $row = Database::fetch_array($result); $doc_path = api_get_path(SYS_COURSE_PATH) . $course_dir . $row['path']; //TODO: mime_content_type is deprecated, fileinfo php extension is enabled by default as of PHP 5.3.0 // now versions of PHP on Debian testing(5.2.6-5) and Ubuntu(5.2.6-2ubuntu) are lower, so wait for a while $doc_mime = mime_content_type($doc_path); $allowed_mime_types = self::file_get_mime_type(true); // mime_content_type does not detect correctly some formats that are going to be supported for index, so an extensions array is used for the moment if (empty($doc_mime)) { $allowed_extensions = array('doc', 'docx', 'ppt', 'pptx', 'pps', 'ppsx', 'xls', 'xlsx', 'odt', 'odp', 'ods', 'pdf', 'txt', 'rtf', 'msg', 'csv', 'html', 'htm'); $extensions = preg_split("/[\\/\\.]/", $doc_path); $doc_ext = strtolower($extensions[count($extensions) - 1]); if (in_array($doc_ext, $allowed_extensions)) { switch ($doc_ext) { case 'ppt': case 'pps': $doc_mime = 'application/vnd.ms-powerpoint'; break; case 'xls': $doc_mime = 'application/vnd.ms-excel'; break; } } } //@todo move this nightmare in a search controller or something like that!!! J.M if (in_array($doc_mime, $allowed_mime_types)) { $file_title = $row['title']; $file_content = self::get_text_content($doc_path, $doc_mime); $course_code = Database::escape_string($course_code); require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php'; require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php'; $ic_slide = new IndexableChunk(); $ic_slide->addValue('title', $file_title); $ic_slide->addCourseId($course_code); $ic_slide->addToolId(TOOL_DOCUMENT); $xapian_data = array(SE_COURSE_ID => $course_code, SE_TOOL_ID => TOOL_DOCUMENT, SE_DATA => array('doc_id' => $docid), SE_USER => api_get_user_id()); $ic_slide->xapian_data = serialize($xapian_data); $di = new ChamiloIndexer(); $return = $di->connectDb(null, null, $lang); require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php'; $specific_fields = get_specific_field_list(); // process different depending on what to do if file exists /** * @TODO Find a way to really verify if the file had been * overwriten. Now all work is done at * handle_uploaded_document() and it's difficult to verify it */ if (!empty($if_exists) && $if_exists == 'overwrite') { // Overwrite the file on search engine // Actually, it consists on a delete of terms from db, // insert new ones, create a new search engine document, // and remove the old one // Get search_did $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1'; $sql = sprintf($sql, $tbl_se_ref, $course_code, TOOL_DOCUMENT, $docid); $res = Database::query($sql); if (Database::num_rows($res) > 0) { $se_ref = Database::fetch_array($res); if (!$simulation) { $di->remove_document($se_ref['search_did']); } $all_specific_terms = ''; foreach ($specific_fields as $specific_field) { if (!$simulation) { delete_all_specific_field_value($course_code, $specific_field['id'], TOOL_DOCUMENT, $docid); } // Update search engine if (isset($specific_fields_values[$specific_field['code']])) { $sterms = trim($specific_fields_values[$specific_field['code']]); } else { //if the specific field is not defined, force an empty one $sterms = ''; } $all_specific_terms .= ' ' . $sterms; $sterms = explode(',', $sterms); foreach ($sterms as $sterm) { $sterm = trim($sterm); if (!empty($sterm)) { $ic_slide->addTerm($sterm, $specific_field['code']); // updated the last param here from $value to $sterm without being sure - see commit15464 if (!$simulation) { add_specific_field_value($specific_field['id'], $course_code, TOOL_DOCUMENT, $docid, $sterm); } } } } // Add terms also to content to make terms findable by probabilistic search $file_content = $all_specific_terms . ' ' . $file_content; if (!$simulation) { $ic_slide->addValue('content', $file_content); $di->addChunk($ic_slide); // Index and return a new search engine document id $did = $di->index(); if ($did) { // update the search_did on db $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $sql = 'UPDATE %s SET search_did=%d WHERE id=%d LIMIT 1'; $sql = sprintf($sql, $tbl_se_ref, (int) $did, (int) $se_ref['id']); Database::query($sql); } } } } else { // Add all terms $all_specific_terms = ''; foreach ($specific_fields as $specific_field) { if (isset($specific_fields_values[$specific_field['code']])) { $sterms = trim($specific_fields_values[$specific_field['code']]); } else { //if the specific field is not defined, force an empty one $sterms = ''; } $all_specific_terms .= ' ' . $sterms; if (!empty($sterms)) { $sterms = explode(',', $sterms); foreach ($sterms as $sterm) { if (!$simulation) { $ic_slide->addTerm(trim($sterm), $specific_field['code']); add_specific_field_value($specific_field['id'], $course_code, TOOL_DOCUMENT, $docid, $sterm); } } } } // Add terms also to content to make terms findable by probabilistic search $file_content = $all_specific_terms . ' ' . $file_content; if (!$simulation) { $ic_slide->addValue('content', $file_content); $di->addChunk($ic_slide); // Index and return search engine document id $did = $di->index(); if ($did) { // Save it to db $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did) VALUES (NULL , \'%s\', \'%s\', %s, %s)'; $sql = sprintf($sql, $tbl_se_ref, $course_code, TOOL_DOCUMENT, $docid, $did); Database::query($sql); } else { return false; } } } } else { return false; } } return true; }
/** * @param int $id * @param array $values */ public static function editLink($id, $values = array()) { $tbl_link = Database::get_course_table(TABLE_LINK); $_course = api_get_course_info(); $course_id = $_course['real_id']; $values['url'] = trim($values['url']); $values['title'] = trim($values['title']); $values['description'] = trim($values['description']); $values['target'] = empty($values['target']) ? '_self' : $values['target']; $values['on_homepage'] = isset($values['on_homepage']) ? $values['on_homepage'] : ''; $categoryId = intval($values['category_id']); // We ensure URL to be absolute. if (strpos($values['url'], '://') === false) { $values['url'] = 'http://' . $_POST['url']; } // If the title is empty, we use the URL as title. if ($values['title'] == '') { $values['title'] = $values['url']; } // If the URL is invalid, an error occurs. if (!api_valid_url($values['url'], true)) { Display::addFlash(Display::return_message(get_lang('GiveURL'), 'error')); return false; } // Finding the old category_id. $sql = "SELECT * FROM " . $tbl_link . "\n WHERE c_id = {$course_id} AND id='" . $id . "'"; $result = Database::query($sql); $row = Database::fetch_array($result); $category_id = $row['category_id']; if ($category_id != $values['category_id']) { $sql = "SELECT MAX(display_order)\n FROM " . $tbl_link . "\n WHERE\n c_id = {$course_id} AND\n category_id='" . intval($values['category_id']) . "'"; $result = Database::query($sql); list($max_display_order) = Database::fetch_row($result); $max_display_order++; } else { $max_display_order = $row['display_order']; } $params = ['url' => $values['url'], 'title' => $values['title'], 'description' => $values['description'], 'category_id' => $values['category_id'], 'display_order' => $max_display_order, 'on_homepage' => $values['on_homepage'], 'target' => $values['target'], 'category_id' => $values['category_id']]; Database::update($tbl_link, $params, ['c_id = ? AND id = ?' => [$course_id, $id]]); // Update search enchine and its values table if enabled. if (api_get_setting('search_enabled') == 'true') { $course_int_id = api_get_course_int_id(); $course_id = api_get_course_id(); $link_title = Database::escape_string($values['title']); $link_description = Database::escape_string($values['description']); // Actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one. // Get search_did. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1'; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $id); $res = Database::query($sql); if (Database::num_rows($res) > 0) { require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php'; require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php'; require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php'; $se_ref = Database::fetch_array($res); $specific_fields = get_specific_field_list(); $ic_slide = new IndexableChunk(); $all_specific_terms = ''; foreach ($specific_fields as $specific_field) { delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_LINK, $id); if (isset($_REQUEST[$specific_field['code']])) { $sterms = trim($_REQUEST[$specific_field['code']]); if (!empty($sterms)) { $all_specific_terms .= ' ' . $sterms; $sterms = explode(',', $sterms); foreach ($sterms as $sterm) { $ic_slide->addTerm(trim($sterm), $specific_field['code']); add_specific_field_value($specific_field['id'], $course_id, TOOL_LINK, $id, $sterm); } } } } // Build the chunk to index. $ic_slide->addValue("title", $link_title); $ic_slide->addCourseId($course_id); $ic_slide->addToolId(TOOL_LINK); $xapian_data = array(SE_COURSE_ID => $course_id, SE_TOOL_ID => TOOL_LINK, SE_DATA => array('link_id' => (int) $id), SE_USER => (int) api_get_user_id()); $ic_slide->xapian_data = serialize($xapian_data); $link_description = $all_specific_terms . ' ' . $link_description; $ic_slide->addValue('content', $link_description); // Add category name if set. if (isset($categoryId) && $categoryId > 0) { $table_link_category = Database::get_course_table(TABLE_LINK_CATEGORY); $sql_cat = 'SELECT * FROM %s WHERE id=%d and c_id = %d LIMIT 1'; $sql_cat = sprintf($sql_cat, $table_link_category, $categoryId, $course_int_id); $result = Database::query($sql_cat); if (Database::num_rows($result) == 1) { $row = Database::fetch_array($result); $ic_slide->addValue('category', $row['category_title']); } } $di = new ChamiloIndexer(); isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english'); $di->connectDb(null, null, $lang); $di->remove_document((int) $se_ref['search_did']); $di->addChunk($ic_slide); // Index and return search engine document id. $did = $di->index(); if ($did) { // Save it to db. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\''; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $id); Database::query($sql); $sql = 'INSERT INTO %s (c_id, id, course_code, tool_id, ref_id_high_level, search_did) VALUES (NULL , \'%s\', \'%s\', %s, %s)'; $sql = sprintf($sql, $tbl_se_ref, $course_int_id, $course_id, TOOL_LINK, $id, $did); Database::query($sql); } } } // "WHAT'S NEW" notification: update table last_toolEdit. api_item_property_update($_course, TOOL_LINK, $id, 'LinkUpdated', api_get_user_id()); Display::addFlash(Display::return_message(get_lang('LinkModded'))); }
function search_engine_delete() { // remove from search engine if enabled if (api_get_setting('search.search_enabled') == 'true' && extension_loaded('xapian')) { $course_id = api_get_course_id(); $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1'; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id); $res = Database::query($sql); if (Database::num_rows($res) > 0) { $row = Database::fetch_array($res); require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php'; $di = new ChamiloIndexer(); $di->remove_document((int) $row['search_did']); unset($di); $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION); foreach ($this->questionList as $question_i) { $sql = 'SELECT type FROM %s WHERE id=%s'; $sql = sprintf($sql, $tbl_quiz_question, $question_i); $qres = Database::query($sql); if (Database::num_rows($qres) > 0) { $qrow = Database::fetch_array($qres); $objQuestion = Question::getInstance($qrow['type']); $objQuestion = Question::read((int) $question_i); $objQuestion->search_engine_edit($this->id, FALSE, TRUE); unset($objQuestion); } } } $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1'; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id); Database::query($sql); // remove terms from db require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php'; delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id); } }
/** * Set index specified prefix terms for all items in this path * @param string Comma-separated list of terms * @param char Xapian term prefix * @return boolean False on error, true otherwise */ public function set_terms_by_prefix($terms_string, $prefix) { $course_id = api_get_course_int_id(); if (api_get_setting('search_enabled') !== 'true') { return false; } if (!extension_loaded('xapian')) { return false; } $terms_string = trim($terms_string); $terms = explode(',', $terms_string); array_walk($terms, 'trim_value'); $stored_terms = $this->get_common_index_terms_by_prefix($prefix); // Don't do anything if no change, verify only at DB, not the search engine. if (count(array_diff($terms, $stored_terms)) == 0 && count(array_diff($stored_terms, $terms)) == 0) { return false; } require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API. require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php'; require_once api_get_path(LIBRARY_PATH) . 'search/xapian/XapianQuery.php'; require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php'; $items_table = Database::get_course_table(TABLE_LP_ITEM); // TODO: Make query secure agains XSS : use member attr instead of post var. $lp_id = intval($_POST['lp_id']); $sql = "SELECT * FROM {$items_table} WHERE c_id = {$course_id} AND lp_id = {$lp_id}"; $result = Database::query($sql); $di = new ChamiloIndexer(); while ($lp_item = Database::fetch_array($result)) { // Get search_did. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d LIMIT 1'; $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']); //echo $sql; echo '<br>'; $res = Database::query($sql); if (Database::num_rows($res) > 0) { $se_ref = Database::fetch_array($res); // Compare terms. $doc = $di->get_document($se_ref['search_did']); $xapian_terms = xapian_get_doc_terms($doc, $prefix); $xterms = array(); foreach ($xapian_terms as $xapian_term) { $xterms[] = substr($xapian_term['name'], 1); } $dterms = $terms; $missing_terms = array_diff($dterms, $xterms); $deprecated_terms = array_diff($xterms, $dterms); // Save it to search engine. foreach ($missing_terms as $term) { $doc->add_term($prefix . $term, 1); } foreach ($deprecated_terms as $term) { $doc->remove_term($prefix . $term); } $di->getDb()->replace_document((int) $se_ref['search_did'], $doc); $di->getDb()->flush(); } else { //@todo What we should do here? } } return true; }
/** * Set the terms for this learnpath item * @param string Terms, as a comma-split list * @return boolean Always return true */ public function set_terms($terms) { global $charset; $course_id = api_get_course_int_id(); $lp_item = Database::get_course_table(TABLE_LP_ITEM); require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php'; $a_terms = split(',', $terms); $i_terms = split(',', $this->get_terms()); foreach ($i_terms as $term) { if (!in_array($term, $a_terms)) { array_push($a_terms, $term); } } $new_terms = $a_terms; $new_terms_string = implode(',', $new_terms); $terms_update_sql = ''; // TODO: Validate csv string. $terms_update_sql = "UPDATE {$lp_item} SET terms = '" . Database::escape_string(api_htmlentities($new_terms_string, ENT_QUOTES, $charset)) . "'\n\t\t WHERE c_id = {$course_id} AND id=" . $this->get_id(); $res = Database::query($terms_update_sql); // Save it to search engine. if (api_get_setting('search_enabled') == 'true') { $di = new ChamiloIndexer(); $di->update_terms($this->get_search_did(), $new_terms); } return true; }
/** * Import the scorm object (as a result from the parse_manifest function) into the database structure * @param string Unique course code * @return bool Returns -1 on error */ function import_manifest($course_code, $use_max_score = 1) { if ($this->debug > 0) { error_log('New LP - Entered import_manifest(' . $course_code . ')', 0); } $course_info = api_get_course_info($course_code); $course_id = $course_info['real_id']; // Get table names. $new_lp = Database::get_course_table(TABLE_LP_MAIN); $new_lp_item = Database::get_course_table(TABLE_LP_ITEM); $use_max_score = intval($use_max_score); foreach ($this->organizations as $id => $dummy) { $is_session = api_get_session_id(); $is_session != 0 ? $session_id = $is_session : ($session_id = 0); $oOrganization =& $this->organizations[$id]; // Prepare and execute insert queries: // -for learnpath // -for items // -for views? $get_max = "SELECT MAX(display_order) FROM {$new_lp} WHERE c_id = {$course_id} "; $res_max = Database::query($get_max); $dsp = 1; if (Database::num_rows($res_max) > 0) { $row = Database::fetch_array($res_max); $dsp = $row[0] + 1; } $myname = $oOrganization->get_name(); $myname = api_utf8_decode($myname); $sql = "INSERT INTO {$new_lp} (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib,display_order, session_id, use_max_score)" . "VALUES ({$course_id} , 2,'" . $myname . "', '" . $oOrganization->get_ref() . "','','" . $this->subdir . "', 0, 'embedded', '" . $this->manifest_encoding . "', 'scorm_api.php', {$dsp}, {$session_id}, {$use_max_score})"; if ($this->debug > 1) { error_log('New LP - In import_manifest(), inserting path: ' . $sql, 0); } $res = Database::query($sql); $lp_id = Database::insert_id(); $this->lp_id = $lp_id; // Insert into item_property. api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'LearnpathAdded', api_get_user_id()); api_item_property_update(api_get_course_info($course_code), TOOL_LEARNPATH, $this->lp_id, 'visible', api_get_user_id()); // Now insert all elements from inside that learning path. // Make sure we also get the href and sco/asset from the resources. $list = $oOrganization->get_flat_items_list(); $parents_stack = array(0); $parent = 0; $previous = 0; $level = 0; foreach ($list as $item) { if ($item['level'] > $level) { // Push something into the parents array. array_push($parents_stack, $previous); $parent = $previous; } elseif ($item['level'] < $level) { $diff = $level - $item['level']; // Pop something out of the parents array. for ($j = 1; $j <= $diff; $j++) { $outdated_parent = array_pop($parents_stack); } $parent = array_pop($parents_stack); // Just save that value, then add it back. array_push($parents_stack, $parent); } $path = ''; $type = 'dir'; if (isset($this->resources[$item['identifierref']])) { $oRes =& $this->resources[$item['identifierref']]; $path = @$oRes->get_path(); if (!empty($path)) { $temptype = $oRes->get_scorm_type(); if (!empty($temptype)) { $type = $temptype; } } } $level = $item['level']; $field_add = ''; $value_add = ''; if (!empty($item['masteryscore'])) { $field_add .= 'mastery_score, '; $value_add .= $item['masteryscore'] . ','; } if (!empty($item['maxtimeallowed'])) { $field_add .= 'max_time_allowed, '; $value_add .= "'" . $item['maxtimeallowed'] . "',"; } $title = Database::escape_string($item['title']); $title = api_utf8_decode($title); $max_score = Database::escape_string($item['max_score']); if ($max_score == 0 || is_null($max_score) || $max_score == '') { //If max score is not set The use_max_score parameter is check in order to use 100 (chamilo style) or '' (strict scorm) if ($use_max_score) { $max_score = "'100'"; } else { $max_score = "NULL"; } } else { //Otherwise save the max score $max_score = "'{$max_score}'"; } $identifier = Database::escape_string($item['identifier']); if (empty($title)) { $title = get_lang('Untitled'); } $prereq = Database::escape_string($item['prerequisites']); $sql_item = "INSERT INTO {$new_lp_item} (c_id, lp_id,item_type,ref,title, path,min_score,max_score, {$field_add} parent_item_id,previous_item_id,next_item_id, prerequisite,display_order,launch_data, parameters) VALUES " . "({$course_id}, {$lp_id}, '{$type}','{$identifier}', '{$title}', '{$path}' , 0, {$max_score}, {$value_add}" . "{$parent}, {$previous}, 0, " . "'{$prereq}', " . $item['rel_order'] . ", '" . $item['datafromlms'] . "'," . "'" . $item['parameters'] . "'" . ")"; $res_item = Database::query($sql_item); if ($this->debug > 1) { error_log('New LP - In import_manifest(), inserting item : ' . $sql_item . ' : ' . Database::error(), 0); } $item_id = Database::insert_id(); // Now update previous item to change next_item_id. $upd = "UPDATE {$new_lp_item} SET next_item_id = {$item_id} WHERE c_id = {$course_id} AND id = {$previous}"; $upd_res = Database::query($upd); // Update previous item id. $previous = $item_id; // Code for indexing, now only index specific fields like terms and the title. if (!empty($_POST['index_document'])) { require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php'; require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php'; require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php'; $di = new ChamiloIndexer(); isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english'); $di->connectDb(null, null, $lang); $ic_slide = new IndexableChunk(); $ic_slide->addValue('title', $title); $specific_fields = get_specific_field_list(); $all_specific_terms = ''; foreach ($specific_fields as $specific_field) { if (isset($_REQUEST[$specific_field['code']])) { $sterms = trim($_REQUEST[$specific_field['code']]); $all_specific_terms .= ' ' . $sterms; if (!empty($sterms)) { $sterms = explode(',', $sterms); foreach ($sterms as $sterm) { $ic_slide->addTerm(trim($sterm), $specific_field['code']); } } } } $body_to_index = $all_specific_terms . ' ' . $title; $ic_slide->addValue("content", $body_to_index); // TODO: Add a comment to say terms separated by commas. $courseid = api_get_course_id(); $ic_slide->addCourseId($courseid); $ic_slide->addToolId(TOOL_LEARNPATH); $xapian_data = array(SE_COURSE_ID => $courseid, SE_TOOL_ID => TOOL_LEARNPATH, SE_DATA => array('lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => ''), SE_USER => (int) api_get_user_id()); $ic_slide->xapian_data = serialize($xapian_data); $di->addChunk($ic_slide); // Index and return search engine document id. $did = $di->index(); if ($did) { // Save it to db. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did) VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)'; $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did); Database::query($sql); } } } } }
function search_engine_delete() { // remove from search engine if enabled if (api_get_setting('search.search_enabled') == 'true' && extension_loaded('xapian')) { $em = Database::getManager(); $course = $em->find('ChamiloCoreBundle:Course', api_get_course_int_id()); $res = $em->createQuery(' SELECT ser FROM ChamiloCoreBundle:SearchEngineRef ser WHERE ser.course = ?1 AND ser.toolId = ?2 AND ser.refIdHighLevel = ?3 AND ser.refIdSecondLevel IS NULL ')->setMaxResults(1)->execute([1 => $course, 2 => TOOL_QUIZ, 3 => $this->id]); if (count($res) > 0) { $row = current($res); require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php'; $di = new ChamiloIndexer(); $di->remove_document($row->getSearchDid()); unset($di); $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION); foreach ($this->questionList as $question_i) { $sql = 'SELECT type FROM %s WHERE id=%s'; $sql = sprintf($sql, $tbl_quiz_question, $question_i); $qres = Database::query($sql); if (Database::num_rows($qres) > 0) { $qrow = Database::fetch_array($qres); $objQuestion = Question::getInstance($qrow['type']); $objQuestion = Question::read((int) $question_i); $objQuestion->search_engine_edit($this->id, FALSE, TRUE); unset($objQuestion); } } } $em->createQuery(' DELETE FROM ChamiloCoreBundle:SearchEngineRef ser WHERE ser.course = ?1 AND ser.toolId = ?2 AND ser.refIdHighLevel = ?3 AND ser.refIdSecondLevel IS NULL ')->setMaxResults(1)->execute([1 => $course, 2 => TOOL_QUIZ, 3 => $this->id]); // remove terms from db require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php'; delete_all_values_for_item($course->getCode(), TOOL_QUIZ, $this->id); } }
/** * Used to edit a link or a category * @todo Rewrite the whole links tool because it is becoming completely cluttered, * code does not follow the coding conventions, does not use html_quickform, ... * Some features were patched in. * @author Patrick Cool <*****@*****.**>, Ghent University * @todo replace the globals with the appropriate $_POST or $_GET values */ function editlinkcategory($type) { global $catlinkstatus; global $id; global $submit_link; global $submit_category; global $_user; global $_course; global $nameTools; global $urllink; global $title; global $description; global $category; global $selectcategory; global $description; global $category_title; global $onhomepage; global $target_link; $tbl_link = Database::get_course_table(TABLE_LINK); $tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY); $course_id = api_get_course_int_id(); if ($type == 'link') { // This is used to populate the link-form with the info found in the database. if (!empty($_GET['id'])) { $sql = "SELECT * FROM " . $tbl_link . "\n WHERE c_id = {$course_id} AND id='" . intval($_GET['id']) . "'"; $result = Database::query($sql); if ($myrow = Database::fetch_array($result)) { $urllink = $myrow['url']; $title = $myrow['title']; $description = $myrow['description']; $category = $myrow['category_id']; if ($myrow['on_homepage'] != 0) { $onhomepage = 'checked'; } $target_link = $myrow['target']; } } // This is used to put the modified info of the link-form into the database. if ($_POST['submitLink']) { // Ivan, 13-OCT-2010: It is a litle bit messy code below, just in case I added some extra-security checks here. $_POST['urllink'] = trim($_POST['urllink']); $_POST['title'] = trim(Security::remove_XSS($_POST['title'])); $_POST['description'] = trim(Security::remove_XSS($_POST['description'])); $_POST['selectcategory'] = intval($_POST['selectcategory']); $_POST['id'] = intval($_POST['id']); // We ensure URL to be absolute. if (strpos($_POST['urllink'], '://') === false) { $_POST['urllink'] = 'http://' . $_POST['urllink']; } // If the title is empty, we use the URL as title. if ($_POST['title'] == '') { $_POST['title'] = $_POST['urllink']; } // If the URL is invalid, an error occurs. if (!api_valid_url($urllink, true)) { // A check against an absolute URL. $msgErr = get_lang('GiveURL'); Display::display_error_message(get_lang('GiveURL')); return false; } $onhomepage = Security::remove_XSS($_POST['onhomepage']); $target = Database::escape_string($_POST['target_link']); if (empty($mytarget)) { $mytarget = '_self'; } $mytarget = ", target='" . $target . "'"; // Finding the old category_id. $sql = "SELECT * FROM " . $tbl_link . "\n WHERE c_id = {$course_id} AND id='" . intval($_POST['id']) . "'"; $result = Database::query($sql); $row = Database::fetch_array($result); $category_id = $row['category_id']; if ($category_id != $_POST['selectcategory']) { $sql = "SELECT MAX(display_order)\n FROM " . $tbl_link . "\n WHERE c_id = {$course_id}\n AND category_id='" . intval($_POST['selectcategory']) . "'"; $result = Database::query($sql); list($max_display_order) = Database::fetch_row($result); $max_display_order++; } else { $max_display_order = $row['display_order']; } $sql = "UPDATE " . $tbl_link . " SET " . "url='" . Database::escape_string($_POST['urllink']) . "', " . "title='" . Database::escape_string($_POST['title']) . "', " . "description='" . Database::escape_string($_POST['description']) . "', " . "category_id='" . Database::escape_string($_POST['selectcategory']) . "', " . "display_order='" . $max_display_order . "', " . "on_homepage= '" . Database::escape_string($onhomepage) . "' {$mytarget} " . " WHERE c_id = {$course_id} AND id='" . intval($_POST['id']) . "'"; Database::query($sql); // Update search enchine and its values table if enabled. if (api_get_setting('search_enabled') == 'true') { $link_id = intval($_POST['id']); $course_int_id = api_get_course_int_id(); $course_id = api_get_course_id(); $link_url = Database::escape_string($_POST['urllink']); $link_title = Database::escape_string($_POST['title']); $link_description = Database::escape_string($_POST['description']); // Actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one. // Get search_did. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1'; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $link_id); $res = Database::query($sql); if (Database::num_rows($res) > 0) { require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php'; require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php'; require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php'; $se_ref = Database::fetch_array($res); $specific_fields = get_specific_field_list(); $ic_slide = new IndexableChunk(); $all_specific_terms = ''; foreach ($specific_fields as $specific_field) { delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_LINK, $link_id); if (isset($_REQUEST[$specific_field['code']])) { $sterms = trim($_REQUEST[$specific_field['code']]); if (!empty($sterms)) { $all_specific_terms .= ' ' . $sterms; $sterms = explode(',', $sterms); foreach ($sterms as $sterm) { $ic_slide->addTerm(trim($sterm), $specific_field['code']); add_specific_field_value($specific_field['id'], $course_id, TOOL_LINK, $link_id, $sterm); } } } } // Build the chunk to index. $ic_slide->addValue("title", $link_title); $ic_slide->addCourseId($course_id); $ic_slide->addToolId(TOOL_LINK); $xapian_data = array(SE_COURSE_ID => $course_id, SE_TOOL_ID => TOOL_LINK, SE_DATA => array('link_id' => (int) $link_id), SE_USER => (int) api_get_user_id()); $ic_slide->xapian_data = serialize($xapian_data); $link_description = $all_specific_terms . ' ' . $link_description; $ic_slide->addValue('content', $link_description); // Add category name if set. if (isset($_POST['selectcategory']) && $selectcategory > 0) { $table_link_category = Database::get_course_table(TABLE_LINK_CATEGORY); $sql_cat = 'SELECT * FROM %s WHERE id=%d and c_id = %d LIMIT 1'; $sql_cat = sprintf($sql_cat, $table_link_category, (int) $selectcategory, $course_int_id); $result = Database::query($sql_cat); if (Database::num_rows($result) == 1) { $row = Database::fetch_array($result); $ic_slide->addValue('category', $row['category_title']); } } $di = new ChamiloIndexer(); isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english'); $di->connectDb(null, null, $lang); $di->remove_document((int) $se_ref['search_did']); $di->addChunk($ic_slide); // Index and return search engine document id. $did = $di->index(); if ($did) { // Save it to db. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\''; $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $link_id); Database::query($sql); $sql = 'INSERT INTO %s (c_id, id, course_code, tool_id, ref_id_high_level, search_did) VALUES (NULL , \'%s\', \'%s\', %s, %s)'; $sql = sprintf($sql, $tbl_se_ref, $course_int_id, $course_id, TOOL_LINK, $link_id, $did); Database::query($sql); } } } // "WHAT'S NEW" notification: update table last_toolEdit. api_item_property_update($_course, TOOL_LINK, $_POST['id'], 'LinkUpdated', $_user['user_id']); Display::display_confirmation_message(get_lang('LinkModded')); } } if ($type == 'category') { // This is used to populate the category-form with the info found in the database. if (!$submit_category) { $sql = "SELECT * FROM " . $tbl_categories . "\n WHERE c_id = {$course_id} AND id='" . intval($_GET['id']) . "'"; $result = Database::query($sql); if ($myrow = Database::fetch_array($result)) { $category_title = $myrow['category_title']; $description = $myrow['description']; } } // This is used to put the modified info of the category-form into the database. if ($submit_category) { $sql = "UPDATE " . $tbl_categories . "\n SET category_title='" . Database::escape_string($_POST['category_title']) . "',\n description='" . Database::escape_string($_POST['description']) . "'\n WHERE c_id = {$course_id} AND id='" . Database::escape_string($_POST['id']) . "'"; Database::query($sql); Display::display_confirmation_message(get_lang('CategoryModded')); } } return true; // On errors before this statement, exit from this function by returning false value. }
/** * Manages page splitting * @param string Page header * @param string Page body * @return void */ function dealPerPage($header, $body) { $em = Database::getManager(); $_course = api_get_course_info(); // Split document to pages. $pages = explode('||page_break||', $body); $first_item = 0; foreach ($pages as $key => $page_content) { // For every pages, we create a new file. $key += 1; $page_content = $this->format_page_content($header, $page_content, $this->base_work_dir . $this->created_dir); $html_file = $this->created_dir . '-' . $key . '.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); $slide_name = ''; if ($document_id) { // Put the document in item_property update. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id(), 0, 0, null, null, api_get_session_id()); $infos = pathinfo($this->filepath); $slide_name = 'Page ' . str_repeat('0', 2 - strlen($key)) . $key; $previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, ''); if ($this->first_item == 0) { $this->first_item = $previous; } // Code for text indexing. if (api_get_setting('search.search_enabled') == 'true') { if (isset($_POST['index_document']) && $_POST['index_document']) { //Display::display_normal_message(print_r($_POST)); $di = new ChamiloIndexer(); isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english'); $di->connectDb(NULL, NULL, $lang); $ic_slide = new IndexableChunk(); $ic_slide->addValue('title', $slide_name); $specific_fields = get_specific_field_list(); $all_specific_terms = ''; foreach ($specific_fields as $specific_field) { if (isset($_REQUEST[$specific_field['code']])) { $sterms = trim($_REQUEST[$specific_field['code']]); $all_specific_terms .= ' ' . $sterms; if (!empty($sterms)) { $sterms = explode(',', $sterms); foreach ($sterms as $sterm) { $ic_slide->addTerm(trim($sterm), $specific_field['code']); } } } } $page_content = $all_specific_terms . ' ' . $page_content; $ic_slide->addValue('content', $page_content); // Add a comment to say terms separated by commas. $courseid = api_get_course_id(); $ic_slide->addCourseId($courseid); $ic_slide->addToolId(TOOL_LEARNPATH); $lp_id = $this->lp_id; $xapian_data = array(SE_COURSE_ID => $courseid, SE_TOOL_ID => TOOL_LEARNPATH, SE_DATA => array('lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => $document_id), SE_USER => (int) api_get_user_id()); $ic_slide->xapian_data = serialize($xapian_data); $di->addChunk($ic_slide); // Index and return search engine document id. $did = $di->index(); if ($did) { $course = $em->find('ChamiloCoreBundle:Course', api_get_course_int_id()); // Save it to db. $searchEngineRef = new \Chamilo\CoreBundle\Entity\SearchEngineRef(); $searchEngineRef->setCourse($course)->setToolId(TOOL_LEARNPATH)->setRefIdHighLevel($lp_id)->setRefIdSecondLevel($previous)->setSearchDid($did); $em->persist($searchEngineRef); $em->flush(); } } } } } }
/** * Set index specified prefix terms for all items in this path * @param string Comma-separated list of terms * @param char Xapian term prefix * @return boolean False on error, true otherwise */ public function set_terms_by_prefix($terms_string, $prefix) { $em = Database::getManager(); $course = $em->find('ChamiloCoreBundle:Course', api_get_course_int_id()); if (api_get_setting('search.search_enabled') !== 'true') { return false; } if (!extension_loaded('xapian')) { return false; } $terms_string = trim($terms_string); $terms = explode(',', $terms_string); array_walk($terms, 'trim_value'); $stored_terms = $this->get_common_index_terms_by_prefix($prefix); // Don't do anything if no change, verify only at DB, not the search engine. if (count(array_diff($terms, $stored_terms)) == 0 && count(array_diff($stored_terms, $terms)) == 0) { return false; } require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API. require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php'; require_once api_get_path(LIBRARY_PATH) . 'search/xapian/XapianQuery.php'; require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php'; $items_table = Database::get_course_table(TABLE_LP_ITEM); // TODO: Make query secure agains XSS : use member attr instead of post var. $lp_id = intval($_POST['lp_id']); $sql = "SELECT * FROM {$items_table} WHERE c_id = {$course->getId()} AND lp_id = {$lp_id}"; $result = Database::query($sql); $di = new ChamiloIndexer(); while ($lp_item = Database::fetch_array($result)) { $lpCourse = $em->getRepository('ChamiloCoreBundle:Course')->findOneBy(['code' => $this->cc]); // Get search_did. $se_ref = $em->getRepository('ChamiloCoreBundle:SearchEngineRef')->findOneBy(['course' => $lpCourse, 'toolId' => TOOL_LEARNPATH, 'refIdHighLevel' => $lp_id, 'refIdSecondLevel' => $lp_item['id']]); if ($se_ref) { // Compare terms. $doc = $di->get_document($se_ref->getSearchDid()); $xapian_terms = xapian_get_doc_terms($doc, $prefix); $xterms = array(); foreach ($xapian_terms as $xapian_term) { $xterms[] = substr($xapian_term['name'], 1); } $dterms = $terms; $missing_terms = array_diff($dterms, $xterms); $deprecated_terms = array_diff($xterms, $dterms); // Save it to search engine. foreach ($missing_terms as $term) { $doc->add_term($prefix . $term, 1); } foreach ($deprecated_terms as $term) { $doc->remove_term($prefix . $term); } $di->getDb()->replace_document($se_ref->getSearchDid(), $doc); $di->getDb()->flush(); } else { //@todo What we should do here? } } return true; }
public function search_engine_edit($exerciseId, $addQs = false, $rmQs = false) { // update search engine and its values table if enabled if (api_get_setting('search.search_enabled') == 'true' && extension_loaded('xapian')) { $em = Database::getManager(); $course = $em->find('ChamiloCoreBundle:Course', api_get_course_int_id()); // get search_did if ($addQs || $rmQs) { //there's only one row per question on normal db and one document per question on search engine db $se_ref = $em->getRepository('ChamiloCoreBundle:SearchEngineRef')->findOneBy(['course' => $course, 'toolId' => TOOL_QUIZ, 'refIdSecondLevel' => $this->id]); } else { $se_ref = $em->getRepository('ChamiloCoreBundle:SearchEngineRef')->findOneBy(['course' => $course, 'toolId' => TOOL_QUIZ, 'refIdHighLevel' => $exerciseId, 'refIdSecondLevel' => $this->id]); } if ($se_ref || $addQs) { require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php'; require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php'; $di = new ChamiloIndexer(); if ($addQs) { $question_exercises = array((int) $exerciseId); } else { $question_exercises = array(); } isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english'); $di->connectDb(NULL, NULL, $lang); // retrieve others exercise ids $se_doc = $di->get_document($se_ref->getSearchDid()); if ($se_doc !== FALSE) { if (($se_doc_data = $di->get_document_data($se_doc)) !== FALSE) { $se_doc_data = unserialize($se_doc_data); if (isset($se_doc_data[SE_DATA]['type']) && $se_doc_data[SE_DATA]['type'] == SE_DOCTYPE_EXERCISE_QUESTION) { if (isset($se_doc_data[SE_DATA]['exercise_ids']) && is_array($se_doc_data[SE_DATA]['exercise_ids'])) { foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) { if (!in_array($old_value, $question_exercises)) { $question_exercises[] = $old_value; } } } } } } if ($rmQs) { while (($key = array_search($exerciseId, $question_exercises)) !== FALSE) { unset($question_exercises[$key]); } } // build the chunk to index $ic_slide = new IndexableChunk(); $ic_slide->addValue("title", $this->question); $ic_slide->addCourseId($course->getCode()); $ic_slide->addToolId(TOOL_QUIZ); $xapian_data = array(SE_COURSE_ID => $course->getCode(), SE_TOOL_ID => TOOL_QUIZ, SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_QUESTION, 'exercise_ids' => $question_exercises, 'question_id' => (int) $this->id), SE_USER => (int) api_get_user_id()); $ic_slide->xapian_data = serialize($xapian_data); $ic_slide->addValue("content", $this->description); //TODO: index answers, see also form validation on question_admin.inc.php $di->remove_document($se_ref->getSearchDid()); $di->addChunk($ic_slide); //index and return search engine document id if (!empty($question_exercises)) { // if empty there is nothing to index $did = $di->index(); unset($di); } if ($did || $rmQs) { // save it to db if ($addQs || $rmQs) { $em->createQuery(' DELETE FROM ChamiloCoreBundle:SearchEngineRef ser WHERE ser.course = ?1 AND ser.toolId = ?2 AND ser.refIdSecondLevel = ?3 ')->execute([1 => $course, 2 => TOOL_QUIZ, 3 => $this->id]); } else { $em->createQuery(' DELETE FROM ChamiloCoreBundle:SearchEngineRef ser WHERE ser.course = ?1 AND ser.toolId = ?2 AND ser.refIdHighLevel = ?3 AND ser.refIdSecondLevel = ?4 ')->execute([1 => $course, 2 => TOOL_QUIZ, 3 => $exerciseId, 4 => $this->id]); } if ($rmQs) { if (!empty($question_exercises)) { $searchEngineRef = new \Chamilo\CoreBundle\Entity\SearchEngineRef(); $searchEngineRef->setCourse($course)->setToolId(TOOL_QUIZ)->setRefIdHighLevel(array_shift($question_exercises))->setRefIdSecondLevel($this->id)->setSearchDid($did); $em->persist($searchEngineRef); $em->flush(); } } else { $searchEngineRef = new \Chamilo\CoreBundle\Entity\SearchEngineRef(); $searchEngineRef->setCourse($course)->setToolId(TOOL_QUIZ)->setRefIdHighLevel($exerciseId)->setRefIdSecondLevel($this->id)->setSearchDid($did); $em->persist($searchEngineRef); $em->flush(); } } } } }