Example #1
0
 /**
  * Generate SQL to select all the links categories in the current course and
  * session
  * @param   int $courseId
  * @param   int $sessionId
  * @return array
  */
 public static function getLinkCategories($courseId, $sessionId)
 {
     $tblLinkCategory = Database::get_course_table(TABLE_LINK_CATEGORY);
     $tblItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $courseId = intval($courseId);
     // Condition for the session.
     $sessionCondition = api_get_session_condition($sessionId, true, true, 'linkcat.session_id');
     // Getting links
     $sql = "SELECT *, linkcat.id\n                FROM {$tblLinkCategory} linkcat\n                WHERE\n                    linkcat.c_id = " . $courseId . "\n                    {$sessionCondition}\n                ORDER BY linkcat.display_order DESC";
     $result = Database::query($sql);
     $categories = Database::store_result($result);
     $sql = "SELECT *, linkcat.id\n                FROM {$tblLinkCategory} linkcat\n                INNER JOIN {$tblItemProperty} itemproperties\n                ON (linkcat.id = itemproperties.ref AND linkcat.c_id = itemproperties.c_id)\n                WHERE\n                    itemproperties.tool = '" . TOOL_LINK_CATEGORY . "' AND\n                    (itemproperties.visibility = '0' OR itemproperties.visibility = '1')\n                    {$sessionCondition} AND\n                    linkcat.c_id = " . $courseId . "\n                ORDER BY linkcat.display_order DESC";
     $result = Database::query($sql);
     $categoryInItemProperty = array();
     if (Database::num_rows($result)) {
         while ($row = Database::fetch_array($result, 'ASSOC')) {
             $categoryInItemProperty[$row['id']] = $row;
         }
     }
     foreach ($categories as &$category) {
         if (!isset($categoryInItemProperty[$category['id']])) {
             api_set_default_visibility($category['id'], TOOL_LINK_CATEGORY);
         }
     }
     $sql = "SELECT DISTINCT linkcat.*, visibility\n                FROM {$tblLinkCategory} linkcat\n                INNER JOIN {$tblItemProperty} itemproperties\n                ON (linkcat.id = itemproperties.ref AND linkcat.c_id = itemproperties.c_id)\n                WHERE\n                    itemproperties.tool = '" . TOOL_LINK_CATEGORY . "' AND\n                    (itemproperties.visibility = '0' OR itemproperties.visibility = '1')\n                    {$sessionCondition} AND\n                    linkcat.c_id = " . $courseId . "\n                GROUP BY c_id, id\n                ORDER BY linkcat.display_order DESC\n                ";
     $result = Database::query($sql);
     return Database::store_result($result, 'ASSOC');
 }
/**
 * 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;
}
 /**
  * updates the exercise in the data base
  *
  * @author Olivier Brouckaert
  */
 public function save($type_e = '')
 {
     $_course = $this->course;
     $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
     $id = $this->id;
     $exercise = $this->exercise;
     $description = $this->description;
     $sound = $this->sound;
     $type = $this->type;
     $attempts = isset($this->attempts) ? $this->attempts : 0;
     $feedback_type = isset($this->feedback_type) ? $this->feedback_type : 0;
     $random = $this->random;
     $random_answers = $this->random_answers;
     $active = $this->active;
     $propagate_neg = $this->propagate_neg;
     $review_answers = isset($this->review_answers) && $this->review_answers ? 1 : 0;
     $randomByCat = $this->randomByCat;
     $text_when_finished = $this->text_when_finished;
     $display_category_name = intval($this->display_category_name);
     $pass_percentage = intval($this->pass_percentage);
     $session_id = $this->sessionId;
     //If direct we do not show results
     if ($feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) {
         $results_disabled = 0;
     } else {
         $results_disabled = intval($this->results_disabled);
     }
     $expired_time = intval($this->expired_time);
     // Exercise already exists
     if ($id) {
         // we prepare date in the database using the api_get_utc_datetime() function
         if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
             $start_time = Database::escape_string($this->start_time);
         } else {
             $start_time = '0000-00-00 00:00:00';
         }
         if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
             $end_time = Database::escape_string($this->end_time);
         } else {
             $end_time = '0000-00-00 00:00:00';
         }
         $params = ['title' => $exercise, 'description' => $description];
         $paramsExtra = [];
         if ($type_e != 'simple') {
             $paramsExtra = ['sound' => $sound, 'type' => $type, 'random' => $random, 'random_answers' => $random_answers, 'active' => $active, 'feedback_type' => $feedback_type, 'start_time' => $start_time, 'end_time' => $end_time, 'max_attempt' => $attempts, 'expired_time' => $expired_time, 'propagate_neg' => $propagate_neg, 'review_answers' => $review_answers, 'random_by_category' => $randomByCat, 'text_when_finished' => $text_when_finished, 'display_category_name' => $display_category_name, 'pass_percentage' => $pass_percentage, 'results_disabled' => $results_disabled];
         }
         $params = array_merge($params, $paramsExtra);
         Database::update($TBL_EXERCISES, $params, ['c_id = ? AND id = ?' => [$this->course_id, $id]]);
         // update into the item_property table
         api_item_property_update($_course, TOOL_QUIZ, $id, 'QuizUpdated', api_get_user_id());
         if (api_get_setting('search.search_enabled') == 'true') {
             $this->search_engine_edit();
         }
     } else {
         // Creates a new exercise
         // In this case of new exercise, we don't do the api_get_utc_datetime()
         // for date because, bellow, we call function api_set_default_visibility()
         // In this function, api_set_default_visibility,
         // the Quiz is saved too, with an $id and api_get_utc_datetime() is done.
         // If we do it now, it will be done twice (cf. https://support.chamilo.org/issues/6586)
         if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
             $start_time = $this->start_time;
         } else {
             $start_time = '0000-00-00 00:00:00';
         }
         if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
             $end_time = $this->end_time;
         } else {
             $end_time = '0000-00-00 00:00:00';
         }
         $params = ['c_id' => $this->course_id, 'start_time' => $start_time, 'end_time' => $end_time, 'title' => $exercise, 'description' => $description, 'sound' => $sound, 'type' => $type, 'random' => $random, 'random_answers' => $random_answers, 'active' => $active, 'results_disabled' => $results_disabled, 'max_attempt' => $attempts, 'feedback_type' => $feedback_type, 'expired_time' => $expired_time, 'session_id' => $session_id, 'review_answers' => $review_answers, 'random_by_category' => $randomByCat, 'text_when_finished' => $text_when_finished, 'display_category_name' => $display_category_name, 'pass_percentage' => $pass_percentage];
         $this->id = Database::insert($TBL_EXERCISES, $params);
         if ($this->id) {
             $sql = "UPDATE {$TBL_EXERCISES} SET id = iid WHERE iid = {$this->id} ";
             Database::query($sql);
             // insert into the item_property table
             api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizAdded', api_get_user_id());
             // This function save the quiz again, carefull about start_time
             // and end_time if you remove this line (see above)
             api_set_default_visibility($this->id, TOOL_QUIZ, null, $this->course);
             if (api_get_setting('search.search_enabled') == 'true' && extension_loaded('xapian')) {
                 $this->search_engine_save();
             }
         }
     }
     // Updates the question position
     $this->update_question_positions();
 }
