function insert_db($db_name, $folder_name, $text) { // TODO: The (global?) variable $_course has not been declared/initialized. $_course['dbName'] = $db_name; $doc_id = add_document_180($_course, '/' . $folder_name, 'folder', 0, api_ucfirst($text)); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', 1); }
/** * Organize the saving of a link, using the parent's save method and * updating the item_property table * @param array $params * @param boolean $show_query Whether to show the query in logs when * calling parent's save method * * @return bool True if link could be saved, false otherwise */ public function save($params, $show_query = null) { $course_info = api_get_course_info(); $params['session_id'] = api_get_session_id(); $params['category_id'] = isset($params['category_id']) ? $params['category_id'] : 0; $id = parent::save($params, $show_query); if (!empty($id)) { api_item_property_update($course_info, TOOL_LINK, $id, 'LinkAdded', api_get_user_id()); } return $id; }
function check_and_create_resource_directory($repository_path, $resource_directory, $resource_directory_name) { global $permissions_for_new_directories; $resource_directory_full_path = substr($repository_path, 0, strlen($repository_path) - 1) . $resource_directory . '/'; if (!is_dir($resource_directory_full_path)) { if (@mkdir($resource_directory_full_path, $permissions_for_new_directories)) { // While we are in a course: Registering the newly created folder in the course's database. if (api_is_in_course()) { global $_course, $_user; global $group_properties, $to_group_id; $group_directory = !empty($group_properties['directory']) ? $group_properties['directory'] : ''; $doc_id = add_document($_course, $group_directory . $resource_directory, 'folder', 0, $resource_directory_name); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id'], $to_group_id); } return true; } return false; } return true; }
/** * Deletes a question from the database * the parameter tells if the question is removed from all exercises (value = 0), * or just from one exercise (value = exercise ID) * * @author Olivier Brouckaert * @param integer $deleteFromEx - exercise ID if the question is only removed from one exercise */ public function delete($deleteFromEx = 0) { $course_id = api_get_course_int_id(); $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION); $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION); $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER); $TBL_QUIZ_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY); $id = $this->id; if ($this->type == MEDIA_QUESTION) { // Removing media for attached questions $sql = "UPDATE {$TBL_QUESTIONS} SET parent_id = '' WHERE parent_id = {$id}"; Database::query($sql); $sql = "DELETE FROM {$TBL_QUESTIONS} WHERE c_id = {$course_id} AND iid='" . Database::escape_string($id) . "'"; Database::query($sql); return true; } // if the question must be removed from all exercises if (!$deleteFromEx) { //update the question_order of each question to avoid inconsistencies $sql = "SELECT exercice_id, question_order FROM {$TBL_EXERCICE_QUESTION}\n WHERE c_id = {$course_id} AND question_id='" . Database::escape_string($id) . "'"; $res = Database::query($sql); if (Database::num_rows($res) > 0) { while ($row = Database::fetch_array($res)) { if (!empty($row['question_order'])) { $sql = "UPDATE {$TBL_EXERCICE_QUESTION}\n SET question_order = question_order - 1\n WHERE c_id = {$course_id} AND\n exercice_id='" . Database::escape_string($row['exercice_id']) . "' AND\n question_order > " . $row['question_order']; Database::query($sql); } } } $sql = "DELETE FROM {$TBL_EXERCICE_QUESTION} WHERE c_id = {$course_id} AND question_id='" . Database::escape_string($id) . "'"; Database::query($sql); $sql = "DELETE FROM {$TBL_QUESTIONS} WHERE c_id = {$course_id} AND iid='" . Database::escape_string($id) . "'"; Database::query($sql); $sql = "DELETE FROM {$TBL_REPONSES} WHERE question_id='" . Database::escape_string($id) . "'"; Database::query($sql); // remove the category of this question in the question_rel_category table $sql = "DELETE FROM {$TBL_QUIZ_QUESTION_REL_CATEGORY}\n WHERE c_id = {$course_id} AND question_id='" . Database::escape_string($id) . "' AND c_id=" . api_get_course_int_id(); Database::query($sql); api_item_property_update($this->course, TOOL_QUIZ, $id, 'QuizQuestionDeleted', api_get_user_id()); $this->removePicture(); // resets the object $this->Question(); } else { // just removes the exercise from the list $this->removeFromList($deleteFromEx); if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) { // disassociate question with this exercise $this->search_engine_edit($deleteFromEx, false, true); } api_item_property_update($this->course, TOOL_QUIZ, $id, 'QuizQuestionDeleted', api_get_user_id()); } }
/** * 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>'; } } }
/** * Returns the form to update or create a document * * @param string Action (add/edit) * @param integer ID of the lp_item (if already exists) * @param mixed Integer if document ID, string if info ('new') * @return string HTML form */ function display_document_form($action = 'add', $id = 0, $extra_info = 'new') { global $charset, $_course; require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php'; require_once api_get_path(LIBRARY_PATH) . 'document.lib.php'; $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM); $tbl_doc = Database::get_course_table(TABLE_DOCUMENT); $path_parts = pathinfo($extra_info['dir']); $no_display_edit_textarea = false; //If action==edit document //We don't display the document form if it's not an editable document (html or txt file) if ($action == "edit") { if (is_array($extra_info)) { if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") { $no_display_edit_textarea = true; } } } $no_display_add = false; //If action==add an existing document //We don't display the document form if it's not an editable document (html or txt file) if ($action == "add") { if (is_numeric($extra_info)) { $sql_doc = "SELECT path FROM " . $tbl_doc . "WHERE id = " . Database::escape_string($extra_info); $result = Database::query($sql_doc, __FILE__, __LINE__); $path_file = Database::result($result, 0, 0); $path_parts = pathinfo($path_file); if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") { $no_display_add = true; } } } // create css folder $css_name = api_get_setting('stylesheets'); $perm = api_get_setting('permissions_for_new_directories'); $perm = octdec(!empty($perm) ? $perm : '0770'); $css_folder = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document/css'; if (!is_dir($css_folder)) { mkdir($css_folder); chmod($css_folder, $perm); $doc_id = add_document($_course, '/css', 'folder', 0, 'css'); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id']); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id']); } if (!file_exists($css_folder . '/templates.css')) { if (file_exists(api_get_path(SYS_PATH) . 'main/css/' . $css_name . '/templates.css')) { $template_content = str_replace('../../img/', api_get_path(REL_CODE_PATH) . 'img/', file_get_contents(api_get_path(SYS_PATH) . 'main/css/' . $css_name . '/templates.css')); $template_content = str_replace('images/', api_get_path(REL_CODE_PATH) . 'css/' . $css_name . '/images/', $template_content); file_put_contents($css_folder . '/templates.css', $template_content); } } if ($action == 'add' && (isset($_GET['tplid']) && $_GET['tplid'] >= 0)) { $table_sys_template = Database::get_main_table(TABLE_MAIN_SYSTEM_TEMPLATE); $user_id = api_get_user_id(); // Session used by the ajax request when we are using php 5.3 $_SESSION['dbName'] = $_course['dbName']; // setting some paths $img_dir = api_get_path(REL_CODE_PATH) . 'img/'; $default_course_dir = api_get_path(REL_CODE_PATH) . 'default_course_document/'; if (!isset($_GET['resource'])) { // Load a template into a document $query = 'SELECT content, title FROM ' . $table_sys_template . ' WHERE id=' . Database::escape_string(Security::remove_XSS($_GET['tplid'])); $result = Database::query($query, __FILE__, __LINE__); $obj = Database::fetch_object($result); $valcontent = $obj->content; $valtitle = $obj->title != '' ? get_lang($obj->title) : get_lang('Empty'); if (isset($_GET['tplid']) && $_GET['tplid'] == 0) { $valcontent = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body></body>'; } $template_css = ''; if (strpos($valcontent, '/css/templates.css') === false) { $template_css = '<link rel="stylesheet" href="' . api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/document/css/templates.css" type="text/css" />'; } $js = ''; if (strpos($valcontent, 'javascript/jquery.highlight.js') === false) { $js .= '<script type="text/javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'javascript/jquery-1.4.2.min.js" language="javascript"></script>'; $js .= '<script type="text/javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'jwplayer/jwplayer.js" language="javascript"></script>' . PHP_EOL; if (api_get_setting('show_glossary_in_documents') != 'none') { $js .= '<script language="javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'javascript/jquery.highlight.js"></script>'; if (api_get_setting('show_glossary_in_documents') == 'ismanual') { $js .= '<script language="javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'fckeditor/editor/plugins/glossary/fck_glossary_manual.js"></script>'; } else { $js .= '<script language="javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'fckeditor/editor/plugins/glossary/fck_glossary_automatic.js"></script>'; } } } $valcontent = str_replace('{CSS}', $template_css . $js, $valcontent); if (strpos($valcontent, '/css/templates.css') === false) { $valcontent = str_replace('</head>', $template_css . '</head>', $valcontent); } if (strpos($valcontent, 'javascript/jquery.highlight.js') === false) { $valcontent = str_replace('</head>', $js . '</head>', $valcontent); } $valcontent = str_replace('{IMG_DIR}', $img_dir, $valcontent); $valcontent = str_replace('{REL_PATH}', api_get_path(REL_PATH), $valcontent); $valcontent = str_replace('{COURSE_DIR}', $default_course_dir, $valcontent); } elseif (isset($_GET['resource']) && $_GET['resource'] == 'mindmap' || $_GET['resource'] == 'video') { // Load a mindmap or video into a document $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY); $curdirpath = '/mindmaps/'; if ($_GET['resource'] == 'video') { $curdirpath = '/video/'; $curdirpath_flv = '/video/flv/'; } $my_course = api_get_course_id(); $src_path = api_get_path(WEB_COURSE_PATH) . $my_course . '/document'; $sql = "SELECT path,title FROM {$tbl_doc} doc,{$propTable} prop WHERE doc.id = prop.ref AND prop.tool = '" . TOOL_DOCUMENT . "'\n AND doc.filetype = 'file' AND (doc.path LIKE '" . $curdirpath . "%' OR doc.path LIKE '" . $curdirpath_flv . "%') AND (doc.path NOT LIKE '" . $curdirpath . "%/%' OR doc.path NOT LIKE '" . $curdirpath_flv . "%/%')\n AND prop.visibility = 1 AND doc.id = '" . Database::escape_string(Security::remove_XSS($_GET['tplid'])) . "'"; $rs = Database::query($sql); $row = Database::fetch_array($rs); $resource = $src_path . $row['path']; $valtitle = $row['title']; if ($valtitle != '') { $search = array('.png', '.gif', '.jpg', '.mpg', '.flv', '.swf'); // Add other extensions $replace = array('', '', '', '', '', ''); $valtitle = str_replace($search, $replace, $valtitle); } if ($_GET['resource'] == 'mindmap') { $valcontent = '<table cellspacing="2" cellpadding="10" border="0" style="width: 95%; height: 500px;"> <tbody> <tr> <td valign="top"><img border="0" vspace="0" hspace="0" src="' . $resource . '" alt="' . $title . '" title="' . $title . '"/></td> </tr> </tbody> </table>'; } elseif ($_GET['resource'] == 'video') { $sys_resource = api_get_path(SYS_COURSE_PATH) . $my_course . '/document' . $row['path']; $resource_info = pathinfo($sys_resource); //$video_web_path = api_get_path(WEB_LIBRARY_PATH) . 'fckeditor/editor/plugins/flvPlayer/'; $valcontent = '<table cellspacing="2" cellpadding="10" border="0" style="width: 95%; height: 500px;"> <tbody> <tr> <td valign="top"> <!-- Video player plugin --> <div id="player986311-parent" align="left"> <div style="border-style: none; height: 240px; width: 375px; overflow: hidden; background-color: rgb(220, 220, 220);" id="test"> <div style="display: none; visibility: hidden; width: 0px; height: 0px; overflow: hidden;" id="player986311-config">url=' . $resource . ' width=375 height=240 loop=1 play=true downloadable=false fullscreen=true</div> <div class="thePlayer" id="player986311">'; if (in_array($resource_info['extension'], array('flv', 'mp4', 'mov'))) { /*if (!api_is_windows_os()) { $valcontent .= ' <script src="'.api_get_path(WEB_CODE_PATH).'inc/lib/fckeditor/editor/plugins/videoPlayer/jwplayer.min.js" type="text/javascript"></script> <object id="player986311-parent2" name="player986311-parent2" width="375" height="240" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"> <param name="movie" value="'.api_get_path(WEB_CODE_PATH).'inc/lib/fckeditor/editor/plugins/videoPlayer/player.swf" /> <param name="allowFullScreen" value="true" /> <param name="allowscriptaccess" value="always" /> <param name="seamlesstabbing" value="true" /> <param name="wmode" value="transparent" /> <param name="flashvars" value="id=player986311-parent2&autostart=true&repeat=false&file='.$resource.'&skin='.api_get_path(WEB_CODE_PATH).'inc/lib/fckeditor/editor/plugins/videoPlayer/skins/facebook.zip&controlbar.position=over" /> </object> '; } else {*/ $valcontent .= ' <script src="' . api_get_path(WEB_CODE_PATH) . 'inc/lib/fckeditor/editor/plugins/videoPlayer/jwplayer.min.js" type="text/javascript"></script> <div id="player986311-parent2">Loading the player ...</div> <script type="text/javascript">jwplayer("player986311-parent2").setup({flashplayer: "' . api_get_path(WEB_CODE_PATH) . 'inc/lib/fckeditor/editor/plugins/videoPlayer/player.swf",autostart: "true",repeat: "always",file: "' . $resource . '",height: 240,width: 375,skin: "' . api_get_path(WEB_CODE_PATH) . 'inc/lib/fckeditor/editor/plugins/videoPlayer/skins/facebook.zip"});</script>'; //} } else { $sType = ''; if ($resource_info['extension'] == 'mpg' || $resource_info['extension'] == 'mpeg') { $sType = 'video/mpeg'; } else { if ($resource_info['extension'] == 'avi' || $resource_info['extension'] == 'wmv' || $resource_info['extension'] == 'asf') { $sType = 'video/x-msvideo'; } } $valcontent .= '<embed type="' . $sType . '" src="' . $resource . '" autosize = "false" autostart = "true" loop = "false" fullscreen = "true" showcontrols = "true" showpositioncontrols = "false" showtracker = "true" showaudiocontrols = "true" showgotobar = "true" showstatusbar = "true" pluginspace = "http://www.microsoft.com/Windows/MediaPlayer/" codebase = "http://www.microsoft.com/Windows/MediaPlayer/"'; $valcontent .= 'width="375px" height="240px"'; $valcontent .= '></embed>'; } $valcontent .= ' </div> </div> </div> </td> </tr> </tbody> </table>'; } } } if ($id != 0 && is_array($extra_info)) { $item_title = stripslashes($extra_info['title']); $item_description = stripslashes($extra_info['description']); $item_terms = stripslashes($extra_info['terms']); if (empty($item_title)) { $path_parts = pathinfo($extra_info['path']); $item_title = stripslashes($path_parts['filename']); } } elseif (is_numeric($extra_info)) { $sql_doc = "SELECT path, title\n\t\t\t\t\t\t\t\t\tFROM " . $tbl_doc . "\n\t\t\t\t\t\t\t\t\tWHERE id = " . Database::escape_string($extra_info); $result = Database::query($sql_doc, __FILE__, __LINE__); $row = Database::fetch_array($result); $explode = explode('.', $row['title']); if (count($explode) > 1) { for ($i = 0; $i < count($explode) - 1; $i++) { $item_title .= $explode[$i]; } } else { $item_title = $row['title']; } $item_title = str_replace('_', ' ', $item_title); if (empty($item_title)) { $path_parts = pathinfo($row['path']); $item_title = stripslashes($path_parts['filename']); } } else { $item_title = ''; $item_description = ''; } /* $return = ' <div class="row"> <div class="form_header">'; */ if ($id != 0 && is_array($extra_info)) { $parent = $extra_info['parent_item_id']; } else { $parent = 0; } $sql = "\n\t\t\t\t\t\tSELECT *\n\t\t\t\t\t\tFROM " . $tbl_lp_item . "\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tlp_id = " . $this->lp_id; $result = Database::query($sql, __FILE__, __LINE__); $arrLP = array(); while ($row = Database::fetch_array($result)) { $arrLP[] = array('id' => $row['id'], 'item_type' => $row['item_type'], 'title' => $row['title'], 'path' => $row['path'], 'description' => $row['description'], 'parent_item_id' => $row['parent_item_id'], 'previous_item_id' => $row['previous_item_id'], 'next_item_id' => $row['next_item_id'], 'display_order' => $row['display_order'], 'max_score' => $row['max_score'], 'min_score' => $row['min_score'], 'mastery_score' => $row['mastery_score'], 'prerequisite' => $row['prerequisite']); } $this->tree_array($arrLP); $arrLP = $this->arrMenu; unset($this->arrMenu); if (isset($_GET['edit']) && $_GET['edit'] == 'true') { $return .= Display::return_warning_message('<strong>' . get_lang("Warning") . ' !</strong><br />' . get_lang("WarningEditingDocument"), false); } require_once api_get_path(LIBRARY_PATH) . 'formvalidator/FormValidator.class.php'; $form = new FormValidator('form', 'POST', api_get_self() . "?" . $_SERVER["QUERY_STRING"], '', 'enctype="multipart/form-data"'); $defaults["title"] = Security::remove_XSS(api_convert_encoding($item_title, api_get_system_encoding(), $this->encoding)); if (empty($item_title)) { $defaults["title"] = Security::remove_XSS($item_title); } $defaults["description"] = api_convert_encoding($item_description, $charset, $this->encoding); $form->addElement('html', $return); if ($action != 'move') { $form->addElement('html', '<div style="float:left;padding-right:135px;">'); $form->addElement('text', 'title', get_lang('Title'), 'id="idTitle" class="learnpath_item_form" size=44%'); $form->applyFilter('title', 'html_filter'); $form->addElement('html', '</div>'); } //$arrHide = array($id); $arrHide[0]['value'] = $this->name; $arrHide[0]['padding'] = 3; for ($i = 0; $i < count($arrLP); $i++) { if ($action != 'add') { if (($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide) && !in_array($arrLP[$i]['parent_item_id'], $arrHide)) { $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title']; $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10; if ($parent == $arrLP[$i]['id']) { $s_selected_parent = $arrHide[$arrLP[$i]['id']]; } } } else { if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') { $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title']; $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10; if ($parent == $arrLP[$i]['id']) { $s_selected_parent = $arrHide[$arrLP[$i]['id']]; } } } } //$parent_select = & $form->addElement('select', 'parent', get_lang('Parent'), '', 'class="learnpath_item_form" style="width:40%;" onchange="load_cbo(this.value);"'); $parent_select =& $form->addElement('select', 'parent', '', '', 'class="learnpath_item_form" style="width:40%;display:none;float:left" onchange="load_cbo(this.value);"'); $my_count = 0; foreach ($arrHide as $key => $value) { if ($my_count != 0) { // the LP name is also the first section and is not in the same charset like the other sections $value['value'] = Security::remove_XSS(api_convert_encoding($value['value'], api_get_system_encoding(), $this->encoding)); $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"'); } else { $value['value'] = Security::remove_XSS($value['value']); $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"'); } $my_count++; } if (!empty($id)) { $parent_select->setSelected($parent); } else { $parent_item_id = $_SESSION['parent_item_id']; $parent_select->setSelected($parent_item_id); } if (is_array($arrLP)) { reset($arrLP); } $arrHide = array(); //POSITION for ($i = 0; $i < count($arrLP); $i++) { if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) { if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) { $s_selected_position = $arrLP[$i]['id']; } elseif ($action == 'add') { $s_selected_position = $arrLP[$i]['id']; } $arrHide[$arrLP[$i]['id']]['value'] = get_lang("After") . ' "' . api_convert_encoding($arrLP[$i]['title'], $charset, $this->encoding) . '"'; } } //$position = & $form->addElement('select', 'previous', get_lang('Position'), '', 'id="idPosition" class="learnpath_item_form" style="width:40%;"'); $position =& $form->addElement('select', 'previous', '', '', 'id="idPosition" class="learnpath_item_form" style="width:40%;float:left;display:none;"'); $position->addOption(get_lang("FirstPosition"), 0); foreach ($arrHide as $key => $value) { $position->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"'); } $position->setSelected($s_selected_position); if (is_array($arrLP)) { reset($arrLP); } if ($action != 'move') { $id_prerequisite = 0; if (is_array($arrLP)) { foreach ($arrLP as $key => $value) { if ($value['id'] == $id) { $id_prerequisite = $value['prerequisite']; break; } } } //comented the prerequisites, only visible in edit (new document) //$select_prerequisites=$form->addElement('select', 'prerequisites', get_lang('Prerequisites'),null,'id="prerequisites" class="learnpath_item_form" style="width:263px;"'); //$select_prerequisites->addOption(get_lang("NoPrerequisites"),0); // form element for uploading an mp3 file //$form->addElement('file','mp3',get_lang('UploadMp3audio'),'id="mp3" size="33"'); //$form->addRule('file', 'The extension of the Song file should be *.mp3', 'filename', '/^.*\.mp3$/'); /* Code deprecated - moved to lp level (not lp-item) if ( api_get_setting('search_enabled') === 'true' ) { //add terms field $terms = $form->addElement('text','terms', get_lang('SearchFeatureTerms').' :','id="idTerms" class="learnpath_item_form"'); $terms->setValue($item_terms); } */ $arrHide = array(); for ($i = 0; $i < count($arrLP); $i++) { if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') { if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) { $s_selected_position = $arrLP[$i]['id']; } elseif ($action == 'add') { $s_selected_position = $arrLP[$i]['id']; } $arrHide[$arrLP[$i]['id']]['value'] = api_convert_encoding($arrLP[$i]['title'], $charset, $this->encoding); } } /* foreach($arrHide as $key => $value){ $select_prerequisites->addOption($value['value'],$key,'style="padding-left:'.$value['padding'].'px;"'); if($key==$s_selected_position && $action == 'add'){ $select_prerequisites -> setSelected(0); } elseif($key==$id_prerequisite && $action == 'edit'){ $select_prerequisites -> setSelected($id_prerequisite); } } */ if (!$no_display_add) { if ($extra_info == 'new' || $extra_info['item_type'] == TOOL_DOCUMENT || $_GET['edit'] == 'true') { if (isset($_POST['content'])) { $content = stripslashes($_POST['content']); } elseif (is_array($extra_info)) { //If it's an html document or a text file if (!$no_display_edit_textarea) { $content = $this->display_document($extra_info['path'], false, false); } } elseif (is_numeric($extra_info)) { $content = $this->display_document($extra_info, false, false); } else { $content = ''; } if (!$no_display_edit_textarea) { // We need to claculate here some specific settings for the online editor. // The calculated settings work for documents in the Documents tool // (on the root or in subfolders). // For documents in native scorm packages it is unclear whether the // online editor should be activated or not. $relative_path = $extra_info['dir']; if ($relative_path == 'n/') { // A new document, it is in the root of the repository. $relative_path = ''; $relative_prefix = ''; } else { // The document already exists. Whe have to determine its relative path towards the repository root. $relative_path = explode('/', $relative_path); $cnt = count($relative_path) - 2; if ($cnt < 0) { $cnt = 0; } $relative_prefix = str_repeat('../', $cnt); $relative_path = array_slice($relative_path, 1, $cnt); $relative_path = implode('/', $relative_path); if (strlen($relative_path) > 0) { $relative_path = $relative_path . '/'; } } $editor_config = array('ToolbarSet' => api_is_allowed_to_edit() ? 'Documents' : 'DocumentsStudent', 'Width' => '100%', 'Height' => '700', 'FullPage' => true, 'CreateDocumentDir' => $relative_prefix, 'CreateDocumentWebDir' => api_get_path('WEB_COURSE_PATH') . api_get_course_path() . '/document/', 'BaseHref' => api_get_path('WEB_COURSE_PATH') . api_get_course_path() . '/document/' . $relative_path); if ($_GET['action'] == 'add_item') { $class = 'save'; $text = get_lang('Validate'); } else { if ($_GET['action'] == 'edit_item') { $class = 'save'; $text = get_lang('SaveDocument'); } } $form->addElement('html', '<div style="float:right;margin-top:-55px">'); $form->addElement('style_submit_button', 'submit_button', $text, 'class="' . $class . '"'); $form->addElement('html', '</div>'); $renderer = $form->defaultRenderer(); $renderer->setElementTemplate('{label}{element}', 'content_lp'); //$form->addElement('html', '<div'); $form->addElement('html_editor', 'content_lp', '', null, $editor_config); //$form->addElement('html', '</div>'); $defaults["content_lp"] = $content; } } elseif (is_numeric($extra_info)) { $form->addElement('style_submit_button', 'submit_button', get_lang('SaveDocument'), 'class="save"'); $return = $this->display_document($extra_info, true, true, true); $form->addElement('html', $return); } } } // Add template to content if ($action == 'add' && (isset($_GET['tplid']) && $_GET['tplid'] >= 0)) { $defaults["content_lp"] = $valcontent; $defaults["title"] = $valtitle; } if ($action == 'move') { $form->addElement('hidden', 'title', $item_title); $form->addElement('hidden', 'description', $item_description); } if (is_numeric($extra_info)) { $form->addElement('style_submit_button', 'submit_button', get_lang('SaveDocument'), 'value="submit_button", class="save" style="float:right"'); $form->addElement('hidden', 'path', $extra_info); } elseif (is_array($extra_info)) { $form->addElement('html', '<div style="float:right;margin-top:-55px">'); $form->addElement('style_submit_button', 'submit_button', get_lang('SaveDocument'), 'class="save"'); $form->addElement('hidden', 'path', $extra_info['path']); $form->addElement('html', '</div>'); } $form->addElement('hidden', 'type', TOOL_DOCUMENT); $form->addElement('hidden', 'post_time', time()); $form->setDefaults($defaults); return $form->return_form(); }
$doc_id = add_document($_course, $dir . 'css', 'folder', 0, 'css'); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $userId, null, null, null, null, $current_session_id); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $userId, null, null, null, null, $current_session_id); } if (!is_file($filepath . 'css/frames.css')) { // Make a copy of the current css for the new document copy(api_get_path(SYS_CODE_PATH) . 'css/' . api_get_setting('stylesheets') . '/frames.css', $filepath . 'css/frames.css'); $doc_id = add_document($_course, $dir . 'css/frames.css', 'file', filesize($filepath . 'css/frames.css'), 'frames.css'); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $userId, null, null, null, null, $current_session_id); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $userId, null, null, null, null, $current_session_id); } $file_size = filesize($filepath . $filename . '.' . $extension); $save_file_path = $dir . $filename . '.' . $extension; $document_id = add_document($_course, $save_file_path, 'file', $file_size, $title, null, $readonly); if ($document_id) { api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $userId, $to_group_id, null, null, null, $current_session_id); // Update parent folders item_property_update_on_folder($_course, $dir, $userId); $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : ''; $new_comment = Database::escape_string($new_comment); $new_title = isset($_POST['title']) ? trim($_POST['title']) : ''; $new_title = htmlspecialchars($new_title); $new_title = Database::escape_string($new_title); if ($new_comment || $new_title) { $ct = ''; if ($new_comment) { $ct .= ", comment='{$new_comment}'"; } if ($new_title) { $ct .= ", title='{$new_title}'"; }
$id = Database::insert_id(); api_item_property_update($course_info, 'work', $id, 'DocumentAdded', $user_id); $result_message[$TBL_STUDENT_PUBLICATION]++; $full_file_name = $course_dir . '/' . $doc_url; $new_file = $course_dir . '/' . $new_url; if (file_exists($full_file_name)) { //deleting old assignment $result = copy($full_file_name, $new_file); if ($result) { unlink($full_file_name); $sql = "DELETE FROM {$TBL_STUDENT_PUBLICATION} WHERE id= " . $data['id']; if ($debug) { var_dump($sql); } $result_delete = Database::query($sql); api_item_property_update($course_info, 'work', $data['id'], 'DocumentDeleted', api_get_user_id()); } } } } } } //9. Survey Pending //10. Dropbox - not neccesary to move categories (no presence of session_id) $sql = "SELECT id FROM {$TBL_DROPBOX_FILE} WHERE uploader_id = {$user_id} AND session_id = {$origin_session_id} AND c_id = {$course_id}"; if ($debug) { var_dump($sql); } $res = Database::query($sql); while ($row = Database::fetch_array($res, 'ASSOC')) { $id = $row['id'];
/** * Modify category name or description of category with id=in_id */ public function modifyCategory() { $table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY); $v_id = intval($this->id); $v_name = Database::escape_string($this->name); $v_description = Database::escape_string($this->description); $sql = "UPDATE {$table} SET\n title = '{$v_name}',\n description = '{$v_description}'\n WHERE id = {$v_id} AND c_id=" . api_get_course_int_id(); $result = Database::query($sql); if (Database::affected_rows($result) <= 0) { return false; } else { // item_property update $course_id = api_get_course_int_id(); $course_info = api_get_course_info_by_id($course_id); api_item_property_update($course_info, TOOL_TEST_CATEGORY, $this->id, 'TestCategoryModified', api_get_user_id()); return true; } }
/** * deletes the exercise from the database * Notice : leaves the question in the data base * * @author Olivier Brouckaert */ public function delete() { $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST); $sql = "UPDATE {$TBL_EXERCISES} SET active='-1'\n WHERE c_id = " . $this->course_id . " AND id = " . intval($this->id) . ""; Database::query($sql); api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizDeleted', api_get_user_id()); api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'delete', api_get_user_id()); if (api_get_setting('search.search_enabled') == 'true' && extension_loaded('xapian')) { $this->search_engine_delete(); } }
/** * 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); } } } } }
/** * This function delete a attachment file by id * @param int $attachmentId * @param array $courseInfo * @return string */ public function deleteAttachmentFile($attachmentId, $courseInfo) { $agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT); $attachmentId = intval($attachmentId); $courseId = $courseInfo['real_id']; if (empty($courseId) || empty($attachmentId)) { return false; } $sql = "DELETE FROM {$agenda_table_attachment}\n WHERE c_id = {$courseId} AND id = " . $attachmentId; $result = Database::query($sql); // update item_property api_item_property_update($courseInfo, 'calendar_event_attachment', $attachmentId, 'AgendaAttachmentDeleted', api_get_user_id()); if (!empty($result)) { return Display::return_message(get_lang("AttachmentFileDeleteSuccess"), 'confirmation'); } }
/** * This function saves a question in the database. * This can be either an update of an existing survey or storing a new survey * @param array $survey_data * @param array $form_content all the information of the form * * @author Patrick Cool <*****@*****.**>, Ghent University * @version January 2007 */ public static function save_question($survey_data, $form_content) { $return_message = ''; if (strlen($form_content['question']) > 1) { // Checks length of the question $empty_answer = false; if ($survey_data['survey_type'] == 1) { if (empty($form_content['choose'])) { $return_message = 'PleaseChooseACondition'; return $return_message; } if ($form_content['choose'] == 2 && $form_content['assigned1'] == $form_content['assigned2']) { $return_message = 'ChooseDifferentCategories'; return $return_message; } } if ($form_content['type'] != 'percentage') { if (isset($form_content['answers'])) { for ($i = 0; $i < count($form_content['answers']); $i++) { if (strlen($form_content['answers'][$i]) < 1) { $empty_answer = true; break; } } } } if ($form_content['type'] == 'score') { if (strlen($form_content['maximum_score']) < 1) { $empty_answer = true; } } $additional = array(); $course_id = api_get_course_int_id(); if (!$empty_answer) { // Table definitions $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION); // Getting all the information of the survey $survey_data = SurveyManager::get_survey($form_content['survey_id']); // Storing the question in the shared database if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) { $shared_question_id = SurveyManager::save_shared_question($form_content, $survey_data); $form_content['shared_question_id'] = $shared_question_id; } // Storing a new question if ($form_content['question_id'] == '' || !is_numeric($form_content['question_id'])) { // Finding the max sort order of the questions in the given survey $sql = "SELECT max(sort) AS max_sort\n\t\t\t\t\t FROM {$tbl_survey_question}\n WHERE c_id = {$course_id} AND survey_id='" . intval($form_content['survey_id']) . "'"; $result = Database::query($sql); $row = Database::fetch_array($result, 'ASSOC'); $max_sort = $row['max_sort']; // Some variables defined for survey-test type $extraParams = []; if (isset($_POST['choose'])) { if ($_POST['choose'] == 1) { $extraParams['survey_group_pri'] = $_POST['assigned']; } elseif ($_POST['choose'] == 2) { $extraParams['survey_group_sec1'] = $_POST['assigned1']; $extraParams['survey_group_sec2'] = $_POST['assigned2']; } } $questionComment = isset($form_content['question_comment']) ? $form_content['question_comment'] : ''; $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : ''; $display = isset($form_content['horizontalvertical']) ? $form_content['horizontalvertical'] : ''; $params = ['c_id' => $course_id, 'survey_id' => $form_content['survey_id'], 'survey_question' => $form_content['question'], 'survey_question_comment' => $questionComment, 'type' => $form_content['type'], 'display' => $display, 'sort' => $max_sort + 1, 'shared_question_id' => $form_content['shared_question_id'], 'max_value' => $maxScore]; $params = array_merge($params, $extraParams); $question_id = Database::insert($tbl_survey_question, $params); if ($question_id) { $sql = "UPDATE {$tbl_survey_question} SET question_id = {$question_id}\n WHERE iid = {$question_id}"; Database::query($sql); $form_content['question_id'] = $question_id; $return_message = 'QuestionAdded'; } } else { // Updating an existing question $extraParams = []; if (isset($_POST['choose'])) { if ($_POST['choose'] == 1) { $extraParams['survey_group_pri'] = $_POST['assigned']; $extraParams['survey_group_sec1'] = 0; $extraParams['survey_group_sec2'] = 0; } elseif ($_POST['choose'] == 2) { $extraParams['survey_group_pri'] = 0; $extraParams['survey_group_sec1'] = $_POST['assigned1']; $extraParams['survey_group_sec2'] = $_POST['assigned2']; } } $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : null; $questionComment = isset($form_content['question_comment']) ? $form_content['question_comment'] : null; // Adding the question to the survey_question table $params = ['survey_question' => $form_content['question'], 'survey_question_comment' => $questionComment, 'display' => $form_content['horizontalvertical']]; $params = array_merge($params, $extraParams); Database::update($tbl_survey_question, $params, ['c_id = ? AND question_id = ?' => [$course_id, $form_content['question_id']]]); $return_message = 'QuestionUpdated'; } if (!empty($form_content['survey_id'])) { //Updating survey api_item_property_update(api_get_course_info(), TOOL_SURVEY, $form_content['survey_id'], 'SurveyUpdated', api_get_user_id()); } // Storing the options of the question SurveyManager::save_question_options($form_content, $survey_data); } else { $return_message = 'PleasFillAllAnswer'; } } else { $return_message = 'PleaseEnterAQuestion'; } if (!empty($return_message)) { Display::addFlash(Display::return_message(get_lang($return_message))); } return $return_message; }
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id(), null, null, null, null, $current_session_id); } if (!is_file($filepath . 'css/frames.css')) { $platform_theme = api_get_setting('stylesheets'); if (file_exists(api_get_path(SYS_CSS_PATH) . 'themes/' . $platform_theme . '/frames.css')) { copy(api_get_path(SYS_CSS_PATH) . 'themes/' . $platform_theme . '/frames.css', $filepath . 'css/frames.css'); $doc_id = FileManager::add_document($_course, $dir . 'css/frames.css', 'file', filesize($filepath . 'css/frames.css'), 'frames.css'); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(), null, null, null, null, $current_session_id); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id(), null, null, null, null, $current_session_id); } } // "WHAT'S NEW" notification: update table item_property $document_id = DocumentManager::get_document_id($_course, $file); if ($document_id) { FileManager::update_existing_document($_course, $document_id, $file_size, $read_only_flag); api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', api_get_user_id(), null, null, null, null, $current_session_id); // Update parent folders FileManager::item_property_update_on_folder($_course, $dir, api_get_user_id()); header('Location: document.php?id=' . $document_data['parent_id']); exit; } else { $msgError = get_lang('Impossible'); } } else { $msgError = get_lang('Impossible'); } } else { if ($document_id) { FileManager::update_existing_document($_course, $document_id, $file_size, $read_only_flag); } }
/** * Import the aicc object (as a result from the parse_config_files function) into the database structure * @param string Unique course code * @return bool Returns -1 on error */ function import_aicc($course_code) { $course_id = api_get_course_int_id(); if ($this->debug > 0) { error_log('New LP - In aicc::import_aicc('.$course_code.')', 0); } // Get table names. $new_lp = 'lp'; $new_lp_item = 'lp_item'; // The previous method wasn't safe to get the database name, so do it manually with the course_code. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." WHERE code='$course_code'"; $res = Database::query($sql); if (Database::num_rows($res) < 1) { error_log('New LP - Database for '.$course_code.' not found '.__FILE__.' '.__LINE__, 0); return -1; } $row = Database::fetch_array($res); $new_lp = Database::get_course_table(TABLE_LP_MAIN); $new_lp_item = Database::get_course_table(TABLE_LP_ITEM); $get_max = "SELECT MAX(display_order) FROM $new_lp WHERE c_id = $course_id"; $res_max = Database::query($get_max); if (Database::num_rows($res_max) < 1) { $dsp = 1; } else { $row = Database::fetch_array($res_max); $dsp = $row[0] + 1; } $this->config_encoding = "ISO-8859-1"; // TODO: We may apply detection for this value, see the function api_detect_encoding(). $sql = "INSERT INTO $new_lp (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib, content_maker,display_order)" . "VALUES " . "($course_id, 3, '".$this->course_title."', '".$this->course_id."','".$this->course_description."'," . "'".$this->subdir."', 0, 'embedded', '".$this->config_encoding."'," . "'aicc_api.php','".$this->course_creator."',$dsp)"; if ($this->debug > 2) { error_log('New LP - In import_aicc(), inserting path: '. $sql, 0); } $res = Database::query($sql); $lp_id = Database::insert_id(); $this->lp_id = $lp_id; 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()); $previous = 0; foreach ($this->aulist as $identifier => $dummy) { $oAu =& $this->aulist[$identifier]; //echo "Item ".$oAu->identifier; $field_add = ''; $value_add = ''; if (!empty($oAu->masteryscore)) { $field_add = 'mastery_score, '; $value_add = $oAu->masteryscore.','; } $title = $oAu->identifier; if (is_object($this->deslist[$identifier])) { $title = $this->deslist[$identifier]->title; } $path = $oAu->path; //$max_score = $oAu->max_score // TODO: Check if special constraint exists for this item. //$min_score = $oAu->min_score // TODO: Check if special constraint exists for this item. $parent = 0; // TODO: Deal with the parent. $previous = 0; $prereq = $oAu->prereq_string; //$previous = (!empty($this->au_order_list_new_id[x]) ? $this->au_order_list_new_id[x] : 0); // TODO: Deal with the previous. $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) " . "VALUES " . "($course_id, $lp_id, 'au','".$oAu->identifier."','".$title."'," . "'$path',0,100, $value_add" . "$parent, $previous, 0, " . "'$prereq', 0" . ")"; $res_item = Database::query($sql_item); if ($this->debug > 1) { error_log('New LP - In aicc::import_aicc() - inserting item : '.$sql_item.' : '.Database::error(), 0); } $item_id = Database::insert_id(); // Now update previous item to change next_item_id. if ($previous != 0) { $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 the previous item id. } $previous = $item_id; } }
/** * Changes visibility * @param int|array $attendanceId one or many attendances id * @param int status * * @return int affected rows */ public function changeVisibility($attendanceId, $status = 1) { $_course = api_get_course_info(); $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE); $user_id = api_get_user_id(); $course_id = $_course['real_id']; $status = intval($status); $action = 'visible'; if ($status == 0) { $action = 'invisible'; } if (is_array($attendanceId)) { foreach ($attendanceId as $id) { $id = intval($id); $sql = "UPDATE {$tbl_attendance} SET active = {$status}\n\t\t\t\t\t\tWHERE c_id = {$course_id} AND id = '{$id}'"; $result = Database::query($sql); $affected_rows = Database::affected_rows($result); if (!empty($affected_rows)) { // update row item property table api_item_property_update($_course, TOOL_ATTENDANCE, $id, $action, $user_id); } } } else { $attendanceId = intval($attendanceId); $sql = "UPDATE {$tbl_attendance} SET active = {$status}\n\t\t\t\t\tWHERE c_id = {$course_id} AND id = '{$attendanceId}'"; $result = Database::query($sql); $affected_rows = Database::affected_rows($result); if (!empty($affected_rows)) { // update row item property table api_item_property_update($_course, TOOL_ATTENDANCE, $attendanceId, $action, $user_id); } } return $affected_rows; }
/** * CSV file import functions * @author René Haentjens , Ghent University */ public static function put_link($url, $cat, $title, $description, $on_homepage, $hidden) { $tbl_link = Database::get_course_table(TABLE_LINK); $course_id = api_get_course_int_id(); $urleq = "url='" . Database::escape_string($url) . "'"; $cateq = "category_id=" . intval($cat); $result = Database::query("SELECT id FROM {$tbl_link}\n WHERE c_id = {$course_id} AND " . $urleq . ' AND ' . $cateq); if (Database::num_rows($result) >= 1 && ($row = Database::fetch_array($result))) { Database::query("UPDATE {$tbl_link} set title='" . Database::escape_string($title) . "', description='" . Database::escape_string($description) . "'\n WHERE c_id = {$course_id} AND id='" . Database::escape_string($row['id']) . "'"); $ipu = 'LinkUpdated'; $rv = 1; // 1 = upd } else { // Add new link $result = Database::query("SELECT MAX(display_order) FROM {$tbl_link}\n WHERE c_id = {$course_id} AND category_id='" . intval($cat) . "'"); list($max_order) = Database::fetch_row($result); Database::query("INSERT INTO {$tbl_link} (c_id, url, title, description, category_id, display_order, on_homepage)\n VALUES (" . api_get_course_int_id() . ",\n '" . Database::escape_string($url) . "',\n '" . Database::escape_string($title) . "',\n '" . Database::escape_string($description) . "',\n '" . intval($cat) . "','" . (intval($max_order) + 1) . "',\n '" . intval($on_homepage) . "')"); $id = Database::insert_id(); $ipu = 'LinkAdded'; $rv = 2; // 2 = new } global $_course, $nameTools, $_user; api_item_property_update($_course, TOOL_LINK, $id, $ipu, $_user['user_id']); if ($hidden && $ipu == 'LinkAdded') { api_item_property_update($_course, TOOL_LINK, $id, 'invisible', $_user['user_id']); } return $rv; }
/** * Create a new document //still needs some finetuning * @param array $_course * @return string */ public function create_document($_course) { $course_id = api_get_course_int_id(); global $charset; $dir = isset($_GET['dir']) ? $_GET['dir'] : $_POST['dir']; // Please, do not modify this dirname formatting. if (strstr($dir, '..')) { $dir = '/'; } if ($dir[0] == '.') { $dir = substr($dir, 1); } if ($dir[0] != '/') { $dir = '/' . $dir; } if ($dir[strlen($dir) - 1] != '/') { $dir .= '/'; } $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document' . $dir; if (empty($_POST['dir']) && empty($_GET['dir'])) { //Generates folder $result = $this->generate_lp_folder($_course); $dir = $result['dir']; $filepath = $result['filepath']; } if (!is_dir($filepath)) { $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document/'; $dir = '/'; } // stripslashes() before calling api_replace_dangerous_char() because $_POST['title'] // is already escaped twice when it gets here. $title = api_replace_dangerous_char(stripslashes($_POST['title'])); $title = FileManager::disable_dangerous_file($title); $filename = $title; $content = $_POST['content_lp']; $tmp_filename = $filename; $i = 0; while (file_exists($filepath . $tmp_filename . '.html')) { $tmp_filename = $filename . '_' . ++$i; } $filename = $tmp_filename . '.html'; $content = stripslashes($content); $content = str_replace(api_get_path(WEB_COURSE_PATH), api_get_path(REL_PATH) . 'courses/', $content); // Change the path of mp3 to absolute. // The first regexp deals with ../../../ urls. $content = preg_replace("|(flashvars=\"file=)(\\.+/)+|", "\$1" . api_get_path(REL_COURSE_PATH) . $_course['path'] . '/document/', $content); // The second regexp deals with audio/ urls. $content = preg_replace("|(flashvars=\"file=)([^/]+)/|", "\$1" . api_get_path(REL_COURSE_PATH) . $_course['path'] . '/document/$2/', $content); // For flv player: To prevent edition problem with firefox, we have to use a strange tip (don't blame me please). $content = str_replace('</body>', '<style type="text/css">body{}</style></body>', $content); if (!file_exists($filepath . $filename)) { if ($fp = @fopen($filepath . $filename, 'w')) { fputs($fp, $content); fclose($fp); $file_size = filesize($filepath . $filename); $save_file_path = $dir . $filename; $document_id = FileManager::add_document($_course, $save_file_path, 'file', $file_size, $tmp_filename); if ($document_id) { api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id(), null, null, null, null, api_get_session_id()); $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : ''; $new_title = isset($_POST['title']) ? trim($_POST['title']) : ''; if ($new_comment || $new_title) { $tbl_doc = Database::get_course_table(TABLE_DOCUMENT); $ct = ''; if ($new_comment) { $ct .= ", comment='" . Database::escape_string($new_comment) . "'"; } if ($new_title) { $ct .= ", title='" . Database::escape_string(htmlspecialchars($new_title, ENT_QUOTES, $charset)) . "' "; } $sql_update = "UPDATE " . $tbl_doc . " SET " . substr($ct, 1) . " WHERE c_id = " . $course_id . " AND id = " . $document_id; Database::query($sql_update); } } return $document_id; } } }
/** * Import PDFs * @param string Filename * @param string The subdirectory in which to put the files in each course */ function import_pdfs($file, $subDir = '/') { $baseDir = api_get_path(SYS_ARCHIVE_PATH); $uploadPath = 'pdfimport/'; $errors = array(); if (!is_dir($baseDir . $uploadPath)) { @mkdir($baseDir . $uploadPath); } if (!unzip_uploaded_file($_FILES['import_file'], $uploadPath, $baseDir, 1024 * 1024 * 1024)) { error_log('Could not unzip uploaded file in ' . __FILE__ . ', line ' . __LINE__); return $errors; } $list = scandir($baseDir . $uploadPath); $i = 0; foreach ($list as $file) { if (substr($file, 0, 1) == '.' or !is_file($baseDir . $uploadPath . $file)) { continue; } $parts = preg_split('/_/', $file); $course = api_get_course_info($parts[0]); if (count($course) > 0) { // Build file info because handle_uploaded_document() needs it (name, type, size, tmp_name) $fileSize = filesize($baseDir . $uploadPath . $file); $docId = add_document($course, $subDir . '/' . $file, 'file', $fileSize, $parts[1] . ' ' . substr($parts[2], 0, -4)); if ($docId > 0) { if (!is_file($baseDir . $uploadPath . $file)) { error_log($baseDir . $uploadPath . $file . ' does not exists in ' . __FILE__); } if (is_file(api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document' . $subDir . '/' . $file)) { error_log(api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document' . $subDir . '/' . $file . ' exists at destination in ' . __FILE__); } if (!is_writeable(api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document' . $subDir)) { error_log('Destination ' . api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document' . $subDir . ' is NOT writeable in ' . __FILE__); } // Place each file in its folder in each course $move = rename($baseDir . $uploadPath . $file, api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document' . $subDir . '/' . $file); api_item_property_update($course, TOOL_DOCUMENT, $docId, 'DocumentAdded', api_get_user_id()); // Redo visibility api_set_default_visibility($docId, TOOL_DOCUMENT); $errors[] = array('Line' => 0, 'Code' => $course['code'], 'Title' => $course['title']); // Now add a link to the file from the Course description tool $link = '<p>Sílabo de la asignatura <a href="' . api_get_path(WEB_CODE_PATH) . 'document/document.php?cidReq=' . $course['code'] . '&id_session=0&gidReq=0&action=download&id=' . $docId . '" target="_blank"><img src="' . api_get_path(WEB_IMG_PATH) . 'icons/32/pdf.png"></a></p>'; $course_description = new CourseDescription(); $session_id = api_get_session_id(); $course_description->set_course_id($course['real_id']); $course_description->set_session_id($session_id); $course_description->set_title('Presentación de la asignatura'); $course_description->set_content($link); $course_description->set_description_type(1); $course_description->insert(); } } else { error_log($parts[0] . ' is not a course, apparently'); $errors[] = array('Line' => 0, 'Code' => $parts[0], 'Title' => $parts[0] . ' - ' . get_lang('CodeDoesNotExists')); } $i++; //found at least one entry that is not a dir or a . } if ($i == 0) { $errors[] = array('Line' => 0, 'Code' => '.', 'Title' => get_lang('NoPDFFoundAtRoot')); } return $errors; }
/** * Generate a default certificate for a courses * * @global string $css CSS directory * @global string $img_dir image directory * @global string $default_course_dir Course directory * @global string $js JS directory * @param array $courseData The course info * @param bool $fromBaseCourse * @param int $sessionId */ public static function generateDefaultCertificate($courseData, $fromBaseCourse = false, $sessionId = 0) { global $css, $img_dir, $default_course_dir, $js; $codePath = api_get_path(REL_CODE_PATH); $dir = '/certificates'; $title = get_lang('DefaultCertificate'); $comment = null; $fileName = api_replace_dangerous_char($title); $filePath = api_get_path(SYS_COURSE_PATH) . "{$courseData['path']}/document{$dir}"; $fileFullPath = "{$filePath}/{$fileName}.html"; $fileSize = 0; $fileType = 'file'; $templateContent = file_get_contents(api_get_path(SYS_CODE_PATH) . 'gradebook/certificate_template/template.html'); $search = array('{CSS}', '{IMG_DIR}', '{REL_CODE_PATH}', '{COURSE_DIR}'); $replace = array($css . $js, $img_dir, $codePath, $default_course_dir); $fileContent = str_replace($search, $replace, $templateContent); $saveFilePath = "{$dir}/{$fileName}.html"; if (!is_dir($filePath)) { mkdir($filePath, api_get_permissions_for_new_directories()); } if ($fromBaseCourse) { $defaultCertificateId = self::get_default_certificate_id($courseData['code'], 0); if (!empty($defaultCertificateId)) { // We have a certificate from the course base $documentData = DocumentManager::get_document_data_by_id($defaultCertificateId, $courseData['code'], false, 0); if ($documentData) { $fileContent = file_get_contents($documentData['absolute_path']); } } } $defaultCertificateFile = $fp = @fopen($fileFullPath, 'w'); if ($defaultCertificateFile != false) { @fputs($defaultCertificateFile, $fileContent); fclose($defaultCertificateFile); chmod($fileFullPath, api_get_permissions_for_new_files()); $fileSize = filesize($fileFullPath); } $documentId = add_document($courseData, $saveFilePath, $fileType, $fileSize, $title, $comment, 0, true, null, $sessionId); api_item_property_update($courseData, TOOL_DOCUMENT, $documentId, 'DocumentAdded', api_get_user_id(), null, null, null, null, $sessionId); $defaultCertificateId = self::get_default_certificate_id($courseData['code'], $sessionId); if (!isset($defaultCertificateId)) { self::attach_gradebook_certificate($courseData['code'], $documentId, $sessionId); } }
/** * 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); } } } } }
/** * Import the aicc object (as a result from the parse_config_files function) into the database structure * @param string Unique course code * @return bool Returns -1 on error */ function import_aicc($course_code) { if ($this->debug > 0) { error_log('New LP - In aicc::import_aicc(' . $course_code . ')', 0); } //get table names $new_lp = 'lp'; $new_lp_item = 'lp_item'; //The previous method wasn't safe to get the database name, so do it manually with the course_code $sql = "SELECT * FROM " . Database::get_main_table(TABLE_MAIN_COURSE) . " WHERE code='{$course_code}'"; $res = Database::query($sql, __FILE__, __LINE__); if (Database::num_rows($res) < 1) { error_log('New LP - Database for ' . $course_code . ' not found ' . __FILE__ . ' ' . __LINE__, 0); return -1; } $row = Database::fetch_array($res); $dbname = Database::get_course_table_prefix() . $row['db_name'] . Database::get_database_glue(); $new_lp = Database::get_course_table(TABLE_LP_MAIN); $new_lp_item = Database::get_course_table(TABLE_LP_ITEM); $get_max = "SELECT MAX(display_order) FROM {$new_lp}"; $res_max = Database::query($get_max); if (Database::num_rows($res_max) < 1) { $dsp = 1; } else { $row = Database::fetch_array($res_max); $dsp = $row[0] + 1; } $this->config_encoding = "ISO-8859-1"; $sql = "INSERT INTO {$new_lp} " . "(lp_type, name, ref, description, " . "path, force_commit, default_view_mod, default_encoding, " . "js_lib, content_maker,display_order)" . "VALUES " . "(3,'" . $this->course_title . "', '" . $this->course_id . "','" . $this->course_description . "'," . "'" . $this->subdir . "', 0, 'embedded', '" . $this->config_encoding . "'," . "'aicc_api.php','" . $this->course_creator . "',{$dsp})"; if ($this->debug > 2) { error_log('New LP - In import_aicc(), inserting path: ' . $sql, 0); } $res = Database::query($sql); $lp_id = Database::insert_id(); $this->lp_id = $lp_id; 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()); $previous = 0; foreach ($this->aulist as $identifier => $dummy) { $oAu =& $this->aulist[$identifier]; //echo "Item ".$oAu->identifier; $field_add = ''; $value_add = ''; if (!empty($oAu->masteryscore)) { $field_add = 'mastery_score, '; $value_add = $oAu->masteryscore . ','; } $title = $oAu->identifier; if (is_object($this->deslist[$identifier])) { $title = $this->deslist[$identifier]->title; } $path = $oAu->path; //$max_score = $oAu->max_score //TODO check if special constraint exists for this item //$min_score = $oAu->min_score //TODO check if special constraint exists for this item $parent = 0; //TODO deal with parent $previous = 0; $prereq = $oAu->prereq_string; $parameters = $oAu->parameters; //$previous = (!empty($this->au_order_list_new_id[x])?$this->au_order_list_new_id[x]:0); //TODO deal with previous $sql_item = "INSERT INTO {$new_lp_item} " . "(lp_id,item_type,ref,title," . "path,parameters, min_score,max_score, {$field_add}" . "parent_item_id,previous_item_id,next_item_id," . "prerequisite,display_order) " . "VALUES " . "({$lp_id}, 'au','" . $oAu->identifier . "','" . $title . "'," . "'{$path}','{$parameters}',0,100, {$value_add}" . "{$parent}, {$previous}, 0, " . "'{$prereq}', 0" . ")"; $res_item = Database::query($sql_item); if ($this->debug > 1) { error_log('New LP - In aicc::import_aicc() - inserting item : ' . $sql_item . ' : ' . mysql_error(), 0); } $item_id = Database::insert_id(); //now update previous item to change next_item_id if ($previous != 0) { $upd = "UPDATE {$new_lp_item} SET next_item_id = {$item_id} WHERE id = {$previous}"; $upd_res = Database::query($upd); //update previous item id } $previous = $item_id; } }
static function delete_note($notebook_id) { if (empty($notebook_id) or $notebook_id != strval(intval($notebook_id))) { return false; } // Database table definition $t_notebook = Database :: get_course_table(TABLE_NOTEBOOK); $course_id = api_get_course_int_id(); $sql = "DELETE FROM $t_notebook WHERE c_id = $course_id AND notebook_id='" . intval($notebook_id) . "' AND user_id = '" . api_get_user_id() . "'"; $result = Database::query($sql); $affected_rows = Database::affected_rows(); if ($affected_rows != 1) { return false; } //update item_property (delete) api_item_property_update(api_get_course_info(), TOOL_NOTEBOOK, intval($notebook_id), 'delete', api_get_user_id()); return true; }
/** * @param $id * @param $copy_courses * @param $copy_users * @param $create_new_courses * @param $set_exercises_lp_invisible * @return int */ public static function copy_session($id, $copy_courses = true, $copy_users = true, $create_new_courses = false, $set_exercises_lp_invisible = false) { $id = intval($id); $params = self::fetch($id); $params['name'] = $params['name'] . ' ' . get_lang('CopyLabelSuffix'); $sid = self::add($params); if (!is_numeric($sid) || empty($sid)) { return false; } if ($copy_courses) { // Register courses from the original session to the new session $courses = self::get_course_list_by_session_id($id); $short_courses = $new_short_courses = array(); if (is_array($courses) && count($courses) > 0) { foreach ($courses as $course) { $short_courses[] = $course; } } $courses = null; //We will copy the current courses of the session to new courses if (!empty($short_courses)) { if ($create_new_courses) { //Just in case if (function_exists('ini_set')) { api_set_memory_limit('256M'); ini_set('max_execution_time', 0); } $params = array(); $params['skip_lp_dates'] = true; foreach ($short_courses as $course_data) { $course_info = CourseManager::copy_course_simple($course_data['title'] . ' ' . get_lang('CopyLabelSuffix'), $course_data['course_code'], $id, $sid, $params); if ($course_info) { //By default new elements are invisible if ($set_exercises_lp_invisible) { $list = new LearnpathList('', $course_info['code'], $sid); $flat_list = $list->get_flat_list(); if (!empty($flat_list)) { foreach ($flat_list as $lp_id => $data) { api_item_property_update($course_info, TOOL_LEARNPATH, $lp_id, 'invisible', api_get_user_id(), 0, 0, 0, 0, $sid); api_item_property_update($course_info, TOOL_LEARNPATH, $lp_id, 'invisible', api_get_user_id(), 0, 0, 0, 0); } } $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST); $course_id = $course_info['real_id']; //@todo check this query //Disabling quiz items $sql = "UPDATE {$quiz_table} SET active = 0 WHERE c_id = {$course_id} "; Database::query($sql); } $new_short_courses[] = $course_info['code']; } } } else { foreach ($short_courses as $course_data) { $new_short_courses[] = $course_data['id']; } } $short_courses = $new_short_courses; $res = self::add_courses_to_session($sid, $short_courses, true); $short_courses = null; } } if ($copy_users) { // Register users from the original session to the new session $users = self::get_users_by_session($id); $short_users = array(); if (is_array($users) && count($users) > 0) { foreach ($users as $user) { $short_users[] = $user['user_id']; } } $users = null; //Subscribing in read only mode $res = self::suscribe_users_to_session($sid, $short_users, SESSION_VISIBLE_READ_ONLY, true, false); $short_users = null; } return $sid; }
/** * Delete a glossary term (and re-order all the others) * * @param integer The id of the glossary term to delete * @return bool True on success, false on failure * @author Patrick Cool <*****@*****.**>, Ghent University, Belgium * @version januari 2009, dokeos 1.8.6 */ public static function delete_glossary($glossary_id, $message = true) { // Database table definition $t_glossary = Database::get_course_table(TABLE_GLOSSARY); $course_id = api_get_course_int_id(); if (empty($glossary_id)) { return false; } $sql = "DELETE FROM {$t_glossary} WHERE c_id = {$course_id} AND glossary_id='" . intval($glossary_id) . "'"; $result = Database::query($sql); if ($result === false or Database::affected_rows($result) < 1) { return false; } //update item_property (delete) api_item_property_update(api_get_course_info(), TOOL_GLOSSARY, intval($glossary_id), 'delete', api_get_user_id()); // reorder the remaining terms GlossaryManager::reorder_glossary(); Session::write('max_glossary_display', GlossaryManager::get_max_glossary_item()); Display::display_confirmation_message(get_lang('TermDeleted')); return true; }
/** * Deletes a blog and it's posts from the course database * @author Toon Keppens * @param Integer $blog_id */ public static function delete_blog($blog_id) { // Init $tbl_blogs = Database::get_course_table(TABLE_BLOGS); $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS); $tbl_blogs_comment = Database::get_course_table(TABLE_BLOGS_COMMENTS); $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS); $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST); $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING); $tbl_blogs_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT); $course_id = api_get_course_int_id(); $blog_id = intval($blog_id); // Delete posts from DB and the attachments delete_all_blog_attachment($blog_id); //Delete comments $sql = "DELETE FROM {$tbl_blogs_comment} WHERE c_id = {$course_id} AND blog_id ='" . $blog_id . "'"; Database::query($sql); // Delete posts $sql = "DELETE FROM {$tbl_blogs_posts} WHERE c_id = {$course_id} AND blog_id ='" . $blog_id . "'"; Database::query($sql); // Delete tasks $sql = "DELETE FROM {$tbl_blogs_tasks} WHERE c_id = {$course_id} AND blog_id ='" . $blog_id . "'"; Database::query($sql); // Delete ratings $sql = "DELETE FROM {$tbl_blogs_rating} WHERE c_id = {$course_id} AND blog_id ='" . $blog_id . "'"; Database::query($sql); // Delete blog $sql = "DELETE FROM {$tbl_blogs} WHERE c_id = {$course_id} AND blog_id ='" . $blog_id . "'"; Database::query($sql); // Delete from course homepage $sql = "DELETE FROM {$tbl_tool} WHERE c_id = {$course_id} AND link = 'blog/blog.php?blog_id=" . $blog_id . "'"; Database::query($sql); //update item_property (delete) api_item_property_update(api_get_course_info(), TOOL_BLOGS, $blog_id, 'delete', api_get_user_id()); }
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()); } } }
} break; case 'visible': if (!$is_allowed_to_edit) { api_not_allowed(); } api_item_property_update($courseInfo, 'work', $work_id, 'visible', api_get_user_id(), null, null, null, null, $session_id); Display::addFlash(Display::return_message(get_lang('VisibilityChanged'), 'confirmation')); header('Location: ' . $currentUrl); exit; break; case 'invisible': if (!$is_allowed_to_edit) { api_not_allowed(); } api_item_property_update($courseInfo, 'work', $work_id, 'invisible', api_get_user_id(), null, null, null, null, $session_id); Display::addFlash(Display::return_message(get_lang('VisibilityChanged'), 'confirmation')); header('Location: ' . $currentUrl); exit; break; case 'list': /* Display list of student publications */ if (!empty($my_folder_data['description'])) { $content = '<p><div><strong>' . get_lang('Description') . ':</strong><p>' . Security::remove_XSS($my_folder_data['description'], STUDENT) . '</p></div></p>'; } if (api_is_allowed_to_edit() || api_is_coach()) { // Work list $content .= '<div class="toolbar-works"><a id="open-view-list" class="btn btn-primary" href="#"><i class="fa fa-users"></i> Ver Estudiantes</a></div>'; $content .= '<div class="row">'; $content .= '<div class="col-md-12">'; $content .= '<div id="work-list" class="table-responsive">';
$doc_id = FileManager::add_document($_course, $dir . 'css', 'folder', 0, 'css'); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id'], null, null, null, null, $current_session_id); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id'], null, null, null, null, $current_session_id); } if (!is_file($filepath . 'css/frames.css')) { // Make a copy of the current css for the new document copy(api_get_path(SYS_CSS_PATH) . 'themes/' . api_get_setting('stylesheets') . '/frames.css', $filepath . 'css/frames.css'); $doc_id = FileManager::add_document($_course, $dir . 'css/frames.css', 'file', filesize($filepath . 'css/frames.css'), 'frames.css'); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], null, null, null, null, $current_session_id); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id'], null, null, null, null, $current_session_id); } $file_size = filesize($filepath . $filename . '.' . $extension); $save_file_path = $dir . $filename . '.' . $extension; $document_id = FileManager::add_document($_course, $save_file_path, 'file', $file_size, $title, null, $readonly); if ($document_id) { api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id); // Update parent folders FileManager::item_property_update_on_folder($_course, $dir, $_user['user_id']); $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : ''; $new_comment = Database::escape_string($new_comment); $new_title = isset($_POST['title']) ? trim($_POST['title']) : ''; $new_title = htmlspecialchars($new_title); $new_title = Database::escape_string($new_title); if ($new_comment || $new_title) { $ct = ''; if ($new_comment) { $ct .= ", comment='{$new_comment}'"; } if ($new_title) { $ct .= ", title='{$new_title}'"; }
/** * Restore Work */ function restore_works($session_id = 0) { $perm = api_get_permissions_for_new_directories(); if ($this->course->has_resources(RESOURCE_WORK)) { $table_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION); $table_work_assignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT); $resources = $this->course->resources; foreach ($resources[RESOURCE_WORK] as $id => $obj) { // check resources inside html from fckeditor tool and copy correct urls into recipient course $obj->params['description'] = DocumentManager::replace_urls_inside_content_html_from_copy_course($obj->params['description'], $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); $obj->params['id'] = null; $obj->params['c_id'] = $this->destination_course_id; $last_id = Database::insert($table_work, $obj->params); // re-create dir // @todo check security against injection of dir in crafted course backup here! $path = $obj->params['url']; $path = '/' . str_replace('/', '', substr($path, 1)); $destination_path = api_get_path(SYS_COURSE_PATH) . $this->course->destination_path . '/work' . $path; $r = @mkdir($destination_path, $perm); if ($r === false) { error_log('Failed creating directory ' . $destination_path . ' in course restore for work tool'); } if (is_numeric($last_id)) { api_item_property_update($this->destination_course_info, 'work', $last_id, "DirectoryCreated", api_get_user_id()); } } } }