function fixDocumentNameCallback($p_event, &$p_header)
{
    global $remove_dir;
    $files = Session::read('doc_files_to_download');
    $storedFile = $remove_dir . $p_header['stored_filename'];
    if (!isset($files[$storedFile])) {
        return 0;
    }
    $documentData = $files[$storedFile];
    $documentNameFixed = DocumentManager::undoFixDocumentName($documentData['path'], $documentData['c_id'], $documentData['session_id'], $documentData['to_group_id']);
    // Changes file.phps to file.php
    $basename = basename($documentNameFixed);
    $basenamePHPFixed = str_replace('.phps', '.php', $basename);
    $documentNameFixed = str_replace($basename, $basenamePHPFixed, $documentNameFixed);
    if ($remove_dir != '/') {
        $documentNameFixed = str_replace($remove_dir, '/', $documentNameFixed);
        if (substr($documentNameFixed, 0, 1) == '/') {
            $documentNameFixed = substr($documentNameFixed, 1, api_strlen($documentNameFixed));
        }
    } else {
        $documentNameFixed = ltrim($documentNameFixed, '/');
    }
    $p_header['stored_filename'] = $documentNameFixed;
    return 1;
}
/**
 * FUNCTIONS
 */
function unset_session_resources()
{
    $_SESSION['addedresource'] = '';
    $_SESSION['addedresourceid'] = '';
    Session::erase('addedresource');
    Session::erase('addedresourceid');
}
 /**
  * Create a Shibboleth session for the user ID
  *
  * @param  string $uid - The user ID
  * @return $_user (array) - The user infos array created when the user logs in
  */
 function login($uid)
 {
     /* This must be set for local.inc.php to register correctly the global variables in session
      * This is BAD. Logic should be migrated into a function and stop relying on global variables.
      */
     global $_uid, $is_allowedCreateCourse, $_real_cid, $_courseUser;
     global $is_courseMember, $is_courseTutor, $is_allowed_in_course, $_gid;
     $_uid = $uid;
     //is_allowedCreateCourse
     $user = User::store()->get_by_user_id($uid);
     if (empty($user)) {
         return;
     }
     $this->logout();
     Chamilo::session()->start();
     Session::write('_uid', $_uid);
     global $_user;
     $_user = (array) $user;
     $_SESSION['_user'] = $_user;
     $_SESSION['_user']['user_id'] = $_uid;
     $_SESSION['noredirection'] = true;
     //must be called before 'init_local.inc.php'
     event_login();
     //used in 'init_local.inc.php' this is BAD but and should be changed
     $loginFailed = false;
     $uidReset = true;
     $gidReset = true;
     $cidReset = false;
     //FALSE !!
     $mainDbName = Database::get_main_database();
     $includePath = api_get_path(INCLUDE_PATH);
     $no_redirection = true;
     require "{$includePath}/local.inc.php";
     return $_user;
 }
 /**
  * @param Application $app
  * @param string $type courses|sessions|mycoursecategories
  * @param string $filter for the userportal courses page. Only works when setting 'history'
  * @param int $page
  *
  * @return Response|void
  */
 public function indexAction(Application $app, $type = 'courses', $filter = 'current', $page = 1)
 {
     // @todo Use filters like "after/before|finish" to manage user access
     api_block_anonymous_users();
     // Abort request because the user is not allowed here - @todo use filters
     if ($app['allowed'] == false) {
         return $app->abort(403, 'Not allowed');
     }
     // Main courses and session list
     $items = null;
     $type = str_replace('/', '', $type);
     /** @var \PageController $pageController */
     $pageController = $app['page_controller'];
     switch ($type) {
         case 'sessions':
             $items = $pageController->returnSessions(api_get_user_id(), $filter, $page);
             break;
         case 'sessioncategories':
             $items = $pageController->returnSessionsCategories(api_get_user_id(), $filter, $page);
             break;
         case 'courses':
             $items = $pageController->returnCourses(api_get_user_id(), $filter, $page);
             break;
         case 'mycoursecategories':
             $items = $pageController->returnMyCourseCategories(api_get_user_id(), $filter, $page);
             break;
         case 'specialcourses':
             $items = $pageController->returnSpecialCourses(api_get_user_id(), $filter, $page);
             break;
     }
     //Show the chamilo mascot
     if (empty($items) && empty($filter)) {
         $pageController->return_welcome_to_course_block($app['template']);
     }
     /*
             $app['my_main_menu'] = function($app) {
                 $menu = $app['knp_menu.factory']->createItem('root');
                 $menu->addChild('Home', array('route' => api_get_path(WEB_CODE_PATH)));
                 return $menu;
             };
             $app['knp_menu.menus'] = array('main' => 'my_main_menu');*/
     $app['template']->assign('content', $items);
     $pageController->setCourseSessionMenu();
     $pageController->setProfileBlock();
     $pageController->setUserImageBlock();
     $pageController->setCourseBlock($filter);
     $pageController->setSessionBlock();
     $pageController->return_reservation_block();
     $pageController->returnNavigationLinks($app['template']->getNavigationLinks());
     $app['template']->assign('search_block', $pageController->return_search_block());
     $app['template']->assign('classes_block', $pageController->return_classes_block());
     $pageController->returnSkillsLinks();
     // Deleting the session_id.
     Session::erase('session_id');
     $response = $app['template']->render_template('userportal/index.tpl');
     return new Response($response, 200, array());
 }
 /**
  * @param Request $request
  * @return null|RedirectResponse
  */
 public function onLogoutSuccess(Request $request)
 {
     $session = $request->getSession();
     \ChamiloSession::setSession($session);
     // Chamilo logout
     $userId = api_get_user_id();
     \Online::logout($userId, false);
     $login = $this->router->generate('index');
     $response = new RedirectResponse($login);
     return $response;
 }
 /**
  * Fired on switch user, you can remove attributes or whatever you want here.
  * @param SwitchUserEvent $event
  */
 public function onSecuritySwitchUser(SwitchUserEvent $event)
 {
     /** @var \Entity\User $user */
     $user = $event->getTargetUser();
     /*var_dump($user );
       var_dump($event->getRequest()->getUser());
       */
     $request = $event->getRequest();
     $session = $request->getSession();
     \ChamiloSession::setSession($session);
     $session = $event->getRequest()->getSession();
     //$session->remove('partThatShouldNotCarryOver');
 }
 /**
  * @return \Symfony\Component\HttpKernel\HttpKernel
  */
 public function createApplication()
 {
     // do not use require_once
     $app = (require __DIR__ . '/../../main/inc/global.inc.php');
     $app['debug'] = true;
     $app['session.test'] = true;
     $app['exception_handler']->disable();
     // Setting session obj for old libraries
     \ChamiloSession::setSession($app['session']);
     \UserManager::setEntityManager($app['orm.em']);
     //$app['monolog'] = $this->getMock('Monolog\Logger');
     return $app;
 }