Example #4
0
 /**
  * Static admin function allowing addition of a learnpath to a course.
  * @param    string    Course code
  * @param    string    Learnpath name
  * @param    string    Learnpath description string, if provided
  * @param    string    Type of learnpath (default = 'guess', others = 'dokeos', 'aicc',...)
  * @param    string    Type of files origin (default = 'zip', others = 'dir','web_dir',...)
  * @param    string    Zip file containing the learnpath or directory containing the learnpath
  * @return    integer    The new learnpath ID on success, 0 on failure
  */
 public static function add_lp($course, $name, $description = '', $learnpath = 'guess', $origin = 'zip', $zipname = '', $publicated_on = '', $expired_on = '', $category_id = 0)
 {
     global $charset;
     $course_id = api_get_course_int_id();
     $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
     // Check course code exists.
     // Check lp_name doesn't exist, otherwise append something.
     $i = 0;
     $name = Database::escape_string($name);
     $category_id = intval($category_id);
     // Session id.
     $session_id = api_get_session_id();
     $check_name = "SELECT * FROM {$tbl_lp} WHERE c_id = {$course_id} AND name = '{$name}'";
     //if ($this->debug > 2) { error_log('New LP - Checking the name for new LP: '.$check_name, 0); }
     $res_name = Database::query($check_name);
     if ($publicated_on == '0000-00-00 00:00:00' || empty($publicated_on)) {
         //by default the publication date is the same that the creation date
         //The behaviour above was changed due BT#2800
         global $_custom;
         if (isset($_custom['lps_hidden_when_no_start_date']) && $_custom['lps_hidden_when_no_start_date']) {
             $publicated_on = '';
         } else {
             $publicated_on = api_get_utc_datetime();
         }
     } else {
         $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
     }
     if ($expired_on == '0000-00-00 00:00:00' || empty($expired_on)) {
         $expired_on = '';
     } else {
         $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
     }
     while (Database::num_rows($res_name)) {
         // There is already one such name, update the current one a bit.
         $i++;
         $name = $name . ' - ' . $i;
         $check_name = "SELECT * FROM {$tbl_lp} WHERE c_id = {$course_id} AND name = '{$name}'";
         //if ($this->debug > 2) { error_log('New LP - Checking the name for new LP: '.$check_name, 0); }
         $res_name = Database::query($check_name);
     }
     // New name does not exist yet; keep it.
     // Escape description.
     $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
     // Kevin: added htmlentities().
     $type = 1;
     switch ($learnpath) {
         case 'guess':
             break;
         case 'dokeos':
         case 'chamilo':
             $type = 1;
             break;
         case 'aicc':
             break;
     }
     switch ($origin) {
         case 'zip':
             // Check zipname string. If empty, we are currently creating a new Chamilo learnpath.
             break;
         case 'manual':
         default:
             $get_max = "SELECT MAX(display_order) FROM {$tbl_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;
             }
             $sql_insert = "INSERT INTO {$tbl_lp} (c_id, lp_type,name,description,path,default_view_mod, default_encoding,display_order,content_maker,content_local,js_lib,session_id, created_on, publicated_on, expired_on, category_id) " . "VALUES ({$course_id}, {$type},'{$name}','{$description}','','embedded','UTF-8','{$dsp}','Chamilo','local','','" . $session_id . "', '" . api_get_utc_datetime() . "' , '" . $publicated_on . "' , '" . $expired_on . "', {$category_id})";
             Database::query($sql_insert);
             $id = Database::insert_id();
             if ($id > 0) {
                 $course_info = api_get_course_info();
                 // Insert into item_property.
                 api_item_property_update($course_info, TOOL_LEARNPATH, $id, 'LearnpathAdded', api_get_user_id());
                 api_set_default_visibility($course_info, $id, TOOL_LEARNPATH);
                 return $id;
             }
             break;
     }
 }
Example #5
0
/**
 * Adds a new document to the database
 *
 * @param array $_course
 * @param string $path
 * @param string $filetype
 * @param int $filesize
 * @param string $title
 * @param string $comment
 * @param int $readonly
 * @param bool $save_visibility
 * @param int $group_id
 * @param int $session_id Session ID, if any
 * @return int id if inserted document
 */
function add_document($_course, $path, $filetype, $filesize, $title, $comment = null, $readonly = 0, $save_visibility = true, $group_id = null, $session_id = 0)
{
    $session_id = intval($session_id);
    if (empty($session_id)) {
        $session_id = api_get_session_id();
    }
    $readonly = intval($readonly);
    $c_id = $_course['real_id'];
    $table_document = Database::get_course_table(TABLE_DOCUMENT);
    $params = ['c_id' => $c_id, 'path' => $path, 'filetype' => $filetype, 'size' => $filesize, 'title' => $title, 'comment' => $comment, 'readonly' => $readonly, 'session_id' => $session_id];
    $documentId = Database::insert($table_document, $params);
    if ($documentId) {
        $sql = "UPDATE {$table_document} SET id = iid WHERE iid = {$documentId}";
        Database::query($sql);
        if ($save_visibility) {
            api_set_default_visibility($documentId, TOOL_DOCUMENT, $group_id, $_course);
        }
        return $documentId;
    } else {
        return false;
    }
}
/**
 * This function stores a new thread. This is done through an entry in the forum_thread table AND
 * in the forum_post table because. The threads are also stored in the item_property table. (forum posts are not (yet))
 *
 * @param array $current_forum
 * @param array $values
 * @param array $courseInfo
 * @param bool $showMessage
 * @return void HTML
 *
 * @author Patrick Cool <*****@*****.**>, Ghent University
 * @version february 2006, dokeos 1.8
 */
