/**
 * Generates statistical, based on n-grams language profile from the given text.
 * @param string $string				The input text. It should be UTF-8 encoded. Practically it should be at least 3000 characters long, 40000 characters size is for increased accuracy.
 * @param int $n_grams_max (optional)	The size of the array of the generated n-grams.
 * @param int $n_max (optional)			The limit if the number of characters that a n-gram may contain.
 * @return array						An array that contains cunstructed n-grams, sorted in reverse order by their frequences. Frequences are not stored in the array.
 */
function &_api_generate_n_grams(&$string, $encoding, $n_grams_max = 350, $n_max = 4)
{
    if (empty($string)) {
        return array();
    }
    // We construct only lowercase n-grams if it is applicable for the given language.
    // Removing all puntuation and some other non-letter characters. Apostrophe characters stay.
    // Splitting the sample text into separate words.
    $words = preg_split('/_/u', preg_replace('/[\\x00-\\x1F\\x20-\\x26\\x28-\\x3E\\?@\\x5B-\\x60{|}~\\x7F]/u', '_', ' ' . api_strtolower(api_utf8_encode($string, $encoding), 'UTF-8') . ' '), -1, PREG_SPLIT_NO_EMPTY);
    $prefix = '_';
    // Beginning of a word.
    $suffix = str_repeat('_', $n_max);
    // End of a word. Only the last '_' stays.
    $n_grams = array();
    // The array that will contain the constructed n-grams.
    foreach ($words as $word) {
        $k = api_strlen($word, 'UTF-8') + 1;
        $word = $prefix . $word . $suffix;
        for ($n = 1; $n <= $n_max; $n++) {
            for ($i = 0; $i < $k; $i++) {
                $n_gram = api_utf8_decode(api_substr($word, $i, $n, 'UTF-8'), $encoding);
                if (isset($n_grams[$n_gram])) {
                    $n_grams[$n_gram]++;
                } else {
                    $n_grams[$n_gram] = 1;
                }
            }
        }
    }
    // Sorting the n-grams in reverse order by their frequences.
    arsort($n_grams);
    // Reduction the number of n-grams.
    return array_keys(array_slice($n_grams, 0, $n_grams_max));
}
Example #2
0
 if ($id) {
     // Insert into agenda
     $agenda_id = 0;
     $end_date = '';
     if (isset($_POST['add_to_calendar']) && $_POST['add_to_calendar'] == 1) {
         require_once api_get_path(SYS_CODE_PATH) . 'calendar/agenda.inc.php';
         require_once api_get_path(SYS_CODE_PATH) . 'resourcelinker/resourcelinker.inc.php';
         // Setting today date
         $date = $end_date = $time;
         $title = sprintf(get_lang('HandingOverOfTaskX'), $_POST['new_dir']);
         if (!empty($_POST['type1'])) {
             $end_date = get_date_from_select('expires');
             $date = $end_date;
         }
         $description = isset($_POST['description']) ? $_POST['description'] : '';
         $content = '<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;curdirpath=' . api_substr($dir_name_sql, 1) . '" >' . $_POST['new_dir'] . '</a>' . $description;
         $agenda_id = agenda_add_item($course_info, $title, $content, $date, $end_date, array('GROUP:' . $group_id), 0);
     }
 }
 //Folder created
 api_item_property_update($course_info, 'work', $id, 'DirectoryCreated', $user_id, $group_id);
 Display::display_confirmation_message(get_lang('DirectoryCreated'), false);
 // insert into student_publication_assignment
 //return something like this: 2008-02-45 00:00:00
 $enable_calification = isset($_POST['qualification_value']) && !empty($_POST['qualification_value']) ? 1 : 0;
 if (!empty($_POST['type1']) || !empty($_POST['type2'])) {
     $sql_add_homework = "INSERT INTO {$TSTDPUBASG} SET\n                                                c_id = {$course_id} ,\n                                                expires_on       \t\t= '" . (isset($_POST['type1']) && $_POST['type1'] == 1 ? api_get_utc_datetime(get_date_from_select('expires')) : '0000-00-00 00:00:00') . "',\n                                                ends_on        \t \t\t= '" . (isset($_POST['type2']) && $_POST['type2'] == 1 ? api_get_utc_datetime(get_date_from_select('ends')) : '0000-00-00 00:00:00') . "',\n                                                add_to_calendar  \t\t= '{$agenda_id}',\n                                                enable_qualification \t= '{$enable_calification}',\n                                                publication_id \t\t\t= '{$id}'";
     Database::query($sql_add_homework);
     $my_last_id = Database::insert_id();
     $sql_add_publication = "UPDATE {$work_table} SET has_properties  = {$my_last_id} , view_properties = 1  WHERE c_id = {$course_id} AND id = {$id}";
     Database::query($sql_add_publication);
Example #3
0
/**
 * This functions cuts a paragraph
 * i.e cut('Merry Xmas from Lima',13) = "Merry Xmas fr..."
 * @param string    The text to "cut"
 * @param int       Count of chars
 * @param bool      Whether to embed in a <span title="...">...</span>
 * @return string
 * */
function cut($text, $maxchar, $embed = false)
{
    if (api_strlen($text) > $maxchar) {
        if ($embed) {
            return '<p title="' . $text . '">' . api_substr($text, 0, $maxchar) . '...</p>';
        }
        return api_substr($text, 0, $maxchar) . ' ...';
    }
    return $text;
}
Example #4
0
$table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
$table_user 					= Database :: get_main_table(TABLE_MAIN_USER);

$course_id = api_get_course_int_id();

// Getting the survey information
$survey_data = survey_manager::get_survey($_GET['survey_id']);
if (empty($survey_data)) {
	Display :: display_header(get_lang('ToolSurvey'));
	Display :: display_error_message(get_lang('InvallidSurvey'), false);
	Display :: display_footer();
	exit;
}

$urlname = api_substr(api_html_entity_decode($survey_data['title'], ENT_QUOTES), 0, 40);
if (api_strlen(strip_tags($survey_data['title'])) > 40) {
	$urlname .= '...';
}

if ($survey_data['survey_type'] == 1) {
	$sql = 'SELECT id FROM '.Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP).'
	        WHERE
                c_id = '.$course_id.' AND
                survey_id = '.(int)$_GET['survey_id'].' LIMIT 1';
	$rs = Database::query($sql);
	if (Database::num_rows($rs)===0) {
		header('Location: '.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.(int)$_GET['survey_id'].'&message='.'YouNeedToCreateGroups');
		exit;
	}
}
$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
$tbl_class = Database::get_main_table(TABLE_MAIN_CLASS);
$tool_name = get_lang('AddClassesToACourse');
$interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
Display::display_header($tool_name);
//api_display_tool_title($tool_name);
if ($_POST['formSent']) {
    $form_sent = $_POST['formSent'];
    $classes = is_array($_POST['ClassList']) ? $_POST['ClassList'] : array();
    $courses = is_array($_POST['CourseList']) ? $_POST['CourseList'] : array();
    $first_letter_class = $_POST['firstLetterClass'];
    $first_letter_course = $_POST['firstLetterCourse'];
    if ($form_sent == 1) {
        if (count($classes) == 0 || count($courses) == 0) {
            Display::display_error_message(get_lang('AtLeastOneClassAndOneCourse'));
        } elseif (api_substr($_POST['formSubmit'], -2) == '>>') {
            foreach ($courses as $course_code) {
                foreach ($classes as $class_id) {
                    ClassManager::subscribe_to_course($class_id, $course_code);
                }
            }
            Display::display_normal_message(get_lang('ClassesSubscribed'));
        } else {
            // remove classes from courses
            foreach ($courses as $course_code) {
                foreach ($classes as $class_id) {
                    ClassManager::unsubscribe_from_course($class_id, $course_code);
                }
            }
            Display::display_normal_message(get_lang('ClassesUnSubscribed'));
        }
Example #6
0
         $imgForum = '';
     }
     $forum_image = $imgForum;
 } else {
     if ($forum['forum_of_group'] == '0') {
         $forum_image = Display::return_icon('forum_group.png', get_lang('GroupForum'), null, ICON_SIZE_LARGE);
     } else {
         $forum_image = Display::return_icon('forum.png', get_lang('Forum'), null, ICON_SIZE_LARGE);
     }
 }
 // Validation when belongs to a session
 $session_img = api_get_session_image($forum['session_id'], $_user['status']);
 if ($forum['forum_of_group'] != '0') {
     $my_all_groups_forum_name = isset($all_groups[$forum['forum_of_group']]['name']) ? $all_groups[$forum['forum_of_group']]['name'] : null;
     $my_all_groups_forum_id = isset($all_groups[$forum['forum_of_group']]['id']) ? $all_groups[$forum['forum_of_group']]['id'] : null;
     $group_title = api_substr($my_all_groups_forum_name, 0, 30);
     $forum_title_group_addition = ' (<a href="../group/group_space.php?' . api_get_cidreq() . '&gidReq=' . $forum['forum_of_group'] . '" class="forum_group_link">' . get_lang('GoTo') . ' ' . $group_title . '</a>)' . $session_img;
 } else {
     $forum_title_group_addition = '';
 }
 if (empty($sessionId) && !empty($forum['session_name'])) {
     $session_displayed = ' (' . $forum['session_name'] . ')';
 } else {
     $session_displayed = '';
 }
 $forum['forum_of_group'] == 0 ? $groupid = '' : ($groupid = $forum['forum_of_group']);
 $number_threads = isset($forum['number_of_threads']) ? $forum['number_of_threads'] : 0;
 $number_posts = isset($forum['number_of_posts']) ? $forum['number_of_posts'] : 0;
 $html .= '<div class="row">';
 $html .= '<div class="col-md-6">';
 $html .= '<div class="col-md-3">';
Example #7
0
$user_id = api_get_user_id();

if ($user_id == 0) {
    $user_id = $survey_invitation['user'];
}
$user_data = UserManager :: get_user_info_by_id($user_id);