Esempio n. 8
0
 /**
  * Displays info stating that the message is sent successfully.
  * @deprecated
  */
 public static function display_success_message($uid)
 {
     $socialExist = Session::read('social_exist');
     $userInfo = api_get_user_info($uid);
     if (isset($socialExist) && $socialExist === true) {
         if (api_get_setting('social.allow_social_tool') == 'true' && api_get_setting('message.allow_message_tool') == 'true') {
             $success = get_lang('MessageSentTo') . "&nbsp;<b>" . $userInfo['complete_name'] . "</b>";
         } else {
             $success = get_lang('MessageSentTo') . "&nbsp;<b>" . $userInfo['complete_name'] . "</b>";
         }
     } else {
         $success = get_lang('MessageSentTo') . "&nbsp;<b>" . $userInfo['complete_name'] . "</b>";
     }
     return Display::return_message(api_xml_http_response_encode($success), 'confirmation', false);
 }
 /**
  * @param Application $app
  * @param int $exerciseId
  * @param int $questionId
  * @return Response
  */
 public function reuseQuestionAction(Application $app, $exerciseId, $questionId)
 {
     /** @var \Question $question */
     $question = \Question::read($questionId);
     if ($question) {
         // adds the exercise ID represented by $fromExercise into the list of exercises for the current question
         $question->addToList($exerciseId);
         $objExercise = new \Exercise();
         $objExercise->read($exerciseId);
         // adds the question ID represented by $recup into the list of questions for the current exercise
         $objExercise->addToList($exerciseId);
         Session::write('objExercise', $objExercise);
         /*$params = array(
               'cidReq' => api_get_course_id(),
               'id_session' => api_get_session_id(),
               'id' => $questionId,
               'exerciseId' => $exerciseId
           );
           $url = $app['url_generator']->generate('exercise_question_pool', $params);
           return $app->redirect($url);*/
         $response = \Display::return_message(get_lang('QuestionReused') . ": " . $question->question);
         return new Response($response, 200, array());
     }
 }
 /**
  * Search for a session based on a given search string
  * @param string A search string
  * @param string A search box type (single or anything else)
  * @return string XajaxResponse
  * @assert () !== ''
  * @assert ('abc','single') !== ''
  */
 function search_courses($needle, $type)
 {
     $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
     $xajax_response = new xajaxResponse();
     $return = '';
     if (!empty($needle) && !empty($type)) {
         // xajax send utf8 datas... datas in db can be non-utf8 datas
         $charset = api_get_system_encoding();
         $needle = api_convert_encoding($needle, $charset, 'utf-8');
         $needle = Database::escape_string($needle);
         $sql = 'SELECT * FROM ' . $tbl_session . ' WHERE name LIKE "' . $needle . '%" ORDER BY id';
         $rs = Database::query($sql);
         $course_list = array();
         $return .= '<select id="origin" name="NoSessionCategoryList[]" multiple="multiple" size="20" style="width:340px;">';
         while ($course = Database::fetch_array($rs)) {
             $course_list[] = $course['id'];
             $return .= '<option value="' . $course['id'] . '" title="' . htmlspecialchars($course['name'], ENT_QUOTES) . '">' . $course['name'] . '</option>';
         }
         $return .= '</select>';
         $xajax_response->addAssign('ajax_list_courses_multiple', 'innerHTML', api_utf8_encode($return));
     }
     Session::write('course_list', $course_list);
     return $xajax_response;
 }