function store_thread($current_forum, $values, $courseInfo = array(), $showMessage = true)
{
    $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
    $_user = api_get_user_info();
    $course_id = $courseInfo['real_id'];
    $courseCode = $courseInfo['code'];
    $table_threads = Database::get_course_table(TABLE_FORUM_THREAD);
    $table_posts = Database::get_course_table(TABLE_FORUM_POST);
    $upload_ok = 1;
    $has_attachment = false;
    if (!empty($_FILES['user_upload']['name'])) {
        $upload_ok = process_uploaded_file($_FILES['user_upload']);
        $has_attachment = true;
    }
    if ($upload_ok) {
        $post_date = api_get_utc_datetime();
        if ($current_forum['approval_direct_post'] == '1' && !api_is_allowed_to_edit(null, true)) {
            $visible = 0;
            // The post has not been approved yet.
        } else {
            $visible = 1;
        }
        $clean_post_title = $values['post_title'];
        // We first store an entry in the forum_thread table because the thread_id is used in the forum_post table.
        $last_thread_id = Database::insert($table_threads, ['c_id' => $course_id, 'thread_title' => $clean_post_title, 'forum_id' => $values['forum_id'], 'thread_poster_id' => $_user['user_id'], 'thread_poster_name' => stripslashes(isset($values['poster_name']) ? $values['poster_name'] : ''), 'thread_date' => $post_date, 'thread_sticky' => isset($values['thread_sticky']) ? $values['thread_sticky'] : '', 'thread_title_qualify' => isset($values['calification_notebook_title']) ? $values['calification_notebook_title'] : '', 'thread_qualify_max' => isset($values['numeric_calification']) ? $values['numeric_calification'] : '', 'thread_weight' => isset($values['weight_calification']) ? $values['weight_calification'] : '', 'thread_peer_qualify' => isset($values['thread_peer_qualify']) ? $values['thread_peer_qualify'] : '', 'session_id' => api_get_session_id(), 'lp_item_id' => isset($values['lp_item_id']) ? intval($values['lp_item_id']) : 0]);
        // Add option gradebook qualify.
        if (isset($values['thread_qualify_gradebook']) && 1 == $values['thread_qualify_gradebook']) {
            // Add function gradebook.
            $resourcetype = 5;
            $resourceid = $last_thread_id;
            $resourcename = stripslashes($values['calification_notebook_title']);
            $maxqualify = $values['numeric_calification'];
            $weigthqualify = $values['weight_calification'];
            $resourcedescription = '';
            GradebookUtils::add_resource_to_course_gradebook($values['category_id'], $courseCode, $resourcetype, $resourceid, $resourcename, $weigthqualify, $maxqualify, $resourcedescription, 0, api_get_session_id());
        }
        if ($last_thread_id) {
            $sql = "UPDATE {$table_threads} SET thread_id = {$last_thread_id}\n                    WHERE iid = {$last_thread_id}";
            Database::query($sql);
            api_item_property_update($courseInfo, TOOL_FORUM_THREAD, $last_thread_id, 'ForumThreadAdded', api_get_user_id(), api_get_group_id(), null, null, null, api_get_session_id());
            // If the forum properties tell that the posts have to be approved
            // we have to put the whole thread invisible,
            // because otherwise the students will see the thread and not the post
            // in the thread.
            // We also have to change $visible because the post itself has to be
            // visible in this case (otherwise the teacher would have
            // to make the thread visible AND the post.
            // Default behaviour
            api_set_default_visibility($last_thread_id, TOOL_FORUM_THREAD, api_get_group_id(), $courseInfo);
            if ($visible == 0) {
                api_item_property_update($courseInfo, TOOL_FORUM_THREAD, $last_thread_id, 'invisible', api_get_user_id(), api_get_group_id());
                $visible = 1;
            }
        }
        // We now store the content in the table_post table.
        $params = ['c_id' => $course_id, 'post_title' => $clean_post_title, 'post_text' => $values['post_text'], 'thread_id' => $last_thread_id, 'forum_id' => $values['forum_id'], 'poster_id' => $_user['user_id'], 'poster_name' => isset($values['poster_name']) ? $values['poster_name'] : '', 'post_date' => $post_date, 'post_notification' => isset($values['post_notification']) ? $values['post_notification'] : '', 'post_parent_id' => 0, 'visible' => $visible];
        $last_post_id = Database::insert($table_posts, $params);
        if ($last_post_id) {
            $sql = "UPDATE {$table_posts} SET post_id = {$last_post_id}\n                    WHERE iid = {$last_post_id}";
            Database::query($sql);
        }
        // Update attached files
        if (!empty($_POST['file_ids']) && is_array($_POST['file_ids'])) {
            foreach ($_POST['file_ids'] as $key => $id) {
                editAttachedFile(array('comment' => $_POST['file_comments'][$key], 'post_id' => $last_post_id), $id);
            }
        }
        // Now we have to update the thread table to fill the thread_last_post
        // field (so that we know when the thread has been updated for the last time).
        $sql = "UPDATE {$table_threads}\n                SET thread_last_post = '" . Database::escape_string($last_post_id) . "'\n                WHERE\n                    c_id = {$course_id} AND\n                    thread_id='" . Database::escape_string($last_thread_id) . "'";
        $result = Database::query($sql);
        $message = get_lang('NewThreadStored');
        // Storing the attachments if any.
        if ($has_attachment) {
            // Try to add an extension to the file if it hasn't one.
            $new_file_name = add_ext_on_mime(stripslashes($_FILES['user_upload']['name']), $_FILES['user_upload']['type']);
            if (!filter_extension($new_file_name)) {
                if ($showMessage) {
                    Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
                }
            } else {
                if ($result) {
                    add_forum_attachment_file(isset($values['file_comment']) ? $values['file_comment'] : null, $last_post_id);
                }
            }
        } else {
            $message .= '<br />';
        }
        if ($current_forum['approval_direct_post'] == '1' && !api_is_allowed_to_edit(null, true)) {
            $message .= get_lang('MessageHasToBeApproved') . '<br />';
            $message .= get_lang('ReturnTo') . ' <a href="viewforum.php?' . api_get_cidreq() . '&forum=' . $values['forum_id'] . '">' . get_lang('Forum') . '</a><br />';
        } else {
            $message .= get_lang('ReturnTo') . ' <a href="viewforum.php?' . api_get_cidreq() . '&forum=' . $values['forum_id'] . '">' . get_lang('Forum') . '</a><br />';
            $message .= get_lang('ReturnTo') . ' <a href="viewthread.php?' . api_get_cidreq() . '&forum=' . $values['forum_id'] . '&thread=' . $last_thread_id . '">' . get_lang('Message') . '</a>';
        }
        $reply_info['new_post_id'] = $last_post_id;
        $my_post_notification = isset($values['post_notification']) ? $values['post_notification'] : null;
        if ($my_post_notification == 1) {
            set_notification('thread', $last_thread_id, true);
        }
        send_notification_mails($last_thread_id, $reply_info);
        Session::erase('formelements');
        Session::erase('origin');
        Session::erase('breadcrumbs');
        Session::erase('addedresource');
        Session::erase('addedresourceid');
        if ($showMessage) {
            Display::display_confirmation_message($message, false);
        }
    } else {
        if ($showMessage) {
            Display::display_error_message(get_lang('UplNoFileUploaded'));
        }
    }
}
 /**
  * Restore a link-category
  */
 public function restore_link_category($id, $session_id = 0)
 {
     $params = [];
     if (!empty($session_id)) {
         $params['session_id'] = $session_id;
     }
     if ($id == 0) {
         return 0;
     }
     $link_cat_table = Database::get_course_table(TABLE_LINK_CATEGORY);
     $resources = $this->course->resources;
     $link_cat = $resources[RESOURCE_LINKCATEGORY][$id];
     if (is_object($link_cat) && !$link_cat->is_restored()) {
         $sql = "SELECT MAX(display_order) FROM  {$link_cat_table}\n\t\t\t        WHERE c_id = " . $this->destination_course_id . " ";
         $result = Database::query($sql);
         list($orderMax) = Database::fetch_array($result, 'NUM');
         $display_order = $orderMax + 1;
         $params['c_id'] = $this->destination_course_id;
         $params['category_title'] = self::DBUTF8($link_cat->title);
         $params['description'] = self::DBUTF8($link_cat->description);
         $params['display_order'] = $display_order;
         $new_id = Database::insert($link_cat_table, $params);
         if ($new_id) {
             $sql = "UPDATE {$link_cat_table} SET id = iid WHERE iid = {$new_id}";
             Database::query($sql);
             api_set_default_visibility($new_id, TOOL_LINK_CATEGORY);
         }
         $this->course->resources[RESOURCE_LINKCATEGORY][$id]->destination_id = $new_id;
         return $new_id;
     }
     return $this->course->resources[RESOURCE_LINKCATEGORY][$id]->destination_id;
 }