if ($survey_data['form_fields'] != '' && $survey_data['anonymous'] == 0 && is_array($user_data)) {
    $form_fields = explode('@', $survey_data['form_fields']);
    $list = array();
    foreach ($form_fields as $field) {
        $field_value = explode(':', $field);
        if ($field_value[1] == 1) {
            if ($field_value[0] != '') {
                $val = api_substr($field_value[0], 8, api_strlen($field_value[0]));
                $list[$val] = 1;
            }
        }
    }

    // We use the same form as in auth/profile.php
    $form = new FormValidator(
        'profile',
        'post',
        api_get_self()."?".str_replace('&show_form=1', '&show_form=1', $_SERVER['QUERY_STRING']),
        null,
        array('style' => 'width: 75%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;'))
    );

    if (api_is_western_name_order()) {
Example #8
0
 function _createElements()
 {
     $this->_separator = $this->_elements = array();
     $separator = '';
     $locale =& $this->_locale[$this->_options['language']];
     $backslash = false;
     // Modified by Ivan Tcholakov, 16-MAR-2010.
     for ($i = 0, $length = api_strlen($this->_options['format']); $i < $length; $i++) {
         $sign = api_substr($this->_options['format'], $i, 1);
         //
         if ($backslash) {
             $backslash = false;
             $separator .= $sign;
         } else {
             $loadSelect = true;
             switch ($sign) {
                 case 'D':
                     // Sunday is 0 like with 'w' in date()
                     $options = $locale['weekdays_short'];
                     break;
                 case 'l':
                     $options = $locale['weekdays_long'];
                     break;
                 case 'd':
                     $options = $this->_createOptionList(1, 31);
                     break;
                 case 'M':
                     $options = $locale['months_short'];
                     array_unshift($options, '');
                     unset($options[0]);
                     break;
                 case 'm':
                     $options = $this->_createOptionList(1, 12);
                     break;
                 case 'F':
                     $options = $locale['months_long'];
                     array_unshift($options, '');
                     unset($options[0]);
                     break;
                 case 'Y':
                     $options = $this->_createOptionList($this->_options['minYear'], $this->_options['maxYear'], $this->_options['minYear'] > $this->_options['maxYear'] ? -1 : 1);
                     break;
                 case 'y':
                     $options = $this->_createOptionList($this->_options['minYear'], $this->_options['maxYear'], $this->_options['minYear'] > $this->_options['maxYear'] ? -1 : 1);
                     array_walk($options, create_function('&$v,$k', '$v = substr($v,-2);'));
                     break;
                 case 'h':
                     $options = $this->_createOptionList(1, 12);
                     break;
                 case 'g':
                     $options = $this->_createOptionList(1, 12);
                     array_walk($options, create_function('&$v,$k', '$v = intval($v);'));
                     break;
                 case 'H':
                     $options = $this->_createOptionList(0, 23);
                     break;
                 case 'i':
                     $options = $this->_createOptionList(0, 59, $this->_options['optionIncrement']['i']);
                     break;
                 case 's':
                     $options = $this->_createOptionList(0, 59, $this->_options['optionIncrement']['s']);
                     break;
                 case 'a':
                     $options = array('am' => 'am', 'pm' => 'pm');
                     break;
                 case 'A':
                     $options = array('AM' => 'AM', 'PM' => 'PM');
                     break;
                 case 'W':
                     $options = $this->_createOptionList(1, 53);
                     break;
                 case '\\':
                     $backslash = true;
                     $loadSelect = false;
                     break;
                 default:
                     $separator .= ' ' == $sign ? '&nbsp;' : $sign;
                     $loadSelect = false;
             }
             if ($loadSelect) {
                 if (0 < count($this->_elements)) {
                     $this->_separator[] = $separator;
                 } else {
                     $this->_wrap[0] = $separator;
                 }
                 $separator = '';
                 // Should we add an empty option to the top of the select?
                 if (!is_array($this->_options['addEmptyOption']) && $this->_options['addEmptyOption'] || is_array($this->_options['addEmptyOption']) && !empty($this->_options['addEmptyOption'][$sign])) {
                     // Using '+' array operator to preserve the keys
                     if (is_array($this->_options['emptyOptionText']) && !empty($this->_options['emptyOptionText'][$sign])) {
                         $options = array($this->_options['emptyOptionValue'] => $this->_options['emptyOptionText'][$sign]) + $options;
                     } else {
                         $options = array($this->_options['emptyOptionValue'] => $this->_options['emptyOptionText']) + $options;
                     }
                 }
                 $this->_elements[] = new HTML_QuickForm_select($sign, null, $options, $this->getAttributes());
             }
         }
     }
     $this->_wrap[1] = $separator . ($backslash ? '\\' : '');
 }
Example #9
0
    $form->addElement('hidden', 'legal_info', $term_preview['legal_id'] . ':' . $term_preview['language_id']);
    if ($term_preview['type'] == 1) {
        $form->addElement('checkbox', 'legal_accept', null, get_lang('IHaveReadAndAgree') . '&nbsp;<a href="inscription.php?legal" target="_blank">' . get_lang('TermsAndConditions') . '</a>');
        $form->addRule('legal_accept', get_lang('ThisFieldIsRequired'), 'required');
    } else {
        $preview = LegalManager::show_last_condition($term_preview);
        $form->addElement('label', null, $preview);
    }
}
$form->addButtonCreate(get_lang('RegisterUser'));
$course_code_redirect = Session::read('course_redirect');
if ($form->validate()) {
    $values = $form->getSubmitValues(1);
    // Make *sure* the login isn't too long
    if (isset($values['username'])) {
        $values['username'] = api_substr($values['username'], 0, USERNAME_MAX_LENGTH);
    }
    if (api_get_setting('registration.allow_registration_as_teacher') == 'false') {
        $values['status'] = STUDENT;
    }
    if (empty($values['official_code']) && !empty($values['username'])) {
        $values['official_code'] = api_strtoupper($values['username']);
    }
    if (api_get_setting('profile.login_is_email') == 'true') {
        $values['username'] = $values['email'];
    }
    if ($user_already_registered_show_terms && api_get_setting('registration.allow_terms_conditions') == 'true') {
        $user_id = $_SESSION['term_and_condition']['user_id'];
        $is_admin = UserManager::is_admin($user_id);
        Session::write('is_platformAdmin', $is_admin);
    } else {
Example #10
0
 /**
  * Creates a course
  * @param   array $params columns in the main.course table
  *
  * @return  mixed  false if the course was not created, array with the course info
  */
 public static function create_course($params, $extraFields = array())
 {
     global $_configuration;
     // Check portal limits
     $access_url_id = 1;
     if (api_get_multiple_access_url()) {
         $access_url_id = api_get_current_access_url_id();
     }
     if (isset($_configuration[$access_url_id]) && is_array($_configuration[$access_url_id])) {
         if (isset($_configuration[$access_url_id]['hosting_limit_courses']) && $_configuration[$access_url_id]['hosting_limit_courses'] > 0) {
             $num = self::count_courses($access_url_id);
             if ($num >= $_configuration[$access_url_id]['hosting_limit_courses']) {
                 api_warn_hosting_contact('hosting_limit_courses');
                 return api_set_failure(get_lang('PortalCoursesLimitReached'));
             }
         }
         if (isset($_configuration[$access_url_id]['hosting_limit_active_courses']) && $_configuration[$access_url_id]['hosting_limit_active_courses'] > 0) {
             $num = self::countActiveCourses($access_url_id);
             if ($num >= $_configuration[$access_url_id]['hosting_limit_active_courses']) {
                 api_warn_hosting_contact('hosting_limit_active_courses');
                 return api_set_failure(get_lang('PortalActiveCoursesLimitReached'));
             }
         }
     }
     if (empty($params['title'])) {
         return false;
     }
     if (empty($params['wanted_code'])) {
         $params['wanted_code'] = $params['title'];
         // Check whether the requested course code has already been occupied.
         $params['wanted_code'] = CourseManager::generate_course_code(api_substr($params['title'], 0, self::MAX_COURSE_LENGTH_CODE));
     }
     // Create the course keys
     $keys = AddCourse::define_course_keys($params['wanted_code']);
     $params['exemplary_content'] = isset($params['exemplary_content']) ? $params['exemplary_content'] : false;
     if (count($keys)) {
         $params['code'] = $keys['currentCourseCode'];
         $params['visual_code'] = $keys['currentCourseId'];
         $params['directory'] = $keys['currentCourseRepository'];
         $course_info = api_get_course_info($params['code']);
         if (empty($course_info)) {
             $course_id = AddCourse::register_course($params);
             $course_info = api_get_course_info_by_id($course_id);
             if (!empty($course_info)) {
                 AddCourse::prepare_course_repository($course_info['directory'], $course_info['code']);
                 AddCourse::fill_db_course($course_id, $course_info['directory'], $course_info['course_language'], $params['exemplary_content']);
                 if (api_get_setting('gradebook.gradebook_enable_grade_model') == 'true') {
                     //Create gradebook_category for the new course and add
                     // a gradebook model for the course
                     if (isset($params['gradebook_model_id']) && !empty($params['gradebook_model_id']) && $params['gradebook_model_id'] != '-1') {
                         GradebookUtils::create_default_course_gradebook($course_info['code'], $params['gradebook_model_id']);
                     }
                 }
                 // If parameter defined, copy the contents from a specific
                 // template course into this new course
                 $template = api_get_setting('course.course_creation_use_template');
                 if (!empty($template)) {
                     // Include the necessary libraries to generate a course copy
                     require_once api_get_path(SYS_CODE_PATH) . 'coursecopy/classes/CourseBuilder.class.php';
                     require_once api_get_path(SYS_CODE_PATH) . 'coursecopy/classes/CourseRestorer.class.php';
                     require_once api_get_path(SYS_CODE_PATH) . 'coursecopy/classes/CourseSelectForm.class.php';
                     // Call the course copy object
                     $originCourse = api_get_course_info_by_id($template);
                     $originCourse['official_code'] = $originCourse['code'];
                     $cb = new CourseBuilder(null, $originCourse);
                     $course = $cb->build(null, $originCourse['code']);
                     $cr = new CourseRestorer($course);
                     $cr->set_file_option();
                     $cr->restore($course_info['id']);
                     //course_info[id] is the course.code value (I know...)
                 }
                 $params['course_code'] = $course_info['code'];
                 $params['item_id'] = $course_info['real_id'];
                 $courseFieldValue = new ExtraFieldValue('course');
                 $courseFieldValue->saveFieldValues($params);
                 return $course_info;
             }
         }
     }
     return false;
 }
$repository = UserManager::getRepository();
/**
 * E-mails list loop
 */
foreach ($list as $mail) {
    $mail = trim($mail);
    $sql = "SELECT user_id, official_code, firstname, lastname, email, username, language\n            FROM {$users} WHERE email = '{$mail}'\n";
    $res = Database::query($sql);
    if ($res === false) {
        echo 'Error in database with email ' . $mail . "\n";
    }
    if (Database::num_rows($res) == 0) {
        echo '[Error] Email not found in database: ' . $row['email'] . "\n";
    } else {
        $row = Database::fetch_assoc($res);
        $pass = api_substr($row['username'], 0, 4) . rand(0, 9) . rand(0, 9);
        if ($user) {
            /** @var User $user */
            $user = $repository->find($row['user_id']);
            $user->setPlainPassword($pass);
            $userManager->updateUser($user, true);
        } else {
            echo "[Error] Error updating password. Skipping {$mail}\n";
            continue;
        }
        $user = array('FirstName' => $row['firstname'], 'LastName' => $row['lastname'], 'UserName' => $row['username'], 'Password' => $pass, 'Email' => $mail);
        $l = api_get_interface_language();
        if (!empty($row['language'])) {
            $l = $row['language'];
        }
        //This comes from main/admin/user_import.php::save_data() slightly modified
/**
 * Display the search results
 * @param string
 * @return void display the results
 * @author Patrick Cool <*****@*****.**>, Ghent University, Belgium
 * @version march 2008, dokeos 1.8.5
 */
function display_forum_search_results($search_term)
{
    $table_threads = Database::get_course_table(TABLE_FORUM_THREAD);
    $table_posts = Database::get_course_table(TABLE_FORUM_POST);
    $table_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
    $session_id = api_get_session_id();
    $course_id = api_get_course_int_id();
    // Defining the search strings as an array.
    if (strstr($search_term, '+')) {
        $search_terms = explode('+', $search_term);
    } else {
        $search_terms[] = $search_term;
    }
    // Search restriction.
    foreach ($search_terms as $value) {
        $search_restriction[] = "\n        (posts.post_title LIKE '%" . Database::escape_string(trim($value)) . "%'\n        OR posts.post_text LIKE '%" . Database::escape_string(trim($value)) . "%')";
    }
    $sql = "SELECT posts.*\n            FROM {$table_posts} posts, {$table_threads} threads, {$table_item_property} item_property\n            WHERE\n                posts.c_id = {$course_id}\n                AND item_property.c_id = {$course_id}\n                AND posts.thread_id = threads.thread_id\n                AND item_property.ref = threads.thread_id\n                AND item_property.visibility = 1\n                AND item_property.session_id = {$session_id}\n                AND posts.visible = 1\n                AND item_property.tool = '" . TOOL_FORUM_THREAD . "'\n                AND " . implode(' AND ', $search_restriction) . "\n                GROUP BY posts.post_id";
    // Getting all the information of the forum categories.
    $forum_categories_list = get_forum_categories();
    // Getting all the information of the forums.
    $forum_list = get_forums();
    $result = Database::query($sql);
    $search_results = [];
    while ($row = Database::fetch_array($result, 'ASSOC')) {
        $display_result = false;
        /*
         We only show it when
         1. forum category is visible
         2. forum is visible
         3. thread is visible (to do)
         4. post is visible
        */
        if (!api_is_allowed_to_edit(null, true)) {
            if ($forum_categories_list[$forum_list[$row['forum_id']]['forum_category']]['visibility'] == '1' and $forum_list[$row['forum_id']]['visibility'] == '1' and $row['visible'] == '1') {
                $display_result = true;
            }
        } else {
            $display_result = true;
        }
        if ($display_result) {
            $search_results_item = '<li><a href="viewforumcategory.php?' . api_get_cidreq() . '&forumcategory=' . $forum_list[$row['forum_id']]['forum_category'] . '&search=' . urlencode($search_term) . '">' . prepare4display($forum_categories_list[$row['forum_id']['forum_category']]['cat_title']) . '</a> &gt; ';
            $search_results_item .= '<a href="viewforum.php?' . api_get_cidreq() . '&forum=' . $row['forum_id'] . '&search=' . urlencode($search_term) . '">' . prepare4display($forum_list[$row['forum_id']]['forum_title']) . '</a> &gt; ';
            //$search_results_item .= '<a href="">THREAD</a> &gt; ';
            $search_results_item .= '<a href="viewthread.php?' . api_get_cidreq() . '&forum=' . $row['forum_id'] . '&thread=' . $row['thread_id'] . '&search=' . urlencode($search_term) . '">' . prepare4display($row['post_title']) . '</a>';
            $search_results_item .= '<br />';
            if (api_strlen($row['post_title']) > 200) {
                $search_results_item .= prepare4display(api_substr(strip_tags($row['post_title']), 0, 200)) . '...';
            } else {
                $search_results_item .= prepare4display($row['post_title']);
            }
            $search_results_item .= '</li>';
            $search_results[] = $search_results_item;
        }
    }
    echo '<legend>' . count($search_results) . ' ' . get_lang('ForumSearchResults') . '</legend>';
    echo '<ol>';
    if ($search_results) {
        echo implode($search_results);
    }
    echo '</ol>';
}
Example #13
0
/**
 * Checks a password to see wether it is OK to use.
 * @param string $password
 * @return true if the password is acceptable, false otherwise
 * Notes about what a password "OK to use" is:
 * 1. The password should be at least 5 characters long.
 * 2. Only English letters (uppercase or lowercase, it doesn't matter) and digits are allowed.
 * 3. The password should contain at least 3 letters.
 * 4. It should contain at least 2 digits.
 * 5. It should not contain 3 or more consequent (according to ASCII table) characters.
 */
function api_check_password($password)
{
    $password_length = api_strlen($password);
    if ($password_length < 5) {
        return false;
    }
    $password = api_strtolower($password);
    $letters = 0;
    $digits = 0;
    $consequent_characters = 0;
    $previous_character_code = 0;
    for ($i = 0; $i < $password_length; $i++) {
        $current_character_code = api_ord(api_substr($password, $i, 1));
        if ($i && abs($current_character_code - $previous_character_code) <= 1) {
            $consequent_characters++;
            if ($consequent_characters == 3) {
                return false;
            }
        } else {
            $consequent_characters = 1;
        }
        if ($current_character_code >= 97 && $current_character_code <= 122) {
            $letters++;
        } elseif ($current_character_code >= 48 && $current_character_code <= 57) {
            $digits++;
        } else {
            return false;
        }
        $previous_character_code = $current_character_code;
    }
    return $letters >= 3 && $digits >= 2;
}
Example #14
0
 switch ($question_obj->type) {
     case FILL_IN_BLANKS:
         $answer_info_db = $answer_info;
         $answer_info = substr($answer_info, 0, strpos($answer_info, '::'));
         $correct_answer = $is_correct;
         $answers = $objExercise->fill_in_blank_answer_to_array($answer_info);
         $counter = 0;
         foreach ($answers as $answer_item) {
             if ($counter == 0) {
                 $data[$id]['name'] = cut($question_obj->question, 100);
             } else {
                 $data[$id]['name'] = '-';
             }
             $data[$id]['answer'] = $answer_item;
             $answer_item = api_substr($answer_item, 1);
             $answer_item = api_substr($answer_item, 0, api_strlen($answer_item) - 1);
             $data[$id]['correct'] = '-';
             $count = get_number_students_answer_count($real_answer_id, $question_id, $exercise_id, $courseCode, $sessionId, FILL_IN_BLANKS, $answer_info_db, $answer_item);
             $percentange = 0;
             if (!empty($count_students)) {
                 $percentange = $count / $count_students * 100;
             }
             $data[$id]['attempts'] = Display::bar_progress($percentange, false, $count . ' / ' . $count_students);
             $id++;
             $counter++;
         }
         break;
     case MATCHING:
         if ($is_correct == 0) {
             if ($answer_id == 1) {
                 $data[$id]['name'] = cut($question_obj->question, 100);
 /**
  * @param string $file
  * @param bool $updatesession options:
  * true: if the session exists it will be updated
  * false: if session exists a new session will be created adding a counter session1, session2, etc
  * @param int $user_id
  * @param $logger
  * @param array convert a file row to an extra field. Example in CSV file there's a SessionID then it will
  * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
  * @param array extra fields
  * @param string extra field id
  * @param int $daysCoachAccessBeforeBeginning
  * @param int $daysCoachAccessAfterBeginning
  * @param int $sessionVisibility
  * @return array
  */
 static function importCSV($file, $updatesession, $defaultUserId = null, $logger = null, $extraFields = array(), $extraFieldId = null, $daysCoachAccessBeforeBeginning = null, $daysCoachAccessAfterBeginning = null, $sessionVisibility = 1, $fieldsToAvoidUpdate = array())
 {
     $content = file($file);
     $error_message = null;
     $session_counter = 0;
     if (empty($defaultUserId)) {
         $defaultUserId = api_get_user_id();
     }
     $eol = PHP_EOL;
     if (PHP_SAPI != 'cli') {
         $eol = '<br />';
     }
     $debug = false;
     if (isset($logger)) {
         $debug = true;
     }
     $extraParameters = null;
     if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
         $extraParameters .= ' , nb_days_access_before_beginning = ' . intval($daysCoachAccessBeforeBeginning);
         $extraParameters .= ' , nb_days_access_after_end = ' . intval($daysCoachAccessAfterBeginning);
     }
     $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
     $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
     $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
     $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
     $sessions = array();
     if (!api_strstr($content[0], ';')) {
         $error_message = get_lang('NotCSV');
     } else {
         $tag_names = array();
         foreach ($content as $key => $enreg) {
             $enreg = explode(';', trim($enreg));
             if ($key) {
                 foreach ($tag_names as $tag_key => $tag_name) {
                     $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
                 }
             } else {
                 foreach ($enreg as $tag_name) {
                     $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\\-]/', '', $tag_name);
                 }
                 if (!in_array('SessionName', $tag_names) || !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)) {
                     $error_message = get_lang('NoNeededData');
                     break;
                 }
             }
         }
         // Looping the sessions.
         foreach ($sessions as $enreg) {
             $user_counter = 0;
             $course_counter = 0;
             if (isset($extraFields) && !empty($extraFields)) {
                 foreach ($extraFields as $original => $to) {
                     $enreg[$to] = $enreg[$original];
                 }
             }
             $session_name = Database::escape_string($enreg['SessionName']);
             $date_start = $enreg['DateStart'];
             $date_end = $enreg['DateEnd'];
             $visibility = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
             $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
             // Searching a general coach.
             if (!empty($enreg['Coach'])) {
                 $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
                 if ($coach_id === false) {
                     // If the coach-user does not exist - I'm the coach.
                     $coach_id = $defaultUserId;
                 }
             } else {
                 $coach_id = $defaultUserId;
             }
             if (!$updatesession) {
                 // Always create a session.
                 $unique_name = false;
                 // This MUST be initializead.
                 $i = 0;
                 // Change session name, verify that session doesn't exist.
                 $suffix = null;
                 while (!$unique_name) {
                     if ($i > 1) {
                         $suffix = ' - ' . $i;
                     }
                     $sql = 'SELECT 1 FROM ' . $tbl_session . ' WHERE name="' . $session_name . $suffix . '"';
                     $rs = Database::query($sql);
                     if (Database::result($rs, 0, 0)) {
                         $i++;
                     } else {
                         $unique_name = true;
                         $session_name .= $suffix;
                     }
                 }
                 // Creating the session.
                 /*$sql_session = "INSERT IGNORE INTO $tbl_session SET
                           name = '".$session_name."',
                           id_coach = '$coach_id',
                           date_start = '$date_start',
                           date_end = '$date_end',
                           visibility = '$visibility',
                           session_category_id = '$session_category_id',
                           session_admin_id=".intval($defaultUserId).$extraParameters;
                   Database::query($sql_session);*/
                 $params = array('id_coach' => $coach_id, 'visibility' => $visibility, 'name' => $session_name, 'access_start_date' => $date_start, 'access_end_date' => $date_end, 'session_category_id' => $session_category_id, 'session_admin_id' => $defaultUserId);
                 $session_id = SessionManager::add($params);
                 if ($debug) {
                     if ($session_id) {
                         foreach ($enreg as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') {
                                 //an extra field
                                 self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                             }
                         }
                         $logger->addInfo("Sessions - Session created: #{$session_id} - {$session_name}");
                     } else {
                         $logger->addError("Sessions - Session NOT created: {$session_name}");
                     }
                 }
                 $session_counter++;
             } else {
                 $sessionId = null;
                 if (isset($extraFields) && !empty($extraFields)) {
                     $sessionId = self::get_session_id_from_original_id($enreg['extra_' . $extraFieldId], $extraFieldId);
                     if (empty($sessionId)) {
                         $my_session_result = false;
                     } else {
                         $my_session_result = true;
                     }
                 } else {
                     $my_session_result = self::get_session_by_name($enreg['SessionName']);
                 }
                 if ($my_session_result === false) {
                     // Creating a session.
                     /*$sql_session = "INSERT IGNORE INTO $tbl_session SET
                       name = '$session_name',
                       id_coach = '$coach_id',
                       date_start = '$date_start',
                       date_end = '$date_end',
                       visibility = '$visibility',
                       session_category_id = '$session_category_id' ".$extraParameters;*/
                     $params = array('id_coach' => $coach_id, 'visibility' => $visibility, 'name' => $session_name, 'access_start_date' => $date_start, 'access_end_date' => $date_end, 'session_category_id' => $session_category_id, 'session_admin_id' => $defaultUserId);
                     $session_id = SessionManager::add($params);
                     // We get the last insert id.
                     /*$my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
                       $session_id = $my_session_result['id'];*/
                     if ($debug) {
                         if ($session_id) {
                             foreach ($enreg as $key => $value) {
                                 if (substr($key, 0, 6) == 'extra_') {
                                     //an extra field
                                     self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                                 }
                             }
                             $logger->addInfo("Sessions - #{$session_id} created: {$session_name}");
                         } else {
                             $logger->addError("Sessions - Session NOT created: {$session_name}");
                         }
                     }
                 } else {
                     $params = array('id_coach' => $coach_id, 'date_start' => $date_start, 'date_end' => $date_end, 'visibility' => $visibility, 'session_category_id' => $session_category_id);
                     if (!empty($fieldsToAvoidUpdate)) {
                         foreach ($fieldsToAvoidUpdate as $field) {
                             unset($params[$field]);
                         }
                     }
                     if (isset($sessionId) && !empty($sessionId)) {
                         // The session already exists, update it then.
                         Database::update($tbl_session, $params, array('id = ?' => $sessionId));
                         $session_id = $sessionId;
                     } else {
                         Database::update($tbl_session, $params, array("name = '?' " => $enreg['SessionName']));
                         $row = Database::query("SELECT id FROM {$tbl_session} WHERE name = '{$session_name}'");
                         list($session_id) = Database::fetch_array($row);
                     }
                     foreach ($enreg as $key => $value) {
                         if (substr($key, 0, 6) == 'extra_') {
                             //an extra field
                             self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                         }
                     }
                     Database::query("DELETE FROM {$tbl_session_user} WHERE id_session='{$session_id}'");
                     Database::query("DELETE FROM {$tbl_session_course} WHERE id_session='{$session_id}'");
                     Database::query("DELETE FROM {$tbl_session_course_user} WHERE id_session='{$session_id}'");
                 }
                 $session_counter++;
             }
             $users = explode('|', $enreg['Users']);
             // Adding the relationship "Session - User".
             if (is_array($users)) {
                 foreach ($users as $user) {
                     $user_id = UserManager::get_user_id_from_username($user);
                     if ($user_id !== false) {
                         // Insert new users.
                         $sql = "INSERT IGNORE INTO {$tbl_session_user} SET\n                                    id_user = '******',\n                                    id_session = '{$session_id}'";
                         Database::query($sql);
                         if ($debug) {
                             $logger->addInfo("Sessions - Adding User #{$user_id} ({$user}) to session #{$session_id}");
                         }
                         $user_counter++;
                     }
                 }
             }
             $courses = explode('|', $enreg['Courses']);
             foreach ($courses as $course) {
                 $course_code = api_strtoupper(api_substr($course, 0, api_strpos($course, '[')));
                 if (CourseManager::course_exists($course_code)) {
                     $courseInfo = api_get_course_info($course_code);
                     $courseId = $courseInfo['real_id'];
                     // Adding the course to a session.
                     $sql_course = "INSERT IGNORE INTO {$tbl_session_course}\n                                       SET c_id = '" . $courseId . "', id_session = '{$session_id}'";
                     Database::query($sql_course);
                     if ($debug) {
                         $logger->addInfo("Sessions - Adding course '{$course_code}' to session #{$session_id}");
                     }
                     $course_counter++;
                     $pattern = "/\\[(.*?)\\]/";
                     preg_match_all($pattern, $course, $matches);
                     if (isset($matches[1])) {
                         $course_coaches = $matches[1][0];
                         $course_users = $matches[1][1];
                     }
                     $course_users = explode(',', $course_users);
                     $course_coaches = explode(',', $course_coaches);
                     // Adding coaches to session course user
                     if (!empty($course_coaches)) {
                         foreach ($course_coaches as $course_coach) {
                             $coach_id = UserManager::get_user_id_from_username($course_coach);
                             if ($coach_id !== false) {
                                 $sql = "INSERT IGNORE INTO {$tbl_session_course_user} SET\n                                            id_user='******',\n                                            c_id ='{$courseId}',\n                                            id_session = '{$session_id}',\n                                            status = 2 ";
                                 Database::query($sql);
                                 if ($debug) {
                                     $logger->addInfo("Sessions - Adding course coach: user #{$coach_id} ({$course_coach}) to course: '{$course_code}' and session #{$session_id}");
                                 }
                             } else {
                                 $error_message .= get_lang('UserDoesNotExist') . ' : ' . $course_coach . $eol;
                             }
                         }
                     }
                     $users_in_course_counter = 0;
                     // Adding the relationship "Session - Course - User".
                     foreach ($course_users as $user) {
                         $user_id = UserManager::get_user_id_from_username($user);
                         if ($user_id !== false) {
                             $sql = "INSERT IGNORE INTO {$tbl_session_course_user} SET\n                                        id_user='******',\n                                        c_id = '{$courseId}',\n                                        id_session = '{$session_id}'";
                             Database::query($sql);
                             if ($debug) {
                                 $logger->addInfo("Sessions - Adding student: user #{$user_id} ({$user}) to course: '{$course_code}' and session #{$session_id}");
                             }
                             $users_in_course_counter++;
                         } else {
                             $error_message .= get_lang('UserDoesNotExist') . ': ' . $user . $eol;
                         }
                     }
                     $sql = "UPDATE {$tbl_session_course} SET nbr_users='{$users_in_course_counter}' WHERE c_id ='{$courseId}'";
                     Database::query($sql);
                     $course_info = CourseManager::get_course_information($course_code);
                     $inserted_in_course[$course_code] = $course_info['title'];
                 }
             }
             $access_url_id = api_get_current_access_url_id();
             UrlManager::add_session_to_url($session_id, $access_url_id);
             $sql_update_users = "UPDATE {$tbl_session} SET nbr_users ='{$user_counter}', nbr_courses='{$course_counter}' WHERE id='{$session_id}'";
             Database::query($sql_update_users);
         }
     }
     return array('error_message' => $error_message, 'session_counter' => $session_counter);
 }
Example #16
0
 /**
  * This function displays the comparative report which allows you to compare two questions
  * A comparative report creates a table where one question is on the x axis and a second question is on the y axis.
  * In the intersection is the number of people who have answerd positive on both options.
  *
  * @return	string	HTML code
  *
  * @author Patrick Cool <*****@*****.**>, Ghent University
  * @version February 2007
  */
 public static function display_comparative_report()
 {
     // Allowed question types for comparative report
     $allowed_question_types = array('yesno', 'multiplechoice', 'multipleresponse', 'dropdown', 'percentage', 'score');
     // Getting all the questions
     $questions = SurveyManager::get_questions($_GET['survey_id']);
     // Actions bar
     echo '<div class="actions">';
     echo '<a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?survey_id=' . intval($_GET['survey_id']) . '&' . api_get_cidreq() . '">' . Display::return_icon('back.png', get_lang('BackTo') . ' ' . get_lang('ReportingOverview'), '', ICON_SIZE_MEDIUM) . '</a>';
     echo '</div>';
     // Displaying an information message that only the questions with predefined answers can be used in a comparative report
     Display::display_normal_message(get_lang('OnlyQuestionsWithPredefinedAnswers'), false);
     // The form for selecting the axis of the table
     echo '<form id="form1" name="form1" method="get" action="' . api_get_self() . '?action=' . Security::remove_XSS($_GET['action']) . '&survey_id=' . intval($_GET['survey_id']) . '&xaxis=' . Security::remove_XSS($_GET['xaxis']) . '&y=' . Security::remove_XSS($_GET['yaxis']) . '">';
     // Survey_id
     echo '<input type="hidden" name="action" value="' . Security::remove_XSS($_GET['action']) . '"/>';
     echo '<input type="hidden" name="survey_id" value="' . intval($_GET['survey_id']) . '"/>';
     // X axis
     echo get_lang('SelectXAxis') . ': ';
     echo '<select name="xaxis">';
     echo '<option value="">---</option>';
     foreach ($questions as $key => &$question) {
         if (is_array($allowed_question_types)) {
             if (in_array($question['type'], $allowed_question_types)) {
                 echo '<option value="' . $question['question_id'] . '"';
                 if (isset($_GET['xaxis']) && $_GET['xaxis'] == $question['question_id']) {
                     echo ' selected="selected"';
                 }
                 echo '">' . api_substr(strip_tags($question['question']), 0, 50) . '</option>';
             }
         }
     }
     echo '</select><br /><br />';
     // Y axis
     echo get_lang('SelectYAxis') . ': ';
     echo '<select name="yaxis">';
     echo '<option value="">---</option>';
     foreach ($questions as $key => &$question) {
         if (in_array($question['type'], $allowed_question_types)) {
             echo '<option value="' . $question['question_id'] . '"';
             if (isset($_GET['yaxis']) && $_GET['yaxis'] == $question['question_id']) {
                 echo ' selected="selected"';
             }
             echo '">' . api_substr(strip_tags($question['question']), 0, 50) . '</option>';
         }
     }
     echo '</select><br /><br />';
     echo '<button class="save" type="submit" name="Submit" value="Submit">' . get_lang('CompareQuestions') . '</button>';
     echo '</form>';
     // Getting all the information of the x axis
     if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis'])) {
         $question_x = SurveyManager::get_question($_GET['xaxis']);
     }
     // Getting all the information of the y axis
     if (isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) {
         $question_y = SurveyManager::get_question($_GET['yaxis']);
     }
     if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis']) && isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) {
         // Getting the answers of the two questions
         $answers_x = SurveyUtil::get_answers_of_question_by_user($_GET['survey_id'], $_GET['xaxis']);
         $answers_y = SurveyUtil::get_answers_of_question_by_user($_GET['survey_id'], $_GET['yaxis']);
         // Displaying the table
         $tableHtml = '<table border="1" class="data_table">';
         $xOptions = array();
         // The header
         $tableHtml .= '	<tr>';
         for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
             if ($ii == 0) {
                 $tableHtml .= '		<th>&nbsp;</th>';
             } else {
                 if ($question_x['type'] == 'score') {
                     for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
                         $tableHtml .= '		<th>' . $question_x['answers'][$ii - 1] . '<br />' . $x . '</th>';
                     }
                     $x = '';
                 } else {
                     $tableHtml .= '		<th>' . $question_x['answers'][$ii - 1] . '</th>';
                 }
                 $optionText = strip_tags($question_x['answers'][$ii - 1]);
                 $optionText = html_entity_decode($optionText);
                 array_push($xOptions, trim($optionText));
             }
         }
         $tableHtml .= '	</tr>';
         $chartData = array();
         // The main part
         for ($ij = 0; $ij < count($question_y['answers']); $ij++) {
             $currentYQuestion = strip_tags($question_y['answers'][$ij]);
             $currentYQuestion = html_entity_decode($currentYQuestion);
             // The Y axis is a scoring question type so we have more rows than the options (actually options * maximum score)
             if ($question_y['type'] == 'score') {
                 for ($y = 1; $y <= $question_y['maximum_score']; $y++) {
                     $tableHtml .= '	<tr>';
                     for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
                         if ($question_x['type'] == 'score') {
                             for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
                                 if ($ii == 0) {
                                     $tableHtml .= ' <th>' . $question_y['answers'][$ij] . ' ' . $y . '</th>';
                                     break;
                                 } else {
                                     $tableHtml .= ' <td align="center">';
                                     $votes = SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][$ii - 1], $question_y['answersid'][$ij], $x, $y);
                                     $tableHtml .= $votes;
                                     array_push($chartData, array('serie' => array($currentYQuestion, $xOptions[$ii - 1]), 'option' => $x, 'votes' => $votes));
                                     $tableHtml .= '</td>';
                                 }
                             }
                         } else {
                             if ($ii == 0) {
                                 $tableHtml .= '<th>' . $question_y['answers'][$ij] . ' ' . $y . '</th>';
                             } else {
                                 $tableHtml .= '<td align="center">';
                                 $votes = SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][$ii - 1], $question_y['answersid'][$ij], 0, $y);
                                 $tableHtml .= $votes;
                                 array_push($chartData, array('serie' => array($currentYQuestion, $xOptions[$ii - 1]), 'option' => $y, 'votes' => $votes));
                                 $tableHtml .= '</td>';
                             }
                         }
                     }
                     $tableHtml .= '	</tr>';
                 }
             } else {
                 $tableHtml .= '	<tr>';
                 for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
                     if ($question_x['type'] == 'score') {
                         for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
                             if ($ii == 0) {
                                 $tableHtml .= '		<th>' . $question_y['answers'][$ij] . '</th>';
                                 break;
                             } else {
                                 $tableHtml .= '		<td align="center">';
                                 $votes = SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][$ii - 1], $question_y['answersid'][$ij], $x, 0);
                                 $tableHtml .= $votes;
                                 array_push($chartData, array('serie' => array($currentYQuestion, $xOptions[$ii - 1]), 'option' => $x, 'votes' => $votes));
                                 $tableHtml .= '</td>';
                             }
                         }
                     } else {
                         if ($ii == 0) {
                             $tableHtml .= '		<th>' . $question_y['answers'][$ij] . '</th>';
                         } else {
                             $tableHtml .= '		<td align="center">';
                             $votes = SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][$ii - 1], $question_y['answersid'][$ij]);
                             $tableHtml .= $votes;
                             array_push($chartData, array('serie' => $xOptions[$ii - 1], 'option' => $currentYQuestion, 'votes' => $votes));
                             $tableHtml .= '</td>';
                         }
                     }
                 }
                 $tableHtml .= '	</tr>';
             }
         }
         $tableHtml .= '</table>';
         echo '<div id="chartContainer" class="col-md-12">';
         echo self::drawChart($chartData, true);
         echo '</div>';
         echo $tableHtml;
     }
 }