Esempio n. 11
0
 case 'delete':
     if (!$is_allowed_to_edit) {
         api_not_allowed(true);
     }
     if ($debug > 0) {
         error_log('New LP - delete action triggered', 0);
     }
     if (!$lp_found) {
         error_log('New LP - No learnpath given for delete', 0);
         require 'lp_list.php';
     } else {
         $_SESSION['refresh'] = 1;
         // Remove lp from homepage if it is there.
         //$_SESSION['oLP']->toggle_visibility((int)$_GET['lp_id'],'i');
         $_SESSION['oLP']->delete(null, (int) $_GET['lp_id'], 'remove');
         Session::erase('oLP');
         require 'lp_list.php';
     }
     break;
 case 'toggle_visible':
     // Change lp visibility (inside lp tool).
     if (!$is_allowed_to_edit) {
         api_not_allowed(true);
     }
     if ($debug > 0) {
         error_log('New LP - visibility action triggered', 0);
     }
     if (!$lp_found) {
         error_log('New LP - No learnpath given for visibility', 0);
         require 'lp_list.php';
     } else {
    $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
    $sql_fraud = "UPDATE $TBL_TRACK_ATTEMPT SET answer = 0, marks = 0, position = 0 WHERE exe_id = $exe_id ";
    Database::query($sql_fraud);
}*/
// Unset session for clock time.
ExerciseLib::exercise_time_control_delete($objExercise->id, $learnpath_id, $learnpath_item_id);
ExerciseLib::delete_chat_exercise_session($exe_id);
if ($origin != 'learnpath') {
    echo '<hr>';
    echo $objExercise->returnEndButtonHTML();
    if (api_is_allowed_to_session_edit()) {
        Session::erase('objExercise');
        Session::erase('exe_id');
        Session::erase('categoryList');
        Session::erase('question_list_flatten');
    }
    Display::display_footer();
} else {
    $lp_mode = $_SESSION['lp_mode'];
    $url = api_get_path(WEB_CODE_PATH) . 'newscorm/lp_controller.php?cidReq=' . api_get_course_id() . '&action=view&lp_id=' . $learnpath_id . '&lp_item_id=' . $learnpath_item_id . '&exeId=' . $exercise_stat_info['exe_id'] . '&fb_type=' . $objExercise->feedback_type;
    $href = $lp_mode == 'fullscreen' ? ' window.opener.location.href="' . $url . '" ' : ' top.location.href="' . $url . '"';
    if (api_is_allowed_to_session_edit()) {
        Session::erase('objExercise');
        Session::erase('exe_id');
        Session::erase('categoryList');
    }
    // Record the results in the learning path, using the SCORM interface (API)
    echo "<script>window.parent.API.void_save_asset('{$total_score}', '{$total_weight}', 0, 'completed');</script>";
    echo '<script type="text/javascript">' . $href . '</script>';
    echo '</body></html>';
}
Esempio n. 13
0
        api_not_allowed();
    }
}
/* Header and Breadcrumbs */
$my_search = isset($_GET['search']) ? $_GET['search'] : '';
$my_action = isset($_GET['action']) ? $_GET['action'] : '';
$gradebook = null;
if (isset($_SESSION['gradebook'])) {
    $gradebook = $_SESSION['gradebook'];
}
if (!empty($gradebook) && $gradebook == 'view') {
    $interbreadcrumb[] = array('url' => '../gradebook/' . $_SESSION['gradebook_dest'], 'name' => get_lang('ToolGradebook'));
}
if (!empty($_GET['gidReq'])) {
    $toolgroup = Database::escape_string($_GET['gidReq']);
    Session::write('toolgroup', $toolgroup);
}
$forumUrl = api_get_path(WEB_CODE_PATH) . 'forum/';
if ($origin == 'group') {
    $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH) . 'group/group.php', 'name' => get_lang('Groups'));
    $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH) . 'group/group_space.php?' . api_get_cidreq(), 'name' => get_lang('GroupSpace') . ' ' . $group_properties['name']);
    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Forum') . ' ' . Security::remove_XSS($current_forum['forum_title']));
} else {
    $interbreadcrumb[] = array('url' => $forumUrl . 'index.php?search=' . Security::remove_XSS($my_search), 'name' => get_lang('ForumCategories'));
    $interbreadcrumb[] = array('url' => $forumUrl . 'viewforumcategory.php?forumcategory=' . $current_forum_category['cat_id'] . '&amp;search=' . Security::remove_XSS(urlencode($my_search)), 'name' => prepare4display($current_forum_category['cat_title']));
    $interbreadcrumb[] = array('url' => '#', 'name' => Security::remove_XSS($current_forum['forum_title']));
}
if ($origin == 'learnpath') {
    Display::display_reduced_header();
} else {
    // The last element of the breadcrumb navigation is already set in interbreadcrumb, so give empty string.
Esempio n. 14
0
$(function() {
<?php 
// grid definition see the $career->display() function
echo Display::grid_js('careers', $url, $columns, $column_model, $extra_params, array(), $action_links, true);
?>
});
</script>
<?php 
$career = new Career();
// Action handling: Add
switch ($action) {
    case 'add':
        if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
            api_not_allowed();
        }
        Session::write('notebook_view', 'creation_date');
        $url = api_get_self() . '?action=' . Security::remove_XSS($_GET['action']);
        $form = $career->return_form($url, 'add');
        // The validation or display
        if ($form->validate()) {
            if ($check) {
                $values = $form->exportValues();
                $res = $career->save($values);
                if ($res) {
                    Display::display_confirmation_message(get_lang('ItemAdded'));
                }
            }
            $career->display();
        } else {
            echo '<div class="actions">';
            echo '<a href="' . api_get_self() . '">' . Display::return_icon('back.png', get_lang('Back'), '', ICON_SIZE_MEDIUM) . '</a>';
 /**
  * function which redefines Question::createAnswersForm
  * @param FormValidator $form
  */
 public function createAnswersForm($form)
 {
     $nb_answers = isset($_POST['nb_answers']) ? $_POST['nb_answers'] : 4;
     $nb_answers += isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0);
     $obj_ex = Session::read('objExercise');
     /* Mise en variable de Affichage "Reponses" et son icone, "N�", "Vrai", "Reponse" */
     $html = '<table class="data_table">
             <tr>
                 <th width="10px">
                     ' . get_lang('Number') . '
                 </th>
                 <th width="10px">
                     ' . get_lang('True') . '
                 </th>
                 <th width="50%">
                     ' . get_lang('Answer') . '
                 </th>';
     $html .= '<th>' . get_lang('Comment') . '</th>';
     $html .= '</tr>';
     $form->addElement('label', get_lang('Answers') . '<br /> <img src="../img/fill_field.png">', $html);
     $defaults = array();
     $correct = 0;
     $answer = false;
     if (!empty($this->id)) {
         $answer = new Answer($this->id);
         $answer->read();
         if (count($answer->nbrAnswers) > 0 && !$form->isSubmitted()) {
             $nb_answers = $answer->nbrAnswers;
         }
     }
     #le nombre de r�ponses est bien enregistr� sous la forme int(nb)
     /* Ajout mise en forme nb reponse */
     $form->addElement('hidden', 'nb_answers');
     $boxes_names = array();
     /* V�rification : Cr�action d'au moins une r�ponse */
     if ($nb_answers < 1) {
         $nb_answers = 1;
         Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
     }
     //D�but affichage score global dans la modification d'une question
     $scoreA = "0";
     //par reponse
     $scoreG = "0";
     //Global
     /* boucle pour sauvegarder les donn�es dans le tableau defaults */
     for ($i = 1; $i <= $nb_answers; ++$i) {
         /* si la reponse est de type objet */
         if (is_object($answer)) {
             $defaults['answer[' . $i . ']'] = $answer->answer[$i];
             $defaults['comment[' . $i . ']'] = $answer->comment[$i];
             $defaults['correct[' . $i . ']'] = $answer->correct[$i];
             // start
             $scoreA = $answer->weighting[$i];
         }
         if ($scoreA > 0) {
             $scoreG = $scoreG + $scoreA;
         }
         //------------- Fin
         //------------- Debut si un des scores par reponse est egal � 0 : la coche vaut 1 (coch�)
         if ($scoreA == 0) {
             $defaults['pts'] = 1;
         }
         $renderer =& $form->defaultRenderer();
         $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct[' . $i . ']');
         $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter[' . $i . ']');
         $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer[' . $i . ']');
         $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment[' . $i . ']');
         //$renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']');
         $answer_number = $form->addElement('text', 'counter[' . $i . ']', null, 'value="' . $i . '"');
         $answer_number->freeze();
         $form->addElement('checkbox', 'correct[' . $i . ']', null, null, 'class="checkbox"');
         $boxes_names[] = 'correct[' . $i . ']';
         $form->addHtmlEditor('answer[' . $i . ']', null, null, array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '100'));
         $form->addRule('answer[' . $i . ']', get_lang('ThisFieldIsRequired'), 'required');
         $form->addHtmlEditor('comment[' . $i . ']', null, null, array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '100'));
         $form->addElement('html', '</tr>');
     }
     //--------- Mise en variable du score global lors d'une modification de la question/r�ponse
     $defaults['weighting[1]'] = round($scoreG);
     $form->addElement('html', '</div></div></table>');
     //$form -> addElement ('html', '<br />');
     $form->add_multiple_required_rule($boxes_names, get_lang('ChooseAtLeastOneCheckbox'), 'multiple_required');
     //only 1 answer the all deal ...
     $form->addElement('text', 'weighting[1]', get_lang('Score'));
     global $pts;
     //--------- Creation coche pour ne pas prendre en compte les n�gatifs
     $form->addElement('checkbox', 'pts', '', get_lang('NoNegativeScore'));
     $form->addElement('html', '<br />');
     // Affiche un message si le score n'est pas renseign�
     $form->addRule('weighting[1]', get_lang('ThisFieldIsRequired'), 'required');
     global $text, $class;
     if ($obj_ex->edit_exercise_in_lp == true) {
         $form->addButtonDelete(get_lang('LessAnswer'), 'lessAnswers');
         $form->addButtonCreate(get_lang('PlusAnswer'), 'moreAnswers');
         $form->addButtonSave($text, 'submitQuestion');
         // setting the save button here and not in the question class.php
     }
     $renderer->setElementTemplate('{element}&nbsp;', 'lessAnswers');
     $renderer->setElementTemplate('{element}&nbsp;', 'submitQuestion');
     $renderer->setElementTemplate('{element}', 'moreAnswers');
     $form->addElement('html', '</div></div>');
     $defaults['correct'] = $correct;
     if (!empty($this->id)) {
         $form->setDefaults($defaults);
     } else {
         if ($this->isContent == 1) {
             $form->setDefaults($defaults);
         }
     }
     $form->setConstants(array('nb_answers' => $nb_answers));
 }