/**
 * Adds a new document to the database
 *
 * @param array $_course
 * @param string $path
 * @param string $filetype
 * @param int $filesize
 * @param string $title
 * @param string $comment
 * @param int $readonly
 * @param bool $save_visibility
 * @param int $group_id
 * @param int $session_id Session ID, if any
 * @return int id if inserted document
 */
function add_document($_course, $path, $filetype, $filesize, $title, $comment = null, $readonly = 0, $save_visibility = true, $group_id = null, $session_id = 0)
{
    $session_id = intval($session_id);
    if (empty($session_id)) {
        $session_id = api_get_session_id();
    }
    $readonly = intval($readonly);
    $comment = Database::escape_string($comment);
    $path = Database::escape_string($path);
    $filetype = Database::escape_string($filetype);
    $filesize = Database::escape_string($filesize);
    $title = Database::escape_string(htmlspecialchars($title));
    $c_id = $_course['real_id'];
    $table_document = Database::get_course_table(TABLE_DOCUMENT);
    $sql = "INSERT INTO {$table_document} (c_id, path, filetype, size, title, comment, readonly, session_id)\n\t        VALUES ({$c_id}, '{$path}','{$filetype}','{$filesize}','{$title}', '{$comment}', {$readonly}, {$session_id})";
    if (Database::query($sql)) {
        $documentId = Database::insert_id();
        if ($documentId) {
            if ($save_visibility) {
                api_set_default_visibility($documentId, TOOL_DOCUMENT, $group_id);
            }
        }
        return $documentId;
    } else {
        return false;
    }
}
 /**
  * Static admin function allowing addition of a learnpath to a course.
  * @param	string	Course code
  * @param	string	Learnpath name
  * @param	string	Learnpath description string, if provided
  * @param	string	Type of learnpath (default = 'guess', others = 'dokeos', 'aicc',...)
  * @param	string	Type of files origin (default = 'zip', others = 'dir','web_dir',...)
  * @param	string	Zip file containing the learnpath or directory containing the learnpath
  * @return	integer	The new learnpath ID on success, 0 on failure
  */
 public static function add_lp($course, $name, $description = '', $learnpath = 'guess', $origin = 'zip', $zipname = '', $publicated_on = '', $expired_on = '', $categoryId = 0)
 {
     global $charset;
     $course_id = api_get_course_int_id();
     $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
     // Check course code exists.
     // Check lp_name doesn't exist, otherwise append something.
     $i = 0;
     $name = Database::escape_string($name);
     $categoryId = intval($categoryId);
     // Session id.
     $session_id = api_get_session_id();
     $check_name = "SELECT * FROM {$tbl_lp}\n                       WHERE c_id = {$course_id} AND name = '{$name}'";
     $res_name = Database::query($check_name);
     if ($publicated_on == '0000-00-00 00:00:00' || empty($publicated_on)) {
         //by default the publication date is the same that the creation date
         //The behaviour above was changed due BT#2800
         global $_custom;
         if (isset($_custom['lps_hidden_when_no_start_date']) && $_custom['lps_hidden_when_no_start_date']) {
             $publicated_on = '';
         } else {
             $publicated_on = api_get_utc_datetime();
         }
     } else {
         $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
     }
     if ($expired_on == '0000-00-00 00:00:00' || empty($expired_on)) {
         $expired_on = '';
     } else {
         $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
     }
     while (Database::num_rows($res_name)) {
         // There is already one such name, update the current one a bit.
         $i++;
         $name = $name . ' - ' . $i;
         $check_name = "SELECT * FROM {$tbl_lp} WHERE c_id = {$course_id} AND name = '{$name}'";
         $res_name = Database::query($check_name);
     }
     // New name does not exist yet; keep it.
     // Escape description.
     // Kevin: added htmlentities().
     $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
     $type = 1;
     switch ($learnpath) {
         case 'guess':
             break;
         case 'dokeos':
         case 'chamilo':
             $type = 1;
             break;
         case 'aicc':
             break;
     }
     switch ($origin) {
         case 'zip':
             // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
             break;
         case 'manual':
         default:
             $get_max = "SELECT MAX(display_order) FROM {$tbl_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;
             }
             $params = ['c_id' => $course_id, 'lp_type' => $type, 'name' => $name, 'description' => $description, 'path' => '', 'default_view_mod' => 'embedded', 'default_encoding' => 'UTF-8', 'display_order' => $dsp, 'content_maker' => 'Chamilo', 'content_local' => 'local', 'js_lib' => '', 'session_id' => $session_id, 'created_on' => api_get_utc_datetime(), 'publicated_on' => $publicated_on, 'expired_on' => $expired_on, 'category_id' => $categoryId];
             $id = Database::insert($tbl_lp, $params);
             if ($id > 0) {
                 $sql = "UPDATE {$tbl_lp} SET id = iid WHERE iid = {$id}";
                 Database::query($sql);
                 $course_info = api_get_course_info();
                 // Insert into item_property.
                 api_item_property_update($course_info, TOOL_LEARNPATH, $id, 'LearnpathAdded', api_get_user_id());
                 api_set_default_visibility($id, TOOL_LEARNPATH);
                 return $id;
             }
             break;
     }
 }
 /**
  * updates the exercise in the data base
  *
  * @author Olivier Brouckaert
  */
 public function save($type_e = '')
 {
     global $_course;
     $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
     $id = $this->id;
     $exercise = $this->exercise;
     $description = $this->description;
     $sound = $this->sound;
     $type = $this->type;
     $attempts = $this->attempts;
     $feedback_type = $this->feedback_type;
     $random = $this->random;
     $random_answers = $this->random_answers;
     $active = $this->active;
     $propagate_neg = $this->propagate_neg;
     $review_answers = isset($this->review_answers) && $this->review_answers ? 1 : 0;
     $randomByCat = $this->randomByCat;
     $text_when_finished = $this->text_when_finished;
     $display_category_name = intval($this->display_category_name);
     $pass_percentage = intval($this->pass_percentage);
     $session_id = api_get_session_id();
     //If direct we do not show results
     if ($feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) {
         $results_disabled = 0;
     } else {
         $results_disabled = intval($this->results_disabled);
     }
     $expired_time = intval($this->expired_time);
     // Exercise already exists
     if ($id) {
         // we prepare date in the database using the api_get_utc_datetime() function
         if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
             $start_time = Database::escape_string($this->start_time);
         } else {
             $start_time = '0000-00-00 00:00:00';
         }
         if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
             $end_time = Database::escape_string($this->end_time);
         } else {
             $end_time = '0000-00-00 00:00:00';
         }
         $sql = "UPDATE {$TBL_EXERCICES} SET\n\t\t\t\t    title='" . Database::escape_string($exercise) . "',\n\t\t\t\t\tdescription='" . Database::escape_string($description) . "'";
         if ($type_e != 'simple') {
             $sql .= ",sound='" . Database::escape_string($sound) . "',\n\t\t\t\t\ttype           = " . intval($type) . ",\n\t\t\t\t\trandom         = " . intval($random) . ",\n\t\t\t\t\trandom_answers = " . intval($random_answers) . ",\n\t\t\t\t\tactive         = " . intval($active) . ",\n\t\t\t\t\tfeedback_type  = " . intval($feedback_type) . ",\n\t\t\t\t\tstart_time     = '{$start_time}',\n\t\t\t\t\tend_time       = '{$end_time}',\n\t\t\t\t\tmax_attempt    = " . intval($attempts) . ",\n     \t\t\t    expired_time   = " . intval($expired_time) . ",\n         \t\t\tpropagate_neg  = " . intval($propagate_neg) . ",\n         \t\t\treview_answers = " . intval($review_answers) . ",\n        \t        random_by_category= " . intval($randomByCat) . ",\n        \t        text_when_finished = '" . Database::escape_string($text_when_finished) . "',\n        \t        display_category_name = " . intval($display_category_name) . ",\n                    pass_percentage = " . intval($pass_percentage) . ",\n\t\t\t\t\tresults_disabled= " . intval($results_disabled) . "";
         }
         $sql .= " WHERE c_id = " . $this->course_id . " AND id = " . intval($id) . "";
         Database::query($sql);
         // update into the item_property table
         api_item_property_update($_course, TOOL_QUIZ, $id, 'QuizUpdated', api_get_user_id());
         if (api_get_setting('search_enabled') == 'true') {
             $this->search_engine_edit();
         }
     } else {
         // creates a new exercise
         // In this case of new exercise, we don't do the api_get_utc_datetime() for date because, bellow, we call function api_set_default_visibility()
         // In this function, api_set_default_visibility, the Quiz is saved too, with an $id and api_get_utc_datetime() is done.
         // If we do it now, it will be done twice (cf. https://support.chamilo.org/issues/6586)
         if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
             $start_time = Database::escape_string($this->start_time);
         } else {
             $start_time = '0000-00-00 00:00:00';
         }
         if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
             $end_time = Database::escape_string($this->end_time);
         } else {
             $end_time = '0000-00-00 00:00:00';
         }
         $sql = "INSERT INTO {$TBL_EXERCICES} (\n                        c_id, start_time, end_time, title, description, sound, type, random, random_answers, active,\n                        results_disabled, max_attempt, feedback_type, expired_time, session_id, review_answers, random_by_category,\n                        text_when_finished, display_category_name, pass_percentage\n                    )\n\t\t\t\t\tVALUES(\n\t\t\t\t\t\t" . $this->course_id . ",\n\t\t\t\t\t\t'{$start_time}','{$end_time}',\n\t\t\t\t\t\t'" . Database::escape_string($exercise) . "',\n\t\t\t\t\t\t'" . Database::escape_string($description) . "',\n\t\t\t\t\t\t'" . Database::escape_string($sound) . "',\n\t\t\t\t\t\t" . intval($type) . ",\n\t\t\t\t\t\t" . intval($random) . ",\n\t\t\t\t\t\t" . intval($random_answers) . ",\n\t\t\t\t\t\t" . intval($active) . ",\n\t\t\t\t\t\t" . intval($results_disabled) . ",\n\t\t\t\t\t\t" . intval($attempts) . ",\n\t\t\t\t\t\t" . intval($feedback_type) . ",\n\t\t\t\t\t\t" . intval($expired_time) . ",\n\t\t\t\t\t\t" . intval($session_id) . ",\n\t\t\t\t\t\t" . intval($review_answers) . ",\n\t\t\t\t\t\t" . intval($randomByCat) . ",\n\t\t\t\t\t\t'" . Database::escape_string($text_when_finished) . "',\n\t\t\t\t\t\t" . intval($display_category_name) . ",\n                        " . intval($pass_percentage) . "\n\t\t\t\t\t\t)";
         Database::query($sql);
         $this->id = Database::insert_id();
         // insert into the item_property table
         api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizAdded', api_get_user_id());
         // This function save the quiz again, carefull about start_time and end_time if you remove this line (see above)
         api_set_default_visibility($this->id, TOOL_QUIZ, null, true);
         if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
             $this->search_engine_save();
         }
     }
     // Updates the question position
     $this->update_question_positions();
 }