Example #17
0
 /**
  * Displays the form to register users in a blog (in a course)
  * The listed users are users subcribed in the course.
  * @author Toon Keppens
  *
  * @param Integer $blog_id
  *
  * @return Html Form with sortable table with users to unsubcribe from a blog.
  */
 public static function display_form_user_unsubscribe($blog_id)
 {
     $_user = api_get_user_info();
     $is_western_name_order = api_is_western_name_order();
     // Init
     $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
     $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
     echo '<legend>' . get_lang('UnsubscribeMembers') . '</legend>';
     $properties["width"] = "100%";
     //table column titles
     $column_header[] = array('', false, '');
     if ($is_western_name_order) {
         $column_header[] = array(get_lang('FirstName'), true, '');
         $column_header[] = array(get_lang('LastName'), true, '');
     } else {
         $column_header[] = array(get_lang('LastName'), true, '');
         $column_header[] = array(get_lang('FirstName'), true, '');
     }
     $column_header[] = array(get_lang('Email'), false, '');
     $column_header[] = array(get_lang('TaskManager'), true, '');
     $column_header[] = array(get_lang('UnRegister'), false, '');
     $course_id = api_get_course_int_id();
     $sql = "SELECT user.user_id, user.lastname, user.firstname, user.email, user.username\n                FROM {$tbl_users} user INNER JOIN {$tbl_blogs_rel_user} blogs_rel_user\n                ON user.user_id = blogs_rel_user.user_id\n                WHERE blogs_rel_user.c_id = {$course_id} AND  blogs_rel_user.blog_id = '" . (int) $blog_id . "'";
     if (!($sql_result = Database::query($sql))) {
         return false;
     }
     $user_data = array();
     while ($myrow = Database::fetch_array($sql_result)) {
         $row = array();
         $row[] = '<input type="checkbox" name="user[]" value="' . $myrow['user_id'] . '" ' . (isset($_GET['selectall']) && $_GET['selectall'] == "unsubscribe" ? ' checked="checked" ' : '') . '/>';
         $username = api_htmlentities(sprintf(get_lang('LoginX'), $myrow["username"]), ENT_QUOTES);
         if ($is_western_name_order) {
             $row[] = $myrow["firstname"];
             $row[] = Display::tag('span', $myrow["lastname"], array('title' => $username));
         } else {
             $row[] = Display::tag('span', $myrow["lastname"], array('title' => $username));
             $row[] = $myrow["firstname"];
         }
         $row[] = Display::icon_mailto_link($myrow["email"]);
         $sql = "SELECT bt.title task\n\t\t\t\t\tFROM " . Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER) . " btu\n\t\t\t\t\tINNER JOIN " . Database::get_course_table(TABLE_BLOGS_TASKS) . " bt\n\t\t\t\t\tON btu.task_id = bt.task_id\n\t\t\t\t\tWHERE \tbtu.c_id \t= {$course_id}  AND\n\t\t\t\t\t\t\tbt.c_id \t= {$course_id}  AND\n\t\t\t\t\t\t\tbtu.blog_id = {$blog_id} AND\n\t\t\t\t\t\t\tbtu.user_id = " . $myrow['user_id'];
         $sql_res = Database::query($sql);
         $task = '';
         while ($r = Database::fetch_array($sql_res)) {
             $task .= stripslashes($r['task']) . ', ';
         }
         //echo $task;
         $task = api_strlen(trim($task)) != 0 ? api_substr($task, 0, api_strlen($task) - 2) : get_lang('Reader');
         $row[] = $task;
         //Link to register users
         if ($myrow["user_id"] != $_user['user_id']) {
             $row[] = "<a class=\"btn btn-primary\" href=\"" . api_get_self() . "?action=manage_members&blog_id={$blog_id}&unregister=yes&user_id=" . $myrow['user_id'] . "\">" . get_lang('UnRegister') . "</a>";
         } else {
             $row[] = '';
         }
         $user_data[] = $row;
     }
     $query_vars['action'] = 'manage_members';
     $query_vars['blog_id'] = $blog_id;
     echo '<form method="post" action="blog.php?action=manage_members&blog_id=' . $blog_id . '">';
     Display::display_sortable_table($column_header, $user_data, null, null, $query_vars);
     $link = '';
     $link .= isset($_GET['action']) ? 'action=' . Security::remove_XSS($_GET['action']) . '&' : '';
     $link .= "blog_id={$blog_id}&";
     echo '<a href="blog.php?' . $link . 'selectall=unsubscribe">' . get_lang('SelectAll') . '</a> - ';
     echo '<a href="blog.php?' . $link . '">' . get_lang('UnSelectAll') . '</a> ';
     echo get_lang('WithSelected') . ' : ';
     echo '<select name="action">';
     echo '<option value="select_unsubscribe">' . get_lang('UnRegister') . '</option>';
     echo '</select>';
     echo '<input type="hidden" name="unregister" value="true" />';
     echo '<button class="save" type="submit">' . get_lang('Ok') . '</button>';
     echo '</form>';
 }
 /**
  * This form will build a form to add users to an evaluation
  */
 protected function build_add_user_to_eval()
 {
     $this->addElement('header', get_lang('ChooseUser'));
     $select = $this->addElement('select', 'firstLetterUser', get_lang('FirstLetter'), null, array('onchange' => 'document.add_users_to_evaluation.submit()'));
     $select->addOption('', '');
     for ($i = 65; $i <= 90; $i++) {
         $letter = chr($i);
         if (isset($this->extra) && $this->extra == $letter) {
             $select->addOption($letter, $letter, 'selected');
         } else {
             $select->addOption($letter, $letter);
         }
     }
     $select = $this->addElement('select', 'add_users', null, null, array('multiple' => 'multiple', 'size' => '15', 'style' => 'width:250px'));
     foreach ($this->evaluation_object->get_not_subscribed_students() as $user) {
         if (!isset($this->extra) || empty($this->extra) || api_strtoupper(api_substr($user[1], 0, 1)) == $this->extra) {
             $select->addoption($user[1] . ' ' . $user[2] . ' (' . $user[3] . ')', $user[0]);
         }
     }
     $this->addButtonCreate(get_lang('AddUserToEval'), 'submit_button');
 }