Esempio n. 16
0
$form_count = 0;
if (api_is_allowed_to_edit(false, true)) {
    //if is called from a learning path lp_id
    $lp_id = isset($_REQUEST['lp_id']) ? intval($_REQUEST['lp_id']) : null;
    handle_forum_and_forumcategories($lp_id);
}
// Notification
if ($actions == 'notify' && isset($_GET['content']) && isset($_GET['id'])) {
    if (api_get_session_id() != 0 && api_is_allowed_to_session_edit(false, true) == false) {
        api_not_allowed();
    }
    $return_message = set_notification($_GET['content'], $_GET['id']);
    Display::display_confirmation_message($return_message, false);
}
get_whats_new();
$whatsnew_post_info = Session::read('whatsnew_post_info');
/* TRACKING */
Event::event_access_tool(TOOL_FORUM);
/*
    RETRIEVING ALL THE FORUM CATEGORIES AND FORUMS
    note: we do this here just after het handling of the actions to be
    sure that we already incorporate the latest changes
*/
// Step 1: We store all the forum categories in an array $forum_categories.
$forumCategories = get_forum_categories();
// Step 2: We find all the forums (only the visible ones if it is a student).
// display group forum in general forum tool depending to configuration option
$setting = api_get_setting('display_groups_forum_in_general_tool');
$forum_list = get_forums('', '', $setting == 'true');
$user_id = api_get_user_id();
/* RETRIEVING ALL GROUPS AND THOSE OF THE USER */
Esempio n. 17
0
$this_section = SECTION_COURSES;
$current_course_tool = TOOL_COURSE_MAINTENANCE;
api_protect_course_script(true);
$_course = api_get_course_info();
$current_course_code = $_course['official_code'];
$current_course_name = $_course['name'];
if (!api_is_allowed_to_edit()) {
    api_not_allowed(true);
}
$tool_name = get_lang('DelCourse');
if (isset($_GET['delete']) && $_GET['delete'] == 'yes') {
    CourseManager::delete_course($_course['sysCode']);
    $obj_cat = new Category();
    $obj_cat->update_category_delete($_course['sysCode']);
    // DELETE CONFIRMATION MESSAGE
    Session::erase('_cid');
    Session::erase('_real_cid');
    $noPHP_SELF = true;
    $message = '<h2>' . get_lang('Course') . ' : ' . $current_course_name . ' (' . $current_course_code . ') </h2>';
    $message .= get_lang('HasDel');
    $message .= '<br /><br /><a href="../../index.php">' . get_lang('BackHome') . ' ' . api_get_setting('platform.site_name') . '</a>';
} else {
    $message = '<h3>' . get_lang('Course') . ' : ' . $current_course_name . ' (' . $current_course_code . ') </h3>';
    $message .= '<p>' . get_lang('ByDel') . '</p>';
    $message .= '<p><a class="btn btn-primary" href="' . api_get_path(WEB_CODE_PATH) . 'course_info/maintenance.php?' . api_get_cidreq() . '">' . get_lang('No') . '</a>&nbsp;<a class="btn" href="' . api_get_self() . '?delete=yes&' . api_get_cidreq() . '">' . get_lang('Yes') . '</a></p>';
    $interbreadcrumb[] = array('url' => 'maintenance.php', 'name' => get_lang('Maintenance'));
}
Display::display_header($tool_name, 'Settings');
echo Display::page_header($tool_name);
Display::display_warning_message($message, false);
Display::display_footer();
Esempio n. 18
0
if (!empty($exercise_stat_info)) {
    $total_score = $exercise_stat_info['exe_result'];
}
$max_score = $objExercise->get_max_score();
Display::display_normal_message(get_lang('Saved') . '<br />', false);
// Display and save questions
ExerciseLib::display_question_list_by_attempt($objExercise, $exe_id, true);
//Unset session for clock time
ExerciseLib::exercise_time_control_delete($objExercise->id, $learnpath_id, $learnpath_item_id);
ExerciseLib::delete_chat_exercise_session($exe_id);
if ($origin != 'learnpath') {
    echo '<hr>';
    echo Display::url(get_lang('ReturnToCourseHomepage'), api_get_course_url(), array('class' => 'btn btn-primary'));
    if (api_is_allowed_to_session_edit()) {
        Session::erase('objExercise');
        Session::erase('exe_id');
    }
    Display::display_footer();
} else {
    $lp_mode = Session::read('lp_mode');
    $url = '../newscorm/lp_controller.php?cidReq=' . api_get_course_id() . '&action=view&lp_id=' . $learnpath_id . '&lp_item_id=' . $learnpath_item_id . '&exeId=' . $exercise_stat_info['exe_id'] . '&fb_type=' . $objExercise->feedback_type;
    $href = $lp_mode == 'fullscreen' ? ' window.opener.location.href="' . $url . '" ' : ' top.location.href="' . $url . '"';
    if (api_is_allowed_to_session_edit()) {
        Session::erase('objExercise');
        Session::erase('exe_id');
    }
    // Record the results in the learning path, using the SCORM interface (API)
    echo "<script>window.parent.API.void_save_asset('{$total_score}', '{$max_score}', 0, 'completed');</script>";
    echo '<script type="text/javascript">' . $href . '</script>';
    echo '</body></html>';
}
Esempio n. 19
0
 /**
  * Get all the data of a glossary
  *
  * @param integer From which item
  * @param integer Number of items to collect
  * @param string  Name of column on which to order
  * @param string  Whether to sort in ascending (ASC) or descending (DESC)
  * @return unknown
  *
  * @author Patrick Cool <*****@*****.**>
  * @author Julio Montoya fixing this function, adding intvals
  * @version januari 2009, dokeos 1.8.6
  */
 public static function get_glossary_data($from, $number_of_items, $column, $direction)
 {
     $_user = api_get_user_info();
     // Database table definition
     $t_glossary = Database::get_course_table(TABLE_GLOSSARY);
     $t_item_propery = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $glossaryView = Session::read('glossary_view');
     if (api_is_allowed_to_edit(null, true)) {
         $col2 = " glossary.glossary_id\tas col2, ";
     } else {
         $col2 = " ";
     }
     //condition for the session
     $session_id = api_get_session_id();
     $condition_session = api_get_session_condition($session_id, true, true, 'glossary.session_id');
     $column = intval($column);
     if (!in_array($direction, array('DESC', 'ASC'))) {
         $direction = 'ASC';
     }
     $from = intval($from);
     $number_of_items = intval($number_of_items);
     $sql = "SELECT\n                    glossary.name \t\t\tas col0,\n\t\t\t\t\tglossary.description \tas col1,\n\t\t\t\t\t{$col2}\n\t\t\t\t\tglossary.session_id\n\t\t\t\tFROM {$t_glossary} glossary, {$t_item_propery} ip\n\t\t\t\tWHERE\n\t\t\t\t    glossary.glossary_id = ip.ref AND\n\t\t\t\t\ttool = '" . TOOL_GLOSSARY . "' {$condition_session} AND\n\t\t\t\t\tglossary.c_id = " . api_get_course_int_id() . " AND\n\t\t\t\t\tip.c_id = " . api_get_course_int_id() . "\n\t\t        ORDER BY col{$column} {$direction}\n\t\t        LIMIT {$from},{$number_of_items}";
     $res = Database::query($sql);
     $return = array();
     $array = array();
     while ($data = Database::fetch_array($res)) {
         // Validation when belongs to a session
         $session_img = api_get_session_image($data['session_id'], $_user['status']);
         $array[0] = $data[0] . $session_img;
         if (!$glossaryView || $glossaryView == 'table') {
             $array[1] = str_replace(array('<p>', '</p>'), array('', '<br />'), $data[1]);
         } else {
             $array[1] = $data[1];
         }
         if (api_is_allowed_to_edit(null, true)) {
             $array[2] = $data[2];
         }
         $return[] = $array;
     }
     return $return;
 }