/**
 * This function stores a new thread. This is done through an entry in the forum_thread table AND
 * in the forum_post table because. The threads are also stored in the item_property table. (forum posts are not (yet))
 *
 * @param array
 * @return void HTML
 *
 * @author Patrick Cool <*****@*****.**>, Ghent University
 * @version february 2006, dokeos 1.8
 */
function store_thread($values)
{
    global $_user;
    $_course = api_get_course_info();
    global $current_forum;
    global $origin;
    $table_threads = Database::get_course_table(TABLE_FORUM_THREAD);
    $table_posts = Database::get_course_table(TABLE_FORUM_POST);
    $course_id = api_get_course_int_id();
    $gradebook = Security::remove_XSS($_GET['gradebook']);
    $upload_ok = 1;
    $has_attachment = false;
    if (!empty($_FILES['user_upload']['name'])) {
        $upload_ok = FileManager::process_uploaded_file($_FILES['user_upload']);
        $has_attachment = true;
    }
    if ($upload_ok) {
        $post_date = api_get_utc_datetime();
        if ($current_forum['approval_direct_post'] == '1' && !api_is_allowed_to_edit(null, true)) {
            $visible = 0;
            // The post has not been approved yet.
        } else {
            $visible = 1;
        }
        $clean_post_title = Database::escape_string(stripslashes($values['post_title']));
        // We first store an entry in the forum_thread table because the thread_id is used in the forum_post table.
        $sql = "INSERT INTO {$table_threads} (c_id, thread_title, forum_id, thread_poster_id, thread_poster_name, thread_date, thread_sticky,thread_title_qualify,thread_qualify_max,thread_weight,session_id)\n                VALUES (\n                \t\t" . $course_id . ",\n                \t\t'" . $clean_post_title . "',\n                        '" . Database::escape_string($values['forum_id']) . "',\n                        '" . Database::escape_string($_user['user_id']) . "',\n                        '" . Database::escape_string(stripslashes(isset($values['poster_name']) ? $values['poster_name'] : null)) . "',\n                        '" . Database::escape_string($post_date) . "',\n                        '" . Database::escape_string(isset($values['thread_sticky']) ? $values['thread_sticky'] : null) . "'," . "'" . Database::escape_string(stripslashes($values['calification_notebook_title'])) . "'," . "'" . Database::escape_string($values['numeric_calification']) . "'," . "'" . Database::escape_string($values['weight_calification']) . "'," . "'" . api_get_session_id() . "')";
        $result = Database::query($sql);
        $last_thread_id = Database::insert_id();
        // Add option gradebook qualify.
        if (isset($values['thread_qualify_gradebook']) && 1 == $values['thread_qualify_gradebook']) {
            // Add function gradebook.
            $coursecode = api_get_course_id();
            $resourcetype = 5;
            $resourceid = $last_thread_id;
            $resourcename = stripslashes($values['calification_notebook_title']);
            $maxqualify = $values['numeric_calification'];
            $weigthqualify = $values['weight_calification'];
            $resourcedescription = '';
            add_resource_to_course_gradebook($values['category_id'], $coursecode, $resourcetype, $resourceid, $resourcename, $weigthqualify, $maxqualify, $resourcedescription, 0, api_get_session_id());
        }
        if ($last_thread_id) {
            api_item_property_update($_course, TOOL_FORUM_THREAD, $last_thread_id, 'ForumThreadAdded', api_get_user_id());
            // If the forum properties tell that the posts have to be approved we have to put the whole thread invisible,
            // because otherwise the students will see the thread and not the post in the thread.
            // We also have to change $visible because the post itself has to be visible in this case (otherwise the teacher would have
            // to make the thread visible AND the post.
            //Default behaviour
            api_set_default_visibility($_course, $last_thread_id, TOOL_FORUM_THREAD);
            if ($visible == 0) {
                api_item_property_update($_course, TOOL_FORUM_THREAD, $last_thread_id, 'invisible', api_get_user_id());
                $visible = 1;
            }
        }
        // We now store the content in the table_post table.
        $sql = "INSERT INTO {$table_posts} (c_id, post_title, post_text, thread_id, forum_id, poster_id, poster_name, post_date, post_notification, post_parent_id, visible)\n                VALUES (\n                " . $course_id . ",\n                '" . $clean_post_title . "',\n                '" . Database::escape_string($values['post_text']) . "',\n                '" . Database::escape_string($last_thread_id) . "',\n                '" . Database::escape_string($values['forum_id']) . "',\n                '" . Database::escape_string($_user['user_id']) . "',\n                '" . Database::escape_string(stripslashes(isset($values['poster_name']) ? $values['poster_name'] : null)) . "',\n                '" . Database::escape_string($post_date) . "',\n                '" . Database::escape_string(isset($values['post_notification']) ? $values['post_notification'] : null) . "','0',\n                '" . Database::escape_string($visible) . "')";
        Database::query($sql);
        $last_post_id = Database::insert_id();
        // Now we have to update the thread table to fill the thread_last_post field (so that we know when the thread has been updated for the last time).
        $sql = "UPDATE {$table_threads} SET thread_last_post='" . Database::escape_string($last_post_id) . "'  WHERE c_id = {$course_id} AND thread_id='" . Database::escape_string($last_thread_id) . "'";
        $result = Database::query($sql);
        $message = get_lang('NewThreadStored');
        // Storing the attachments if any.
        if ($has_attachment) {
            $course_dir = $_course['path'] . '/upload/forum';
            $sys_course_path = api_get_path(SYS_COURSE_PATH);
            $updir = $sys_course_path . $course_dir;
            // Try to add an extension to the file if it hasn't one.
            $new_file_name = FileManager::add_ext_on_mime(stripslashes($_FILES['user_upload']['name']), $_FILES['user_upload']['type']);
            // User's file name
            $file_name = $_FILES['user_upload']['name'];
            if (!FileManager::filter_extension($new_file_name)) {
                Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
            } else {
                if ($result) {
                    $comment = Database::escape_string($comment);
                    add_forum_attachment_file($comment, $last_post_id);
                }
            }
        } else {
            $message .= '<br />';
        }
        if ($current_forum['approval_direct_post'] == '1' && !api_is_allowed_to_edit(null, true)) {
            $message .= get_lang('MessageHasToBeApproved') . '<br />';
            $message .= get_lang('ReturnTo') . ' <a href="viewforum.php?' . api_get_cidreq() . '&amp;forum=' . $values['forum_id'] . '&amp;gidReq=' . $_SESSION['toolgroup'] . '&amp;origin=' . $origin . '">' . get_lang('Forum') . '</a><br />';
        } else {
            $message .= get_lang('ReturnTo') . ' <a href="viewforum.php?' . api_get_cidreq() . '&amp;forum=' . $values['forum_id'] . '&amp;gidReq=' . $_SESSION['toolgroup'] . '&amp;origin=' . $origin . '">' . get_lang('Forum') . '</a><br />';
            $message .= get_lang('ReturnTo') . ' <a href="viewthread.php?' . api_get_cidreq() . '&amp;forum=' . $values['forum_id'] . '&amp;gidReq=' . $_SESSION['toolgroup'] . '&amp;origin=' . $origin . '&amp;gradebook=' . $gradebook . '&amp;thread=' . $last_thread_id . '">' . get_lang('Message') . '</a>';
        }
        $reply_info['new_post_id'] = $last_post_id;
        $my_post_notification = isset($values['post_notification']) ? $values['post_notification'] : null;
        if ($my_post_notification == 1) {
            set_notification('thread', $last_thread_id, true);
        }
        send_notification_mails($last_thread_id, $reply_info);
        Session::erase('formelements');
        Session::erase('origin');
        Session::erase('breadcrumbs');
        Session::erase('addedresource');
        Session::erase('addedresourceid');
        Display::display_confirmation_message($message, false);
    } else {
        Display::display_error_message(get_lang('UplNoFileUploaded'));
    }
}
 /**
  * updates the exercise in the data base
  *
  * @author - Olivier Brouckaert
  */
 public function save($type_e = '')
 {
     $_course = $this->course;
     $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
     $id = $this->id;
     $exercise = $this->exercise;
     $sound = $this->sound;
     $type = $this->type;
     $attempts = $this->attempts;
     $feedback_type = $this->feedback_type;
     $random = $this->random;
     $random_answers = $this->random_answers;
     $active = $this->active;
     $propagate_neg = $this->propagate_neg;
     $review_answers = isset($this->review_answers) && $this->review_answers ? 1 : 0;
     $randomByCat = $this->randomByCat;
     $text_when_finished = $this->text_when_finished;
     $display_category_name = intval($this->display_category_name);
     $pass_percentage = intval($this->pass_percentage);
     $session_id = api_get_session_id();
     // If direct we do not show results
     if ($feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) {
         $results_disabled = 0;
     } else {
         $results_disabled = intval($this->results_disabled);
     }
     $expired_time = intval($this->expired_time);
     if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
         $start_time = Database::escape_string(api_get_utc_datetime($this->start_time));
     } else {
         $start_time = '0000-00-00 00:00:00';
     }
     if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
         $end_time = Database::escape_string(api_get_utc_datetime($this->end_time));
     } else {
         $end_time = '0000-00-00 00:00:00';
     }
     // Exercise already exists
     if ($id) {
         $sql = "UPDATE {$TBL_EXERCICES} SET\n\t\t\t\t    title='" . Database::escape_string($exercise) . "',\n\t\t\t\t\tdescription='" . Database::escape_string($this->description) . "'";
         if ($type_e != 'simple') {
             $sql .= ",sound='" . Database::escape_string($sound) . "',\n\t\t\t\t\ttype           ='" . Database::escape_string($type) . "',\n\t\t\t\t\trandom         ='" . Database::escape_string($random) . "',\n\t\t\t\t\trandom_answers ='" . Database::escape_string($random_answers) . "',\n\t\t\t\t\tactive         ='" . Database::escape_string($active) . "',\n\t\t\t\t\tfeedback_type  ='" . Database::escape_string($feedback_type) . "',\n\t\t\t\t\tstart_time     = '{$start_time}',\n\t\t\t\t\tend_time       = '{$end_time}',\n\t\t\t\t\tmax_attempt    ='" . Database::escape_string($attempts) . "',\n     \t\t\t    expired_time   ='" . Database::escape_string($expired_time) . "',\n         \t\t\tpropagate_neg  ='" . Database::escape_string($propagate_neg) . "',\n         \t\t\treview_answers  ='" . Database::escape_string($review_answers) . "',\n        \t        random_by_category='" . Database::escape_string($randomByCat) . "',\n        \t        text_when_finished = '" . Database::escape_string($text_when_finished) . "',\n        \t        display_category_name = '" . Database::escape_string($display_category_name) . "',\n                    pass_percentage = '" . Database::escape_string($pass_percentage) . "',\n                    end_button = '" . $this->selectEndButton() . "',\n                    email_notification_template = '" . Database::escape_string($this->selectEmailNotificationTemplate()) . "',\n                    model_type = '" . $this->getModelType() . "',\n                    question_selection_type = '" . $this->getQuestionSelectionType() . "',\n                    hide_question_title = '" . $this->getHideQuestionTitle() . "',\n                    score_type_model = '" . $this->getScoreTypeModel() . "',\n                    global_category_id = '" . $this->getGlobalCategoryId() . "',\n\t\t\t\t\tresults_disabled='" . Database::escape_string($results_disabled) . "'";
         }
         $sql .= " WHERE iid = " . Database::escape_string($id) . " AND c_id = {$this->course_id}";
         Database::query($sql);
         // Update into the item_property table
         api_item_property_update($_course, TOOL_QUIZ, $id, 'QuizUpdated', api_get_user_id());
         if (api_get_setting('search_enabled') == 'true') {
             $this->search_engine_edit();
         }
     } else {
         // Creates a new exercise
         $sql = "INSERT INTO {$TBL_EXERCICES} (\n                        c_id, start_time, end_time, title, description, sound, type, random, random_answers, active,\n                        max_attempt, feedback_type, expired_time, session_id, review_answers, random_by_category,\n                        text_when_finished, display_category_name, pass_percentage, end_button, email_notification_template,\n                        results_disabled, model_type, question_selection_type, score_type_model, global_category_id, hide_question_title)\n\t\t\t\t\tVALUES(\n\t\t\t\t\t\t" . $this->course_id . ",\n\t\t\t\t\t\t'{$start_time}',\n                        '{$end_time}',\n\t\t\t\t\t\t'" . Database::escape_string($exercise) . "',\n\t\t\t\t\t\t'" . Database::escape_string($this->description) . "',\n\t\t\t\t\t\t'" . Database::escape_string($sound) . "',\n\t\t\t\t\t\t'" . Database::escape_string($type) . "',\n\t\t\t\t\t\t'" . Database::escape_string($random) . "',\n\t\t\t\t\t\t'" . Database::escape_string($random_answers) . "',\n\t\t\t\t\t\t'" . Database::escape_string($active) . "',\n\t\t\t\t\t\t'" . Database::escape_string($attempts) . "',\n\t\t\t\t\t\t'" . Database::escape_string($feedback_type) . "',\n\t\t\t\t\t\t'" . Database::escape_string($expired_time) . "',\n\t\t\t\t\t\t'" . Database::escape_string($session_id) . "',\n\t\t\t\t\t\t'" . Database::escape_string($review_answers) . "',\n\t\t\t\t\t\t'" . Database::escape_string($randomByCat) . "',\n\t\t\t\t\t\t'" . Database::escape_string($text_when_finished) . "',\n\t\t\t\t\t\t'" . Database::escape_string($display_category_name) . "',\n                        '" . Database::escape_string($pass_percentage) . "',\n                        '" . Database::escape_string($this->selectEndButton()) . "',\n                        '" . Database::escape_string($this->selectEmailNotificationTemplate()) . "',\n                        '" . Database::escape_string($results_disabled) . "',\n                        '" . Database::escape_string($this->getModelType()) . "',\n                        '" . Database::escape_string($this->getQuestionSelectionType()) . "',\n                        '" . Database::escape_string($this->getScoreTypeModel()) . "',\n                        '" . Database::escape_string($this->getGlobalCategoryId()) . "',\n                        '" . Database::escape_string($this->getHideQuestionTitle()) . "'\n\t\t\t\t\t\t)";
         Database::query($sql);
         $this->id = Database::insert_id();
         $this->addExerciseToOrderTable();
         // insert into the item_property table
         api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizAdded', api_get_user_id());
         api_set_default_visibility($this->course, $this->id, TOOL_QUIZ);
         if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
             $this->search_engine_save();
         }
     }
     $this->save_categories_in_exercise($this->categories);
     // Updates the question position.
     $this->update_question_positions();
 }