include 'answer.class.php';
include '../inc/global.inc.php';
include '../inc/lib/database.lib.php';
$courseCode = $_GET['coursecode'];
$questionId = $_GET['questionId'];
$coordinates = $_GET['coord'];
$objExcercise = $_SESSION['objExercise'];
$exerciseId = $objExcercise->selectId();
// Save clicking order
$answerOrderId = count($_SESSION['exerciseResult'][$questionId]['ids']) + 1;
if ($_GET['answerId'] == "0") {
    $hit = 0;
    $answerId = NULL;
} else {
    $hit = 1;
    $answerId = api_substr($_GET['answerId'], 22, 2);
    // Save into session
    $_SESSION['exerciseResult'][$questionId][$answerId] = $hit;
}
//round-up the coordinates
$coords = explode('/', $coordinates);
$coordinates = '';
foreach ($coords as $coord) {
    list($x, $y) = explode(';', $coord);
    $coordinates .= round($x) . ';' . round($y) . '/';
}
$coordinates = substr($coordinates, 0, -1);
$TBL_TRACK_E_HOTSPOT = Database::get_statistic_table(STATISTIC_TRACK_E_HOTSPOTS);
// Save into db
$sql = "INSERT INTO {$TBL_TRACK_E_HOTSPOT} (user_id , course_id , quiz_id , question_id , answer_id , correct , coordinate ) VALUES (\n\t\t\t" . intval($_user['user_id']) . ",\n\t\t\t'" . Database::escape_string($courseCode) . "',\n\t\t\t" . intval($exerciseId) . ",\n\t\t\t" . intval($questionId) . ",\n\t\t\t" . intval($answerId) . ",\n\t\t\t" . intval($hit) . "',\n\t\t\t'" . Database::escape_string($coordinates) . "')";
$result = Database::query($sql);
Example #20
0
 /**
  * @param array $answer
  * @param string $user_answer
  * @return array
  */
 public static function check_fill_in_blanks($answer, $user_answer)
 {
     // the question is encoded like this
     // [A] B [C] D [E] F::10,10,10@1
     // number 1 before the "@" means that is a switchable fill in blank question
     // [A] B [C] D [E] F::10,10,10@ or  [A] B [C] D [E] F::10,10,10
     // means that is a normal fill blank question
     // first we explode the "::"
     $pre_array = explode('::', $answer);
     // is switchable fill blank or not
     $last = count($pre_array) - 1;
     $is_set_switchable = explode('@', $pre_array[$last]);
     $switchable_answer_set = false;
     if (isset($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
         $switchable_answer_set = true;
     }
     $answer = '';
     for ($k = 0; $k < $last; $k++) {
         $answer .= $pre_array[$k];
     }
     // splits weightings that are joined with a comma
     $answerWeighting = explode(',', $is_set_switchable[0]);
     // we save the answer because it will be modified
     //$temp = $answer;
     $temp = $answer;
     $answer = '';
     $j = 0;
     //initialise answer tags
     $user_tags = $correct_tags = $real_text = array();
     // the loop will stop at the end of the text
     while (1) {
         // quits the loop if there are no more blanks (detect '[')
         if (($pos = api_strpos($temp, '[')) === false) {
             // adds the end of the text
             $answer = $temp;
             $real_text[] = $answer;
             break;
             //no more "blanks", quit the loop
         }
         // adds the piece of text that is before the blank
         //and ends with '[' into a general storage array
         $real_text[] = api_substr($temp, 0, $pos + 1);
         $answer .= api_substr($temp, 0, $pos + 1);
         //take the string remaining (after the last "[" we found)
         $temp = api_substr($temp, $pos + 1);
         // quit the loop if there are no more blanks, and update $pos to the position of next ']'
         if (($pos = api_strpos($temp, ']')) === false) {
             // adds the end of the text
             $answer .= $temp;
             break;
         }
         $str = $user_answer;
         preg_match_all('#\\[([^[]*)\\]#', $str, $arr);
         $str = str_replace('\\r\\n', '', $str);
         $choice = $arr[1];
         $tmp = api_strrpos($choice[$j], ' / ');
         $choice[$j] = api_substr($choice[$j], 0, $tmp);
         $choice[$j] = trim($choice[$j]);
         //Needed to let characters ' and " to work as part of an answer
         $choice[$j] = stripslashes($choice[$j]);
         $user_tags[] = api_strtolower($choice[$j]);
         //put the contents of the [] answer tag into correct_tags[]
         $correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
         $j++;
         $temp = api_substr($temp, $pos + 1);
     }
     $answer = '';
     $real_correct_tags = $correct_tags;
     $chosen_list = array();
     $good_answer = array();
     for ($i = 0; $i < count($real_correct_tags); $i++) {
         if (!$switchable_answer_set) {
             //needed to parse ' and " characters
             $user_tags[$i] = stripslashes($user_tags[$i]);
             if ($correct_tags[$i] == $user_tags[$i]) {
                 $good_answer[$correct_tags[$i]] = 1;
             } elseif (!empty($user_tags[$i])) {
                 $good_answer[$correct_tags[$i]] = 0;
             } else {
                 $good_answer[$correct_tags[$i]] = 0;
             }
         } else {
             // switchable fill in the blanks
             if (in_array($user_tags[$i], $correct_tags)) {
                 $correct_tags = array_diff($correct_tags, $chosen_list);
                 $good_answer[$correct_tags[$i]] = 1;
             } elseif (!empty($user_tags[$i])) {
                 $good_answer[$correct_tags[$i]] = 0;
             } else {
                 $good_answer[$correct_tags[$i]] = 0;
             }
         }
         // adds the correct word, followed by ] to close the blank
         $answer .= ' / <font color="green"><b>' . $real_correct_tags[$i] . '</b></font>]';
         if (isset($real_text[$i + 1])) {
             $answer .= $real_text[$i + 1];
         }
     }
     return $good_answer;
 }
Example #21
0
 }
 if ($debug > 0) {
     error_log('Videoconf upload path: ' . VIDEOCONF_UPLOAD_PATH);
 }
 /* $canDelete = ($canDelete && $isBellowVideoConfUploadPath);
  */
 $can_delete = $is_manager && $is_below_videoconf_dir;
 // get files list
 $files = DocumentManager::get_all_document_data($_course, $cwd, 0, null, false);
 printf("<dokeosobject><fileListMeta></fileListMeta><fileList>");
 printf("<folders>");
 // title filter
 if (is_array($files)) {
     foreach (array_keys($files) as $k) {
         // converting to UTF-8
         $files[$k]['title'] = api_convert_encoding(api_strlen($files[$k]['title']) > 32 ? api_substr($files[$k]['title'], 0, 32) . "..." : $files[$k]['title'], 'utf-8', api_get_system_encoding());
         // removing '<', '>' and '_'
         $files[$k]['title'] = str_replace(array('<', '>', '_'), ' ', $files[$k]['title']);
     }
 }
 if (is_array($files)) {
     foreach ($files as $i) {
         if ($i["filetype"] == "folder") {
             printf('<folder><path>%s</path><title>%s</title><canDelete>%s</canDelete></folder>', $i['path'], $i['title'], $can_delete ? 'true' : 'false');
         }
     }
 }
 printf("</folders><files>");
 if (is_array($files)) {
     foreach ($files as $i) {
         $extension = strrpos($i['path'], '.') > 0 ? substr($i['path'], strrpos($i['path'], '.'), 10) : '';
Example #22
0
$question_counter = 1;
$sql = "SELECT * FROM {$table_survey_question_group}\n        WHERE c_id = '.{$course_id}.' AND survey_id = '" . Database::escape_string($survey_id) . "' ORDER BY id";
$result = Database::query($sql);
$groups = array();
while ($row = Database::fetch_array($result)) {
    $groups[$row['id']] = $row['name'];
}
$sql = "SELECT survey_question.*, count(survey_question_option.question_option_id) as number_of_options\n        FROM {$table_survey_question} survey_question\n        LEFT JOIN {$table_survey_question_option} survey_question_option\n        ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = {$course_id}\n        WHERE\n            survey_question.survey_id \t= '" . Database::escape_string($survey_id) . "' AND\n             survey_question.c_id \t\t= {$course_id}\n        GROUP BY survey_question.question_id\n        ORDER BY survey_question.sort ASC";
$result = Database::query($sql);
$question_counter_max = Database::num_rows($result);
while ($row = Database::fetch_array($result, 'ASSOC')) {
    echo '<tr>';
    echo '	<td>' . $question_counter . '</td>';
    echo '	<td>';
    if (api_strlen($row['survey_question']) > 100) {
        echo api_substr(strip_tags($row['survey_question']), 0, 100) . ' ... ';
    } else {
        echo $row['survey_question'];
    }
    if ($row['type'] == 'yesno') {
        $tool_name = get_lang('YesNo');
    } else {
        if ($row['type'] == 'multiplechoice') {
            $tool_name = get_lang('UniqueSelect');
        } else {
            $tool_name = get_lang(api_ucfirst(Security::remove_XSS($row['type'])));
        }
    }
    echo '</td>';
    echo '	<td>' . $tool_name . '</td>';
    echo '	<td>' . $row['number_of_options'] . '</td>';
                 $userscourse .= str_replace(';', ',', $rowUsersCourse['username']) . ',';
             } else {
                 $courses .= "\t\t\t<User>{$rowUsersCourse['username']}</User>\n";
             }
         }
         if ($cvs) {
             if (!empty($userscourse)) {
                 $userscourse = api_substr($userscourse, 0, api_strlen($userscourse) - 1);
             }
             $courses .= $userscourse . ']|';
         } else {
             $courses .= "\t\t</Course>\n";
         }
     }
     if (!empty($courses) && $cvs) {
         $courses = api_substr($courses, 0, api_strlen($courses) - 1);
     }
     $add .= $courses;
     if (in_array($file_type, ['csv', 'xls'])) {
         $sessionListToExport[] = [$row['name'], $row['username'], $row['access_start_date'], $row['access_end_date'], $row['visibility'], $row['session_category'], $users, $courses];
     } else {
         $add = "\t<Session>\n" . "\t\t<SessionName>{$row['name']}</SessionName>\n" . "\t\t<Coach>{$row['username']}</Coach>\n" . "\t\t<DateStart>{$row['access_start_date']}</DateStart>\n" . "\t\t<DateEnd>{$row['access_end_date']}</DateEnd>\n" . "\t\t<Visibility>{$row['visibility']}</Visibility>\n" . "\t\t<SessionCategory>{$row['session_category']}</SessionCategory>\n";
     }
     if (!$cvs) {
         $add .= "\t</Session>\n";
         fputs($fp, $add);
     }
 }
 switch ($file_type) {
     case 'xml':
         fputs($fp, "</Sessions>\n");
 public function fill_in_blank_answer_to_string($answer)
 {
     $teacher_answer_list = $this->fill_in_blank_answer_to_array($answer);
     $result = '';
     if (!empty($teacher_answer_list)) {
         $i = 0;
         foreach ($teacher_answer_list as $teacher_item) {
             $value = null;
             //Cleaning student answer list
             $value = strip_tags($teacher_item);
             $value = api_substr($value, 1, api_strlen($value) - 2);
             $value = explode('/', $value);
             if (!empty($value[0])) {
                 $value = trim($value[0]);
                 $value = str_replace('&nbsp;', '', $value);
                 $result .= $value;
             }
         }
     }
     return $result;
 }
Example #25
0
 /**
  * @param array $group_list
  * @param int $category_id
  */
 static function process_groups($group_list, $category_id = null)
 {
     global $origin, $charset;
     $category_id = intval($category_id);
     $totalRegistered = 0;
     $group_data = array();
     $user_info = api_get_user_info();
     $session_id = api_get_session_id();
     $user_id = $user_info['user_id'];
     $orig = isset($origin) ? $origin : null;
     foreach ($group_list as $this_group) {
         // Validation when belongs to a session
         $session_img = api_get_session_image($this_group['session_id'], $user_info['status']);
         // All the tutors of this group
         $tutorsids_of_group = self::get_subscribed_tutors($this_group['id'], true);
         // Create a new table-row
         $row = array();
         // Checkbox
         if (api_is_allowed_to_edit(false, true) && count($group_list) > 1) {
             $row[] = $this_group['id'];
         }
         // Group name
         if ((api_is_allowed_to_edit(false, true) || in_array($user_id, $tutorsids_of_group) || $this_group['is_member'] || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_FORUM) || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_DOCUMENTS) || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_CALENDAR) || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_ANNOUNCEMENT) || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_WORK) || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_WIKI)) && !(api_is_course_coach() && intval($this_group['session_id']) != $session_id)) {
             $group_name = '<a href="group_space.php?cidReq=' . api_get_course_id() . '&amp;origin=' . $orig . '&amp;gidReq=' . $this_group['id'] . '">' . Security::remove_XSS($this_group['name']) . '</a> ';
             if (!empty($user_id) && !empty($this_group['id_tutor']) && $user_id == $this_group['id_tutor']) {
                 $group_name .= Display::label(get_lang('OneMyGroups'), 'success');
             } elseif ($this_group['is_member']) {
                 $group_name .= Display::label(get_lang('MyGroup'), 'success');
             }
             if (api_is_allowed_to_edit() && !empty($this_group['session_name'])) {
                 $group_name .= ' (' . $this_group['session_name'] . ')';
             }
             $group_name .= $session_img;
             $row[] = $group_name . '<br />' . stripslashes(trim($this_group['description']));
         } else {
             $row[] = $this_group['name'] . '<br />' . stripslashes(trim($this_group['description']));
         }
         // Tutor name
         $tutor_info = null;
         if (count($tutorsids_of_group) > 0) {
             foreach ($tutorsids_of_group as $tutor_id) {
                 $tutor = api_get_user_info($tutor_id);
                 $username = api_htmlentities(sprintf(get_lang('LoginX'), $tutor['username']), ENT_QUOTES);
                 if (api_get_setting('show_email_addresses') == 'true') {
                     $tutor_info .= Display::tag('span', Display::encrypted_mailto_link($tutor['mail'], api_get_person_name($tutor['firstName'], $tutor['lastName'])), array('title' => $username)) . ', ';
                 } else {
                     if (api_is_allowed_to_edit()) {
                         $tutor_info .= Display::tag('span', Display::encrypted_mailto_link($tutor['mail'], api_get_person_name($tutor['firstName'], $tutor['lastName'])), array('title' => $username)) . ', ';
                     } else {
                         $tutor_info .= Display::tag('span', api_get_person_name($tutor['firstName'], $tutor['lastName']), array('title' => $username)) . ', ';
                     }
                 }
             }
         }
         $tutor_info = api_substr($tutor_info, 0, api_strlen($tutor_info) - 2);
         $row[] = $tutor_info;
         // Max number of members in group
         $max_members = $this_group['maximum_number_of_members'] == self::MEMBER_PER_GROUP_NO_LIMIT ? ' ' : ' / ' . $this_group['maximum_number_of_members'];
         // Number of members in group
         $row[] = $this_group['number_of_members'] . $max_members;
         // Self-registration / unregistration
         if (!api_is_allowed_to_edit(false, true)) {
             if (self::is_self_registration_allowed($user_id, $this_group['id'])) {
                 $row[] = '<a class = "btn" href="group.php?' . api_get_cidreq() . '&category=' . $category_id . '&amp;action=self_reg&amp;group_id=' . $this_group['id'] . '" onclick="javascript:if(!confirm(' . "'" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset)) . "'" . ')) return false;">' . get_lang('GroupSelfRegInf') . '</a>';
             } elseif (self::is_self_unregistration_allowed($user_id, $this_group['id'])) {
                 $row[] = '<a class = "btn" href="group.php?' . api_get_cidreq() . '&category=' . $category_id . '&amp;action=self_unreg&amp;group_id=' . $this_group['id'] . '" onclick="javascript:if(!confirm(' . "'" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset)) . "'" . ')) return false;">' . get_lang('GroupSelfUnRegInf') . '</a>';
             } else {
                 $row[] = '-';
             }
         }
         $url = api_get_path(WEB_CODE_PATH) . 'group/';
         // Edit-links
         if (api_is_allowed_to_edit(false, true) && !(api_is_course_coach() && intval($this_group['session_id']) != $session_id)) {
             $edit_actions = '<a href="' . $url . 'settings.php?' . api_get_cidreq(true, false) . '&gidReq=' . $this_group['id'] . '"  title="' . get_lang('Edit') . '">' . Display::return_icon('edit.png', get_lang('EditGroup'), '', ICON_SIZE_SMALL) . '</a>&nbsp;';
             $edit_actions .= '<a href="' . $url . 'member_settings.php?' . api_get_cidreq(true, false) . '&gidReq=' . $this_group['id'] . '"  title="' . get_lang('GroupMembers') . '">' . Display::return_icon('user.png', get_lang('GroupMembers'), '', ICON_SIZE_SMALL) . '</a>&nbsp;';
             $edit_actions .= '<a href="' . $url . 'group_overview.php?action=export&type=xls&' . api_get_cidreq(true, false) . '&id=' . $this_group['id'] . '"  title="' . get_lang('ExportUsers') . '">' . Display::return_icon('export_excel.png', get_lang('Export'), '', ICON_SIZE_SMALL) . '</a>&nbsp;';
             /*$edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&amp;action=empty_one&amp;id='.$this_group['id'].'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('EmptyGroup').'">'.
               Display::return_icon('clean.png',get_lang('EmptyGroup'),'',ICON_SIZE_SMALL).'</a>&nbsp;';*/
             $edit_actions .= '<a href="' . api_get_self() . '?' . api_get_cidreq(true, false) . '&category=' . $category_id . '&amp;action=fill_one&amp;id=' . $this_group['id'] . '" onclick="javascript: if(!confirm(' . "'" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES)) . "'" . ')) return false;" title="' . get_lang('FillGroup') . '">' . Display::return_icon('fill.png', get_lang('FillGroup'), '', ICON_SIZE_SMALL) . '</a>&nbsp;';
             $edit_actions .= '<a href="' . api_get_self() . '?' . api_get_cidreq(true, false) . '&category=' . $category_id . '&amp;action=delete_one&amp;id=' . $this_group['id'] . '" onclick="javascript: if(!confirm(' . "'" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES)) . "'" . ')) return false;" title="' . get_lang('Delete') . '">' . Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>&nbsp;';
             $row[] = $edit_actions;
         }
         if (!empty($this_group['nbMember'])) {
             $totalRegistered = $totalRegistered + $this_group['nbMember'];
         }
         $group_data[] = $row;
     }
     // end loop
     $table = new SortableTableFromArrayConfig($group_data, 1, 20, 'group_category_' . $category_id);
     $table->set_additional_parameters(array('category' => $category_id));
     $column = 0;
     if (api_is_allowed_to_edit(false, true) and count($group_list) > 1) {
         $table->set_header($column++, '', false);
     }
     $table->set_header($column++, get_lang('Groups'));
     $table->set_header($column++, get_lang('GroupTutor'));
     $table->set_header($column++, get_lang('Registered'), false);
     if (!api_is_allowed_to_edit(false, true)) {
         // If self-registration allowed
         $table->set_header($column++, get_lang('GroupSelfRegistration'), false);
     }
     if (api_is_allowed_to_edit(false, true)) {
         // Only for course administrator
         $table->set_header($column++, get_lang('Modify'), false);
         $form_actions = array();
         $form_actions['fill_selected'] = get_lang('FillGroup');
         $form_actions['empty_selected'] = get_lang('EmptyGroup');
         $form_actions['delete_selected'] = get_lang('Delete');
         if (count($group_list) > 1) {
             $table->set_form_actions($form_actions, 'group');
         }
     }
     $table->display();
 }