Esempio n. 20
0
                        //Reading Answers obj of the current course
                        $new_answer_obj = new Answer($old_question_id, $origin_course_id);
                        $new_answer_obj->read();
                        //Duplicating the Answers in the current course
                        $new_answer_obj->duplicate($new_id, $current_course);
                        // destruction of the Question object
                        unset($new_question_obj);
                        unset($old_question_obj);
                        if (!$objExercise instanceof Exercise) {
                            $objExercise = new Exercise();
                            $objExercise->read($fromExercise);
                        }
                    }
                }
            }
            Session::write('objExercise', $objExercise);
        }
    }
}
if (isset($_SESSION['gradebook'])) {
    $gradebook = $_SESSION['gradebook'];
}
if (!empty($gradebook) && $gradebook == 'view') {
    $interbreadcrumb[] = array('url' => '../gradebook/' . Security::remove_XSS($_SESSION['gradebook_dest']), 'name' => get_lang('ToolGradebook'));
}
// if admin of course
if (!$is_allowedToEdit) {
    api_not_allowed(true);
}
$confirmYourChoice = addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset));
$htmlHeadXtra[] = "\n<script>\n\tfunction submit_form(obj) {\n\t\tdocument.question_pool.submit();\n\t}\n\n\tfunction mark_course_id_changed() {\n\t\t\$('#course_id_changed').val('1');\n\t}\n\n\tfunction mark_exercice_id_changed() {\n\t\t\$('#exercice_id_changed').val('1');\n\t}\n\n\tfunction confirm_your_choice() {\n\t\treturn confirm('{$confirmYourChoice}');\n\t}\n</script>";
 /**
  * Returns the current user (logged in user) relationship with the course.
  * I.e his role
  * 
  * @return array
  */
 public function user()
 {
     $result = Session::read('_courseUser');
     $result = $result ? $result : array();
     return $result;
 }