Example #13
0
/**
 * Used to add a link or a category
 * @param string $type, "link" or "category"
 * @todo replace strings by constants
 * @author Patrick Cool <*****@*****.**>, Ghent University
 */
function addlinkcategory($type)
{
    global $catlinkstatus;
    global $msgErr;
    $ok = true;
    $course_id = api_get_course_int_id();
    $courseInfo = api_get_course_info();
    if ($type == 'link') {
        $tbl_link = Database::get_course_table(TABLE_LINK);
        $title = Security::remove_XSS(stripslashes($_POST['title']));
        $urllink = Security::remove_XSS($_POST['urllink']);
        $description = Security::remove_XSS($_POST['description']);
        $selectcategory = Security::remove_XSS($_POST['selectcategory']);
        if ($_POST['onhomepage'] == '') {
            $onhomepage = 0;
        } else {
            $onhomepage = Security::remove_XSS($_POST['onhomepage']);
        }
        if (empty($_POST['target_link'])) {
            $target = '_self';
            // Default target.
        } else {
            $target = Security::remove_XSS($_POST['target_link']);
        }
        $urllink = trim($urllink);
        $title = trim($title);
        $description = trim($description);
        // We ensure URL to be absolute.
        if (strpos($urllink, '://') === false) {
            $urllink = 'http://' . $urllink;
        }
        // If the title is empty, we use the URL as title.
        if ($title == '') {
            $title = $urllink;
        }
        // If the URL is invalid, an error occurs.
        // Ivan, 13-OCT-2010, Chamilo 1.8.8: Let us still tolerate PHP 5.1.x and avoid a specific bug in filter_var(), see http://bugs.php.net/51192
        //if (!filter_var($urllink, FILTER_VALIDATE_URL)) {
        if (!api_valid_url($urllink, true)) {
            // A check against an absolute URL
            $msgErr = get_lang('GiveURL');
            Display::display_error_message(get_lang('GiveURL'));
            $ok = false;
        } else {
            // Looking for the largest order number for this category.
            $result = Database::query("SELECT MAX(display_order) FROM  " . $tbl_link . " WHERE c_id = {$course_id} AND category_id = '" . intval($_POST['selectcategory']) . "'");
            list($orderMax) = Database::fetch_row($result);
            $order = $orderMax + 1;
            $session_id = api_get_session_id();
            $sql = "INSERT INTO " . $tbl_link . " (c_id, url, title, description, category_id, display_order, on_homepage, target, session_id)\n\t\t\t        VALUES (" . $course_id . ", '" . Database::escape_string($urllink) . "','" . Database::escape_string($title) . "','" . Database::escape_string($description) . "','" . Database::escape_string($selectcategory) . "','" . Database::escape_string($order) . "', '" . Database::escape_string($onhomepage) . "','" . Database::escape_string($target) . "','" . Database::escape_string($session_id) . "')";
            $catlinkstatus = get_lang('LinkAdded');
            Database::query($sql);
            $link_id = Database::insert_id();
            if ($link_id) {
                api_set_default_visibility($courseInfo, $link_id, TOOL_LINK);
            }
            if (api_get_setting('search_enabled') == 'true' && $link_id && extension_loaded('xapian')) {
                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';
                $course_int_id = api_get_course_int_id();
                $courseid = api_get_course_id();
                $specific_fields = get_specific_field_list();
                $ic_slide = new IndexableChunk();
                // Add all terms to db.
                $all_specific_terms = '';
                foreach ($specific_fields as $specific_field) {
                    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'], $courseid, TOOL_LINK, $link_id, $sterm);
                            }
                        }
                    }
                }
                // Build the chunk to index.
                $ic_slide->addValue('title', $title);
                $ic_slide->addCourseId($courseid);
                $ic_slide->addToolId(TOOL_LINK);
                $xapian_data = array(SE_COURSE_ID => $courseid, 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);
                $description = $all_specific_terms . ' ' . $description;
                $ic_slide->addValue('content', $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->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 (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, $courseid, TOOL_LINK, $link_id, $did);
                    Database::query($sql);
                }
            }
            unset($urllink, $title, $description, $selectcategory);
            Display::display_confirmation_message(get_lang('LinkAdded'));
        }
    } elseif ($type == 'category') {
        $tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
        $category_title = trim($_POST['category_title']);
        $description = trim($_POST['description']);
        if (empty($category_title)) {
            $msgErr = get_lang('GiveCategoryName');
            Display::display_error_message(get_lang('GiveCategoryName'));
            $ok = false;
        } else {
            // Looking for the largest order number for this category.
            $result = Database::query("SELECT MAX(display_order) FROM  " . $tbl_categories . " WHERE c_id = {$course_id} ");
            list($orderMax) = Database::fetch_row($result);
            $order = $orderMax + 1;
            $order = intval($order);
            $session_id = api_get_session_id();
            $sql = "INSERT INTO " . $tbl_categories . " (c_id, category_title, description, display_order, session_id)\n\t\t\t        VALUES (" . $course_id . ", '" . Database::escape_string($category_title) . "', '" . Database::escape_string($description) . "', '{$order}', '{$session_id}')";
            Database::query($sql);
            $catlinkstatus = get_lang('CategoryAdded');
            unset($category_title, $description);
            Display::display_confirmation_message(get_lang('CategoryAdded'));
        }
    }
    // "WHAT'S NEW" notification : update last tool Edit.
    if ($type == 'link') {
        global $_user;
        $_course = api_get_course_info();
        global $nameTools;
        api_item_property_update($_course, TOOL_LINK, $link_id, 'LinkAdded', $_user['user_id']);
    }
    return $ok;
}