Example #26
0
 /**
  * Returns the form to update or create a document
  * @param    string    Action (add/edit)
  * @param    integer    ID of the lp_item (if already exists)
  * @param    mixed    Integer if document ID, string if info ('new')
  * @return    string    HTML form
  */
 public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
 {
     $course_id = api_get_course_int_id();
     $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
     $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
     $no_display_edit_textarea = false;
     //If action==edit document
     //We don't display the document form if it's not an editable document (html or txt file)
     if ($action == "edit") {
         if (is_array($extra_info)) {
             $path_parts = pathinfo($extra_info['dir']);
             if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
                 $no_display_edit_textarea = true;
             }
         }
     }
     $no_display_add = false;
     // If action==add an existing document
     // We don't display the document form if it's not an editable document (html or txt file).
     if ($action == "add") {
         if (is_numeric($extra_info)) {
             $sql_doc = "SELECT path FROM " . $tbl_doc . " WHERE c_id = " . $course_id . " AND id = " . Database::escape_string($extra_info);
             $result = Database::query($sql_doc);
             $path_file = Database::result($result, 0, 0);
             $path_parts = pathinfo($path_file);
             if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
                 $no_display_add = true;
             }
         }
     }
     if ($id != 0 && is_array($extra_info)) {
         $item_title = stripslashes($extra_info['title']);
         $item_description = stripslashes($extra_info['description']);
         $item_terms = stripslashes($extra_info['terms']);
         if (empty($item_title)) {
             $path_parts = pathinfo($extra_info['path']);
             $item_title = stripslashes($path_parts['filename']);
         }
     } elseif (is_numeric($extra_info)) {
         $sql_doc = "SELECT path, title FROM " . $tbl_doc . "\n                        WHERE c_id = " . $course_id . " AND id = " . Database::escape_string($extra_info);
         $result = Database::query($sql_doc);
         $row = Database::fetch_array($result);
         $explode = explode('.', $row['title']);
         if (count($explode) > 1) {
             for ($i = 0; $i < count($explode) - 1; $i++) {
                 $item_title .= $explode[$i];
             }
         } else {
             $item_title = $row['title'];
         }
         $item_title = str_replace('_', ' ', $item_title);
         if (empty($item_title)) {
             $path_parts = pathinfo($row['path']);
             $item_title = stripslashes($path_parts['filename']);
         }
     } else {
         $item_title = '';
         $item_description = '';
     }
     $return = '<legend>';
     if ($id != 0 && is_array($extra_info)) {
         $parent = $extra_info['parent_item_id'];
     } else {
         $parent = 0;
     }
     $sql = "SELECT * FROM " . $tbl_lp_item . "\n                WHERE c_id = " . $course_id . " AND lp_id = " . $this->lp_id;
     $result = Database::query($sql);
     $arrLP = array();
     while ($row = Database::fetch_array($result)) {
         $arrLP[] = array('id' => $row['id'], 'item_type' => $row['item_type'], 'title' => $row['title'], 'path' => $row['path'], 'description' => $row['description'], 'parent_item_id' => $row['parent_item_id'], 'previous_item_id' => $row['previous_item_id'], 'next_item_id' => $row['next_item_id'], 'display_order' => $row['display_order'], 'max_score' => $row['max_score'], 'min_score' => $row['min_score'], 'mastery_score' => $row['mastery_score'], 'prerequisite' => $row['prerequisite']);
     }
     $this->tree_array($arrLP);
     $arrLP = null;
     if (isset($this->arrMenu)) {
         $arrLP = $this->arrMenu;
         unset($this->arrMenu);
     }
     if ($action == 'add') {
         $return .= get_lang('CreateTheDocument');
     } elseif ($action == 'move') {
         $return .= get_lang('MoveTheCurrentDocument');
     } else {
         $return .= get_lang('EditTheCurrentDocument');
     }
     $return .= '</legend>';
     if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
         $return .= Display::return_warning_message('<strong>' . get_lang('Warning') . ' !</strong><br />' . get_lang('WarningEditingDocument'), false);
     }
     $form = new FormValidator('form', 'POST', api_get_self() . '?' . $_SERVER['QUERY_STRING'], '', array('enctype' => "multipart/form-data"));
     $defaults['title'] = Security::remove_XSS($item_title);
     if (empty($item_title)) {
         $defaults['title'] = Security::remove_XSS($item_title);
     }
     $defaults['description'] = $item_description;
     $form->addElement('html', $return);
     if ($action != 'move') {
         $form->addElement('text', 'title', get_lang('Title'), array('id' => 'idTitle', 'class' => 'span4'));
         $form->applyFilter('title', 'html_filter');
     }
     //$arrHide = array($id);
     $arrHide[0]['value'] = $this->name;
     $arrHide[0]['padding'] = 3;
     for ($i = 0; $i < count($arrLP); $i++) {
         if ($action != 'add') {
             if (($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide) && !in_array($arrLP[$i]['parent_item_id'], $arrHide)) {
                 $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
                 $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10;
                 if ($parent == $arrLP[$i]['id']) {
                     $s_selected_parent = $arrHide[$arrLP[$i]['id']];
                 }
             }
         } else {
             if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') {
                 $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
                 $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10;
                 if ($parent == $arrLP[$i]['id']) {
                     $s_selected_parent = $arrHide[$arrLP[$i]['id']];
                 }
             }
         }
     }
     $parent_select = $form->addElement('select', 'parent', get_lang('Parent'), '', 'class="learnpath_item_form" id="idParent" style="width:40%;" onchange="javascript: load_cbo(this.value);"');
     $my_count = 0;
     foreach ($arrHide as $key => $value) {
         if ($my_count != 0) {
             // The LP name is also the first section and is not in the same charset like the other sections.
             $value['value'] = Security::remove_XSS($value['value']);
             $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"');
         } else {
             $value['value'] = Security::remove_XSS($value['value']);
             $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"');
         }
         $my_count++;
     }
     if (!empty($id)) {
         $parent_select->setSelected($parent);
     } else {
         $parent_item_id = Session::read('parent_item_id');
         $parent_select->setSelected($parent_item_id);
     }
     if (is_array($arrLP)) {
         reset($arrLP);
     }
     $arrHide = array();
     $s_selected_position = null;
     //POSITION
     for ($i = 0; $i < count($arrLP); $i++) {
         if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
             if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id']) {
                 $s_selected_position = $arrLP[$i]['id'];
             } elseif ($action == 'add') {
                 $s_selected_position = $arrLP[$i]['id'];
             }
             $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After') . ' "' . $arrLP[$i]['title'] . '"';
         }
     }
     $position = $form->addElement('select', 'previous', get_lang('Position'), '', 'id="previous" class="learnpath_item_form" style="width:40%;"');
     $position->addOption(get_lang('FirstPosition'), 0);
     foreach ($arrHide as $key => $value) {
         $padding = isset($value['padding']) ? $value['padding'] : 0;
         $position->addOption($value['value'], $key, 'style="padding-left:' . $padding . 'px;"');
     }
     $position->setSelected($s_selected_position);
     if (is_array($arrLP)) {
         reset($arrLP);
     }
     if ($action != 'move') {
         $id_prerequisite = 0;
         if (is_array($arrLP)) {
             foreach ($arrLP as $key => $value) {
                 if ($value['id'] == $id) {
                     $id_prerequisite = $value['prerequisite'];
                     break;
                 }
             }
         }
         $arrHide = array();
         for ($i = 0; $i < count($arrLP); $i++) {
             if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
                 if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id']) {
                     $s_selected_position = $arrLP[$i]['id'];
                 } elseif ($action == 'add') {
                     $s_selected_position = $arrLP[$i]['id'];
                 }
                 $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
             }
         }
         if (!$no_display_add) {
             if ($extra_info == 'new' || $extra_info['item_type'] == TOOL_DOCUMENT || $_GET['edit'] == 'true') {
                 if (isset($_POST['content'])) {
                     $content = stripslashes($_POST['content']);
                 } elseif (is_array($extra_info)) {
                     //If it's an html document or a text file
                     if (!$no_display_edit_textarea) {
                         $content = $this->display_document($extra_info['path'], false, false);
                     }
                 } elseif (is_numeric($extra_info)) {
                     $content = $this->display_document($extra_info, false, false);
                 } else {
                     $content = '';
                 }
                 if (!$no_display_edit_textarea) {
                     // We need to calculate here some specific settings for the online editor.
                     // The calculated settings work for documents in the Documents tool
                     // (on the root or in subfolders).
                     // For documents in native scorm packages it is unclear whether the
                     // online editor should be activated or not.
                     // A new document, it is in the root of the repository.
                     $relative_path = '';
                     $relative_prefix = '';
                     if (is_array($extra_info) && $extra_info != 'new') {
                         // The document already exists. Whe have to determine its relative path towards the repository root.
                         $relative_path = explode('/', $extra_info['dir']);
                         $cnt = count($relative_path) - 2;
                         if ($cnt < 0) {
                             $cnt = 0;
                         }
                         $relative_prefix = str_repeat('../', $cnt);
                         $relative_path = array_slice($relative_path, 1, $cnt);
                         $relative_path = implode('/', $relative_path);
                         if (strlen($relative_path) > 0) {
                             $relative_path = $relative_path . '/';
                         }
                     } else {
                         $_course = api_get_course_info();
                         $result = $this->generate_lp_folder($_course);
                         $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
                         $relative_prefix = '../../';
                     }
                     $editor_config = array('ToolbarSet' => 'LearningPathDocuments', 'Width' => '100%', 'Height' => '500', 'FullPage' => true, 'CreateDocumentDir' => $relative_prefix, 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH) . api_get_course_path() . '/document/', 'BaseHref' => api_get_path(WEB_COURSE_PATH) . api_get_course_path() . '/document/' . $relative_path);
                     if ($_GET['action'] == 'add_item') {
                         $class = 'add';
                         $text = get_lang('LPCreateDocument');
                     } else {
                         if ($_GET['action'] == 'edit_item') {
                             $class = 'save';
                             $text = get_lang('SaveDocument');
                         }
                     }
                     $form->addElement('style_submit_button', 'submit_button', $text, 'class="' . $class . '"');
                     $renderer = $form->defaultRenderer();
                     $renderer->setElementTemplate('<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}', 'content_lp');
                     $form->addElement('html', '<div>');
                     $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
                     $form->addElement('html', '</div>');
                     $defaults['content_lp'] = $content;
                 }
             } elseif (is_numeric($extra_info)) {
                 $form->addElement('style_submit_button', 'submit_button', get_lang('SaveDocument'), 'class="save"');
                 $return = $this->display_document($extra_info, true, true, true);
                 $form->addElement('html', $return);
             }
         }
     }
     if ($action == 'move') {
         $form->addElement('hidden', 'title', $item_title);
         $form->addElement('hidden', 'description', $item_description);
     }
     if (is_numeric($extra_info)) {
         $form->addElement('style_submit_button', 'submit_button', get_lang('SaveDocument'), 'value="submit_button", class="save"');
         $form->addElement('hidden', 'path', $extra_info);
     } elseif (is_array($extra_info)) {
         $form->addElement('style_submit_button', 'submit_button', get_lang('SaveDocument'), 'class="save"');
         $form->addElement('hidden', 'path', $extra_info['path']);
     }
     $form->addElement('hidden', 'type', TOOL_DOCUMENT);
     $form->addElement('hidden', 'post_time', time());
     $form->setDefaults($defaults);
     return $form->return_form();
 }
 /**
  * Manages chapter splitting
  * @param	string	Chapter header
  * @param	string	Content
  * @return	void
  */
 function dealPerChapter($header, $content)
 {
     $_course = api_get_course_info();
     $content = str_replace('||page_break||', '', $content);
     // Get all the h1.
     preg_match_all("|<h1[^>]*>([^(h1)+]*)</h1>|is", $content, $matches_temp);
     // Empty the fake chapters.
     $new_index = 0;
     for ($i = 0; $i < count($matches_temp[0]); $i++) {
         if (trim($matches_temp[1][$i]) !== '') {
             $matches[0][$new_index] = $matches_temp[0][$i];
             $matches[1][$new_index] = $matches_temp[1][$i];
             $new_index++;
         }
     }
     // Add intro item.
     $intro_content = api_substr($content, 0, api_strpos($content, $matches[0][0]));
     $items_to_create[get_lang('Introduction')] = $intro_content;
     for ($i = 0; $i < count($matches[0]); $i++) {
         if (empty($matches[1][$i])) {
             continue;
         }
         $content = api_strstr($content, $matches[0][$i]);
         if ($i + 1 !== count($matches[0])) {
             $chapter_content = api_substr($content, 0, api_strpos($content, $matches[0][$i + 1]));
         } else {
             $chapter_content = $content;
         }
         $items_to_create[$matches[1][$i]] = $chapter_content;
     }
     $i = 0;
     foreach ($items_to_create as $item_title => $item_content) {
         $i++;
         $page_content = $this->format_page_content($header, $item_content);
         $html_file = $this->created_dir . '-' . $i . '.html';
         $handle = fopen($this->base_work_dir . $this->created_dir . '/' . $html_file, 'w+');
         fwrite($handle, $page_content);
         fclose($handle);
         $document_id = add_document($_course, $this->created_dir . '/' . $html_file, 'file', filesize($this->base_work_dir . $this->created_dir . '/' . $html_file), $html_file);
         if ($document_id) {
             // Put the document in item_property update.
             api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_SESSION['_uid'], 0, 0, null, null, api_get_session_id());
             $infos = pathinfo($this->filepath);
             $slide_name = strip_tags(nl2br($item_title));
             $slide_name = str_replace(array("\r\n", "\r", "\n"), '', $slide_name);
             $slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_system_encoding());
             $previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, '');
             if ($this->first_item == 0) {
                 $this->first_item = $previous;
             }
         }
     }
 }
 /**
  * Creates a username using person's names, i.e. creates jmontoya from Julio Montoya.
  * @param string $firstname The first name of the user.
  * @param string $lastname The last name of the user.
  * @param string $language (optional)    The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  * @param string $encoding (optional)    The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  * @return string Suggests a username that contains only ASCII-letters and digits, without check for uniqueness within the system.
  * @author Julio Montoya Armas
  * @author Ivan Tcholakov, 2009 - rework about internationalization.
  * @assert ('','') === false
  * @assert ('a','b') === 'ab'
  */
 public static function create_username($firstname, $lastname, $language = null, $encoding = null)
 {
     if (empty($firstname) && empty($lastname)) {
         return false;
     }
     $firstname = api_substr(preg_replace(USERNAME_PURIFIER, '', $firstname), 0, 1);
     // The first letter only.
     //Looking for a space in the lastname
     $pos = api_strpos($lastname, ' ');
     if ($pos !== false) {
         $lastname = api_substr($lastname, 0, $pos);
     }
     $lastname = preg_replace(USERNAME_PURIFIER, '', $lastname);
     $username = $firstname . $lastname;
     if (empty($username)) {
         $username = '******';
     }
     $username = URLify::transliterate($username);
     return strtolower(substr($username, 0, USERNAME_MAX_LENGTH - 3));
 }