Esempio n. 22
0
$url = api_get_course_url($course_code, $session_id);
if ($form->validate()) {
    $accept_legal = $form->exportValue('accept_legal');
    if ($accept_legal == 1) {
        CourseManager::save_user_legal($user_id, $course_code, $session_id);
        if (api_check_user_access_to_legal($course_info['visibility'])) {
            Session::write($variable, true);
        }
        if ($pluginLegal) {
            header('Location:' . $url);
            exit;
        }
    }
}
$user_pass_open_course = false;
if (api_check_user_access_to_legal($course_info['visibility']) && Session::read($variable)) {
    $user_pass_open_course = true;
}
if (empty($session_id)) {
    if (CourseManager::is_user_subscribed_in_course($user_id, $course_code) || api_check_user_access_to_legal($course_info['visibility'])) {
        $user_accepted_legal = CourseManager::is_user_accepted_legal($user_id, $course_code);
        if ($user_accepted_legal || $user_pass_open_course) {
            //Redirect to course home
            header('Location: ' . $url);
            exit;
        }
    } else {
        api_not_allowed();
    }
} else {
    if (api_is_platform_admin()) {
Esempio n. 23
0
 * @todo This piece of code should probably move to local.inc.php where the actual login procedure is handled.
 * @todo Check if this code is used. I think this code is never executed because after clicking the submit button
 *       the code does the stuff in local.inc.php and then redirects to index.php or user_portal.php depending
 *       on api_get_setting('page_after_login').
 */
if (!empty($_POST['submitAuth'])) {
    // The user has been already authenticated, we are now to find the last login of the user.
    if (isset($_user['user_id'])) {
        $track_login_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
        $sql_last_login = "******" . $_user['user_id'] . "'\n                                ORDER BY login_date DESC LIMIT 1";
        $result_last_login = Database::query($sql_last_login);
        if (!$result_last_login) {
            if (Database::num_rows($result_last_login) > 0) {
                $user_last_login_datetime = Database::fetch_array($result_last_login);
                $user_last_login_datetime = $user_last_login_datetime[0];
                Session::write('user_last_login_datetime', $user_last_login_datetime);
            }
        }
        //Event::event_login();
    }
    // End login -- if ($_POST['submitAuth'])
} else {
    // Only if login form was not sent because if the form is sent the user was already on the page.
    Event::event_open();
}
if (api_get_setting('display_categories_on_homepage') == 'true') {
    $controller->tpl->assign('course_category_block', $controller->return_courses_in_categories());
}
$controller->set_login_form();
//@todo move this inside the IndexManager
if (!api_is_anonymous()) {
Esempio n. 24
0
 /**
  * Calculate the score of this evaluation
  * @param int $stud_id (default: all students who have results for this eval - then the average is returned)
  * @param string $type (best, average, ranking)
  * @return	array (score, max) if student is given
  * 			array (sum of scores, number of scores) otherwise
  * 			or null if no scores available
  */
 public function calc_score($stud_id = null, $type = null)
 {
     $useSession = true;
     if (isset($stud_id) && empty($type)) {
         $key = 'result_score_student_list_' . api_get_course_int_id() . '_' . api_get_session_id() . '_' . $this->id . '_' . $stud_id;
         $data = Session::read('calc_score');
         $results = isset($data[$key]) ? $data[$key] : null;
         if ($useSession == false) {
             $results = null;
         }
         if (empty($results)) {
             $results = Result::load(null, $stud_id, $this->id);
             Session::write('calc_score', array($key => $results));
         }
         $score = 0;
         /** @var Result $res */
         foreach ($results as $res) {
             $score = $res->get_score();
         }
         return array($score, $this->get_max());
     } else {
         $count = 0;
         $sum = 0;
         $bestResult = 0;
         $weight = 0;
         $sumResult = 0;
         $key = 'result_score_student_list_' . api_get_course_int_id() . '_' . api_get_session_id() . '_' . $this->id;
         $data = Session::read('calc_score');
         $allResults = isset($data[$key]) ? $data[$key] : null;
         if ($useSession == false) {
             $allResults = null;
         }
         if (empty($allResults)) {
             $allResults = Result::load(null, null, $this->id);
             Session::write($key, $allResults);
         }
         $students = array();
         /** @var Result $res */
         foreach ($allResults as $res) {
             $score = $res->get_score();
             if (!empty($score) || $score == '0') {
                 $count++;
                 $sum += $score / $this->get_max();
                 $sumResult += $score;
                 if ($score > $bestResult) {
                     $bestResult = $score;
                 }
                 $weight = $this->get_max();
             }
             $students[$res->get_user_id()] = $score;
         }
         if (empty($count)) {
             return null;
         }
         switch ($type) {
             case 'best':
                 return array($bestResult, $weight);
                 break;
             case 'average':
                 return array($sumResult / $count, $weight);
                 break;
             case 'ranking':
                 $students = array();
                 /** @var Result $res */
                 foreach ($allResults as $res) {
                     $score = $res->get_score();
                     $students[$res->get_user_id()] = $score;
                 }
                 return AbstractLink::getCurrentUserRanking($stud_id, $students);
                 break;
             default:
                 return array($sum, $count);
                 break;
         }
     }
 }
Esempio n. 25
0
*	@package chamilo.auth.ldap
*/
/**
 * An external authentification module needs to set
 * - $loginFailed
 * - $uidReset
 * - $_user['user_id']
 * - register the $_user['user_id'] in the session
 *
 * As the LDAP code shows, this is not as difficult as you might think.
 * LDAP authentification module
 * this calls the loginWithLdap function
 * from the LDAP library, and sets a few
 * variables based on the result.
 */
//require_once('../../inc/global.inc.php'); - this script should be loaded by the /index.php script anyway, so global is already loaded
use ChamiloSession as Session;
require_once 'authldap.php';
$loginLdapSucces = ldap_login($login, $password);
if ($loginLdapSucces) {
    $loginFailed = false;
    $uidReset = true;
    $_user['user_id'] = $uData['user_id'];
    Session::write('_uid', $_uid);
    // Jand: copied from event_login in events.lib.php to enable login statistics:
    Event::event_login($uData['user_id']);
} else {
    $loginFailed = true;
    unset($_user['user_id']);
    $uidReset = false;
}
Esempio n. 26
0
 /**
  * @param int $questionId
  * @param int $in_display_category_name
  * @return null|string
  */
 public static function returnCategoryAndTitle($questionId, $in_display_category_name = 1)
 {
     $is_student = !(api_is_allowed_to_edit(null, true) || api_is_session_admin());
     $objExercise = Session::read('objExercise');
     if (!empty($objExercise)) {
         $in_display_category_name = $objExercise->display_category_name;
     }
     $content = null;
     if (TestCategory::getCategoryNameForQuestion($questionId) != "" && ($in_display_category_name == 1 || !$is_student)) {
         $content .= '<div class="page-header">';
         $content .= '<h4>' . get_lang('Category') . ": " . TestCategory::getCategoryNameForQuestion($questionId) . '</h4>';
         $content .= "</div>";
     }
     return $content;
 }
Esempio n. 27
0
use ChamiloSession as Session;
global $cas_auth_ver, $cas_auth_server, $cas_auth_port, $cas_auth_uri;
// phpCAS
/*
If we are not logged and in our browser enter an URL with a name of a course
e.g. http://www.chamilo.fr/chamilo/courses/COURSTESTOSETE/?id_session=0
We go to page api_not_allowed :
> You are not allowed to see this page.
> Sorry, you are not allowed to access this page, or maybe your connection has expired.
> Please click your browser's \"Back\" button or follow the link below to return to the previous page
If we click on the link to go to homepage, some datas are entered in $_SESSION and if we enter our CAS loggin, we go to api_not_allowad_page again
and again
As a result, if we are not logged on, we have to destroy the session variables, before calling CAS page
*/
if (api_is_anonymous()) {
    Session::destroy();
}
if (cas_configured()) {
    $firstpage = "";
    if (isset($_GET['firstpage'])) {
        $firstpage = $_GET['firstpage'];
        setcookie("GotoCourse", $firstpage);
    }
    if (!is_object($PHPCAS_CLIENT)) {
        phpCAS::client($cas_auth_ver, $cas_auth_server, $cas_auth_port, $cas_auth_uri);
        phpCAS::setNoCasServerValidation();
    }
    phpCAS::forceAuthentication();
    header('Location: ' . api_get_path(WEB_PATH) . api_get_setting('page_after_login'));
} else {
    header('Location: ' . api_get_path(WEB_PATH));
Esempio n. 28
0
        $total_skills_to_search[$my_skill] = $my_skill;
    }
}
$total_skills_to_search = $skill->get_skills_info($total_skills_to_search);
$action = isset($_REQUEST['a']) ? $_REQUEST['a'] : null;
$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : null;
switch ($action) {
    case 'remove_skill':
        $new_skill = array();
        foreach ($skills as $skill_id) {
            if ($id != $skill_id) {
                $new_skill[] = $skill_id;
            }
        }
        $skills = $new_skill;
        Session::write('skills', $skills);
        break;
    case 'load_profile':
        $skill_profile = new SkillRelProfile();
        $skills = $skill_profile->get_skills_by_profile($id);
        $total_skills_to_search = $skill->get_skills_info($skills);
        break;
}
$skill_list = array();
foreach ($total_skills_to_search as $skill_info) {
    $skill_list[$skill_info['id']] = $skill_info;
}
$tpl->assign('skill_list', $skill_list);
$tpl->assign('search_skill_list', $skills);
$form_to_html = $form->returnForm();
$tpl->assign('form', $form_to_html);
Esempio n. 29
0
/**
 * 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>';
        }
    }
}
                stop: function() {
                    stop = true;
                }
            });
        });
    </script>
<?php 
//we filter the type of questions we can add
Question::display_type_menu($objExercise);
// Re sets the question list
$objExercise->setQuestionList();
echo '<div style="clear:both;"></div>';
echo '<div id="message"></div>';
$token = Security::get_token();
//deletes a session when using don't know question type (ugly fix)
Session::erase('less_answer');
// If we are in a test
$inATest = isset($exerciseId) && $exerciseId > 0;
if (!$inATest) {
    echo "<div class='alert alert-warning'>" . get_lang("ChoiceQuestionType") . "</div>";
} else {
    // Title line
    echo "<div class='table-responsive'>";
    echo "<table class='table table-condensed'>";
    echo "<tr>";
    echo "<th style=\"width: 50%;\">" . get_lang('Questions') . "</th>";
    echo "<th style=\"width: 6%;\">" . get_lang('Type') . "</th>";
    echo "<th style=\"width: 22%; text-align:center;\">" . get_lang('Category') . "</th>";
    echo "<th style=\"width: 6%;\">" . get_lang('Difficulty') . "</th>";
    echo "<th style=\"width: 16%; float:left;\">" . get_lang('Score') . "</th>";
    echo "</tr>";