Example #29
0
                break;
            case 'setinvisible':
                foreach ($_POST['id'] as $indexstr) {
                    if (api_substr($indexstr, 0, 4) == 'CATE') {
                        $cats = Category::load(api_substr($indexstr, 4));
                        $cats[0]->set_visible(0);
                        $cats[0]->save();
                        $cats[0]->apply_visibility_to_children();
                    }
                    if (api_substr($indexstr, 0, 4) == 'EVAL') {
                        $eval = Evaluation::load(api_substr($indexstr, 4));
                        $eval[0]->set_visible(0);
                        $eval[0]->save();
                    }
                    if (api_substr($indexstr, 0, 4) == 'LINK') {
                        $link = LinkFactory::load(api_substr($indexstr, 4));
                        $link[0]->set_visible(0);
                        $link[0]->save();
                    }
                }
                $confirmation_message = get_lang('ItemsInVisible');
                $filter_confirm_msg = false;
                break;
        }
    }
}
if (isset($_POST['submit']) && isset($_POST['keyword'])) {
    header('Location: ' . api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat']) . '&search=' . Security::remove_XSS($_POST['keyword']));
    exit;
}
// DISPLAY HEADERS AND MESSAGES                           -
$_course = api_get_course_info();
isset($_course) or give_up(get_lang('Sorry'));
$is_allowed_to_edit = isset($_user['user_id']) && $is_courseMember && api_is_allowed_to_edit();
if (!$is_allowed_to_edit) {
    give_up(get_lang('Denied'));
}
$baseWorkDir = get_course_path() . ($courseDir = $_course['path'] . '/scorm');
$mdStore = new mdstore($is_allowed_to_edit);
// create table if needed
require api_get_path(LIBRARY_PATH) . 'xmd.lib.php';
require api_get_path(LIBRARY_PATH) . 'xht.lib.php';
require 'md_phpdig.php';
// SET CURRENT SCORM DIRECTORY - HEADER --------------------------------------->
if (isset($workWith)) {
    $scormdocument = Database::get_course_table(TABLE_LP_MAIN);
    $sql = "SELECT id FROM {$scormdocument} WHERE path='" . Database::escape_string(api_substr($workWith, 1)) . "' OR path='" . Database::escape_string(substr($workWith, 1)) . "/.'";
    $result = Database::query($sql);
    if (Database::num_rows($result) == 1) {
        if ($row = Database::fetch_array($result)) {
            $sdi = $row['id'];
        }
    }
}
if (isset($sdi) && is_numeric($sdi) && $sdi > 0 && $sdi == (int) $sdi) {
    $mdObj = new mdobject($_course, $sdi);
    $workWith = $mdObj->mdo_path;
    $hdrInfo = ' ' . get_lang('WorkOn') . ' ' . ($workWith ? htmlspecialchars($workWith, ENT_QUOTES, $charset) . ', ' : '') . 'SD-id= ' . htmlspecialchars($sdi, ENT_QUOTES, $charset) . ($sdisub ? ' (' . htmlspecialchars($sdisub, ENT_QUOTES, $charset) . ')' : '');
} else {
    unset($sdi);
    $mdObj = new mdobject($_course, 0);
    if ($workWith) {