From d1addaf9fbefb9c57452780af200343b60e842a4 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 17 Dec 2012 14:01:17 +0100 Subject: [PATCH 01/23] Minor - php warnings --- main/exercice/exercise.class.php | 3 ++- main/exercice/exercise.lib.php | 2 ++ main/exercice/question.class.php | 2 +- main/inc/global.inc.php | 4 ++-- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/main/exercice/exercise.class.php b/main/exercice/exercise.class.php index 542c5deb70..84600065fb 100644 --- a/main/exercice/exercise.class.php +++ b/main/exercice/exercise.class.php @@ -2276,7 +2276,7 @@ class Exercise { $str = str_replace('\r\n', '', $str); $choice = $arr[1]; - $tmp = api_strrpos($choice[$j],' / '); + $tmp = api_strrpos($choice[$j],' / '); $choice[$j] = api_substr($choice[$j],0,$tmp); $choice[$j] = trim($choice[$j]); @@ -3439,6 +3439,7 @@ class Exercise { public function is_visible($lp_id = 0, $lp_item_id = 0 , $lp_item_view_id = 0, $filter_by_admin = true) { //1. By default the exercise is visible $is_visible = true; + $message = null; //1.1 Admins and teachers can access to the exercise if ($filter_by_admin) { diff --git a/main/exercice/exercise.lib.php b/main/exercice/exercise.lib.php index 275e5fa655..9be6be97c5 100644 --- a/main/exercice/exercise.lib.php +++ b/main/exercice/exercise.lib.php @@ -203,6 +203,8 @@ function showQuestion($questionId, $only_questions = false, $origin = false, $cu $numAnswer = $objAnswerTmp->selectAutoId($answerId); $comment = $objAnswerTmp->selectComment($answerId); + $attributes = array(); + // Unique answer if ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_NO_OPTION) { $input_id = 'choice-'.$questionId.'-'.$answerId; diff --git a/main/exercice/question.class.php b/main/exercice/question.class.php index a53c524346..ddbd3e7ca1 100644 --- a/main/exercice/question.class.php +++ b/main/exercice/question.class.php @@ -1460,7 +1460,7 @@ abstract class Question // display question category, if any $header = Testcategory::returnCategoryAndTitle($this->id); - + $show_media = null; if ($show_media) { $header .= $this->show_media_content(); } diff --git a/main/inc/global.inc.php b/main/inc/global.inc.php index 88a94b1a9c..5141b6826d 100644 --- a/main/inc/global.inc.php +++ b/main/inc/global.inc.php @@ -307,8 +307,8 @@ if (!$x = strpos($_SERVER['PHP_SELF'], 'whoisonline.php')) { // ===== end "who is logged in?" module section ===== if (api_get_setting('server_type') == 'test') { - //error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED); - error_reporting(-1); + error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED); + //error_reporting(-1); } else { /* Server type is not test From 8c270acf6c3d67a23e980e55ff5c6e8eb57f35d3 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 17 Dec 2012 14:34:16 +0100 Subject: [PATCH 02/23] Minor - form prerequisites UI improved --- main/newscorm/learnpath.class.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/main/newscorm/learnpath.class.php b/main/newscorm/learnpath.class.php index 3687d79c89..0f7623a77b 100644 --- a/main/newscorm/learnpath.class.php +++ b/main/newscorm/learnpath.class.php @@ -7784,10 +7784,9 @@ class learnpath { $return .= get_lang('AddEditPrerequisites'); $return .= ''; - $return .= '
'; $return .= '
'; - $return .= ''; + $return .= '
'; $return .= ''; $return .= ''; $return .= ''; @@ -7835,6 +7834,9 @@ class learnpath { break; $return .= ''; $return .= ''; + //$return .= '
' . get_lang('LearnpathPrerequisites') . '' . get_lang('Minimum') . '
'; + + $return .= ''; $return .= ''; if ($arrLP[$i]['item_type'] == TOOL_QUIZ) { @@ -7872,10 +7875,8 @@ class learnpath { $return .= '
'; $return .= '
'; $return .= ''; - $return .= '
'; - $return .= '
'; - // $return .= '
'; + $return .= ''; return $return; } From e07a0cd1e08ff2b0e90fdcf7c6c9d276e8219b69 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 17 Dec 2012 15:32:02 +0100 Subject: [PATCH 03/23] Adding clear prerequisites/set previous step as prerequisite see BT#4848 --- main/css/base.css | 8 +- main/inc/lib/display.lib.php | 256 ++++++++++++++++-------------- main/newscorm/learnpath.class.php | 61 ++++++- main/newscorm/lp_controller.php | 11 +- 4 files changed, 212 insertions(+), 124 deletions(-) diff --git a/main/css/base.css b/main/css/base.css index a98ddac384..cdb6c3358d 100644 --- a/main/css/base.css +++ b/main/css/base.css @@ -419,10 +419,16 @@ footer .container .row { vertical-align:middle; } .actions a { - display:inline-block; + display: block; + float: left; margin-right: 10px; vertical-align:middle; } + +.actions .btn-toolbar { + margin : 0px; +} + .actions span { margin-right: 10px; vertical-align:middle; diff --git a/main/inc/lib/display.lib.php b/main/inc/lib/display.lib.php index ca6ee76194..005f3a0288 100644 --- a/main/inc/lib/display.lib.php +++ b/main/inc/lib/display.lib.php @@ -27,7 +27,7 @@ define('ICON_SIZE_HUGE', 128); define('SHOW_TEXT_NEAR_ICONS', false); - + /** * Display class * contains several public functions dealing with the display of @@ -37,27 +37,27 @@ define('SHOW_TEXT_NEAR_ICONS', false); */ class Display { - + /* The main template*/ static $global_template; static $preview_style = null; - + private function __construct() { } - + /** * Displays the page header * @param string The name of the page (will be showed in the page title) * @param string Optional help file name */ - public static function display_header($tool_name ='', $help = null, $page_header = null) { - self::$global_template = new Template($tool_name); + public static function display_header($tool_name ='', $help = null, $page_header = null) { + self::$global_template = new Template($tool_name); self::$global_template->set_help($help); - if (!empty(self::$preview_style)) { + if (!empty(self::$preview_style)) { self::$global_template->preview_theme = self::$preview_style; self::$global_template->set_css_files(); self::$global_template->set_js_files(); - + } if (!empty($page_header)) { self::$global_template->assign('header', $page_header); @@ -68,34 +68,34 @@ class Display { /** * Displays the reduced page header (without banner) */ - public static function display_reduced_header() { + public static function display_reduced_header() { global $show_learnpath, $tool_name; - self::$global_template = new Template($tool_name, false, false, $show_learnpath); - echo self::$global_template ->show_header_template(); + self::$global_template = new Template($tool_name, false, false, $show_learnpath); + echo self::$global_template ->show_header_template(); } - - public static function display_no_header() { + + public static function display_no_header() { global $tool_name; $disable_js_and_css_files = true; - self::$global_template = new Template($tool_name, false, false, $show_learnpath); - //echo self::$global_template->show_header_template(); + self::$global_template = new Template($tool_name, false, false, $show_learnpath); + //echo self::$global_template->show_header_template(); } - + /** * Displays the reduced page header (without banner) */ - public static function set_header() { + public static function set_header() { global $show_learnpath; - self::$global_template = new Template($tool_name, false, false, $show_learnpath); + self::$global_template = new Template($tool_name, false, false, $show_learnpath); } /** * Display the page footer */ - public static function display_footer() { - echo self::$global_template ->show_footer_template(); + public static function display_footer() { + echo self::$global_template ->show_footer_template(); } - + public static function page() { return new Page(); @@ -113,7 +113,7 @@ class Display { public static function display_introduction_section($tool, $editor_config = null) { echo self::return_introduction_section($tool, $editor_config); } - + public static function return_introduction_section($tool, $editor_config = null) { $is_allowed_to_edit = api_is_allowed_to_edit(); $moduleId = $tool; @@ -231,7 +231,7 @@ class Display { global $origin; $column = 0; $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20; - $table = new SortableTableFromArray($content, $column, $default_items_per_page, $name); + $table = new SortableTableFromArray($content, $column, $default_items_per_page, $name); if (is_array($query_vars)) { $table->set_additional_parameters($query_vars); } @@ -304,7 +304,7 @@ class Display { /** * Displays an warning message. Use this if you want to draw attention to something * This can also be used for instance with the hint in the exercises - * + * */ public static function display_warning_message($message, $filter = true) { echo self::return_message($message, 'warning', $filter); @@ -329,11 +329,11 @@ class Display { public static function display_error_message ($message, $filter = true) { echo self::return_message($message, 'error', $filter); } - + public static function return_message_and_translate($message, $type='normal', $filter = true) { $message = get_lang($message); echo self::return_message($message, $type, $filter); - } + } /** * Returns a div html string with @@ -344,7 +344,7 @@ class Display { */ public static function return_message($message, $type='normal', $filter = true) { if ($filter) { - $message = api_htmlentities($message, ENT_QUOTES, api_is_xml_http_request() ? 'UTF-8' : api_get_system_encoding()); + $message = api_htmlentities($message, ENT_QUOTES, api_is_xml_http_request() ? 'UTF-8' : api_get_system_encoding()); //$message = Security::remove_XSS($message); } $class = ""; @@ -406,7 +406,7 @@ class Display { // Return encrypted mailto hyperlink return ''.$hclickable_text.''; } - + /** * Returns an mailto icon hyperlink * @@ -449,7 +449,7 @@ class Display { return ''.$name.''; } - + /** * Prints an "; - } - echo ""; - } - - /** - * Get user picture URL or path from user ID (returns an array). - * The return format is a complete path, enabling recovery of the directory - * with dirname() or the file with basename(). This also works for the - * functions dealing with the user's productions, as they are located in - * the same directory. - * @param integer User ID - * @param string Type of path to return (can be 'none', 'system', 'rel', 'web') - * @param bool Whether we want to have the directory name returned 'as if' there was a file or not (in the case we want to know which directory to create - otherwise no file means no split subdir) - * @param bool If we want that the function returns the /main/img/unknown.jpg image set it at true - * @return array Array of 2 elements: 'dir' and 'file' which contain the dir and file as the name implies if image does not exist it will return the unknow image if anonymous parameter is true if not it returns an empty er's - */ - public static function get_user_picture_path_by_id($id, $type = 'none', $preview = false, $anonymous = false) { - - switch ($type) { - case 'system': // Base: absolute system path. - $base = api_get_path(SYS_CODE_PATH); - break; - case 'rel': // Base: semi-absolute web path (no server base). - $base = api_get_path(REL_CODE_PATH); - break; - case 'web': // Base: absolute web path. - $base = api_get_path(WEB_CODE_PATH); - break; - case 'none': - default: // Base: empty, the result path below will be relative. - $base = ''; - } - - if (empty($id) || empty($type)) { - return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => ''); - } - - $user_id = intval($id); - - $user_table = Database :: get_main_table(TABLE_MAIN_USER); - $sql = "SELECT picture_uri FROM $user_table WHERE user_id=".$user_id; - $res = Database::query($sql); - - if (!Database::num_rows($res)) { - return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => ''); - } - - $user = Database::fetch_array($res); - $picture_filename = trim($user['picture_uri']); - - if (api_get_setting('split_users_upload_directory') === 'true') { - if (!empty($picture_filename) or $preview) { - $dir = $base.'upload/users/'.substr((string)$user_id, 0, 1).'/'.$user_id.'/'; - } else { - $dir = $base.'upload/users/'.$user_id.'/'; - } - } else { - $dir = $base.'upload/users/'.$user_id.'/'; - } - if (empty($picture_filename) && $anonymous) { - return array('dir' => $base.'img/', 'file' => 'unknown.jpg'); - } - return array('dir' => $dir, 'file' => $picture_filename); - } - - - /** - * Creates new user pfotos in various sizes of a user, or deletes user pfotos. - * Note: This method relies on configuration setting from dokeos/main/inc/conf/profile.conf.php - * @param int $user_id The user internal identitfication number. - * @param string $file The common file name for the newly created pfotos. - * It will be checked and modified for compatibility with the file system. - * If full name is provided, path component is ignored. - * If an empty name is provided, then old user photos are deleted only, - * @see UserManager::delete_user_picture() as the prefered way for deletion. - * @param string $source_file The full system name of the image from which user photos will be created. - * @return string/bool Returns the resulting common file name of created images which usually should be stored in database. - * When deletion is recuested returns empty string. In case of internal error or negative validation returns FALSE. - */ - public static function update_user_picture($user_id, $file = null, $source_file = null) { - if (empty($user_id)) { - return false; - } - $delete = empty($file); - if (empty($source_file)) { - $source_file = $file; - } - - // Configuration options about user photos. - require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php'; - - // User-reserved directory where photos have to be placed. - $path_info = self::get_user_picture_path_by_id($user_id, 'system', true); - $path = $path_info['dir']; - // If this directory does not exist - we create it. - if (!file_exists($path)) { - @mkdir($path, api_get_permissions_for_new_directories(), true); - } - - // The old photos (if any). - $old_file = $path_info['file']; - - // Let us delete them. - if (!empty($old_file)) { - if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) { - $prefix = 'saved_'.date('Y_m_d_H_i_s').'_'.uniqid('').'_'; - @rename($path.'small_'.$old_file, $path.$prefix.'small_'.$old_file); - @rename($path.'medium_'.$old_file, $path.$prefix.'medium_'.$old_file); - @rename($path.'big_'.$old_file, $path.$prefix.'big_'.$old_file); - @rename($path.$old_file, $path.$prefix.$old_file); - } else { - @unlink($path.'small_'.$old_file); - @unlink($path.'medium_'.$old_file); - @unlink($path.'big_'.$old_file); - @unlink($path.$old_file); - } - } - - // Exit if only deletion has been requested. Return an empty picture name. - if ($delete) { - return ''; - } - - // Validation 2. - $allowed_types = array('jpg', 'jpeg', 'png', 'gif'); - $file = str_replace('\\', '/', $file); - $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file; - $extension = strtolower(substr(strrchr($filename, '.'), 1)); - if (!in_array($extension, $allowed_types)) { - return false; - } - - // This is the common name for the new photos. - if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) { - $old_extension = strtolower(substr(strrchr($old_file, '.'), 1)); - $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file; - $filename = (substr($filename, -1) == '.') ? $filename.$extension : $filename.'.'.$extension; - } else { - $filename = replace_dangerous_char($filename); - if (PREFIX_IMAGE_FILENAME_WITH_UID) { - $filename = uniqid('').'_'.$filename; - } - // We always prefix user photos with user ids, so on setting - // api_get_setting('split_users_upload_directory') === 'true' - // the correspondent directories to be found successfully. - $filename = $user_id.'_'.$filename; - } - - // Storing the new photos in 4 versions with various sizes. - - $small = self::resize_picture($source_file, 22); - $medium = self::resize_picture($source_file, 85); - $normal = self::resize_picture($source_file, 200); - - $big = new Image($source_file); // This is the original picture. - - $ok = false; - $ok = $small->send_image($path.'small_'.$filename) && - $medium->send_image($path.'medium_'.$filename) && - $normal->send_image($path.$filename) && - $big->send_image( $path.'big_'.$filename); - return $ok ? $filename : false; - } - - /** - * Deletes user pfotos. - * Note: This method relies on configuration setting from dokeos/main/inc/conf/profile.conf.php - * @param int $user_id The user internal identitfication number. - * @return string/bool Returns empty string on success, FALSE on error. - */ - public static function delete_user_picture($user_id) { - return self::update_user_picture($user_id); - } - - /* PRODUCTIONS FUNCTIONS */ - - /** - * Returns an XHTML formatted list of productions for a user, or FALSE if he - * doesn't have any. - * - * If there has been a request to remove a production, the function will return - * without building the list unless forced to do so by the optional second - * parameter. This increases performance by avoiding to read through the - * productions on the filesystem before the removal request has been carried - * out because they'll have to be re-read afterwards anyway. - * - * @param $user_id User id - * @param $force Optional parameter to force building after a removal request - * @return A string containing the XHTML code to dipslay the production list, or FALSE - */ - public static function build_production_list($user_id, $force = false, $showdelete = false) { - - if (!$force && !empty($_POST['remove_production'])) { - return true; // postpone reading from the filesystem - } - $productions = self::get_user_productions($user_id); - - if (empty($productions)) { - return false; - } - - $production_path = self::get_user_picture_path_by_id($user_id, 'web', true); - $production_dir = $production_path['dir'].$user_id.'/'; - $del_image = api_get_path(WEB_CODE_PATH).'img/delete.gif'; - $del_text = get_lang('Delete'); - $production_list = ''; - if (count($productions) > 0) { - $production_list = '
    '; - foreach ($productions as $file) { - $production_list .= '
  • '.htmlentities($file).''; - if ($showdelete) { - $production_list .= '
  • '; - } - } - $production_list .= '
'; - } - - return $production_list; - } - - /** - * Returns an array with the user's productions. - * - * @param $user_id User id - * @return An array containing the user's productions - */ - public static function get_user_productions($user_id) { - $production_path = self::get_user_picture_path_by_id($user_id, 'system', true); - $production_repository = $production_path['dir'].$user_id.'/'; - $productions = array(); - - if (is_dir($production_repository)) { - $handle = opendir($production_repository); - - while ($file = readdir($handle)) { - if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($production_repository.$file)) { - continue; // skip current/parent directory and .htaccess - } - if (preg_match('/('.$user_id.'|[0-9a-f]{13}|saved)_.+\.(png|jpg|jpeg|gif)$/i', $file)) { - // User's photos should not be listed as productions. - continue; - } - $productions[] = $file; - } - } - - return $productions; // can be an empty array - } - - /** - * Remove a user production. - * - * @param $user_id User id - * @param $production The production to remove - */ - public static function remove_user_production($user_id, $production) { - $production_path = self::get_user_picture_path_by_id($user_id, 'system', true); - $production_file = $production_path['dir'].$user_id.'/'.$production; - if (is_file($production_file)) { - unlink($production_file); - return true; - } - return false; - } - - /** - * Update an extra field. This function is called when a user changes his/her profile - * and by consequence fills or edits his/her extra fields. - * - * @param integer Field ID - * @param array Database columns and their new value - * @return boolean true if field updated, false otherwise - */ - public static function update_extra_field($fid, $columns) { - //TODO check that values added are values proposed for enumerated field types - $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD); - $fid = Database::escape_string($fid); - $sqluf = "UPDATE $t_uf SET "; - $known_fields = array('id', 'field_variable', 'field_type', 'field_display_text', 'field_default_value', 'field_order', 'field_visible', 'field_changeable', 'field_filter'); - $safecolumns = array(); - foreach ($columns as $index => $newval) { - if (in_array($index, $known_fields)) { - $safecolumns[$index] = Database::escape_string($newval); - $sqluf .= $index." = '".$safecolumns[$index]."', "; - } - } - $time = time(); - $sqluf .= " tms = FROM_UNIXTIME($time) WHERE id='$fid'"; - $resuf = Database::query($sqluf); - return $resuf; - } - - /** - * Update an extra field value for a given user - * @param integer User ID - * @param string Field variable name - * @param string Field value - * @return boolean true if field updated, false otherwise - */ - public static function update_extra_field_value($user_id, $fname, $fvalue = '') { - //TODO check that values added are values proposed for enumerated field types - $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD); - $t_ufo = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS); - $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES); - $fname = Database::escape_string($fname); - if ($user_id != strval(intval($user_id))) return false; - if ($user_id === false) return false; - $fvalues = ''; - - //echo '
'; print_r($fvalue);
-		if (is_array($fvalue)) {
-			foreach($fvalue as $val) {
-				$fvalues .= Database::escape_string($val).';';
-			}
-			if (!empty($fvalues)) {
-				$fvalues = substr($fvalues, 0, -1);
-			}
-		} else {
-			$fvalues = Database::escape_string($fvalue);
-		}
-		$sqluf = "SELECT * FROM $t_uf WHERE field_variable='$fname'";
-		$resuf = Database::query($sqluf);
-		if (Database::num_rows($resuf) == 1) {
-			//ok, the field exists
-			// Check if enumerated field, if the option is available
-			$rowuf = Database::fetch_array($resuf);
-			switch ($rowuf['field_type']) {
-				case self::USER_FIELD_TYPE_TAG :
-					//4. Tags are process here comes from main/auth/profile.php
-					UserManager::process_tags(explode(';', $fvalues), $user_id, $rowuf['id']);
-					return true;
-                    break;
-				case self::USER_FIELD_TYPE_RADIO:
-				case self::USER_FIELD_TYPE_SELECT:
-				case self::USER_FIELD_TYPE_SELECT_MULTIPLE:
-					$sqluo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowuf['id'];
-					$resuo = Database::query($sqluo);
-					$values = split(';',$fvalues);
-					if (Database::num_rows($resuo) > 0) {
-						$check = false;
-						while ($rowuo = Database::fetch_array($resuo)) {
-							if (in_array($rowuo['option_value'], $values)) {
-								$check = true;
-								break;
-							}
-						}
-						if (!$check) {
-							return false; //option value not found
-						}
-					} else {
-						return false; //enumerated type but no option found
-					}
-					break;
-				case 1:
-				case 2:
-				default:
-					break;
-			}
-			$tms = time();
-			$sqlufv = "SELECT * FROM $t_ufv WHERE user_id = $user_id AND field_id = ".$rowuf['id']." ORDER BY id";
-			$resufv = Database::query($sqlufv);
-			$n = Database::num_rows($resufv);
-			if ($n > 1) {
-				//problem, we already have to values for this field and user combination - keep last one
-				while ($rowufv = Database::fetch_array($resufv)) {
-					if ($n > 1) {
-						$sqld = "DELETE FROM $t_ufv WHERE id = ".$rowufv['id'];
-						Database::query($sqld);
-						$n--;
-					}
-					$rowufv = Database::fetch_array($resufv);
-					if ($rowufv['field_value'] != $fvalues) {
-						$sqlu = "UPDATE $t_ufv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowufv['id'];
-						$resu = Database::query($sqlu);
-						return($resu ? true : false);
-					}
-					return true;
-				}
-			} elseif ($n == 1) {
-				//we need to update the current record
-				$rowufv = Database::fetch_array($resufv);
-				if ($rowufv['field_value'] != $fvalues) {
-					// If the new field is empty, delete it
-					if ($fvalues == '') {
-						$sql_query = "DELETE FROM $t_ufv WHERE id = ".$rowufv['id'].";";
-					} else {
-						// Otherwise update it
-						$sql_query = "UPDATE $t_ufv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowufv['id'];
-					}
-
-					$resu = Database::query($sql_query);
-					return($resu ? true : false);
-				}
-				return true;
-			} else {
-				$sqli = "INSERT INTO $t_ufv (user_id,field_id,field_value,tms) " .
-					"VALUES ($user_id,".$rowuf['id'].",'$fvalues',FROM_UNIXTIME($tms))";
-				//error_log('UM::update_extra_field_value: '.$sqli);
-				$resi = Database::query($sqli);
-				return($resi ? true : false);
-			}
-		} else {
-			return false; //field not found
-		}
-	}
-
-	/**
-	 * Get an array of extra fieds with field details (type, default value and options)
-	 * @param	integer	Offset (from which row)
-	 * @param	integer	Number of items
-	 * @param	integer	Column on which sorting is made
-	 * @param	string	Sorting direction
-	 * @param	boolean	Optional. Whether we get all the fields or just the visible ones
-	 * @param	int		Optional. Whether we get all the fields with field_filter 1 or 0 or everything
-	 * @return	array	Extra fields details (e.g. $list[2]['type'], $list[4]['options'][2]['title']
-	 */
-	public static function get_extra_fields($from = 0, $number_of_items = 0, $column = 5, $direction = 'ASC', $all_visibility = true, $field_filter = null) {
-		$fields = array();
-		$t_uf  = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
-		$t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-		$columns = array('id', 'field_variable', 'field_type', 'field_display_text', 'field_default_value', 'field_order', 'field_filter', 'tms');
-		$column = intval($column);
-		$sort_direction = '';
-		if (in_array(strtoupper($direction), array('ASC', 'DESC'))) {
-			$sort_direction = strtoupper($direction);
-		}
-		$sqlf = "SELECT * FROM $t_uf WHERE 1 = 1  ";
-		if (!$all_visibility) {
-			$sqlf .= " AND field_visible = 1 ";
-		}
-		if (!is_null($field_filter)) {
-		    $field_filter = intval($field_filter);
-            $sqlf .= " AND field_filter = $field_filter ";
-		}
-		$sqlf .= " ORDER BY ".$columns[$column]." $sort_direction " ;
-		if ($number_of_items != 0) {
-			$sqlf .= " LIMIT ".Database::escape_string($from).','.Database::escape_string($number_of_items);
-		}
-
-		$resf = Database::query($sqlf);
-		if (Database::num_rows($resf) > 0) {
-			while($rowf = Database::fetch_array($resf)) {
-				$fields[$rowf['id']] = array(
-					0 => $rowf['id'],
-					1 => $rowf['field_variable'],
-					2 => $rowf['field_type'],
-					//3 => (empty($rowf['field_display_text']) ? '' : get_lang($rowf['field_display_text'], '')),
-					// Temporarily removed auto-translation. Need update to get_lang() to know if translation exists (todo)
-					// Ivan, 15-SEP-2009: get_lang() has been modified accordingly in order this issue to be solved.
-					3 => (empty($rowf['field_display_text']) ? '' : $rowf['field_display_text']),
-					4 => $rowf['field_default_value'],
-					5 => $rowf['field_order'],
-					6 => $rowf['field_visible'],
-					7 => $rowf['field_changeable'],
-					8 => $rowf['field_filter'],
-					9 => array()
-				);
-
-				$sqlo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowf['id']." ORDER BY option_order ASC";
-				$reso = Database::query($sqlo);
-				if (Database::num_rows($reso) > 0) {
-					while ($rowo = Database::fetch_array($reso)) {
-						$fields[$rowf['id']][9][$rowo['id']] = array(
-							0 => $rowo['id'],
-							1 => $rowo['option_value'],
-							//2 => (empty($rowo['option_display_text']) ? '' : get_lang($rowo['option_display_text'], '')),
-							2 => (empty($rowo['option_display_text']) ? '' : $rowo['option_display_text']),
-							3 => $rowo['option_order']
-						);
-					}
-				}
-			}
-		}
-
-		return $fields;
-	}
-
-	/**
-	 * Get the list of options attached to an extra field
-	 * @param string $fieldname the name of the field
-	 * @return array the list of options
-	 */
-	public static function get_extra_field_options($field_name) {
-		$t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
-		$t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-
-		$sql = 'SELECT options.*
-				FROM '.$t_ufo.' options
-					INNER JOIN '.$t_uf.' fields
-						ON fields.id = options.field_id
-							AND fields.field_variable="'.Database::escape_string($field_name).'"';
-		$rs = Database::query($sql);
-		return Database::store_result($rs);
-	}
-
-	/**
-	 * Get the number of extra fields currently recorded
-	 * @param	boolean	Optional switch. true (default) returns all fields, false returns only visible fields
-	 * @return	integer	Number of fields
-	 */
-	public static function get_number_of_extra_fields($all_visibility = true) {
-		$t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
-		$sqlf = "SELECT * FROM $t_uf ";
-		if (!$all_visibility) {
-			$sqlf .= " WHERE field_visible = 1 ";
-		}
-		$sqlf .= " ORDER BY field_order";
-		$resf = Database::query($sqlf);
-		return Database::num_rows($resf);
-	}
-
-	/**
-	  * Creates a new extra field
-	  * @param	string	Field's internal variable name
-	  * @param	int		Field's type
-	  * @param	string	Field's language var name
-	  * @param	string	Field's default value
-	  * @param	string	Optional comma-separated list of options to provide for select and radio
-	  * @return int     new user id - if the new user creation succeeds, false otherwise
-	  */
-	public static function create_extra_field($fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions = '') {
-		// database table definition
-		$table_field 		= Database::get_main_table(TABLE_MAIN_USER_FIELD);
-		$table_field_options= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-
-		// First check wether the login already exists
-		if (self::is_extra_field_available($fieldvarname)) {
-			return api_set_failure('login-pass already taken');
-		}
-		$sql = "SELECT MAX(field_order) FROM $table_field";
-		$res = Database::query($sql);
-		$order = 0;
-		if (Database::num_rows($res) > 0) {
-			$row = Database::fetch_array($res);
-			$order = $row[0]+1;
-		}
-		$time = time();
-		$sql = "INSERT INTO $table_field
-				SET field_type = '".Database::escape_string($fieldtype)."',
-				field_variable = '".Database::escape_string($fieldvarname)."',
-				field_display_text = '".Database::escape_string($fieldtitle)."',
-				field_default_value = '".Database::escape_string($fielddefault)."',
-				field_order = '$order',
-				tms = FROM_UNIXTIME($time)";
-		$result = Database::query($sql);
-		if ($result) {
-			//echo "id returned";
-			$return = Database::insert_id();
-		} else {
-			//echo "false - failed" ;
-			return false;
-		}
-
-		if (!empty($fieldoptions) && in_array($fieldtype, array(self::USER_FIELD_TYPE_RADIO, self::USER_FIELD_TYPE_SELECT, self::USER_FIELD_TYPE_SELECT_MULTIPLE, self::USER_FIELD_TYPE_DOUBLE_SELECT))) {
-			if ($fieldtype == self::USER_FIELD_TYPE_DOUBLE_SELECT) {
-				$twolist = explode('|', $fieldoptions);
-				$counter = 0;
-				foreach ($twolist as $individual_list) {
-					$splitted_individual_list = split(';', $individual_list);
-					foreach	($splitted_individual_list as $individual_list_option) {
-						//echo 'counter:'.$counter;
-						if ($counter == 0) {
-							$list[] = $individual_list_option;
-						} else {
-							$list[] = str_repeat('*', $counter).$individual_list_option;
-						}
-					}
-					$counter++;
-				}
-			} else {
-				$list = split(';', $fieldoptions);
-			}
-			foreach ($list as $option) {
-				$option = Database::escape_string($option);
-				$sql = "SELECT * FROM $table_field_options WHERE field_id = $return AND option_value = '".$option."'";
-				$res = Database::query($sql);
-				if (Database::num_rows($res) > 0) {
-					//the option already exists, do nothing
-				} else {
-					$sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = $return";
-					$res = Database::query($sql);
-					$max = 1;
-					if (Database::num_rows($res) > 0) {
-						$row = Database::fetch_array($res);
-						$max = $row[0] + 1;
-					}
-					$time = time();
-					$sql = "INSERT INTO $table_field_options (field_id,option_value,option_display_text,option_order,tms) VALUES ($return,'$option','$option',$max,FROM_UNIXTIME($time))";
-					$res = Database::query($sql);
-					if ($res === false) {
-						$return = false;
-					}
-				}
-			}
-		}
-		return $return;
-	}
-
-	/**
-	  * Save the changes in the definition of the extra user profile field
-	  * The function is called after you (as admin) decide to store the changes you have made to one of the fields you defined
-	  *
-	  * There is quite some logic in this field
-	  * 1.  store the changes to the field (tupe, name, label, default text)
-	  * 2.  remove the options and the choices of the users from the database that no longer occur in the form field 'possible values'. We should only remove
-	  * 	the options (and choices) that do no longer have to appear. We cannot remove all options and choices because if you remove them all
-	  * 	and simply re-add them all then all the user who have already filled this form will loose their selected value.
-	  * 3.	we add the options that are newly added
-	  *
-	  *  current options are a;b;c and the user changes this to a;b;x (removing c and adding x)
-	  * 			we first remove c (and also the entry in the option_value table for the users who have chosen this)
-	  * 			we then add x
-	  * 			a and b are neither removed nor added
-	  * 
-	  * @param 	integer $fieldid		the id of the field we are editing
-	  * @param	string	$fieldvarname	the internal variable name of the field
-	  * @param	int		$fieldtype		the type of the field
-	  * @param	string	$fieldtitle		the title of the field
-	  * @param	string	$fielddefault	the default value of the field
-	  * @param	string	$fieldoptions	Optional comma-separated list of options to provide for select and radio
-	  * @return boolean true
-	  *
-	  *
-	  * @author Patrick Cool , Ghent University, Belgium
-	  * @version July 2008
-	  * @since Dokeos 1.8.6
-	  */
-	public static function save_extra_field_changes($fieldid, $fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions = '') {
-		// database table definition
-		$table_field 				= Database::get_main_table(TABLE_MAIN_USER_FIELD);
-		$table_field_options		= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-		$table_field_options_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-
-		// we first update the field definition with the new values
-		$time = time();
-		$sql = "UPDATE $table_field
-				SET field_type = '".Database::escape_string($fieldtype)."',
-				field_variable = '".Database::escape_string($fieldvarname)."',
-				field_display_text = '".Database::escape_string($fieldtitle)."',
-				field_default_value = '".Database::escape_string($fielddefault)."',
-				tms = FROM_UNIXTIME($time)
-			WHERE id = '".Database::escape_string($fieldid)."'";
-		$result = Database::query($sql);
-
-		// we create an array with all the options (will be used later in the script)
-		if ($fieldtype == self::USER_FIELD_TYPE_DOUBLE_SELECT) {
-			$twolist = explode('|', $fieldoptions);
-			$counter = 0;
-			foreach ($twolist as $individual_list) {
-				$splitted_individual_list = split(';', $individual_list);
-				foreach	($splitted_individual_list as $individual_list_option) {
-					//echo 'counter:'.$counter;
-					if ($counter == 0) {
-						$list[] = trim($individual_list_option);
-					} else {
-						$list[] = str_repeat('*', $counter).trim($individual_list_option);
-					}
-				}
-				$counter++;
-			}
-		} else {
-			$templist = split(';', $fieldoptions);
-			$list = array_map('trim', $templist);
-		}
-
-		// Remove all the field options (and also the choices of the user) that are NOT in the new list of options
-		$sql = "SELECT * FROM $table_field_options WHERE option_value NOT IN ('".implode("','", $list)."') AND field_id = '".Database::escape_string($fieldid)."'";
-		$result = Database::query($sql);
-		$return['deleted_options'] = 0;
-		while ($row = Database::fetch_array($result)) {
-			// deleting the option
-			$sql_delete_option = "DELETE FROM $table_field_options WHERE id='".Database::escape_string($row['id'])."'";
-			Database::query($sql_delete_option);
-			$return['deleted_options']++;
-
-			// deleting the answer of the user who has chosen this option
-			$sql_delete_option_value = "DELETE FROM $table_field_options_values WHERE field_id = '".Database::escape_string($fieldid)."' AND field_value = '".Database::escape_string($row['option_value'])."'";
-			Database::query($sql_delete_option_value);
-			$return['deleted_option_values'] = $return['deleted_option_values'] + Database::affected_rows();
-		}
-
-		// we now try to find the field options that are newly added
-		$sql = "SELECT * FROM $table_field_options WHERE field_id = '".Database::escape_string($fieldid)."'";
-		$result = Database::query($sql);
-		while ($row = Database::fetch_array($result)) {
-			// we remove every option that is already in the database from the $list
-			if (in_array(trim($row['option_display_text']), $list)) {
-				$key = array_search(trim($row['option_display_text']), $list);
-				unset($list[$key]);
-			}
-		}
-
-		// we store the new field options in the database
-		foreach ($list as $key => $option) {
-			$sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = '".Database::escape_string($fieldid)."'";
-			$res = Database::query($sql);
-			$max = 1;
-			if (Database::num_rows($res) > 0) {
-				$row = Database::fetch_array($res);
-				$max = $row[0] + 1;
-			}
-			$time = time();
-			$sql = "INSERT INTO $table_field_options (field_id,option_value,option_display_text,option_order,tms) VALUES ('".Database::escape_string($fieldid)."','".Database::escape_string($option)."','".Database::escape_string($option)."',$max,FROM_UNIXTIME($time))";
-			$result = Database::query($sql);
-		}
-		return true;
-	}
-
-	/**
-	 * Check if a field is available
-	 * @param	string	the wanted fieldname
-	 * @return	boolean	true if the wanted username is available
-	 */
-	public static function is_extra_field_available($fieldname) {
-		$t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
-		$sql = "SELECT * FROM $t_uf WHERE field_variable = '".Database::escape_string($fieldname)."'";
-		$res = Database::query($sql);
-		return Database::num_rows($res) > 0;
-	}
-
-	/**
-	 * Gets user extra fields data
-	 * @param	integer	User ID
-	 * @param	boolean	Whether to prefix the fields indexes with "extra_" (might be used by formvalidator)
-	 * @param	boolean	Whether to return invisible fields as well
-	 * @param	boolean	Whether to split multiple-selection fields or not
-	 * @return	array	Array of fields => value for the given user
-	 */
-	public static function get_extra_user_data($user_id, $prefix = false, $all_visibility = true, $splitmultiple = false, $field_filter = null) {
-		// A sanity check.
-		if (empty($user_id)) {
-			$user_id = 0;
-		} else {
-			if ($user_id != strval(intval($user_id))) return array();
-		}
-		$extra_data = array();
-		$t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
-		$t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-		$user_id = Database::escape_string($user_id);
-		$sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
-        $filter_cond = '';
+    /**
+     * Get user information
+     * @param     string     The username
+     * @return array All user information as an associative array
+     */
+    public static function get_user_info($username) {
+        $user_table = Database :: get_main_table(TABLE_MAIN_USER);
+        $username = Database::escape_string($username);
+        $sql = "SELECT * FROM $user_table WHERE username='".$username."'";
+        $res = Database::query($sql);
+        if (Database::num_rows($res) > 0) {
+            return Database::fetch_array($res);
+        }
+        return false;
+    }
 
-        if (!$all_visibility) {
-            if (isset($field_filter)) {
-                $field_filter = intval($field_filter);
-                $filter_cond .= " AND field_filter = $field_filter ";
-            }
-			$sql .= " WHERE f.field_visible = 1 $filter_cond ";
-		} else {
-            if (isset($field_filter)) {
-                $field_filter = intval($field_filter);
-                $sql .= " WHERE field_filter = $field_filter ";
+    /**
+     * Get user information
+     * @param    string    The id
+     * @param    boolean    Whether to return the user's extra fields (defaults to false)
+     * @return    array     All user information as an associative array
+     * @todo    Use api_get_user_info() instead
+     */
+    public static function get_user_info_by_id($user_id, $user_fields = false) {
+        $user_id = intval($user_id);
+        $user_table = Database :: get_main_table(TABLE_MAIN_USER);
+        $sql = "SELECT * FROM $user_table WHERE user_id=".$user_id;
+        $res = Database::query($sql);
+        if (Database::num_rows($res) > 0) {
+            $user = Database::fetch_array($res);
+            $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+            $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+            $sqlf = "SELECT * FROM $t_uf ORDER BY field_order";
+            $resf = Database::query($sqlf);
+            if (Database::num_rows($resf) > 0) {
+                while ($rowf = Database::fetch_array($resf)) {
+                    $sqlv = "SELECT * FROM $t_ufv WHERE field_id = ".$rowf['id']." AND user_id = ".$user['user_id']." ORDER BY id DESC";
+                    $resv = Database::query($sqlv);
+                    if (Database::num_rows($resv) > 0) {
+                        //There should be only one value for a field and a user
+                        $rowv = Database::fetch_array($resv);
+                        $user['extra'][$rowf['field_variable']] = $rowv['field_value'];
+                    } else {
+                        $user['extra'][$rowf['field_variable']] = '';
+                    }
+                }
             }
+            return $user;
         }
-		$sql .= " ORDER BY f.field_order";
-
-		$res = Database::query($sql);
-		if (Database::num_rows($res) > 0) {
-			while ($row = Database::fetch_array($res)) {
-				if ($row['type'] == self::USER_FIELD_TYPE_TAG) {
-					$tags = self::get_user_tags_to_string($user_id,$row['id'],false);
-					$extra_data['extra_'.$row['fvar']] = $tags;
-				} else {
-					$sqlu = "SELECT field_value as fval FROM $t_ufv WHERE field_id=".$row['id']." AND user_id = ".$user_id;
-					$resu = Database::query($sqlu);
-					$fval = '';
-					// get default value
-					$sql_df = "SELECT field_default_value as fval_df " .
-							" FROM $t_uf " .
-							" WHERE id=".$row['id'];
-					$res_df = Database::query($sql_df);
-
-					if (Database::num_rows($resu) > 0) {
-						$rowu = Database::fetch_array($resu);
-						$fval = $rowu['fval'];
-						if ($row['type'] ==  self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
-							$fval = split(';',$rowu['fval']);
-						}
-					} else {
-						$row_df = Database::fetch_array($res_df);
-						$fval = $row_df['fval_df'];
-					}
-                    // We get here (and fill the $extra_data array) even if there is no user with data (we fill it with default values)
-					if ($prefix) {
-						if ($row['type'] ==  self::USER_FIELD_TYPE_RADIO) {
-							$extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
-						} else {
-							$extra_data['extra_'.$row['fvar']] = $fval;
-						}
-					} else {
-						if ($row['type'] ==  self::USER_FIELD_TYPE_RADIO) {
-							$extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
-						} else {
-							$extra_data[$row['fvar']] = $fval;
-						}
-					}
-				}
-			}
-		}
-		return $extra_data;
-	}
-
-	/** Get extra user data by field
-	 * @param int	user ID
-	 * @param string the internal variable name of the field
-	 * @return array with extra data info of a user i.e array('field_variable'=>'value');
-	 */
-	public static function get_extra_user_data_by_field($user_id, $field_variable, $prefix = false, $all_visibility = true, $splitmultiple = false) {
-		// A sanity check.
-		if (empty($user_id)) {
-			$user_id = 0;
-		} else {
-			if ($user_id != strval(intval($user_id))) return array();
-		}
-		$extra_data = array();
-		$t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
-		$t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-		$user_id = Database::escape_string($user_id);
-
-		$sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
-		$sql .= " WHERE f.field_variable = '$field_variable' ";
-
-		if (!$all_visibility) {
-			$sql .= " AND f.field_visible = 1 ";
-		}
-
-		$sql .= " ORDER BY f.field_order";
-
-		$res = Database::query($sql);
-		if (Database::num_rows($res) > 0) {
-			while ($row = Database::fetch_array($res)) {
-				$sqlu = "SELECT field_value as fval " .
-						" FROM $t_ufv " .
-						" WHERE field_id=".$row['id']."" .
-						" AND user_id=".$user_id;
-				$resu = Database::query($sqlu);
-				$fval = '';
-				if (Database::num_rows($resu) > 0) {
-					$rowu = Database::fetch_array($resu);
-					$fval = $rowu['fval'];
-					if ($row['type'] ==  self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
-						$fval = split(';',$rowu['fval']);
-					}
-				}
-				if ($prefix) {
-					$extra_data['extra_'.$row['fvar']] = $fval;
-				} else {
-					$extra_data[$row['fvar']] = $fval;
-				}
-			}
-		}
-
-		return $extra_data;
-	}
-
-	/**
-	 * Get the extra field information for a certain field (the options as well)
-	 * @param  int     The name of the field we want to know everything about
-	 * @return array   Array containing all the information about the extra profile field (first level of array contains field details, then 'options' sub-array contains options details, as returned by the database)
-	 * @author Julio Montoya
-	 * @since Dokeos 1.8.6
-	 */
-	public static function get_extra_field_information_by_name($field_variable, $fuzzy = false) {
-		// database table definition
-		$table_field 			= Database::get_main_table(TABLE_MAIN_USER_FIELD);
-		$table_field_options	= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-
-		// all the information of the field
-		$sql = "SELECT * FROM $table_field WHERE field_variable='".Database::escape_string($field_variable)."'";
-		$result = Database::query($sql);
-		$return = Database::fetch_array($result);
-
-		// all the options of the field
-		$sql = "SELECT * FROM $table_field_options WHERE field_id='".Database::escape_string($return['id'])."' ORDER BY option_order ASC";
-		$result = Database::query($sql);
-		while ($row = Database::fetch_array($result)) {
-			$return['options'][$row['id']] = $row;
-		}
-		return $return;
-	}
-
-	public static function get_all_extra_field_by_type($field_type) {
-		// database table definition
-		$table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
-
-		// all the information of the field
-		$sql = "SELECT * FROM $table_field WHERE field_type='".Database::escape_string($field_type)."'";
-		$result = Database::query($sql);
-        $return = array();
-		while ($row = Database::fetch_array($result)) {
-			$return[] = $row['id'];
-		}
-		return $return;
-	}
-
-	/**
-	 * Get all the extra field information of a certain field (also the options)
-	 *
-	 * @param int $field_name the name of the field we want to know everything of
-	 * @return array $return containing all th information about the extra profile field
-	 * @author Julio Montoya
-	 * @since Dokeos 1.8.6
-	 */
-	public static function get_extra_field_information($field_id) {
-		// database table definition
-		$table_field 			= Database::get_main_table(TABLE_MAIN_USER_FIELD);
-		$table_field_options	= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-
-		// all the information of the field
-		$sql = "SELECT * FROM $table_field WHERE id='".Database::escape_string($field_id)."'";
-		$result = Database::query($sql);
-		$return = Database::fetch_array($result);
-
-		// all the options of the field
-		$sql = "SELECT * FROM $table_field_options WHERE field_id='".Database::escape_string($field_id)."' ORDER BY option_order ASC";
-		$result = Database::query($sql);
-		while ($row = Database::fetch_array($result)) {
-			$return['options'][$row['id']] = $row;
-		}
-		return $return;
-	}
-
-	/** Get extra user data by value
-	 * @param string the internal variable name of the field
-	 * @param string the internal value of the field
-	 * @return array with extra data info of a user i.e array('field_variable'=>'value');
-	 */
-
-	public static function get_extra_user_data_by_value($field_variable, $field_value, $all_visibility = true) {
-		$extra_data = array();
-		$table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
-		$table_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-		$table_user_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-		$where = '';
-		/*
-		if (is_array($field_variable_array) && is_array($field_value_array)) {
-			if (count($field_variable_array) == count($field_value_array)) {
-				$field_var_count = count($field_variable_array);
-				for ($i = 0; $i < $field_var_count; $i++) {
-					if ($i != 0 && $i != $field_var_count) {
-						$where.= ' AND ';
-					}
-					$where.= "field_variable='".Database::escape_string($field_variable_array[$i])."' AND user_field_options.id='".Database::escape_string($field_value_array[$i])."'";
-				}
-			}
-
-		}*/
-		$where = "field_variable='".Database::escape_string($field_variable)."' AND field_value='".Database::escape_string($field_value)."'";
-
-		$sql = "SELECT user_id FROM $table_user_field user_field INNER JOIN $table_user_field_values user_field_values
-					ON (user_field.id = user_field_values.field_id)
-				WHERE $where";
-
-		if ($all_visibility) {
-			$sql .= " AND user_field.field_visible = 1 ";
-		} else {
-			$sql .= " AND user_field.field_visible = 0 ";
-		}
-		$res = Database::query($sql);
-		$result_data = array();
-		if (Database::num_rows($res) > 0) {
-			while ($row = Database::fetch_array($res)) {
-				$result_data[] = $row['user_id'];
-			}
-		}
-		return $result_data;
-	}
-
-	/**
-	 * Get extra user data by field variable
-	 * @param string	field variable
-	 * @return array	data
-	 */
-	public static function get_extra_user_data_by_field_variable($field_variable) {
-		$tbl_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-		$extra_information_by_variable = self::get_extra_field_information_by_name($field_variable);
-		$field_id = intval($extra_information_by_variable['id']);
-		$data = array();
-		$sql = "SELECT * FROM $tbl_user_field_values WHERE field_id='$field_id'";
-		$rs  = Database::query($sql);
-		if (Database::num_rows($rs) > 0) {
-			while ($row = Database::fetch_array($rs)) {
-				$user_id = $row['user_id'];
-				$data[$user_id] = $row;
-			}
-		}
-		return $data;
-	}
-
-	/**
-	 * Gives a list of [session_category][session_id] for the current user.
-	 * @param integer $user_id
-	 * @param boolean whether to fill the first element or not (to give space for courses out of categories)
-	 * @param boolean  optional true if limit time from session is over, false otherwise
-	 * @return array  list of statuses [session_category][session_id]
-	 * @todo ensure multiple access urls are managed correctly
-	 */
-	public static function get_sessions_by_category($user_id, $is_time_over = false) {
-		// Database Table Definitions
-		$tbl_session				= Database :: get_main_table(TABLE_MAIN_SESSION);
-		$tbl_session_course_user	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-        $tbl_session_category       = Database :: get_main_table(TABLE_MAIN_SESSION_CATEGORY);
+        return false;
+    }
 
-		if ($user_id != strval(intval($user_id))) return array();
+    /** Get the teacher list
+     * @param int the course ID
+     * @param array Content the list ID of user_id selected
+     */
+    //for survey
+    // TODO: Ivan, 14-SEP-2009: It seems that this method is not used at all (it can be located in a test unit only. To be deprecated?
+    public static function get_teacher_list($course_id, $sel_teacher = '') {
+        $user_course_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+        $user_table = Database :: get_main_table(TABLE_MAIN_USER);
+        $course_id = Database::escape_string($course_id);
+        $sql_query = "SELECT * FROM $user_table a, $user_course_table b where a.user_id=b.user_id AND b.status=1 AND b.course_code='$course_id'";
+        $sql_result = Database::query($sql_query);
+        echo "";
+    }
 
-		$categories = array();
+    /**
+     * Get user picture URL or path from user ID (returns an array).
+     * The return format is a complete path, enabling recovery of the directory
+     * with dirname() or the file with basename(). This also works for the
+     * functions dealing with the user's productions, as they are located in
+     * the same directory.
+     * @param    integer    User ID
+     * @param    string    Type of path to return (can be 'none', 'system', 'rel', 'web')
+     * @param    bool    Whether we want to have the directory name returned 'as if' there was a file or not (in the case we want to know which directory to create - otherwise no file means no split subdir)
+     * @param    bool    If we want that the function returns the /main/img/unknown.jpg image set it at true
+     * @return    array     Array of 2 elements: 'dir' and 'file' which contain the dir and file as the name implies if image does not exist it will return the unknow image if anonymous parameter is true if not it returns an empty er's
+     */
+    public static function get_user_picture_path_by_id($id, $type = 'none', $preview = false, $anonymous = false) {
+
+        switch ($type) {
+            case 'system': // Base: absolute system path.
+                $base = api_get_path(SYS_CODE_PATH);
+                break;
+            case 'rel': // Base: semi-absolute web path (no server base).
+                $base = api_get_path(REL_CODE_PATH);
+                break;
+            case 'web': // Base: absolute web path.
+                $base = api_get_path(WEB_CODE_PATH);
+                break;
+            case 'none':
+            default: // Base: empty, the result path below will be relative.
+                $base = '';
+        }
+
+        if (empty($id) || empty($type)) {
+            return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => '');
+        }
+
+        $user_id = intval($id);
+
+        $user_table = Database :: get_main_table(TABLE_MAIN_USER);
+        $sql = "SELECT picture_uri FROM $user_table WHERE user_id=".$user_id;
+        $res = Database::query($sql);
+
+        if (!Database::num_rows($res)) {
+            return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => '');
+        }
+
+        $user = Database::fetch_array($res);
+        $picture_filename = trim($user['picture_uri']);
+
+        if (api_get_setting('split_users_upload_directory') === 'true') {
+            if (!empty($picture_filename) or $preview) {
+                $dir = $base.'upload/users/'.substr((string)$user_id, 0, 1).'/'.$user_id.'/';
+            } else {
+                $dir = $base.'upload/users/'.$user_id.'/';
+            }
+        } else {
+            $dir = $base.'upload/users/'.$user_id.'/';
+        }
+        if (empty($picture_filename) && $anonymous) {
+            return array('dir' => $base.'img/', 'file' => 'unknown.jpg');
+        }
+        return array('dir' => $dir, 'file' => $picture_filename);
+    }
+
+
+    /**
+     * Creates new user pfotos in various sizes of a user, or deletes user pfotos.
+     * Note: This method relies on configuration setting from dokeos/main/inc/conf/profile.conf.php
+     * @param     int $user_id        The user internal identitfication number.
+     * @param     string $file        The common file name for the newly created pfotos.
+     *                                 It will be checked and modified for compatibility with the file system.
+     *                                 If full name is provided, path component is ignored.
+     *                                 If an empty name is provided, then old user photos are deleted only,
+     * @see     UserManager::delete_user_picture() as the prefered way for deletion.
+     * @param     string $source_file    The full system name of the image from which user photos will be created.
+     * @return     string/bool            Returns the resulting common file name of created images which usually should be stored in database.
+     * When deletion is recuested returns empty string. In case of internal error or negative validation returns FALSE.
+     */
+    public static function update_user_picture($user_id, $file = null, $source_file = null) {
+        if (empty($user_id)) {
+            return false;
+        }
+        $delete = empty($file);
+        if (empty($source_file)) {
+            $source_file = $file;
+        }
+
+        // Configuration options about user photos.
+        require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
+
+        // User-reserved directory where photos have to be placed.
+        $path_info = self::get_user_picture_path_by_id($user_id, 'system', true);
+        $path = $path_info['dir'];
+        // If this directory does not exist - we create it.
+        if (!file_exists($path)) {
+            @mkdir($path, api_get_permissions_for_new_directories(), true);
+        }
+
+        // The old photos (if any).
+        $old_file = $path_info['file'];
+
+        // Let us delete them.
+        if (!empty($old_file)) {
+            if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
+                $prefix = 'saved_'.date('Y_m_d_H_i_s').'_'.uniqid('').'_';
+                @rename($path.'small_'.$old_file, $path.$prefix.'small_'.$old_file);
+                @rename($path.'medium_'.$old_file, $path.$prefix.'medium_'.$old_file);
+                @rename($path.'big_'.$old_file, $path.$prefix.'big_'.$old_file);
+                @rename($path.$old_file, $path.$prefix.$old_file);
+            } else {
+                @unlink($path.'small_'.$old_file);
+                @unlink($path.'medium_'.$old_file);
+                @unlink($path.'big_'.$old_file);
+                @unlink($path.$old_file);
+            }
+        }
+
+        // Exit if only deletion has been requested. Return an empty picture name.
+        if ($delete) {
+            return '';
+        }
+
+        // Validation 2.
+        $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
+        $file = str_replace('\\', '/', $file);
+        $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file;
+        $extension = strtolower(substr(strrchr($filename, '.'), 1));
+        if (!in_array($extension, $allowed_types)) {
+            return false;
+        }
+
+        // This is the common name for the new photos.
+        if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) {
+            $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
+            $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
+            $filename = (substr($filename, -1) == '.') ? $filename.$extension : $filename.'.'.$extension;
+        } else {
+            $filename = replace_dangerous_char($filename);
+            if (PREFIX_IMAGE_FILENAME_WITH_UID) {
+                $filename = uniqid('').'_'.$filename;
+            }
+            // We always prefix user photos with user ids, so on setting
+            // api_get_setting('split_users_upload_directory') === 'true'
+            // the correspondent directories to be found successfully.
+            $filename = $user_id.'_'.$filename;
+        }
+
+        // Storing the new photos in 4 versions with various sizes.
+
+        $small  = self::resize_picture($source_file, 22);
+        $medium = self::resize_picture($source_file, 85);
+        $normal = self::resize_picture($source_file, 200);
+
+        $big    = new Image($source_file); // This is the original picture.
+
+        $ok = false;
+        $ok = $small->send_image($path.'small_'.$filename) &&
+              $medium->send_image($path.'medium_'.$filename) &&
+              $normal->send_image($path.$filename) &&
+              $big->send_image( $path.'big_'.$filename);
+        return $ok ? $filename : false;
+    }
+
+    /**
+     * Deletes user pfotos.
+     * Note: This method relies on configuration setting from dokeos/main/inc/conf/profile.conf.php
+     * @param int $user_id            The user internal identitfication number.
+     * @return string/bool            Returns empty string on success, FALSE on error.
+     */
+    public static function delete_user_picture($user_id) {
+        return self::update_user_picture($user_id);
+    }
+
+    /* PRODUCTIONS FUNCTIONS */
+
+    /**
+     * Returns an XHTML formatted list of productions for a user, or FALSE if he
+     * doesn't have any.
+     *
+     * If there has been a request to remove a production, the function will return
+     * without building the list unless forced to do so by the optional second
+     * parameter. This increases performance by avoiding to read through the
+     * productions on the filesystem before the removal request has been carried
+     * out because they'll have to be re-read afterwards anyway.
+     *
+     * @param    $user_id    User id
+     * @param    $force    Optional parameter to force building after a removal request
+     * @return    A string containing the XHTML code to dipslay the production list, or FALSE
+     */
+    public static function build_production_list($user_id, $force = false, $showdelete = false) {
+
+        if (!$force && !empty($_POST['remove_production'])) {
+            return true; // postpone reading from the filesystem
+        }
+        $productions = self::get_user_productions($user_id);
+
+        if (empty($productions)) {
+            return false;
+        }
+
+        $production_path = self::get_user_picture_path_by_id($user_id, 'web', true);
+        $production_dir = $production_path['dir'].$user_id.'/';
+        $del_image = api_get_path(WEB_CODE_PATH).'img/delete.gif';
+        $del_text = get_lang('Delete');
+        $production_list = '';
+        if (count($productions) > 0) {
+            $production_list = '
    '; + foreach ($productions as $file) { + $production_list .= '
  • '.htmlentities($file).''; + if ($showdelete) { + $production_list .= '
  • '; + } + } + $production_list .= '
'; + } + + return $production_list; + } + + /** + * Returns an array with the user's productions. + * + * @param $user_id User id + * @return An array containing the user's productions + */ + public static function get_user_productions($user_id) { + $production_path = self::get_user_picture_path_by_id($user_id, 'system', true); + $production_repository = $production_path['dir'].$user_id.'/'; + $productions = array(); + + if (is_dir($production_repository)) { + $handle = opendir($production_repository); + + while ($file = readdir($handle)) { + if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($production_repository.$file)) { + continue; // skip current/parent directory and .htaccess + } + if (preg_match('/('.$user_id.'|[0-9a-f]{13}|saved)_.+\.(png|jpg|jpeg|gif)$/i', $file)) { + // User's photos should not be listed as productions. + continue; + } + $productions[] = $file; + } + } + + return $productions; // can be an empty array + } + + /** + * Remove a user production. + * + * @param $user_id User id + * @param $production The production to remove + */ + public static function remove_user_production($user_id, $production) { + $production_path = self::get_user_picture_path_by_id($user_id, 'system', true); + $production_file = $production_path['dir'].$user_id.'/'.$production; + if (is_file($production_file)) { + unlink($production_file); + return true; + } + return false; + } + + /** + * Update an extra field. This function is called when a user changes his/her profile + * and by consequence fills or edits his/her extra fields. + * + * @param integer Field ID + * @param array Database columns and their new value + * @return boolean true if field updated, false otherwise + */ + public static function update_extra_field($fid, $columns) { + //TODO check that values added are values proposed for enumerated field types + $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD); + $fid = Database::escape_string($fid); + $sqluf = "UPDATE $t_uf SET "; + $known_fields = array('id', 'field_variable', 'field_type', 'field_display_text', 'field_default_value', 'field_order', 'field_visible', 'field_changeable', 'field_filter'); + $safecolumns = array(); + foreach ($columns as $index => $newval) { + if (in_array($index, $known_fields)) { + $safecolumns[$index] = Database::escape_string($newval); + $sqluf .= $index." = '".$safecolumns[$index]."', "; + } + } + $time = time(); + $sqluf .= " tms = FROM_UNIXTIME($time) WHERE id='$fid'"; + $resuf = Database::query($sqluf); + return $resuf; + } + + /** + * Update an extra field value for a given user + * @param integer User ID + * @param string Field variable name + * @param string Field value + * @return boolean true if field updated, false otherwise + */ + public static function update_extra_field_value($user_id, $fname, $fvalue = '') { + //TODO check that values added are values proposed for enumerated field types + $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD); + $t_ufo = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS); + $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES); + $fname = Database::escape_string($fname); + if ($user_id != strval(intval($user_id))) return false; + if ($user_id === false) return false; + $fvalues = ''; + + //echo '
'; print_r($fvalue);
+        if (is_array($fvalue)) {
+            foreach($fvalue as $val) {
+                $fvalues .= Database::escape_string($val).';';
+            }
+            if (!empty($fvalues)) {
+                $fvalues = substr($fvalues, 0, -1);
+            }
+        } else {
+            $fvalues = Database::escape_string($fvalue);
+        }
+        $sqluf = "SELECT * FROM $t_uf WHERE field_variable='$fname'";
+        $resuf = Database::query($sqluf);
+        if (Database::num_rows($resuf) == 1) {
+            //ok, the field exists
+            // Check if enumerated field, if the option is available
+            $rowuf = Database::fetch_array($resuf);
+            switch ($rowuf['field_type']) {
+                case self::USER_FIELD_TYPE_TAG :
+                    //4. Tags are process here comes from main/auth/profile.php
+                    UserManager::process_tags(explode(';', $fvalues), $user_id, $rowuf['id']);
+                    return true;
+                    break;
+                case self::USER_FIELD_TYPE_RADIO:
+                case self::USER_FIELD_TYPE_SELECT:
+                case self::USER_FIELD_TYPE_SELECT_MULTIPLE:
+                    $sqluo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowuf['id'];
+                    $resuo = Database::query($sqluo);
+                    $values = split(';',$fvalues);
+                    if (Database::num_rows($resuo) > 0) {
+                        $check = false;
+                        while ($rowuo = Database::fetch_array($resuo)) {
+                            if (in_array($rowuo['option_value'], $values)) {
+                                $check = true;
+                                break;
+                            }
+                        }
+                        if (!$check) {
+                            return false; //option value not found
+                        }
+                    } else {
+                        return false; //enumerated type but no option found
+                    }
+                    break;
+                case 1:
+                case 2:
+                default:
+                    break;
+            }
+            $tms = time();
+            $sqlufv = "SELECT * FROM $t_ufv WHERE user_id = $user_id AND field_id = ".$rowuf['id']." ORDER BY id";
+            $resufv = Database::query($sqlufv);
+            $n = Database::num_rows($resufv);
+            if ($n > 1) {
+                //problem, we already have to values for this field and user combination - keep last one
+                while ($rowufv = Database::fetch_array($resufv)) {
+                    if ($n > 1) {
+                        $sqld = "DELETE FROM $t_ufv WHERE id = ".$rowufv['id'];
+                        Database::query($sqld);
+                        $n--;
+                    }
+                    $rowufv = Database::fetch_array($resufv);
+                    if ($rowufv['field_value'] != $fvalues) {
+                        $sqlu = "UPDATE $t_ufv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowufv['id'];
+                        $resu = Database::query($sqlu);
+                        return($resu ? true : false);
+                    }
+                    return true;
+                }
+            } elseif ($n == 1) {
+                //we need to update the current record
+                $rowufv = Database::fetch_array($resufv);
+                if ($rowufv['field_value'] != $fvalues) {
+                    // If the new field is empty, delete it
+                    if ($fvalues == '') {
+                        $sql_query = "DELETE FROM $t_ufv WHERE id = ".$rowufv['id'].";";
+                    } else {
+                        // Otherwise update it
+                        $sql_query = "UPDATE $t_ufv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowufv['id'];
+                    }
+
+                    $resu = Database::query($sql_query);
+                    return($resu ? true : false);
+                }
+                return true;
+            } else {
+                $sqli = "INSERT INTO $t_ufv (user_id,field_id,field_value,tms) " .
+                    "VALUES ($user_id,".$rowuf['id'].",'$fvalues',FROM_UNIXTIME($tms))";
+                //error_log('UM::update_extra_field_value: '.$sqli);
+                $resi = Database::query($sqli);
+                return($resi ? true : false);
+            }
+        } else {
+            return false; //field not found
+        }
+    }
+
+    /**
+     * Get an array of extra fieds with field details (type, default value and options)
+     * @param    integer    Offset (from which row)
+     * @param    integer    Number of items
+     * @param    integer    Column on which sorting is made
+     * @param    string    Sorting direction
+     * @param    boolean    Optional. Whether we get all the fields or just the visible ones
+     * @param    int        Optional. Whether we get all the fields with field_filter 1 or 0 or everything
+     * @return    array    Extra fields details (e.g. $list[2]['type'], $list[4]['options'][2]['title']
+     */
+    public static function get_extra_fields($from = 0, $number_of_items = 0, $column = 5, $direction = 'ASC', $all_visibility = true, $field_filter = null) {
+        $fields = array();
+        $t_uf  = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
+        $t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+        $columns = array('id', 'field_variable', 'field_type', 'field_display_text', 'field_default_value', 'field_order', 'field_filter', 'tms');
+        $column = intval($column);
+        $sort_direction = '';
+        if (in_array(strtoupper($direction), array('ASC', 'DESC'))) {
+            $sort_direction = strtoupper($direction);
+        }
+        $sqlf = "SELECT * FROM $t_uf WHERE 1 = 1  ";
+        if (!$all_visibility) {
+            $sqlf .= " AND field_visible = 1 ";
+        }
+        if (!is_null($field_filter)) {
+            $field_filter = intval($field_filter);
+            $sqlf .= " AND field_filter = $field_filter ";
+        }
+        $sqlf .= " ORDER BY ".$columns[$column]." $sort_direction " ;
+        if ($number_of_items != 0) {
+            $sqlf .= " LIMIT ".Database::escape_string($from).','.Database::escape_string($number_of_items);
+        }
+
+        $resf = Database::query($sqlf);
+        if (Database::num_rows($resf) > 0) {
+            while($rowf = Database::fetch_array($resf)) {
+                $fields[$rowf['id']] = array(
+                    0 => $rowf['id'],
+                    1 => $rowf['field_variable'],
+                    2 => $rowf['field_type'],
+                    //3 => (empty($rowf['field_display_text']) ? '' : get_lang($rowf['field_display_text'], '')),
+                    // Temporarily removed auto-translation. Need update to get_lang() to know if translation exists (todo)
+                    // Ivan, 15-SEP-2009: get_lang() has been modified accordingly in order this issue to be solved.
+                    3 => (empty($rowf['field_display_text']) ? '' : $rowf['field_display_text']),
+                    4 => $rowf['field_default_value'],
+                    5 => $rowf['field_order'],
+                    6 => $rowf['field_visible'],
+                    7 => $rowf['field_changeable'],
+                    8 => $rowf['field_filter'],
+                    9 => array()
+                );
+
+                $sqlo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowf['id']." ORDER BY option_order ASC";
+                $reso = Database::query($sqlo);
+                if (Database::num_rows($reso) > 0) {
+                    while ($rowo = Database::fetch_array($reso)) {
+                        $fields[$rowf['id']][9][$rowo['id']] = array(
+                            0 => $rowo['id'],
+                            1 => $rowo['option_value'],
+                            //2 => (empty($rowo['option_display_text']) ? '' : get_lang($rowo['option_display_text'], '')),
+                            2 => (empty($rowo['option_display_text']) ? '' : $rowo['option_display_text']),
+                            3 => $rowo['option_order']
+                        );
+                    }
+                }
+            }
+        }
+
+        return $fields;
+    }
+
+    /**
+     * Get the list of options attached to an extra field
+     * @param string $fieldname the name of the field
+     * @return array the list of options
+     */
+    public static function get_extra_field_options($field_name) {
+        $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
+        $t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+
+        $sql = 'SELECT options.*
+                FROM '.$t_ufo.' options
+                    INNER JOIN '.$t_uf.' fields
+                        ON fields.id = options.field_id
+                            AND fields.field_variable="'.Database::escape_string($field_name).'"';
+        $rs = Database::query($sql);
+        return Database::store_result($rs);
+    }
+
+    /**
+     * Get the number of extra fields currently recorded
+     * @param    boolean    Optional switch. true (default) returns all fields, false returns only visible fields
+     * @return    integer    Number of fields
+     */
+    public static function get_number_of_extra_fields($all_visibility = true) {
+        $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
+        $sqlf = "SELECT * FROM $t_uf ";
+        if (!$all_visibility) {
+            $sqlf .= " WHERE field_visible = 1 ";
+        }
+        $sqlf .= " ORDER BY field_order";
+        $resf = Database::query($sqlf);
+        return Database::num_rows($resf);
+    }
+
+    /**
+      * Creates a new extra field
+      * @param    string    Field's internal variable name
+      * @param    int        Field's type
+      * @param    string    Field's language var name
+      * @param    string    Field's default value
+      * @param    string    Optional comma-separated list of options to provide for select and radio
+      * @return int     new user id - if the new user creation succeeds, false otherwise
+      */
+    public static function create_extra_field($fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions = '') {
+        // database table definition
+        $table_field         = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+        $table_field_options= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+
+        // First check wether the login already exists
+        if (self::is_extra_field_available($fieldvarname)) {
+            return api_set_failure('login-pass already taken');
+        }
+        $sql = "SELECT MAX(field_order) FROM $table_field";
+        $res = Database::query($sql);
+        $order = 0;
+        if (Database::num_rows($res) > 0) {
+            $row = Database::fetch_array($res);
+            $order = $row[0]+1;
+        }
+        $time = time();
+        $sql = "INSERT INTO $table_field
+                SET field_type = '".Database::escape_string($fieldtype)."',
+                field_variable = '".Database::escape_string($fieldvarname)."',
+                field_display_text = '".Database::escape_string($fieldtitle)."',
+                field_default_value = '".Database::escape_string($fielddefault)."',
+                field_order = '$order',
+                tms = FROM_UNIXTIME($time)";
+        $result = Database::query($sql);
+        if ($result) {
+            //echo "id returned";
+            $return = Database::insert_id();
+        } else {
+            //echo "false - failed" ;
+            return false;
+        }
+
+        if (!empty($fieldoptions) && in_array($fieldtype, array(self::USER_FIELD_TYPE_RADIO, self::USER_FIELD_TYPE_SELECT, self::USER_FIELD_TYPE_SELECT_MULTIPLE, self::USER_FIELD_TYPE_DOUBLE_SELECT))) {
+            if ($fieldtype == self::USER_FIELD_TYPE_DOUBLE_SELECT) {
+                $twolist = explode('|', $fieldoptions);
+                $counter = 0;
+                foreach ($twolist as $individual_list) {
+                    $splitted_individual_list = split(';', $individual_list);
+                    foreach    ($splitted_individual_list as $individual_list_option) {
+                        //echo 'counter:'.$counter;
+                        if ($counter == 0) {
+                            $list[] = $individual_list_option;
+                        } else {
+                            $list[] = str_repeat('*', $counter).$individual_list_option;
+                        }
+                    }
+                    $counter++;
+                }
+            } else {
+                $list = split(';', $fieldoptions);
+            }
+            foreach ($list as $option) {
+                $option = Database::escape_string($option);
+                $sql = "SELECT * FROM $table_field_options WHERE field_id = $return AND option_value = '".$option."'";
+                $res = Database::query($sql);
+                if (Database::num_rows($res) > 0) {
+                    //the option already exists, do nothing
+                } else {
+                    $sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = $return";
+                    $res = Database::query($sql);
+                    $max = 1;
+                    if (Database::num_rows($res) > 0) {
+                        $row = Database::fetch_array($res);
+                        $max = $row[0] + 1;
+                    }
+                    $time = time();
+                    $sql = "INSERT INTO $table_field_options (field_id,option_value,option_display_text,option_order,tms) VALUES ($return,'$option','$option',$max,FROM_UNIXTIME($time))";
+                    $res = Database::query($sql);
+                    if ($res === false) {
+                        $return = false;
+                    }
+                }
+            }
+        }
+        return $return;
+    }
+
+    /**
+      * Save the changes in the definition of the extra user profile field
+      * The function is called after you (as admin) decide to store the changes you have made to one of the fields you defined
+      *
+      * There is quite some logic in this field
+      * 1.  store the changes to the field (tupe, name, label, default text)
+      * 2.  remove the options and the choices of the users from the database that no longer occur in the form field 'possible values'. We should only remove
+      *     the options (and choices) that do no longer have to appear. We cannot remove all options and choices because if you remove them all
+      *     and simply re-add them all then all the user who have already filled this form will loose their selected value.
+      * 3.    we add the options that are newly added
+      *
+      *  current options are a;b;c and the user changes this to a;b;x (removing c and adding x)
+      *             we first remove c (and also the entry in the option_value table for the users who have chosen this)
+      *             we then add x
+      *             a and b are neither removed nor added
+      * 
+      * @param     integer $fieldid        the id of the field we are editing
+      * @param    string    $fieldvarname    the internal variable name of the field
+      * @param    int        $fieldtype        the type of the field
+      * @param    string    $fieldtitle        the title of the field
+      * @param    string    $fielddefault    the default value of the field
+      * @param    string    $fieldoptions    Optional comma-separated list of options to provide for select and radio
+      * @return boolean true
+      *
+      *
+      * @author Patrick Cool , Ghent University, Belgium
+      * @version July 2008
+      * @since Dokeos 1.8.6
+      */
+    public static function save_extra_field_changes($fieldid, $fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions = '') {
+        // database table definition
+        $table_field                 = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+        $table_field_options        = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+        $table_field_options_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+
+        // we first update the field definition with the new values
+        $time = time();
+        $sql = "UPDATE $table_field
+                SET field_type = '".Database::escape_string($fieldtype)."',
+                field_variable = '".Database::escape_string($fieldvarname)."',
+                field_display_text = '".Database::escape_string($fieldtitle)."',
+                field_default_value = '".Database::escape_string($fielddefault)."',
+                tms = FROM_UNIXTIME($time)
+            WHERE id = '".Database::escape_string($fieldid)."'";
+        $result = Database::query($sql);
+
+        // we create an array with all the options (will be used later in the script)
+        if ($fieldtype == self::USER_FIELD_TYPE_DOUBLE_SELECT) {
+            $twolist = explode('|', $fieldoptions);
+            $counter = 0;
+            foreach ($twolist as $individual_list) {
+                $splitted_individual_list = split(';', $individual_list);
+                foreach    ($splitted_individual_list as $individual_list_option) {
+                    //echo 'counter:'.$counter;
+                    if ($counter == 0) {
+                        $list[] = trim($individual_list_option);
+                    } else {
+                        $list[] = str_repeat('*', $counter).trim($individual_list_option);
+                    }
+                }
+                $counter++;
+            }
+        } else {
+            $templist = split(';', $fieldoptions);
+            $list = array_map('trim', $templist);
+        }
+
+        // Remove all the field options (and also the choices of the user) that are NOT in the new list of options
+        $sql = "SELECT * FROM $table_field_options WHERE option_value NOT IN ('".implode("','", $list)."') AND field_id = '".Database::escape_string($fieldid)."'";
+        $result = Database::query($sql);
+        $return['deleted_options'] = 0;
+        while ($row = Database::fetch_array($result)) {
+            // deleting the option
+            $sql_delete_option = "DELETE FROM $table_field_options WHERE id='".Database::escape_string($row['id'])."'";
+            Database::query($sql_delete_option);
+            $return['deleted_options']++;
+
+            // deleting the answer of the user who has chosen this option
+            $sql_delete_option_value = "DELETE FROM $table_field_options_values WHERE field_id = '".Database::escape_string($fieldid)."' AND field_value = '".Database::escape_string($row['option_value'])."'";
+            Database::query($sql_delete_option_value);
+            $return['deleted_option_values'] = $return['deleted_option_values'] + Database::affected_rows();
+        }
+
+        // we now try to find the field options that are newly added
+        $sql = "SELECT * FROM $table_field_options WHERE field_id = '".Database::escape_string($fieldid)."'";
+        $result = Database::query($sql);
+        while ($row = Database::fetch_array($result)) {
+            // we remove every option that is already in the database from the $list
+            if (in_array(trim($row['option_display_text']), $list)) {
+                $key = array_search(trim($row['option_display_text']), $list);
+                unset($list[$key]);
+            }
+        }
+
+        // we store the new field options in the database
+        foreach ($list as $key => $option) {
+            $sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = '".Database::escape_string($fieldid)."'";
+            $res = Database::query($sql);
+            $max = 1;
+            if (Database::num_rows($res) > 0) {
+                $row = Database::fetch_array($res);
+                $max = $row[0] + 1;
+            }
+            $time = time();
+            $sql = "INSERT INTO $table_field_options (field_id,option_value,option_display_text,option_order,tms) VALUES ('".Database::escape_string($fieldid)."','".Database::escape_string($option)."','".Database::escape_string($option)."',$max,FROM_UNIXTIME($time))";
+            $result = Database::query($sql);
+        }
+        return true;
+    }
+
+    /**
+     * Check if a field is available
+     * @param    string    the wanted fieldname
+     * @return    boolean    true if the wanted username is available
+     */
+    public static function is_extra_field_available($fieldname) {
+        $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
+        $sql = "SELECT * FROM $t_uf WHERE field_variable = '".Database::escape_string($fieldname)."'";
+        $res = Database::query($sql);
+        return Database::num_rows($res) > 0;
+    }
+
+    /**
+     * Gets user extra fields data
+     * @param    integer    User ID
+     * @param    boolean    Whether to prefix the fields indexes with "extra_" (might be used by formvalidator)
+     * @param    boolean    Whether to return invisible fields as well
+     * @param    boolean    Whether to split multiple-selection fields or not
+     * @return    array    Array of fields => value for the given user
+     */
+    public static function get_extra_user_data($user_id, $prefix = false, $all_visibility = true, $splitmultiple = false, $field_filter = null) {
+        // A sanity check.
+        if (empty($user_id)) {
+            $user_id = 0;
+        } else {
+            if ($user_id != strval(intval($user_id))) return array();
+        }
+        $extra_data = array();
+        $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+        $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+        $user_id = Database::escape_string($user_id);
+        $sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
+        $filter_cond = '';
+
+        if (!$all_visibility) {
+            if (isset($field_filter)) {
+                $field_filter = intval($field_filter);
+                $filter_cond .= " AND field_filter = $field_filter ";
+            }
+            $sql .= " WHERE f.field_visible = 1 $filter_cond ";
+        } else {
+            if (isset($field_filter)) {
+                $field_filter = intval($field_filter);
+                $sql .= " WHERE field_filter = $field_filter ";
+            }
+        }
+        $sql .= " ORDER BY f.field_order";
+
+        $res = Database::query($sql);
+        if (Database::num_rows($res) > 0) {
+            while ($row = Database::fetch_array($res)) {
+                if ($row['type'] == self::USER_FIELD_TYPE_TAG) {
+                    $tags = self::get_user_tags_to_string($user_id,$row['id'],false);
+                    $extra_data['extra_'.$row['fvar']] = $tags;
+                } else {
+                    $sqlu = "SELECT field_value as fval FROM $t_ufv WHERE field_id=".$row['id']." AND user_id = ".$user_id;
+                    $resu = Database::query($sqlu);
+                    $fval = '';
+                    // get default value
+                    $sql_df = "SELECT field_default_value as fval_df " .
+                            " FROM $t_uf " .
+                            " WHERE id=".$row['id'];
+                    $res_df = Database::query($sql_df);
+
+                    if (Database::num_rows($resu) > 0) {
+                        $rowu = Database::fetch_array($resu);
+                        $fval = $rowu['fval'];
+                        if ($row['type'] ==  self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
+                            $fval = split(';',$rowu['fval']);
+                        }
+                    } else {
+                        $row_df = Database::fetch_array($res_df);
+                        $fval = $row_df['fval_df'];
+                    }
+                    // We get here (and fill the $extra_data array) even if there is no user with data (we fill it with default values)
+                    if ($prefix) {
+                        if ($row['type'] ==  self::USER_FIELD_TYPE_RADIO) {
+                            $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
+                        } else {
+                            $extra_data['extra_'.$row['fvar']] = $fval;
+                        }
+                    } else {
+                        if ($row['type'] ==  self::USER_FIELD_TYPE_RADIO) {
+                            $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
+                        } else {
+                            $extra_data[$row['fvar']] = $fval;
+                        }
+                    }
+                }
+            }
+        }
+        return $extra_data;
+    }
+
+    /** Get extra user data by field
+     * @param int    user ID
+     * @param string the internal variable name of the field
+     * @return array with extra data info of a user i.e array('field_variable'=>'value');
+     */
+    public static function get_extra_user_data_by_field($user_id, $field_variable, $prefix = false, $all_visibility = true, $splitmultiple = false) {
+        // A sanity check.
+        if (empty($user_id)) {
+            $user_id = 0;
+        } else {
+            if ($user_id != strval(intval($user_id))) return array();
+        }
+        $extra_data = array();
+        $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+        $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+        $user_id = Database::escape_string($user_id);
+
+        $sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
+        $sql .= " WHERE f.field_variable = '$field_variable' ";
+
+        if (!$all_visibility) {
+            $sql .= " AND f.field_visible = 1 ";
+        }
+
+        $sql .= " ORDER BY f.field_order";
+
+        $res = Database::query($sql);
+        if (Database::num_rows($res) > 0) {
+            while ($row = Database::fetch_array($res)) {
+                $sqlu = "SELECT field_value as fval " .
+                        " FROM $t_ufv " .
+                        " WHERE field_id=".$row['id']."" .
+                        " AND user_id=".$user_id;
+                $resu = Database::query($sqlu);
+                $fval = '';
+                if (Database::num_rows($resu) > 0) {
+                    $rowu = Database::fetch_array($resu);
+                    $fval = $rowu['fval'];
+                    if ($row['type'] ==  self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
+                        $fval = split(';',$rowu['fval']);
+                    }
+                }
+                if ($prefix) {
+                    $extra_data['extra_'.$row['fvar']] = $fval;
+                } else {
+                    $extra_data[$row['fvar']] = $fval;
+                }
+            }
+        }
+
+        return $extra_data;
+    }
+
+    /**
+     * Get the extra field information for a certain field (the options as well)
+     * @param  int     The name of the field we want to know everything about
+     * @return array   Array containing all the information about the extra profile field (first level of array contains field details, then 'options' sub-array contains options details, as returned by the database)
+     * @author Julio Montoya
+     * @since Dokeos 1.8.6
+     */
+    public static function get_extra_field_information_by_name($field_variable, $fuzzy = false) {
+        // database table definition
+        $table_field             = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+        $table_field_options    = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+
+        // all the information of the field
+        $sql = "SELECT * FROM $table_field WHERE field_variable='".Database::escape_string($field_variable)."'";
+        $result = Database::query($sql);
+        $return = Database::fetch_array($result);
+
+        // all the options of the field
+        $sql = "SELECT * FROM $table_field_options WHERE field_id='".Database::escape_string($return['id'])."' ORDER BY option_order ASC";
+        $result = Database::query($sql);
+        while ($row = Database::fetch_array($result)) {
+            $return['options'][$row['id']] = $row;
+        }
+        return $return;
+    }
+
+    public static function get_all_extra_field_by_type($field_type) {
+        // database table definition
+        $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+
+        // all the information of the field
+        $sql = "SELECT * FROM $table_field WHERE field_type='".Database::escape_string($field_type)."'";
+        $result = Database::query($sql);
+        $return = array();
+        while ($row = Database::fetch_array($result)) {
+            $return[] = $row['id'];
+        }
+        return $return;
+    }
+
+    /**
+     * Get all the extra field information of a certain field (also the options)
+     *
+     * @param int $field_name the name of the field we want to know everything of
+     * @return array $return containing all th information about the extra profile field
+     * @author Julio Montoya
+     * @since Dokeos 1.8.6
+     */
+    public static function get_extra_field_information($field_id) {
+        // database table definition
+        $table_field             = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+        $table_field_options    = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+
+        // all the information of the field
+        $sql = "SELECT * FROM $table_field WHERE id='".Database::escape_string($field_id)."'";
+        $result = Database::query($sql);
+        $return = Database::fetch_array($result);
+
+        // all the options of the field
+        $sql = "SELECT * FROM $table_field_options WHERE field_id='".Database::escape_string($field_id)."' ORDER BY option_order ASC";
+        $result = Database::query($sql);
+        while ($row = Database::fetch_array($result)) {
+            $return['options'][$row['id']] = $row;
+        }
+        return $return;
+    }
+
+    /** Get extra user data by value
+     * @param string the internal variable name of the field
+     * @param string the internal value of the field
+     * @return array with extra data info of a user i.e array('field_variable'=>'value');
+     */
+
+    public static function get_extra_user_data_by_value($field_variable, $field_value, $all_visibility = true) {
+        $extra_data = array();
+        $table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
+        $table_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+        $table_user_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
+        $where = '';
+        /*
+        if (is_array($field_variable_array) && is_array($field_value_array)) {
+            if (count($field_variable_array) == count($field_value_array)) {
+                $field_var_count = count($field_variable_array);
+                for ($i = 0; $i < $field_var_count; $i++) {
+                    if ($i != 0 && $i != $field_var_count) {
+                        $where.= ' AND ';
+                    }
+                    $where.= "field_variable='".Database::escape_string($field_variable_array[$i])."' AND user_field_options.id='".Database::escape_string($field_value_array[$i])."'";
+                }
+            }
+
+        }*/
+        $where = "field_variable='".Database::escape_string($field_variable)."' AND field_value='".Database::escape_string($field_value)."'";
+
+        $sql = "SELECT user_id FROM $table_user_field user_field INNER JOIN $table_user_field_values user_field_values
+                    ON (user_field.id = user_field_values.field_id)
+                WHERE $where";
+
+        if ($all_visibility) {
+            $sql .= " AND user_field.field_visible = 1 ";
+        } else {
+            $sql .= " AND user_field.field_visible = 0 ";
+        }
+        $res = Database::query($sql);
+        $result_data = array();
+        if (Database::num_rows($res) > 0) {
+            while ($row = Database::fetch_array($res)) {
+                $result_data[] = $row['user_id'];
+            }
+        }
+        return $result_data;
+    }
+
+    /**
+     * Get extra user data by field variable
+     * @param string    field variable
+     * @return array    data
+     */
+    public static function get_extra_user_data_by_field_variable($field_variable) {
+        $tbl_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+        $extra_information_by_variable = self::get_extra_field_information_by_name($field_variable);
+        $field_id = intval($extra_information_by_variable['id']);
+        $data = array();
+        $sql = "SELECT * FROM $tbl_user_field_values WHERE field_id='$field_id'";
+        $rs  = Database::query($sql);
+        if (Database::num_rows($rs) > 0) {
+            while ($row = Database::fetch_array($rs)) {
+                $user_id = $row['user_id'];
+                $data[$user_id] = $row;
+            }
+        }
+        return $data;
+    }
+
+    /**
+     * Gives a list of [session_category][session_id] for the current user.
+     * @param integer $user_id
+     * @param boolean whether to fill the first element or not (to give space for courses out of categories)
+     * @param boolean  optional true if limit time from session is over, false otherwise
+     * @return array  list of statuses [session_category][session_id]
+     * @todo ensure multiple access urls are managed correctly
+     */
+    public static function get_sessions_by_category($user_id, $is_time_over = false) {
+        // Database Table Definitions
+        $tbl_session                = Database :: get_main_table(TABLE_MAIN_SESSION);
+        $tbl_session_course_user    = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $tbl_session_category       = Database :: get_main_table(TABLE_MAIN_SESSION_CATEGORY);
+
+        if ($user_id != strval(intval($user_id))) return array();
 
-		// Get the list of sessions per user
+        $categories = array();
+
+        // Get the list of sessions per user
         $now = api_get_utc_datetime();
 
-		$condition_date_end = "";
-		if ($is_time_over) {
-			$condition_date_end = " AND (session.date_end < '$now' AND session.date_end != '0000-00-00')  ";
-		} else {
+        $condition_date_end = "";
+        if ($is_time_over) {
+            $condition_date_end = " AND (session.date_end < '$now' AND session.date_end != '0000-00-00')  ";
+        } else {
             if (api_is_allowed_to_create_course()) {
                 //Teachers can access the session depending in the access_coach date
                 $condition_date_end = null;
             } else {
                 $condition_date_end = " AND (session.date_end >= '$now' OR session.date_end = '0000-00-00') ";
             }
-		}
+        }
 
         //ORDER BY session_category_id, date_start, date_end
         $sql = "SELECT DISTINCT session.id,
@@ -2000,76 +2028,76 @@ class UserManager {
 
             }
         }
-		return $categories;
-	}
-
-	/**
-	 * Gives a list of [session_id-course_code] => [status] for the current user.
-	 * @param integer $user_id
-	 * @return array  list of statuses (session_id-course_code => status)
-	 */
-	public static function get_personal_session_course_list($user_id) {
-		// Database Table Definitions
-		$tbl_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
-		$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-		$tbl_session 				= Database :: get_main_table(TABLE_MAIN_SESSION);
-		$tbl_session_user			= Database :: get_main_table(TABLE_MAIN_SESSION_USER);
-		$tbl_course_user 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-		$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-		if ($user_id != strval(intval($user_id))) return array();
-
-		//we filter the courses from the URL
-		$join_access_url = $where_access_url = '';
-
-		if (api_get_multiple_access_url()) {
-			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1) {
-				$tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-				$join_access_url = "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
-				$where_access_url = " AND access_url_id = $access_url_id ";
-			}
-		}
-
-		//Courses in which we suscribed out of any session
-		$tbl_user_course_category = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
-
-		$personal_course_list_sql = "SELECT course.code, course_rel_user.status course_rel_status, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
-			                         FROM ".$tbl_course_user." course_rel_user
-				                     LEFT JOIN ".$tbl_course." course
-					                 ON course.code = course_rel_user.course_code
-				                     LEFT JOIN ".$tbl_user_course_category." user_course_category
-					                 ON course_rel_user.user_course_cat = user_course_category.id
-				                     $join_access_url
-			                         WHERE  course_rel_user.user_id = '".$user_id."' AND
-			                                course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."  $where_access_url
-								     ORDER BY user_course_category.sort, course_rel_user.sort, course.title ASC";
-
-		$course_list_sql_result = Database::query($personal_course_list_sql);
-
-		$personal_course_list = array();
-		if (Database::num_rows($course_list_sql_result) > 0 ) {
-			while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
+        return $categories;
+    }
+
+    /**
+     * Gives a list of [session_id-course_code] => [status] for the current user.
+     * @param integer $user_id
+     * @return array  list of statuses (session_id-course_code => status)
+     */
+    public static function get_personal_session_course_list($user_id) {
+        // Database Table Definitions
+        $tbl_course                 = Database :: get_main_table(TABLE_MAIN_COURSE);
+        $tbl_user                     = Database :: get_main_table(TABLE_MAIN_USER);
+        $tbl_session                 = Database :: get_main_table(TABLE_MAIN_SESSION);
+        $tbl_session_user            = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
+        $tbl_course_user             = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+        $tbl_session_course_user     = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+
+        if ($user_id != strval(intval($user_id))) return array();
+
+        //we filter the courses from the URL
+        $join_access_url = $where_access_url = '';
+
+        if (api_get_multiple_access_url()) {
+            $access_url_id = api_get_current_access_url_id();
+            if ($access_url_id != -1) {
+                $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+                $join_access_url = "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
+                $where_access_url = " AND access_url_id = $access_url_id ";
+            }
+        }
+
+        //Courses in which we suscribed out of any session
+        $tbl_user_course_category = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+
+        $personal_course_list_sql = "SELECT course.code, course_rel_user.status course_rel_status, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
+                                     FROM ".$tbl_course_user." course_rel_user
+                                     LEFT JOIN ".$tbl_course." course
+                                     ON course.code = course_rel_user.course_code
+                                     LEFT JOIN ".$tbl_user_course_category." user_course_category
+                                     ON course_rel_user.user_course_cat = user_course_category.id
+                                     $join_access_url
+                                     WHERE  course_rel_user.user_id = '".$user_id."' AND
+                                            course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."  $where_access_url
+                                     ORDER BY user_course_category.sort, course_rel_user.sort, course.title ASC";
+
+        $course_list_sql_result = Database::query($personal_course_list_sql);
+
+        $personal_course_list = array();
+        if (Database::num_rows($course_list_sql_result) > 0 ) {
+            while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
                 $course_info = api_get_course_info($result_row['code']);
                 $result_row['course_info'] = $course_info;
-				$personal_course_list[] = $result_row;
-			}
-		}
-
-		// Get the list of sessions where the user is subscribed
-		$sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
-						FROM $tbl_session_user, $tbl_session
-						WHERE   (id_session=id AND
+                $personal_course_list[] = $result_row;
+            }
+        }
+
+        // Get the list of sessions where the user is subscribed
+        $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
+                        FROM $tbl_session_user, $tbl_session
+                        WHERE   (id_session=id AND
                                 id_user=$user_id AND
                                 relation_type<>".SESSION_RELATION_TYPE_RRHH.") OR
                                 (id_coach = $user_id)
-						ORDER BY date_start, date_end, name";
-		$result     = Database::query($sessions_sql);
-		$sessions   = Database::store_result($result, 'ASSOC');
+                        ORDER BY date_start, date_end, name";
+        $result     = Database::query($sessions_sql);
+        $sessions   = Database::store_result($result, 'ASSOC');
 
-		if (api_is_allowed_to_create_course()) {
+        if (api_is_allowed_to_create_course()) {
 
-			foreach ($sessions as $enreg) {
+            foreach ($sessions as $enreg) {
                 $session_id = $enreg['id'];
                 $session_visibility = api_get_session_visibility($session_id);
 
@@ -2077,126 +2105,126 @@ class UserManager {
                     continue;
                 }
 
-				$id_session = $enreg['id'];
-				$personal_course_list_sql = "SELECT DISTINCT course.code code, course.title i,
-				                            ".(api_is_western_name_order() ? "CONCAT(user.firstname,' ',user.lastname)" : "CONCAT(user.lastname,' ',user.firstname)")." t, email, course.course_language l, 1 sort,
-				                               category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name
-					FROM $tbl_session_course_user as session_course_user
-						INNER JOIN $tbl_course AS course
-							ON course.code = session_course_user.course_code
-						INNER JOIN $tbl_session as session
-							ON session.id = session_course_user.id_session
-						LEFT JOIN $tbl_user as user
-							ON user.user_id = session_course_user.id_user OR session.id_coach = user.user_id
-					WHERE session_course_user.id_session = $id_session
-						AND ((session_course_user.id_user=$user_id AND session_course_user.status = 2) OR session.id_coach = $user_id)
-					ORDER BY i";
-
-				$course_list_sql_result = Database::query($personal_course_list_sql);
-
-				while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
+                $id_session = $enreg['id'];
+                $personal_course_list_sql = "SELECT DISTINCT course.code code, course.title i,
+                                            ".(api_is_western_name_order() ? "CONCAT(user.firstname,' ',user.lastname)" : "CONCAT(user.lastname,' ',user.firstname)")." t, email, course.course_language l, 1 sort,
+                                               category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name
+                    FROM $tbl_session_course_user as session_course_user
+                        INNER JOIN $tbl_course AS course
+                            ON course.code = session_course_user.course_code
+                        INNER JOIN $tbl_session as session
+                            ON session.id = session_course_user.id_session
+                        LEFT JOIN $tbl_user as user
+                            ON user.user_id = session_course_user.id_user OR session.id_coach = user.user_id
+                    WHERE session_course_user.id_session = $id_session
+                        AND ((session_course_user.id_user=$user_id AND session_course_user.status = 2) OR session.id_coach = $user_id)
+                    ORDER BY i";
+
+                $course_list_sql_result = Database::query($personal_course_list_sql);
+
+                while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
                     $result_row['course_info'] = api_get_course_info($result_row['code']);
-					$key = $result_row['id_session'].' - '.$result_row['code'];
-					$personal_course_list[$key] = $result_row;
-				}
-			}
-		}
-
-		foreach ($sessions as $enreg) {
-			$session_id = $enreg['id'];
+                    $key = $result_row['id_session'].' - '.$result_row['code'];
+                    $personal_course_list[$key] = $result_row;
+                }
+            }
+        }
+
+        foreach ($sessions as $enreg) {
+            $session_id = $enreg['id'];
             $session_visibility = api_get_session_visibility($session_id);
             if ($session_visibility == SESSION_INVISIBLE) {
                 continue;
             }
 
-			// this query is very similar to the above query, but it will check the session_rel_course_user table if there are courses registered to our user or not
-			$personal_course_list_sql = "SELECT DISTINCT course.code code, course.title i, CONCAT(user.lastname,' ',user.firstname) t, email,
-			                             course.course_language l, 1 sort, category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name, " .
+            // this query is very similar to the above query, but it will check the session_rel_course_user table if there are courses registered to our user or not
+            $personal_course_list_sql = "SELECT DISTINCT course.code code, course.title i, CONCAT(user.lastname,' ',user.firstname) t, email,
+                                         course.course_language l, 1 sort, category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name, " .
                                         "IF((session_course_user.id_user = 3 AND session_course_user.status=2),'2', '5')
-										FROM $tbl_session_course_user as session_course_user
-										INNER JOIN $tbl_course AS course
-										ON course.code = session_course_user.course_code AND session_course_user.id_session = $session_id
-										INNER JOIN $tbl_session as session ON session_course_user.id_session = session.id
-										LEFT JOIN $tbl_user as user ON user.user_id = session_course_user.id_user
-										WHERE session_course_user.id_user = $user_id
+                                        FROM $tbl_session_course_user as session_course_user
+                                        INNER JOIN $tbl_course AS course
+                                        ON course.code = session_course_user.course_code AND session_course_user.id_session = $session_id
+                                        INNER JOIN $tbl_session as session ON session_course_user.id_session = session.id
+                                        LEFT JOIN $tbl_user as user ON user.user_id = session_course_user.id_user
+                                        WHERE session_course_user.id_user = $user_id
                                         ORDER BY i";
 
-			$course_list_sql_result = Database::query($personal_course_list_sql);
+            $course_list_sql_result = Database::query($personal_course_list_sql);
 
-			while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
+            while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
                 $result_row['course_info'] = api_get_course_info($result_row['code']);
-				$key = $result_row['id_session'].' - '.$result_row['code'];
-				if (!isset($personal_course_list[$key])) {
-					$personal_course_list[$key] = $result_row;
-				}
-			}
-		}
-		return $personal_course_list;
-	}
-
-	/**
-	 * Gives a list of courses for the given user in the given session
-	 * @param integer $user_id
-	 * @return array  list of statuses (session_id-course_code => status)
-	 */
-	public static function get_courses_list_by_session($user_id, $session_id) {
-		// Database Table Definitions
-		$tbl_session 				= Database :: get_main_table(TABLE_MAIN_SESSION);
-		$tbl_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-		$user_id    = intval($user_id);
-		$session_id = intval($session_id);
-		//we filter the courses from the URL
-		$join_access_url=$where_access_url='';
-
-		if (api_get_multiple_access_url()) {
-			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1) {
-				$tbl_url_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-				$join_access_url= " ,  $tbl_url_session url_rel_session ";
-				$where_access_url=" AND access_url_id = $access_url_id AND url_rel_session.session_id = $session_id ";
-			}
-		}
-
-		$personal_course_list = array();
-		$courses = array();
-
-		// this query is very similar to the above query, but it will check the session_rel_course_user table if there are courses registered to our user or not
-		$personal_course_list_sql = "SELECT DISTINCT scu.course_code as code
+                $key = $result_row['id_session'].' - '.$result_row['code'];
+                if (!isset($personal_course_list[$key])) {
+                    $personal_course_list[$key] = $result_row;
+                }
+            }
+        }
+        return $personal_course_list;
+    }
+
+    /**
+     * Gives a list of courses for the given user in the given session
+     * @param integer $user_id
+     * @return array  list of statuses (session_id-course_code => status)
+     */
+    public static function get_courses_list_by_session($user_id, $session_id) {
+        // Database Table Definitions
+        $tbl_session                 = Database :: get_main_table(TABLE_MAIN_SESSION);
+        $tbl_session_course_user     = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+
+        $user_id    = intval($user_id);
+        $session_id = intval($session_id);
+        //we filter the courses from the URL
+        $join_access_url=$where_access_url='';
+
+        if (api_get_multiple_access_url()) {
+            $access_url_id = api_get_current_access_url_id();
+            if ($access_url_id != -1) {
+                $tbl_url_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+                $join_access_url= " ,  $tbl_url_session url_rel_session ";
+                $where_access_url=" AND access_url_id = $access_url_id AND url_rel_session.session_id = $session_id ";
+            }
+        }
+
+        $personal_course_list = array();
+        $courses = array();
+
+        // this query is very similar to the above query, but it will check the session_rel_course_user table if there are courses registered to our user or not
+        $personal_course_list_sql = "SELECT DISTINCT scu.course_code as code
                                     FROM $tbl_session_course_user as scu $join_access_url
-									WHERE scu.id_user = $user_id AND scu.id_session = $session_id $where_access_url
-									ORDER BY code";
-
-		$course_list_sql_result = Database::query($personal_course_list_sql);
-
-		if (Database::num_rows($course_list_sql_result) > 0) {
-			while ($result_row = Database::fetch_array($course_list_sql_result)) {
-				$result_row['status'] = 5;
-				if (!in_array($result_row['code'], $courses)) {
-					$personal_course_list[] = $result_row;
-					$courses[] = $result_row['code'];
-				}
-			}
-		}
-
-		if (api_is_allowed_to_create_course()) {
-			$personal_course_list_sql = "SELECT DISTINCT scu.course_code as code
+                                    WHERE scu.id_user = $user_id AND scu.id_session = $session_id $where_access_url
+                                    ORDER BY code";
+
+        $course_list_sql_result = Database::query($personal_course_list_sql);
+
+        if (Database::num_rows($course_list_sql_result) > 0) {
+            while ($result_row = Database::fetch_array($course_list_sql_result)) {
+                $result_row['status'] = 5;
+                if (!in_array($result_row['code'], $courses)) {
+                    $personal_course_list[] = $result_row;
+                    $courses[] = $result_row['code'];
+                }
+            }
+        }
+
+        if (api_is_allowed_to_create_course()) {
+            $personal_course_list_sql = "SELECT DISTINCT scu.course_code as code
                                         FROM $tbl_session_course_user as scu, $tbl_session as s $join_access_url
-										WHERE s.id = $session_id AND scu.id_session = s.id AND ((scu.id_user=$user_id AND scu.status=2) OR s.id_coach = $user_id)
-										$where_access_url
-										ORDER BY code";
+                                        WHERE s.id = $session_id AND scu.id_session = s.id AND ((scu.id_user=$user_id AND scu.status=2) OR s.id_coach = $user_id)
+                                        $where_access_url
+                                        ORDER BY code";
             $course_list_sql_result = Database::query($personal_course_list_sql);
 
-			if (Database::num_rows($course_list_sql_result)>0) {
-				while ($result_row = Database::fetch_array($course_list_sql_result)) {
-					$result_row['status'] = 2;
-					if (!in_array($result_row['code'],$courses)) {
-						$personal_course_list[] = $result_row;
-						$courses[] = $result_row['code'];
-					}
-				}
-			}
-		}
+            if (Database::num_rows($course_list_sql_result)>0) {
+                while ($result_row = Database::fetch_array($course_list_sql_result)) {
+                    $result_row['status'] = 2;
+                    if (!in_array($result_row['code'],$courses)) {
+                        $personal_course_list[] = $result_row;
+                        $courses[] = $result_row['code'];
+                    }
+                }
+            }
+        }
 
         if (api_is_drh()) {
             $session_list = SessionManager::get_sessions_followed_by_drh($user_id);
@@ -2210,75 +2238,75 @@ class UserManager {
                 }
             }
         }
-		return $personal_course_list;
-	}
-
-	/**
-	 * Get user id from a username
-	 * @param	string	Username
-	 * @return	int		User ID (or false if not found)
-	 */
-	public static function get_user_id_from_username($username) {
-	    if (empty($username)) {
-	        return false;
-	    }
-		$username = Database::escape_string($username);
-		$t_user = Database::get_main_table(TABLE_MAIN_USER);
-		$sql = "SELECT user_id FROM $t_user WHERE username = '$username'";
-		$res = Database::query($sql);
-		if ($res === false) { return false; }
-		if (Database::num_rows($res) !== 1) { return false; }
-		$row = Database::fetch_array($res);
-		return $row['user_id'];
-	}
-
-	/**
-	 * Get the users files upload from his share_folder
-	 * @param	string	User ID
-	 * @param   string  course directory
-	 * @param   string  resourcetype: images, all
-	 * @return	int		User ID (or false if not found)
-	 */
-	public static function get_user_upload_files_by_course($user_id, $course, $resourcetype='all') {
-		$return = '';
-		if (!empty($user_id) && !empty($course)) {
-			$user_id = intval($user_id);
-			$path = api_get_path(SYS_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
-			$web_path = api_get_path(WEB_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
-			$file_list = array();
-
-			if (is_dir($path)) {
-				$handle = opendir($path);
-				while ($file = readdir($handle)) {
-					if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($path.$file)) {
-						continue; // skip current/parent directory and .htaccess
-					}
-					$file_list[] = $file;
-				}
-				if (count($file_list) > 0) {
-					$return = "

$course

"; - $return .= '
    '; - } - foreach ($file_list as $file) { - if ($resourcetype=="all") { - $return .= '
  • '.htmlentities($file).'
  • '; - } elseif($resourcetype=="images") { - //get extension - $ext = explode('.', $file); - if ($ext[1]=='jpg' || $ext[1]=='jpeg'|| $ext[1]=='png' || $ext[1]=='gif' || $ext[1]=='bmp' || $ext[1]=='tif') { + return $personal_course_list; + } + + /** + * Get user id from a username + * @param string Username + * @return int User ID (or false if not found) + */ + public static function get_user_id_from_username($username) { + if (empty($username)) { + return false; + } + $username = Database::escape_string($username); + $t_user = Database::get_main_table(TABLE_MAIN_USER); + $sql = "SELECT user_id FROM $t_user WHERE username = '$username'"; + $res = Database::query($sql); + if ($res === false) { return false; } + if (Database::num_rows($res) !== 1) { return false; } + $row = Database::fetch_array($res); + return $row['user_id']; + } + + /** + * Get the users files upload from his share_folder + * @param string User ID + * @param string course directory + * @param string resourcetype: images, all + * @return int User ID (or false if not found) + */ + public static function get_user_upload_files_by_course($user_id, $course, $resourcetype='all') { + $return = ''; + if (!empty($user_id) && !empty($course)) { + $user_id = intval($user_id); + $path = api_get_path(SYS_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/'; + $web_path = api_get_path(WEB_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/'; + $file_list = array(); + + if (is_dir($path)) { + $handle = opendir($path); + while ($file = readdir($handle)) { + if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($path.$file)) { + continue; // skip current/parent directory and .htaccess + } + $file_list[] = $file; + } + if (count($file_list) > 0) { + $return = "

    $course

    "; + $return .= '
      '; + } + foreach ($file_list as $file) { + if ($resourcetype=="all") { + $return .= '
    • '.htmlentities($file).'
    • '; + } elseif($resourcetype=="images") { + //get extension + $ext = explode('.', $file); + if ($ext[1]=='jpg' || $ext[1]=='jpeg'|| $ext[1]=='png' || $ext[1]=='gif' || $ext[1]=='bmp' || $ext[1]=='tif') { $return .= '
    • '; - } - } - } - if (count($file_list) > 0) { - $return .= '
    '; - } - } - } - return $return; - } + } + } + } + if (count($file_list) > 0) { + $return .= '
'; + } + } + } + return $return; + } /** * Gets the API key (or keys) and return them into an array @@ -2286,7 +2314,7 @@ class UserManager { * @return array Non-indexed array containing the list of API keys for this user, or FALSE on error */ public static function get_api_keys($user_id = null, $api_service = 'dokeos') { - if ($user_id != strval(intval($user_id))) return false; + if ($user_id != strval(intval($user_id))) return false; if (empty($user_id)) { $user_id = api_get_user_id(); } if ($user_id === false) return false; $service_name = Database::escape_string($api_service); @@ -2299,7 +2327,7 @@ class UserManager { if ($num == 0) return false; $list = array(); while ($row = Database::fetch_array($res)) { - $list[$row['id']] = $row['api_key']; + $list[$row['id']] = $row['api_key']; } return $list; } @@ -2348,11 +2376,11 @@ class UserManager { * Regenerate an API key from the user's account * @param int user ID (defaults to the results of api_get_user_id()) * @param string API key's internal ID - * @return int num + * @return int num */ public static function update_api_key($user_id, $api_service) { - if ($user_id != strval(intval($user_id))) return false; - if ($user_id === false) return false; + if ($user_id != strval(intval($user_id))) return false; + if ($user_id === false) return false; $service_name = Database::escape_string($api_service); if (is_string($service_name) === false) { return false; } $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY); @@ -2360,31 +2388,31 @@ class UserManager { $res = Database::query($sql); $num = Database::num_rows($res); if ($num == 1) { - $id_key = Database::fetch_array($res, 'ASSOC'); - self::delete_api_key($id_key['id']); - $num = self::add_api_key($user_id, $api_service); + $id_key = Database::fetch_array($res, 'ASSOC'); + self::delete_api_key($id_key['id']); + $num = self::add_api_key($user_id, $api_service); } elseif ($num == 0) { - $num = self::add_api_key($user_id); - } + $num = self::add_api_key($user_id); + } return $num; } /** * @param int user ID (defaults to the results of api_get_user_id()) - * @param string API key's internal ID - * @return int row ID, or return false if not found + * @param string API key's internal ID + * @return int row ID, or return false if not found */ public static function get_api_key_id($user_id, $api_service) { - if ($user_id != strval(intval($user_id))) return false; - if ($user_id === false) return false; - if (empty($api_service)) return false; + if ($user_id != strval(intval($user_id))) return false; + if ($user_id === false) return false; + if (empty($api_service)) return false; $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY); $service_name = Database::escape_string($api_service); $sql = "SELECT id FROM $t_api WHERE user_id=".$user_id." AND api_service='".$api_service."'"; $res = Database::query($sql); - if (Database::num_rows($res)<1) { - return false; - } + if (Database::num_rows($res)<1) { + return false; + } $row = Database::fetch_array($res, 'ASSOC'); return $row['id']; } @@ -2407,11 +2435,11 @@ class UserManager { * Get the total count of users * @param int Status of users to be counted * @param int Access URL ID (optional) - * @return mixed Number of users or false on error + * @return mixed Number of users or false on error */ public static function get_number_of_users($status=0, $access_url_id=null) { $t_u = Database::get_main_table(TABLE_MAIN_USER); - $t_a = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); + $t_a = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); $sql = "SELECT count(*) FROM $t_u u"; $sql2 = ''; if (is_int($status) && $status>0) { @@ -2424,358 +2452,358 @@ class UserManager { $sql = $sql.$sql2; $res = Database::query($sql); if (Database::num_rows($res) === 1) { - return (int) Database::result($res, 0, 0); + return (int) Database::result($res, 0, 0); + } + return false; + } + + /** + * Resize a picture + * + * @param string file picture + * @param int size in pixels + * @todo move this function somewhere else image.lib? + * @return obj image object + */ + public static function resize_picture($file, $max_size_for_picture) { + $temp = null; + if (file_exists($file)) { + $temp = new Image($file); + $image_size = $temp->get_image_size($file); + $width = $image_size['width']; + $height = $image_size['height']; + if ($width >= $height) { + if ($width >= $max_size_for_picture) { + // scale height + $new_height = round($height * ($max_size_for_picture / $width)); + $temp->resize($max_size_for_picture, $new_height, 0); + } + } else { // height > $width + if ($height >= $max_size_for_picture) { + // scale width + $new_width = round($width * ($max_size_for_picture / $height)); + $temp->resize($new_width, $max_size_for_picture, 0); + } + } + } + return $temp; + } + + /** + * Gets the current user image + * @param string user id + * @param string picture user name + * @param string height + * @param string picture size it can be USER_IMAGE_SIZE_SMALL, USER_IMAGE_SIZE_MEDIUM, USER_IMAGE_SIZE_BIG or USER_IMAGE_SIZE_ORIGINAL + * @param string style css + * @return array with the file and the style of an image i.e $array['file'] $array['style'] + */ + public static function get_picture_user($user_id, $picture_file, $height, $size_picture = USER_IMAGE_SIZE_MEDIUM , $style = '') { + $picture = array(); + $picture['style'] = $style; + if ($picture_file == 'unknown.jpg') { + $picture['file'] = api_get_path(WEB_CODE_PATH).'img/'.$picture_file; + return $picture; + } + switch ($size_picture) { + case USER_IMAGE_SIZE_ORIGINAL : + $size_picture = ''; + break; + case USER_IMAGE_SIZE_BIG : + $size_picture = 'big_'; + break; + case USER_IMAGE_SIZE_MEDIUM : + $size_picture = 'medium_'; + break; + case USER_IMAGE_SIZE_SMALL : + $size_picture = 'small_'; + break; + default: + $size_picture = 'medium_'; + } + + $image_array_sys = self::get_user_picture_path_by_id($user_id, 'system', false, true); + $image_array = self::get_user_picture_path_by_id($user_id, 'web', false, true); + + $file = $image_array_sys['dir'].$size_picture.$picture_file; + + if (file_exists($file)) { + $picture['file'] = $image_array['dir'].$size_picture.$picture_file; + $picture['style'] = ''; + if ($height > 0) { + $dimension = api_getimagesize($picture['file']); + $margin = (($height - $dimension['width']) / 2); + + //@ todo the padding-top should not be here + $picture['style'] = ' style="padding-top:'.$margin.'px; width:'.$dimension['width'].'px; height:'.$dimension['height'].'px;" '; + $picture['original_height'] = $dimension['width']; + $picture['original_width'] = $dimension['height']; + } + } else { + $file = $image_array_sys['dir'].$picture_file; + if (file_exists($file) && !is_dir($file)) { + $picture['file'] = $image_array['dir'].$picture_file; + } else { + switch ($size_picture) { + case 'big_' : + $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg'; break; + case 'medium_' : + $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown_50_50.jpg'; break; + case 'small_' : + $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg'; break; + default: + $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg'; break; + } + + } + } + return $picture; + } + + /** + * @author Isaac flores + * @param string The email administrator + * @param integer The user id + * @param string The message title + * @param string The content message + */ + public static function send_message_in_outbox($email_administrator, $user_id, $title, $content) { + $table_message = Database::get_main_table(TABLE_MESSAGE); + $table_user = Database::get_main_table(TABLE_MAIN_USER); + $title = api_utf8_decode($title); + $content = api_utf8_decode($content); + $email_administrator = Database::escape_string($email_administrator); + //message in inbox + $sql_message_outbox = 'SELECT user_id from '.$table_user.' WHERE email="'.$email_administrator.'" '; + //$num_row_query = Database::num_rows($sql_message_outbox); + $res_message_outbox = Database::query($sql_message_outbox); + $array_users_administrator = array(); + while ($row_message_outbox = Database::fetch_array($res_message_outbox, 'ASSOC')) { + $array_users_administrator[] = $row_message_outbox['user_id']; + } + //allow to insert messages in outbox + for ($i = 0; $i < count($array_users_administrator); $i++) { + $sql_insert_outbox = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content ) ". + " VALUES (". + "'".(int)$user_id."', '".(int)($array_users_administrator[$i])."', '4', '".date('Y-m-d H:i:s')."','".Database::escape_string($title)."','".Database::escape_string($content)."'". + ")"; + $rs = Database::query($sql_insert_outbox); + } + } + + /* + * + * USER TAGS + * + * Intructions to create a new user tag by Julio Montoya + * + * 1. Create a new extra field in main/admin/user_fields.php with the "TAG" field type make it available and visible. Called it "books" for example. + * 2. Go to profile main/auth/profile.php There you will see a special input (facebook style) that will show suggestions of tags. + * 3. All the tags are registered in the user_tag table and the relationship between user and tags is in the user_rel_tag table + * 4. Tags are independent this means that tags can't be shared between tags + book + hobbies. + * 5. Test and enjoy. + * + */ + + /** + * Gets the tags of a specific field_id + * + * @param int field_id + * @param string how we are going to result value in array or in a string (json) + * @return mixed + * @since Nov 2009 + * @version 1.8.6.2 + */ + public static function get_tags($tag, $field_id, $return_format='json',$limit=10) { + // database table definition + $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); + $field_id = intval($field_id); + $limit = intval($limit); + $tag = trim(Database::escape_string($tag)); + + // all the information of the field + $sql = "SELECT DISTINCT id, tag from $table_user_tag + WHERE field_id = $field_id AND tag LIKE '$tag%' ORDER BY tag LIMIT $limit"; + $result = Database::query($sql); + $return = array(); + if (Database::num_rows($result)>0) { + while ($row = Database::fetch_array($result,'ASSOC')) { + $return[] = array('caption'=>$row['tag'], 'value'=>$row['tag']); + } + } + if ($return_format=='json') { + $return = json_encode($return); + } + return $return; + } + + public static function get_top_tags($field_id, $limit=100) { + // database table definition + $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); + $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG); + $field_id = intval($field_id); + $limit = intval($limit); + // all the information of the field + $sql = "SELECT count(*) count, tag FROM $table_user_tag_values uv INNER JOIN $table_user_tag ut ON(ut.id = uv.tag_id) + WHERE field_id = $field_id GROUP BY tag_id ORDER BY count DESC LIMIT $limit"; + $result = Database::query($sql); + $return = array(); + if (Database::num_rows($result)>0) { + while ($row = Database::fetch_array($result,'ASSOC')) { + $return[] = $row; + } + } + return $return; + } + + /** + * Get user's tags + * @param int field_id + * @param int user_id + * @return array + */ + public static function get_user_tags($user_id,$field_id) { + // database table definition + $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); + $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG); + $field_id = intval($field_id); + $user_id = intval($user_id); + + // all the information of the field + $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.ID) + WHERE field_id = $field_id AND user_id = $user_id ORDER BY tag"; + $result = Database::query($sql); + $return = array(); + if (Database::num_rows($result)> 0) { + while ($row = Database::fetch_array($result,'ASSOC')) { + $return[$row['id']] = array('tag'=>$row['tag'],'count'=>$row['count']); + } } - return false; + return $return; } + /** - * Resize a picture - * - * @param string file picture - * @param int size in pixels - * @todo move this function somewhere else image.lib? - * @return obj image object + * Get user's tags + * @param int user_id + * @param int field_id + * @param bool show links or not + * @return array */ - public static function resize_picture($file, $max_size_for_picture) { - $temp = null; - if (file_exists($file)) { - $temp = new Image($file); - $image_size = $temp->get_image_size($file); - $width = $image_size['width']; - $height = $image_size['height']; - if ($width >= $height) { - if ($width >= $max_size_for_picture) { - // scale height - $new_height = round($height * ($max_size_for_picture / $width)); - $temp->resize($max_size_for_picture, $new_height, 0); - } - } else { // height > $width - if ($height >= $max_size_for_picture) { - // scale width - $new_width = round($width * ($max_size_for_picture / $height)); - $temp->resize($new_width, $max_size_for_picture, 0); - } + public static function get_user_tags_to_string($user_id,$field_id,$show_links=true) { + // database table definition + $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); + $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG); + $field_id = intval($field_id); + $user_id = intval($user_id); + + // all the information of the field + $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.ID) + WHERE field_id = $field_id AND user_id = $user_id ORDER BY tag"; + + $result = Database::query($sql); + $return = array(); + if (Database::num_rows($result)> 0) { + while ($row = Database::fetch_array($result,'ASSOC')) { + $return[$row['id']] = array('tag'=>$row['tag'],'count'=>$row['count']); } } - return $temp; + $user_tags = $return; + $tag_tmp = array(); + foreach ($user_tags as $tag) { + if ($show_links) { + $tag_tmp[] = ''.$tag['tag'].''; + } else { + $tag_tmp[] = $tag['tag']; + } + } + if (is_array($user_tags) && count($user_tags)>0) { + $return = implode(', ',$tag_tmp); + } else { + return ''; + } + return $return; } + /** - * Gets the current user image - * @param string user id - * @param string picture user name - * @param string height - * @param string picture size it can be USER_IMAGE_SIZE_SMALL, USER_IMAGE_SIZE_MEDIUM, USER_IMAGE_SIZE_BIG or USER_IMAGE_SIZE_ORIGINAL - * @param string style css - * @return array with the file and the style of an image i.e $array['file'] $array['style'] + * Get the tag id + * @param int tag + * @param int field_id + * @return int returns 0 if fails otherwise the tag id */ - public static function get_picture_user($user_id, $picture_file, $height, $size_picture = USER_IMAGE_SIZE_MEDIUM , $style = '') { - $picture = array(); - $picture['style'] = $style; - if ($picture_file == 'unknown.jpg') { - $picture['file'] = api_get_path(WEB_CODE_PATH).'img/'.$picture_file; - return $picture; - } - switch ($size_picture) { - case USER_IMAGE_SIZE_ORIGINAL : - $size_picture = ''; - break; - case USER_IMAGE_SIZE_BIG : - $size_picture = 'big_'; - break; - case USER_IMAGE_SIZE_MEDIUM : - $size_picture = 'medium_'; - break; - case USER_IMAGE_SIZE_SMALL : - $size_picture = 'small_'; - break; - default: - $size_picture = 'medium_'; - } - - $image_array_sys = self::get_user_picture_path_by_id($user_id, 'system', false, true); - $image_array = self::get_user_picture_path_by_id($user_id, 'web', false, true); - - $file = $image_array_sys['dir'].$size_picture.$picture_file; + public static function get_tag_id($tag, $field_id) { + $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); + $tag = Database::escape_string($tag); + $field_id = intval($field_id); + //with COLLATE latin1_bin to select query in a case sensitive mode + $sql = "SELECT id FROM $table_user_tag WHERE tag LIKE '$tag' AND field_id = $field_id"; + $result = Database::query($sql); + if (Database::num_rows($result)>0) { + $row = Database::fetch_array($result,'ASSOC'); + return $row['id']; + } else { + return 0; + } + } - if (file_exists($file)) { - $picture['file'] = $image_array['dir'].$size_picture.$picture_file; - $picture['style'] = ''; - if ($height > 0) { - $dimension = api_getimagesize($picture['file']); - $margin = (($height - $dimension['width']) / 2); - - //@ todo the padding-top should not be here - $picture['style'] = ' style="padding-top:'.$margin.'px; width:'.$dimension['width'].'px; height:'.$dimension['height'].'px;" '; - $picture['original_height'] = $dimension['width']; - $picture['original_width'] = $dimension['height']; - } - } else { - $file = $image_array_sys['dir'].$picture_file; - if (file_exists($file) && !is_dir($file)) { - $picture['file'] = $image_array['dir'].$picture_file; - } else { - switch ($size_picture) { - case 'big_' : - $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg'; break; - case 'medium_' : - $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown_50_50.jpg'; break; - case 'small_' : - $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg'; break; - default: - $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg'; break; - } - - } - } - return $picture; + /** + * Get the tag id + * @param int tag + * @param int field_id + * @return int 0 if fails otherwise the tag id + */ + public static function get_tag_id_from_id($tag_id, $field_id) { + $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); + $tag_id = intval($tag_id); + $field_id = intval($field_id); + $sql = "SELECT id FROM $table_user_tag WHERE id = '$tag_id' AND field_id = $field_id"; + $result = Database::query($sql); + if (Database::num_rows($result)>0) { + $row = Database::fetch_array($result,'ASSOC'); + return $row['id']; + } else { + return false; + } } + /** - * @author Isaac flores - * @param string The email administrator - * @param integer The user id - * @param string The message title - * @param string The content message + * Adds a user-tag value + * @param mixed tag + * @param int The user id + * @param int field id of the tag + * @return bool */ - public static function send_message_in_outbox($email_administrator, $user_id, $title, $content) { - $table_message = Database::get_main_table(TABLE_MESSAGE); - $table_user = Database::get_main_table(TABLE_MAIN_USER); - $title = api_utf8_decode($title); - $content = api_utf8_decode($content); - $email_administrator = Database::escape_string($email_administrator); - //message in inbox - $sql_message_outbox = 'SELECT user_id from '.$table_user.' WHERE email="'.$email_administrator.'" '; - //$num_row_query = Database::num_rows($sql_message_outbox); - $res_message_outbox = Database::query($sql_message_outbox); - $array_users_administrator = array(); - while ($row_message_outbox = Database::fetch_array($res_message_outbox, 'ASSOC')) { - $array_users_administrator[] = $row_message_outbox['user_id']; - } - //allow to insert messages in outbox - for ($i = 0; $i < count($array_users_administrator); $i++) { - $sql_insert_outbox = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content ) ". - " VALUES (". - "'".(int)$user_id."', '".(int)($array_users_administrator[$i])."', '4', '".date('Y-m-d H:i:s')."','".Database::escape_string($title)."','".Database::escape_string($content)."'". - ")"; - $rs = Database::query($sql_insert_outbox); - } - } - - /* - * - * USER TAGS - * - * Intructions to create a new user tag by Julio Montoya - * - * 1. Create a new extra field in main/admin/user_fields.php with the "TAG" field type make it available and visible. Called it "books" for example. - * 2. Go to profile main/auth/profile.php There you will see a special input (facebook style) that will show suggestions of tags. - * 3. All the tags are registered in the user_tag table and the relationship between user and tags is in the user_rel_tag table - * 4. Tags are independent this means that tags can't be shared between tags + book + hobbies. - * 5. Test and enjoy. - * - */ - - /** - * Gets the tags of a specific field_id - * - * @param int field_id - * @param string how we are going to result value in array or in a string (json) - * @return mixed - * @since Nov 2009 - * @version 1.8.6.2 - */ - public static function get_tags($tag, $field_id, $return_format='json',$limit=10) { - // database table definition - $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); - $field_id = intval($field_id); - $limit = intval($limit); - $tag = trim(Database::escape_string($tag)); - - // all the information of the field - $sql = "SELECT DISTINCT id, tag from $table_user_tag - WHERE field_id = $field_id AND tag LIKE '$tag%' ORDER BY tag LIMIT $limit"; - $result = Database::query($sql); - $return = array(); - if (Database::num_rows($result)>0) { - while ($row = Database::fetch_array($result,'ASSOC')) { - $return[] = array('caption'=>$row['tag'], 'value'=>$row['tag']); - } - } - if ($return_format=='json') { - $return = json_encode($return); - } - return $return; - } - - public static function get_top_tags($field_id, $limit=100) { - // database table definition - $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); - $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG); - $field_id = intval($field_id); - $limit = intval($limit); - // all the information of the field - $sql = "SELECT count(*) count, tag FROM $table_user_tag_values uv INNER JOIN $table_user_tag ut ON(ut.id = uv.tag_id) - WHERE field_id = $field_id GROUP BY tag_id ORDER BY count DESC LIMIT $limit"; - $result = Database::query($sql); - $return = array(); - if (Database::num_rows($result)>0) { - while ($row = Database::fetch_array($result,'ASSOC')) { - $return[] = $row; - } - } - return $return; - } - - /** - * Get user's tags - * @param int field_id - * @param int user_id - * @return array - */ - public static function get_user_tags($user_id,$field_id) { - // database table definition - $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); - $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG); - $field_id = intval($field_id); - $user_id = intval($user_id); - - // all the information of the field - $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.ID) - WHERE field_id = $field_id AND user_id = $user_id ORDER BY tag"; - $result = Database::query($sql); - $return = array(); - if (Database::num_rows($result)> 0) { - while ($row = Database::fetch_array($result,'ASSOC')) { - $return[$row['id']] = array('tag'=>$row['tag'],'count'=>$row['count']); - } - } - return $return; - } - - - /** - * Get user's tags - * @param int user_id - * @param int field_id - * @param bool show links or not - * @return array - */ - public static function get_user_tags_to_string($user_id,$field_id,$show_links=true) { - // database table definition - $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); - $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG); - $field_id = intval($field_id); - $user_id = intval($user_id); - - // all the information of the field - $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.ID) - WHERE field_id = $field_id AND user_id = $user_id ORDER BY tag"; + public static function add_tag($tag, $user_id, $field_id) { + // database table definition + $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); + $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG); + $tag = trim(Database::escape_string($tag)); + $user_id = intval($user_id); + $field_id = intval($field_id); + + $tag_id = UserManager::get_tag_id($tag, $field_id); + + /* IMPORTANT + * @todo we don't create tags with numbers + * + */ + if (is_numeric($tag)) { + //the form is sending an id this means that the user select it from the list so it MUST exists + /*$new_tag_id = UserManager::get_tag_id_from_id($tag,$field_id); + if ($new_tag_id !== false) { + $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $new_tag_id"; + $result = Database::query($sql); + $last_insert_id = $new_tag_id; + } else { + $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)"; + $result = Database::query($sql); + $last_insert_id = Database::get_last_insert_id(); + }*/ + } else { - $result = Database::query($sql); - $return = array(); - if (Database::num_rows($result)> 0) { - while ($row = Database::fetch_array($result,'ASSOC')) { - $return[$row['id']] = array('tag'=>$row['tag'],'count'=>$row['count']); - } - } - $user_tags = $return; - $tag_tmp = array(); - foreach ($user_tags as $tag) { - if ($show_links) { - $tag_tmp[] = ''.$tag['tag'].''; - } else { - $tag_tmp[] = $tag['tag']; - } - } - if (is_array($user_tags) && count($user_tags)>0) { - $return = implode(', ',$tag_tmp); - } else { - return ''; - } - return $return; - } - - - /** - * Get the tag id - * @param int tag - * @param int field_id - * @return int returns 0 if fails otherwise the tag id - */ - public static function get_tag_id($tag, $field_id) { - $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); - $tag = Database::escape_string($tag); - $field_id = intval($field_id); - //with COLLATE latin1_bin to select query in a case sensitive mode - $sql = "SELECT id FROM $table_user_tag WHERE tag LIKE '$tag' AND field_id = $field_id"; - $result = Database::query($sql); - if (Database::num_rows($result)>0) { - $row = Database::fetch_array($result,'ASSOC'); - return $row['id']; - } else { - return 0; - } - } - - /** - * Get the tag id - * @param int tag - * @param int field_id - * @return int 0 if fails otherwise the tag id - */ - public static function get_tag_id_from_id($tag_id, $field_id) { - $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); - $tag_id = intval($tag_id); - $field_id = intval($field_id); - $sql = "SELECT id FROM $table_user_tag WHERE id = '$tag_id' AND field_id = $field_id"; - $result = Database::query($sql); - if (Database::num_rows($result)>0) { - $row = Database::fetch_array($result,'ASSOC'); - return $row['id']; - } else { - return false; - } - } - - - /** - * Adds a user-tag value - * @param mixed tag - * @param int The user id - * @param int field id of the tag - * @return bool - */ - public static function add_tag($tag, $user_id, $field_id) { - // database table definition - $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); - $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG); - $tag = trim(Database::escape_string($tag)); - $user_id = intval($user_id); - $field_id = intval($field_id); - - $tag_id = UserManager::get_tag_id($tag, $field_id); - - /* IMPORTANT - * @todo we don't create tags with numbers - * - */ - if (is_numeric($tag)) { - //the form is sending an id this means that the user select it from the list so it MUST exists - /*$new_tag_id = UserManager::get_tag_id_from_id($tag,$field_id); - if ($new_tag_id !== false) { - $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $new_tag_id"; - $result = Database::query($sql); - $last_insert_id = $new_tag_id; - } else { - $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)"; - $result = Database::query($sql); - $last_insert_id = Database::get_last_insert_id(); - }*/ - } else { - - } + } //this is a new tag if ($tag_id == 0) { @@ -2790,70 +2818,70 @@ class UserManager { $last_insert_id = $tag_id; } - if (!empty($last_insert_id) && ($last_insert_id!=0)) { - //we insert the relationship user-tag - $sql_select ="SELECT tag_id FROM $table_user_tag_values WHERE user_id = $user_id AND tag_id = $last_insert_id "; - $result = Database::query($sql_select); - //if the relationship does not exist we create it - if (Database::num_rows($result)==0) { - $sql = "INSERT INTO $table_user_tag_values SET user_id = $user_id, tag_id = $last_insert_id"; - $result = Database::query($sql); - } - } - } - - /** - * Deletes an user tag - * @param int user id - * @param int field id - * - */ - public static function delete_user_tags($user_id, $field_id) { - // database table definition - $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG); - $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG); - $tags = UserManager::get_user_tags($user_id, $field_id); - //echo '
';var_dump($tags);
-		if(is_array($tags) && count($tags)>0) {
-			foreach ($tags as $key=>$tag) {
-				if ($tag['count']>'0') {
-					$sql = "UPDATE $table_user_tag SET count = count - 1  WHERE id = $key ";
-					$result = Database::query($sql);
-				}
-				$sql = "DELETE FROM $table_user_tag_values WHERE user_id = $user_id AND tag_id = $key";
-				$result = Database::query($sql);
-			}
-
-		}
-	}
-
-	/**
-	 * Process the tag list comes from the UserManager::update_extra_field_value() function
-	 * @param array the tag list that will be added
-	 * @param int user id
-	 * @param int field id
-	 * @return bool
-	 */
-	public static function process_tags($tags, $user_id, $field_id) {
-		//We loop the tags and add it to the DB
-		if (is_array($tags)) {
-			foreach($tags as $tag) {
-				UserManager::add_tag($tag, $user_id, $field_id);
-			}
-		} else {
-			UserManager::add_tag($tags,$user_id, $field_id);
-		}
-		return true;
-	}
-
-    /**
-	 * Returns a list of all admninistrators
-	 * @author jmontoya
-	 * @return array
-	 */
-	 public static function get_all_administrators() {
-	 	$table_user = Database::get_main_table(TABLE_MAIN_USER);
-	 	$table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
+        if (!empty($last_insert_id) && ($last_insert_id!=0)) {
+            //we insert the relationship user-tag
+            $sql_select ="SELECT tag_id FROM $table_user_tag_values WHERE user_id = $user_id AND tag_id = $last_insert_id ";
+            $result = Database::query($sql_select);
+            //if the relationship does not exist we create it
+            if (Database::num_rows($result)==0) {
+                $sql = "INSERT INTO $table_user_tag_values SET user_id = $user_id, tag_id = $last_insert_id";
+                $result = Database::query($sql);
+            }
+        }
+    }
+
+    /**
+     * Deletes an user tag
+     * @param int user id
+     * @param int field id
+     *
+     */
+    public static function delete_user_tags($user_id, $field_id) {
+        // database table definition
+        $table_user_tag            = Database::get_main_table(TABLE_MAIN_TAG);
+        $table_user_tag_values    = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
+        $tags = UserManager::get_user_tags($user_id, $field_id);
+        //echo '
';var_dump($tags);
+        if(is_array($tags) && count($tags)>0) {
+            foreach ($tags as $key=>$tag) {
+                if ($tag['count']>'0') {
+                    $sql = "UPDATE $table_user_tag SET count = count - 1  WHERE id = $key ";
+                    $result = Database::query($sql);
+                }
+                $sql = "DELETE FROM $table_user_tag_values WHERE user_id = $user_id AND tag_id = $key";
+                $result = Database::query($sql);
+            }
+
+        }
+    }
+
+    /**
+     * Process the tag list comes from the UserManager::update_extra_field_value() function
+     * @param array the tag list that will be added
+     * @param int user id
+     * @param int field id
+     * @return bool
+     */
+    public static function process_tags($tags, $user_id, $field_id) {
+        //We loop the tags and add it to the DB
+        if (is_array($tags)) {
+            foreach($tags as $tag) {
+                UserManager::add_tag($tag, $user_id, $field_id);
+            }
+        } else {
+            UserManager::add_tag($tags,$user_id, $field_id);
+        }
+        return true;
+    }
+
+    /**
+     * Returns a list of all admninistrators
+     * @author jmontoya
+     * @return array
+     */
+     public static function get_all_administrators() {
+         $table_user = Database::get_main_table(TABLE_MAIN_USER);
+         $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
         $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $access_url_id = api_get_current_access_url_id();
         if (api_get_multiple_access_url()) {
@@ -2865,180 +2893,180 @@ class UserManager {
             $sql = "SELECT admin.user_id, username, firstname, lastname, email FROM $table_admin as admin
                     INNER JOIN $table_user u ON (u.user_id=admin.user_id)";
         }
-	 	$result = Database::query($sql);
-		$return = array();
-		if (Database::num_rows($result)> 0) {
-			while ($row = Database::fetch_array($result,'ASSOC')) {
-				$return[$row['user_id']] = $row;
-			}
-		}
-		return $return;
-	 }
-
-
-	/**
-	 * Searchs an user (tags, firstname, lastname and email )
-	 * @param string the tag
-	 * @param int field id of the tag
-	 * @param int where to start in the query
-	 * @param int number of items
-	 * @return array
-	 */
-	public static function get_all_user_tags($tag, $field_id = 0, $from = 0, $number_of_items = 10) {
-
-		$user_table 			= Database::get_main_table(TABLE_MAIN_USER);
-		$table_user_tag			= Database::get_main_table(TABLE_MAIN_TAG);
-		$table_user_tag_values	= Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
-
-		$tag = Database::escape_string($tag);
-		$field_id = intval($field_id);
-		$from = intval($from);
-		$number_of_items = intval($number_of_items);
-
-    	$where_field = "";
-		if ($field_id != 0) {
-			$where_field = " field_id = $field_id AND ";
-		}
-		// all the information of the field
-		$sql = "SELECT u.user_id,u.username,firstname, lastname, email, tag, picture_uri FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.id)
-				INNER JOIN $user_table u ON(uv.user_id =u.user_id)
-				WHERE $where_field tag LIKE '$tag%' ORDER BY tag";
-		$sql .= " LIMIT $from,$number_of_items";
-
-		$result = Database::query($sql);
-		$return = array();
-		if (Database::num_rows($result) > 0) {
-			while ($row = Database::fetch_array($result,'ASSOC')) {
-			    if (isset($return[$row['user_id']]) && !empty($return[$row['user_id']]['tag'])) {
-			        $row['tag'] = $return[$row['user_id']]['tag'].' '.Display::url($row['tag'] , api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'] , array('class'=>'tag'));
-			    } else {
-			        $row['tag'] = Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'],   array('class'=>'tag'));
-			    }
-			    $return[$row['user_id']] = $row;
-			}
-		}
-
-		$keyword = $tag;
-		$sql = "SELECT u.user_id, u.username, firstname, lastname, email, picture_uri FROM $user_table u";
-
-		if (api_get_multiple_access_url()) {
-			$access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-			$sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
-		}
-
-		if (isset ($keyword)) {
-				$keyword = Database::escape_string($keyword);
-				//OR u.official_code LIKE '%".$keyword."%'
-				// OR u.email LIKE '%".$keyword."%'
-				$sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%'  OR u.username LIKE '%".$keyword."%' OR concat(u.firstname,' ',u.lastname) LIKE '%".$keyword."%' OR concat(u.lastname,' ',u.firstname) LIKE '%".$keyword."%' )";
-			}
-		$keyword_active = true;
-		//only active users
-		if ($keyword_active) {
-			$sql .= " AND u.active='1'";
-		}
-		//avoid anonymous
-		$sql .= " AND u.status <> 6 ";
-
-	    // adding the filter to see the user's only of the current access_url
-		if (api_get_multiple_access_url() && api_get_current_access_url_id()!=-1) {
-	    		$sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
-	    }
-		$direction = 'ASC';
-	    if (!in_array($direction, array('ASC','DESC'))) {
-	    	$direction = 'ASC';
-	    }
-
-	    //$column = intval($column);
-	    $from = intval($from);
-	    $number_of_items = intval($number_of_items);
-
-		//$sql .= " ORDER BY col$column $direction ";
-		$sql .= " LIMIT $from,$number_of_items";
-
-		$res = Database::query($sql);
-		if (Database::num_rows($res)> 0) {
-			while ($row = Database::fetch_array($res,'ASSOC')) {
-				if (!in_array($row['user_id'], array_keys($return))) {
-					$return[$row['user_id']] = $row;
-				}
-			}
-		}
-		return $return;
-	}
-
-	/**
-	 * Show the search form
-	 * @param string the value of the search box
-	 *
-	 */
-	public static function get_search_form($query) {
-		return '
-		';
-	}
-
-	/**
-	 * Shows the user menu
-	 */
-	public static function show_menu(){
-		echo '';
-	}
-
-	/**
-	 * Gives a list of course auto-register (field special_course)
-	 * @return array  list of course
-	 * @author Jhon Hinojosa 
-	 * @deprecated this function is never use in chamilo, use CourseManager::get_special_course_list
-	 * @since Dokeos 1.8.6.2
-	 */
-	public static function get_special_course_list() {
-		// Database Table Definitions
-		$tbl_course_user 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-		$tbl_course 				= Database :: get_main_table(TABLE_MAIN_COURSE);
-		$tbl_course_field 			= Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
-		$tbl_course_field_value		= Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
-		$tbl_user_course_category   = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
-
-		//we filter the courses from the URL
-		$join_access_url=$where_access_url='';
-
-		if (api_get_multiple_access_url()) {
-			$access_url_id = api_get_current_access_url_id();
-
-			$tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-			$join_access_url= "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
-			$where_access_url=" AND access_url_id = $access_url_id ";
-
-		}
-
-		// Filter special courses
-		$sql_special_course = "SELECT course_code FROM $tbl_course_field_value tcfv INNER JOIN $tbl_course_field tcf ON " .
-				" tcfv.field_id =  tcf.id WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 ";
-		$special_course_result = Database::query($sql_special_course);
-		$code_special_courses = '';
-		if(Database::num_rows($special_course_result)>0) {
-			$special_course_list = array();
-			while ($result_row = Database::fetch_array($special_course_result)) {
-				$special_course_list[] = '"'.$result_row['course_code'].'"';
-			}
-			$code_special_courses = ' course.code IN ('.join($special_course_list, ',').') ';
-		}
-
-		// variable initialisation
-		$course_list_sql = '';
-		$course_list = array();
-		if(!empty($code_special_courses)) {
-			$course_list_sql = "SELECT course.code k, course.directory d, course.visual_code c, course.db_name db, course.title i, course.tutor_name t, course.course_language l, course_rel_user.status s, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
+         $result = Database::query($sql);
+        $return = array();
+        if (Database::num_rows($result)> 0) {
+            while ($row = Database::fetch_array($result,'ASSOC')) {
+                $return[$row['user_id']] = $row;
+            }
+        }
+        return $return;
+     }
+
+
+    /**
+     * Searchs an user (tags, firstname, lastname and email )
+     * @param string the tag
+     * @param int field id of the tag
+     * @param int where to start in the query
+     * @param int number of items
+     * @return array
+     */
+    public static function get_all_user_tags($tag, $field_id = 0, $from = 0, $number_of_items = 10) {
+
+        $user_table             = Database::get_main_table(TABLE_MAIN_USER);
+        $table_user_tag            = Database::get_main_table(TABLE_MAIN_TAG);
+        $table_user_tag_values    = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
+
+        $tag = Database::escape_string($tag);
+        $field_id = intval($field_id);
+        $from = intval($from);
+        $number_of_items = intval($number_of_items);
+
+        $where_field = "";
+        if ($field_id != 0) {
+            $where_field = " field_id = $field_id AND ";
+        }
+        // all the information of the field
+        $sql = "SELECT u.user_id,u.username,firstname, lastname, email, tag, picture_uri FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.id)
+                INNER JOIN $user_table u ON(uv.user_id =u.user_id)
+                WHERE $where_field tag LIKE '$tag%' ORDER BY tag";
+        $sql .= " LIMIT $from,$number_of_items";
+
+        $result = Database::query($sql);
+        $return = array();
+        if (Database::num_rows($result) > 0) {
+            while ($row = Database::fetch_array($result,'ASSOC')) {
+                if (isset($return[$row['user_id']]) && !empty($return[$row['user_id']]['tag'])) {
+                    $row['tag'] = $return[$row['user_id']]['tag'].' '.Display::url($row['tag'] , api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'] , array('class'=>'tag'));
+                } else {
+                    $row['tag'] = Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'],   array('class'=>'tag'));
+                }
+                $return[$row['user_id']] = $row;
+            }
+        }
+
+        $keyword = $tag;
+        $sql = "SELECT u.user_id, u.username, firstname, lastname, email, picture_uri FROM $user_table u";
+
+        if (api_get_multiple_access_url()) {
+            $access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+            $sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
+        }
+
+        if (isset ($keyword)) {
+                $keyword = Database::escape_string($keyword);
+                //OR u.official_code LIKE '%".$keyword."%'
+                // OR u.email LIKE '%".$keyword."%'
+                $sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%'  OR u.username LIKE '%".$keyword."%' OR concat(u.firstname,' ',u.lastname) LIKE '%".$keyword."%' OR concat(u.lastname,' ',u.firstname) LIKE '%".$keyword."%' )";
+            }
+        $keyword_active = true;
+        //only active users
+        if ($keyword_active) {
+            $sql .= " AND u.active='1'";
+        }
+        //avoid anonymous
+        $sql .= " AND u.status <> 6 ";
+
+        // adding the filter to see the user's only of the current access_url
+        if (api_get_multiple_access_url() && api_get_current_access_url_id()!=-1) {
+                $sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
+        }
+        $direction = 'ASC';
+        if (!in_array($direction, array('ASC','DESC'))) {
+            $direction = 'ASC';
+        }
+
+        //$column = intval($column);
+        $from = intval($from);
+        $number_of_items = intval($number_of_items);
+
+        //$sql .= " ORDER BY col$column $direction ";
+        $sql .= " LIMIT $from,$number_of_items";
+
+        $res = Database::query($sql);
+        if (Database::num_rows($res)> 0) {
+            while ($row = Database::fetch_array($res,'ASSOC')) {
+                if (!in_array($row['user_id'], array_keys($return))) {
+                    $return[$row['user_id']] = $row;
+                }
+            }
+        }
+        return $return;
+    }
+
+    /**
+     * Show the search form
+     * @param string the value of the search box
+     *
+     */
+    public static function get_search_form($query) {
+        return '
+        ';
+    }
+
+    /**
+     * Shows the user menu
+     */
+    public static function show_menu(){
+        echo '';
+    }
+
+    /**
+     * Gives a list of course auto-register (field special_course)
+     * @return array  list of course
+     * @author Jhon Hinojosa 
+     * @deprecated this function is never use in chamilo, use CourseManager::get_special_course_list
+     * @since Dokeos 1.8.6.2
+     */
+    public static function get_special_course_list() {
+        // Database Table Definitions
+        $tbl_course_user             = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+        $tbl_course                 = Database :: get_main_table(TABLE_MAIN_COURSE);
+        $tbl_course_field             = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
+        $tbl_course_field_value        = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
+        $tbl_user_course_category   = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
+
+        //we filter the courses from the URL
+        $join_access_url=$where_access_url='';
+
+        if (api_get_multiple_access_url()) {
+            $access_url_id = api_get_current_access_url_id();
+
+            $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+            $join_access_url= "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
+            $where_access_url=" AND access_url_id = $access_url_id ";
+
+        }
+
+        // Filter special courses
+        $sql_special_course = "SELECT course_code FROM $tbl_course_field_value tcfv INNER JOIN $tbl_course_field tcf ON " .
+                " tcfv.field_id =  tcf.id WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 ";
+        $special_course_result = Database::query($sql_special_course);
+        $code_special_courses = '';
+        if(Database::num_rows($special_course_result)>0) {
+            $special_course_list = array();
+            while ($result_row = Database::fetch_array($special_course_result)) {
+                $special_course_list[] = '"'.$result_row['course_code'].'"';
+            }
+            $code_special_courses = ' course.code IN ('.join($special_course_list, ',').') ';
+        }
+
+        // variable initialisation
+        $course_list_sql = '';
+        $course_list = array();
+        if(!empty($code_special_courses)) {
+            $course_list_sql = "SELECT course.code k, course.directory d, course.visual_code c, course.db_name db, course.title i, course.tutor_name t, course.course_language l, course_rel_user.status s, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
                                 FROM    ".$tbl_course_user." course_rel_user
                                 LEFT JOIN ".$tbl_course." course
                                 ON course.code = course_rel_user.course_code
@@ -3048,122 +3076,122 @@ class UserManager {
                                 WHERE  $code_special_courses $where_access_url
                                 GROUP BY course.code
                                 ORDER BY user_course_category.sort,course.title,course_rel_user.sort ASC";
-			$course_list_sql_result = Database::query($course_list_sql);
-			while ($result_row = Database::fetch_array($course_list_sql_result)) {
-				$course_list[] = $result_row;
-			}
-		}
-		return $course_list;
-	}
-
-	/**
-	 * Allow to register contact to social network
-	 * @param int user friend id
-	 * @param int user id
-	 * @param int relation between users see constants definition
-	 */
-	public static function relate_users ($friend_id,$my_user_id,$relation_type) {
-		$tbl_my_friend = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
-
-		$friend_id = intval($friend_id);
-		$my_user_id = intval($my_user_id);
-		$relation_type = intval($relation_type);
-
-		$sql = 'SELECT COUNT(*) as count FROM ' . $tbl_my_friend . ' WHERE friend_user_id=' .$friend_id.' AND user_id='.$my_user_id.' AND relation_type <> '.USER_RELATION_TYPE_RRHH.' ';
-		$result = Database::query($sql);
-		$row = Database :: fetch_array($result, 'ASSOC');
-		$current_date=date('Y-m-d H:i:s');
-
-		if ($row['count'] == 0) {
-			$sql_i = 'INSERT INTO ' . $tbl_my_friend . '(friend_user_id,user_id,relation_type,last_edit)values(' . $friend_id . ','.$my_user_id.','.$relation_type.',"'.$current_date.'");';
-			Database::query($sql_i);
-			return true;
-		} else {
-			$sql = 'SELECT COUNT(*) as count, relation_type  FROM ' . $tbl_my_friend . ' WHERE friend_user_id=' . $friend_id . ' AND user_id='.$my_user_id.' AND relation_type <> '.USER_RELATION_TYPE_RRHH.' ';
-			$result = Database::query($sql);
-			$row = Database :: fetch_array($result, 'ASSOC');
-			if ($row['count'] == 1) {
-				//only for the case of a RRHH
-				if ($row['relation_type'] != $relation_type && $relation_type == USER_RELATION_TYPE_RRHH) {
-					$sql_i = 'INSERT INTO ' . $tbl_my_friend . '(friend_user_id,user_id,relation_type,last_edit)values(' . $friend_id . ','.$my_user_id.','.$relation_type.',"'.$current_date.'");';
-				} else {
-					$sql_i = 'UPDATE ' . $tbl_my_friend . ' SET relation_type='.$relation_type.' WHERE friend_user_id=' . $friend_id.' AND user_id='.$my_user_id;
-				}
-				Database::query($sql_i);
-				return true;
-			} else {
-				return false;
-			}
-		}
-	}
-
-	/**
-	 * Deletes a contact
-	 * @param int user friend id
-	 * @param bool true will delete ALL friends relationship from $friend_id
-	 * @author isaac flores paz 
-	 * @author Julio Montoya  Cleaning code
-	 */
-	public static function remove_user_rel_user ($friend_id, $real_removed = false, $with_status_condition = '') {
-		$tbl_my_friend  = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
-		$tbl_my_message = Database :: get_main_table(TABLE_MAIN_MESSAGE);
-		$friend_id = intval($friend_id);
-
-		if ($real_removed) {
-			//Delete user friend
-			/*
-			$sql_delete_relationship1 = 'UPDATE ' . $tbl_my_friend .'  SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE friend_user_id='.$friend_id;
-			$sql_delete_relationship2 = 'UPDATE ' . $tbl_my_friend . ' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id=' . $friend_id;
-			Database::query($sql_delete_relationship1);
-			Database::query($sql_delete_relationship2);*/
-			$extra_condition = '';
-			if ($with_status_condition != '') {
-				$extra_condition = ' AND relation_type = '.intval($with_status_condition);
-			}
-			$sql_delete_relationship1 = 'DELETE FROM ' . $tbl_my_friend .'  WHERE relation_type <> '.USER_RELATION_TYPE_RRHH.' AND friend_user_id='.$friend_id.' '.$extra_condition;
-			$sql_delete_relationship2 = 'DELETE FROM ' . $tbl_my_friend . ' WHERE relation_type <> '.USER_RELATION_TYPE_RRHH.' AND user_id=' . $friend_id.' '.$extra_condition;
-			Database::query($sql_delete_relationship1);
-			Database::query($sql_delete_relationship2);
-
-		} else {
-			$user_id = api_get_user_id();
-			$sql = 'SELECT COUNT(*) as count FROM ' . $tbl_my_friend . ' WHERE user_id=' . $user_id . ' AND relation_type NOT IN('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND friend_user_id='.$friend_id;
-			$result = Database::query($sql);
-			$row = Database :: fetch_array($result, 'ASSOC');
-			if ($row['count'] == 1) {
-				//Delete user rel user
-				$sql_i = 'UPDATE ' . $tbl_my_friend .' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id='.$user_id.' AND friend_user_id='.$friend_id;
-				$sql_j = 'UPDATE ' . $tbl_my_message.' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.' WHERE user_receiver_id=' . $user_id.' AND user_sender_id='.$friend_id.' AND update_date="0000-00-00 00:00:00" ';
-				//Delete user
-				$sql_ij = 'UPDATE ' . $tbl_my_friend . '  SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id=' . $friend_id.' AND friend_user_id='.$user_id;
-				$sql_ji = 'UPDATE ' . $tbl_my_message . ' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.' WHERE user_receiver_id=' . $friend_id.' AND user_sender_id='.$user_id.' AND update_date="0000-00-00 00:00:00" ';
-				Database::query($sql_i);
-				Database::query($sql_j);
-				Database::query($sql_ij);
-				Database::query($sql_ji);
-			}
-		}
-	}
-
-	/**
-	 * get users folloewd by human resource manager
-	 * @param int  		hr_dept id
-	 * @param int		user status (optional)
-	 * @return array 	users
-	 */
-	public static function get_users_followed_by_drh($hr_dept_id, $user_status = 0) {
-		// Database Table Definitions
-		$tbl_user                = Database::get_main_table(TABLE_MAIN_USER);
-		$tbl_user_rel_user       = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
+            $course_list_sql_result = Database::query($course_list_sql);
+            while ($result_row = Database::fetch_array($course_list_sql_result)) {
+                $course_list[] = $result_row;
+            }
+        }
+        return $course_list;
+    }
+
+    /**
+     * Allow to register contact to social network
+     * @param int user friend id
+     * @param int user id
+     * @param int relation between users see constants definition
+     */
+    public static function relate_users ($friend_id,$my_user_id,$relation_type) {
+        $tbl_my_friend = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
+
+        $friend_id = intval($friend_id);
+        $my_user_id = intval($my_user_id);
+        $relation_type = intval($relation_type);
+
+        $sql = 'SELECT COUNT(*) as count FROM ' . $tbl_my_friend . ' WHERE friend_user_id=' .$friend_id.' AND user_id='.$my_user_id.' AND relation_type <> '.USER_RELATION_TYPE_RRHH.' ';
+        $result = Database::query($sql);
+        $row = Database :: fetch_array($result, 'ASSOC');
+        $current_date=date('Y-m-d H:i:s');
+
+        if ($row['count'] == 0) {
+            $sql_i = 'INSERT INTO ' . $tbl_my_friend . '(friend_user_id,user_id,relation_type,last_edit)values(' . $friend_id . ','.$my_user_id.','.$relation_type.',"'.$current_date.'");';
+            Database::query($sql_i);
+            return true;
+        } else {
+            $sql = 'SELECT COUNT(*) as count, relation_type  FROM ' . $tbl_my_friend . ' WHERE friend_user_id=' . $friend_id . ' AND user_id='.$my_user_id.' AND relation_type <> '.USER_RELATION_TYPE_RRHH.' ';
+            $result = Database::query($sql);
+            $row = Database :: fetch_array($result, 'ASSOC');
+            if ($row['count'] == 1) {
+                //only for the case of a RRHH
+                if ($row['relation_type'] != $relation_type && $relation_type == USER_RELATION_TYPE_RRHH) {
+                    $sql_i = 'INSERT INTO ' . $tbl_my_friend . '(friend_user_id,user_id,relation_type,last_edit)values(' . $friend_id . ','.$my_user_id.','.$relation_type.',"'.$current_date.'");';
+                } else {
+                    $sql_i = 'UPDATE ' . $tbl_my_friend . ' SET relation_type='.$relation_type.' WHERE friend_user_id=' . $friend_id.' AND user_id='.$my_user_id;
+                }
+                Database::query($sql_i);
+                return true;
+            } else {
+                return false;
+            }
+        }
+    }
+
+    /**
+     * Deletes a contact
+     * @param int user friend id
+     * @param bool true will delete ALL friends relationship from $friend_id
+     * @author isaac flores paz 
+     * @author Julio Montoya  Cleaning code
+     */
+    public static function remove_user_rel_user ($friend_id, $real_removed = false, $with_status_condition = '') {
+        $tbl_my_friend  = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
+        $tbl_my_message = Database :: get_main_table(TABLE_MAIN_MESSAGE);
+        $friend_id = intval($friend_id);
+
+        if ($real_removed) {
+            //Delete user friend
+            /*
+            $sql_delete_relationship1 = 'UPDATE ' . $tbl_my_friend .'  SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE friend_user_id='.$friend_id;
+            $sql_delete_relationship2 = 'UPDATE ' . $tbl_my_friend . ' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id=' . $friend_id;
+            Database::query($sql_delete_relationship1);
+            Database::query($sql_delete_relationship2);*/
+            $extra_condition = '';
+            if ($with_status_condition != '') {
+                $extra_condition = ' AND relation_type = '.intval($with_status_condition);
+            }
+            $sql_delete_relationship1 = 'DELETE FROM ' . $tbl_my_friend .'  WHERE relation_type <> '.USER_RELATION_TYPE_RRHH.' AND friend_user_id='.$friend_id.' '.$extra_condition;
+            $sql_delete_relationship2 = 'DELETE FROM ' . $tbl_my_friend . ' WHERE relation_type <> '.USER_RELATION_TYPE_RRHH.' AND user_id=' . $friend_id.' '.$extra_condition;
+            Database::query($sql_delete_relationship1);
+            Database::query($sql_delete_relationship2);
+
+        } else {
+            $user_id = api_get_user_id();
+            $sql = 'SELECT COUNT(*) as count FROM ' . $tbl_my_friend . ' WHERE user_id=' . $user_id . ' AND relation_type NOT IN('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND friend_user_id='.$friend_id;
+            $result = Database::query($sql);
+            $row = Database :: fetch_array($result, 'ASSOC');
+            if ($row['count'] == 1) {
+                //Delete user rel user
+                $sql_i = 'UPDATE ' . $tbl_my_friend .' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id='.$user_id.' AND friend_user_id='.$friend_id;
+                $sql_j = 'UPDATE ' . $tbl_my_message.' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.' WHERE user_receiver_id=' . $user_id.' AND user_sender_id='.$friend_id.' AND update_date="0000-00-00 00:00:00" ';
+                //Delete user
+                $sql_ij = 'UPDATE ' . $tbl_my_friend . '  SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id=' . $friend_id.' AND friend_user_id='.$user_id;
+                $sql_ji = 'UPDATE ' . $tbl_my_message . ' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.' WHERE user_receiver_id=' . $friend_id.' AND user_sender_id='.$user_id.' AND update_date="0000-00-00 00:00:00" ';
+                Database::query($sql_i);
+                Database::query($sql_j);
+                Database::query($sql_ij);
+                Database::query($sql_ji);
+            }
+        }
+    }
+
+    /**
+     * get users folloewd by human resource manager
+     * @param int          hr_dept id
+     * @param int        user status (optional)
+     * @return array     users
+     */
+    public static function get_users_followed_by_drh($hr_dept_id, $user_status = 0) {
+        // Database Table Definitions
+        $tbl_user                = Database::get_main_table(TABLE_MAIN_USER);
+        $tbl_user_rel_user       = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
         $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 
-		$hr_dept_id = intval($hr_dept_id);
-		$assigned_users_to_hrm = array();
+        $hr_dept_id = intval($hr_dept_id);
+        $assigned_users_to_hrm = array();
 
-		$condition_status = '';
-		if (!empty($user_status)) {
-			$condition_status = ' AND u.status = '.$user_status;
-		}
+        $condition_status = '';
+        if (!empty($user_status)) {
+            $condition_status = ' AND u.status = '.$user_status;
+        }
         if (api_get_multiple_access_url()) {
             $sql = "SELECT u.user_id, u.username, u.lastname, u.firstname, u.email FROM $tbl_user u
                     INNER JOIN $tbl_user_rel_user uru ON (uru.user_id = u.user_id) LEFT JOIN $tbl_user_rel_access_url a
@@ -3188,23 +3216,23 @@ class UserManager {
             $sql .= " ORDER BY u.lastname, u.firstname ";
         }
 
-		$rs_assigned_users = Database::query($sql);
-		if (Database::num_rows($rs_assigned_users) > 0) {
-			while ($row_assigned_users = Database::fetch_array($rs_assigned_users))	{
-				$assigned_users_to_hrm[$row_assigned_users['user_id']] = $row_assigned_users;
-			}
-		}
-		return $assigned_users_to_hrm;
+        $rs_assigned_users = Database::query($sql);
+        if (Database::num_rows($rs_assigned_users) > 0) {
+            while ($row_assigned_users = Database::fetch_array($rs_assigned_users))    {
+                $assigned_users_to_hrm[$row_assigned_users['user_id']] = $row_assigned_users;
+            }
+        }
+        return $assigned_users_to_hrm;
 
-	}
+    }
 
-	/**
-	  * Subscribes users to human resource manager (Dashboard feature)
-	  *	@param	int 		hr dept id
-	  * @param	array		Users id
-	  * @param	int			affected rows
-	  **/
-	public static function suscribe_users_to_hr_manager($hr_dept_id, $users_id) {
+    /**
+      * Subscribes users to human resource manager (Dashboard feature)
+      *    @param    int         hr dept id
+      * @param    array        Users id
+      * @param    int            affected rows
+      **/
+    public static function suscribe_users_to_hr_manager($hr_dept_id, $users_id) {
 
         // Database Table Definitions
         $tbl_user           =   Database::get_main_table(TABLE_MAIN_USER);
@@ -3228,75 +3256,75 @@ class UserManager {
             }
         }
 
-		// inserting new user list
-		if (is_array($users_id)) {
-			foreach ($users_id as $user_id) {
-				$user_id = intval($user_id);
-				$insert_sql = "INSERT IGNORE INTO $tbl_user_rel_user(user_id, friend_user_id, relation_type) VALUES('$user_id', $hr_dept_id, '".USER_RELATION_TYPE_RRHH."')";
-				Database::query($insert_sql);
-				$affected_rows = Database::affected_rows();
-			}
-		}
-		return $affected_rows;
-	}
-
-
-	/**
-	 * This function check if an user is followed by human resources manager
-	 * @param 	int 	User id
-	 * @param	int		Human resources manager
-	 * @return	bool
-	 */
-	public static function is_user_followed_by_drh($user_id, $hr_dept_id) {
-
-		// Database table and variables Definitions
-		$tbl_user_rel_user 	= 	Database::get_main_table(TABLE_MAIN_USER_REL_USER);
-		$user_id 	= intval($user_id);
-		$hr_dept_id = intval($hr_dept_id);
-		$result = false;
-
-		$sql = "SELECT user_id FROM $tbl_user_rel_user WHERE user_id='$user_id' AND friend_user_id='$hr_dept_id' AND relation_type = ".USER_RELATION_TYPE_RRHH." ";
-		$rs  = Database::query($sql);
-		if (Database::num_rows($rs) > 0) {
-			$result = true;
-		}
-		return $result;
-
-	}
-	/**
-	 * get user id of teacher or session administrator
-	 * @param string The course id
-	 * @return int The user id
-	 */
-	 public static function get_user_id_of_course_admin_or_session_admin ($course_id) {
-	 	$session=api_get_session_id();
-		$table_user = Database::get_main_table(TABLE_MAIN_USER);
-		$table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
-		$table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-	 	if ($session==0 || is_null($session)) {
-	 		$sql='SELECT u.user_id FROM '.$table_user.' u
-					INNER JOIN '.$table_course_user.' ru ON ru.user_id=u.user_id
-					WHERE ru.status=1 AND ru.course_code="'.Database::escape_string($course_id).'" ';
-			$rs=Database::query($sql);
-			$num_rows=Database::num_rows($rs);
-			if ($num_rows==1) {
-				$row=Database::fetch_array($rs);
-				return $row['user_id'];
-			} else {
-				$my_num_rows=$num_rows;
-				$my_user_id=Database::result($rs,$my_num_rows-1,'user_id');
-				return $my_user_id;
-			}
-		} elseif ($session>0) {
-			$sql='SELECT u.user_id FROM '.$table_user.' u
-				INNER JOIN '.$table_session_course_user.' sru
-				ON sru.id_user=u.user_id WHERE sru.course_code="'.Database::escape_string($course_id).'" ';
-			$rs=Database::query($sql);
-			$row=Database::fetch_array($rs);
-
-			return $row['user_id'];
-		 	}
-		 }
+        // inserting new user list
+        if (is_array($users_id)) {
+            foreach ($users_id as $user_id) {
+                $user_id = intval($user_id);
+                $insert_sql = "INSERT IGNORE INTO $tbl_user_rel_user(user_id, friend_user_id, relation_type) VALUES('$user_id', $hr_dept_id, '".USER_RELATION_TYPE_RRHH."')";
+                Database::query($insert_sql);
+                $affected_rows = Database::affected_rows();
+            }
+        }
+        return $affected_rows;
+    }
+
+
+    /**
+     * This function check if an user is followed by human resources manager
+     * @param     int     User id
+     * @param    int        Human resources manager
+     * @return    bool
+     */
+    public static function is_user_followed_by_drh($user_id, $hr_dept_id) {
+
+        // Database table and variables Definitions
+        $tbl_user_rel_user     =     Database::get_main_table(TABLE_MAIN_USER_REL_USER);
+        $user_id     = intval($user_id);
+        $hr_dept_id = intval($hr_dept_id);
+        $result = false;
+
+        $sql = "SELECT user_id FROM $tbl_user_rel_user WHERE user_id='$user_id' AND friend_user_id='$hr_dept_id' AND relation_type = ".USER_RELATION_TYPE_RRHH." ";
+        $rs  = Database::query($sql);
+        if (Database::num_rows($rs) > 0) {
+            $result = true;
+        }
+        return $result;
+
+    }
+    /**
+     * get user id of teacher or session administrator
+     * @param string The course id
+     * @return int The user id
+     */
+     public static function get_user_id_of_course_admin_or_session_admin ($course_id) {
+         $session=api_get_session_id();
+        $table_user = Database::get_main_table(TABLE_MAIN_USER);
+        $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+        $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+         if ($session==0 || is_null($session)) {
+             $sql='SELECT u.user_id FROM '.$table_user.' u
+                    INNER JOIN '.$table_course_user.' ru ON ru.user_id=u.user_id
+                    WHERE ru.status=1 AND ru.course_code="'.Database::escape_string($course_id).'" ';
+            $rs=Database::query($sql);
+            $num_rows=Database::num_rows($rs);
+            if ($num_rows==1) {
+                $row=Database::fetch_array($rs);
+                return $row['user_id'];
+            } else {
+                $my_num_rows=$num_rows;
+                $my_user_id=Database::result($rs,$my_num_rows-1,'user_id');
+                return $my_user_id;
+            }
+        } elseif ($session>0) {
+            $sql='SELECT u.user_id FROM '.$table_user.' u
+                INNER JOIN '.$table_session_course_user.' sru
+                ON sru.id_user=u.user_id WHERE sru.course_code="'.Database::escape_string($course_id).'" ';
+            $rs=Database::query($sql);
+            $row=Database::fetch_array($rs);
+
+            return $row['user_id'];
+             }
+         }
 
   /**
    * Determines if a user is a gradebook certified
@@ -3304,17 +3332,17 @@ class UserManager {
    * @param int The user id
    * @return boolean
    */
-	public static function is_user_certified($cat_id,$user_id) {
-		$table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
-		$sql  = 'SELECT path_certificate FROM '.$table_certificate.' WHERE cat_id="'.Database::escape_string($cat_id).'" AND user_id="'.Database::escape_string($user_id).'" ';
-		$rs   = Database::query($sql);
-		$row  = Database::fetch_array($rs);
-		if ($row['path_certificate']=='' || is_null($row['path_certificate'])) {
-			return false;
-		} else {
-			return true;
-		}
-	}
+    public static function is_user_certified($cat_id,$user_id) {
+        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
+        $sql  = 'SELECT path_certificate FROM '.$table_certificate.' WHERE cat_id="'.Database::escape_string($cat_id).'" AND user_id="'.Database::escape_string($user_id).'" ';
+        $rs   = Database::query($sql);
+        $row  = Database::fetch_array($rs);
+        if ($row['path_certificate']=='' || is_null($row['path_certificate'])) {
+            return false;
+        } else {
+            return true;
+        }
+    }
 
    /**
    * Gets the info about a gradebook certificate for a user by course
@@ -3322,118 +3350,118 @@ class UserManager {
    * @param int The user id
    * @return array  if there is not information return false
    */
-	public static function get_info_gradebook_certificate($course_code, $user_id) {
-	  	$tbl_grade_certificate 	= Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
-	  	$tbl_grade_category 	= Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
-	  	$session_id             = api_get_session_id();
-
-	  	if (empty($session_id)) {
-	  	    $session_condition = ' AND (session_id = "" OR session_id = 0 OR session_id IS NULL )';
-	  	} else {
-	  	    $session_condition = " AND session_id = $session_id";
-	  	}
-	  	//Getting gradebook score
-	  	require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be.inc.php';
-	  	require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/scoredisplay.class.php';
-
-	  	$sql = 'SELECT * FROM '.$tbl_grade_certificate.' WHERE cat_id = (SELECT id FROM '.$tbl_grade_category.' WHERE course_code = "'.Database::escape_string($course_code).'" '.$session_condition.' LIMIT 1 ) AND user_id='.Database::escape_string($user_id);
-
-	  	$rs  = Database::query($sql);
-	  	if (Database::num_rows($rs) > 0) {
-	  	    $row = Database::fetch_array($rs,'ASSOC');
-	  	    $score 		  = $row['score_certificate'];
-	  	    $category_id  = $row['cat_id'];
-	  	    $cat         = Category::load($category_id);
-	  	    $displayscore = ScoreDisplay::instance();
+    public static function get_info_gradebook_certificate($course_code, $user_id) {
+          $tbl_grade_certificate     = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
+          $tbl_grade_category     = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
+          $session_id             = api_get_session_id();
+
+          if (empty($session_id)) {
+              $session_condition = ' AND (session_id = "" OR session_id = 0 OR session_id IS NULL )';
+          } else {
+              $session_condition = " AND session_id = $session_id";
+          }
+          //Getting gradebook score
+          require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be.inc.php';
+          require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/scoredisplay.class.php';
+
+          $sql = 'SELECT * FROM '.$tbl_grade_certificate.' WHERE cat_id = (SELECT id FROM '.$tbl_grade_category.' WHERE course_code = "'.Database::escape_string($course_code).'" '.$session_condition.' LIMIT 1 ) AND user_id='.Database::escape_string($user_id);
+
+          $rs  = Database::query($sql);
+          if (Database::num_rows($rs) > 0) {
+              $row = Database::fetch_array($rs,'ASSOC');
+              $score           = $row['score_certificate'];
+              $category_id  = $row['cat_id'];
+              $cat         = Category::load($category_id);
+              $displayscore = ScoreDisplay::instance();
             $grade = '';
-	  	    if (isset($cat) && $displayscore->is_custom()) {
+              if (isset($cat) && $displayscore->is_custom()) {
                 $grade = $displayscore->display_score(array($score, $cat[0]->get_weight()), SCORE_DIV_PERCENT_WITH_CUSTOM);
             } else {
                 $grade = $displayscore->display_score(array($score, $cat[0]->get_weight()));
             }
-	  	    $row['grade'] = $grade;
-	  	    return $row;
-        }
-	  	return false;
-	}
-
-	 /**
-	  * Gets the user path of user certificated
-	  * @param int The user id
-	  * @return array  containing path_certificate and cat_id
-	  */
-	public static function get_user_path_certificate($user_id) {
-	 	$my_certificate = array();
-		$table_certificate 			= Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
-		$table_gradebook_category 	= Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
-
-	 	$session_id = api_get_session_id();
-	 	$user_id = intval($user_id);
-	 	if ($session_id==0 || is_null($session_id)) {
-	 		$sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
-	 	} elseif ($session_id>0) {
-	 		$sql_session='AND session_id='.Database::escape_string($session_id);
-	 	} else {
-	 		$sql_session='';
-	 	}
-	 	$sql= "SELECT tc.path_certificate,tc.cat_id,tgc.course_code,tgc.name FROM $table_certificate tc, $table_gradebook_category tgc
-			   WHERE tgc.id = tc.cat_id AND tc.user_id='$user_id'  ORDER BY tc.date_certificate DESC limit 5";
-
-	 	$rs=Database::query($sql);
-	 	while ($row=Database::fetch_array($rs)) {
-	 		$my_certificate[]=$row;
-	 	}
- 		return $my_certificate;
-	}
-
-
-	 /**
-	  * This function check if the user is a coach inside session course
-	  * @param  int     User id
-	  * @param  string  Course code
-	  * @param  int     Session id
-	  * @return bool    True if the user is a coach
-	  *
-	  */
-	public static function is_session_course_coach($user_id, $course_code, $session_id) {
-		$tbl_session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-	    // Protect data
-		$user_id = intval($user_id);
-		$course_code = Database::escape_string($course_code);
-		$session_id = intval($session_id);
-		$result = false;
-
-		$sql = "SELECT id_session FROM $tbl_session_course_rel_user WHERE id_session=$session_id AND course_code='$course_code' AND id_user = $user_id AND status=2 ";
-	    $res = Database::query($sql);
-
-	    if (Database::num_rows($res) > 0) {
-	    	$result = true;
-	    }
-	    return $result;
-	}
-
-	/**
-	 * This function returns an icon path that represents the favicon of the website of which the url given. Defaults to the current Chamilo favicon
-	 * @param	string	URL of website where to look for favicon.ico
-	 * @param	string	Optional second URL of website where to look for favicon.ico
-	 * @return	string	Path of icon to load
-	 */
-	public static function get_favicon_from_url($url1, $url2 = null) {
-		$icon_link = '';
-		$url = $url1;
-		if (empty($url1)) {
-			$url = $url2;
-			if (empty($url)) {
-				$url = api_get_access_url(api_get_current_access_url_id());
-				$url = $url[0];
-			}
-		}
-		if (!empty($url)) {
-			$pieces = parse_url($url);
-			$icon_link = $pieces['scheme'].'://'.$pieces['host'].'/favicon.ico';
-		}
-		return $icon_link;
-	}
+              $row['grade'] = $grade;
+              return $row;
+        }
+          return false;
+    }
+
+     /**
+      * Gets the user path of user certificated
+      * @param int The user id
+      * @return array  containing path_certificate and cat_id
+      */
+    public static function get_user_path_certificate($user_id) {
+         $my_certificate = array();
+        $table_certificate             = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
+        $table_gradebook_category     = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
+
+         $session_id = api_get_session_id();
+         $user_id = intval($user_id);
+         if ($session_id==0 || is_null($session_id)) {
+             $sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
+         } elseif ($session_id>0) {
+             $sql_session='AND session_id='.Database::escape_string($session_id);
+         } else {
+             $sql_session='';
+         }
+         $sql= "SELECT tc.path_certificate,tc.cat_id,tgc.course_code,tgc.name FROM $table_certificate tc, $table_gradebook_category tgc
+               WHERE tgc.id = tc.cat_id AND tc.user_id='$user_id'  ORDER BY tc.date_certificate DESC limit 5";
+
+         $rs=Database::query($sql);
+         while ($row=Database::fetch_array($rs)) {
+             $my_certificate[]=$row;
+         }
+         return $my_certificate;
+    }
+
+
+     /**
+      * This function check if the user is a coach inside session course
+      * @param  int     User id
+      * @param  string  Course code
+      * @param  int     Session id
+      * @return bool    True if the user is a coach
+      *
+      */
+    public static function is_session_course_coach($user_id, $course_code, $session_id) {
+        $tbl_session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        // Protect data
+        $user_id = intval($user_id);
+        $course_code = Database::escape_string($course_code);
+        $session_id = intval($session_id);
+        $result = false;
+
+        $sql = "SELECT id_session FROM $tbl_session_course_rel_user WHERE id_session=$session_id AND course_code='$course_code' AND id_user = $user_id AND status=2 ";
+        $res = Database::query($sql);
+
+        if (Database::num_rows($res) > 0) {
+            $result = true;
+        }
+        return $result;
+    }
+
+    /**
+     * This function returns an icon path that represents the favicon of the website of which the url given. Defaults to the current Chamilo favicon
+     * @param    string    URL of website where to look for favicon.ico
+     * @param    string    Optional second URL of website where to look for favicon.ico
+     * @return    string    Path of icon to load
+     */
+    public static function get_favicon_from_url($url1, $url2 = null) {
+        $icon_link = '';
+        $url = $url1;
+        if (empty($url1)) {
+            $url = $url2;
+            if (empty($url)) {
+                $url = api_get_access_url(api_get_current_access_url_id());
+                $url = $url[0];
+            }
+        }
+        if (!empty($url)) {
+            $pieces = parse_url($url);
+            $icon_link = $pieces['scheme'].'://'.$pieces['host'].'/favicon.ico';
+        }
+        return $icon_link;
+    }
 
     /**
      *
@@ -3441,7 +3469,6 @@ class UserManager {
      * @param int   years
      * @param bool  show warning_message
      * @param bool  return_timestamp
-
      */
     public static function delete_inactive_student($student_id, $years = 2, $warning_message = false, $return_timestamp = false) {
         $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
@@ -3502,7 +3529,7 @@ class UserManager {
                     $form->applyFilter('extra_'.$field_details[1], 'trim');
 
                     if (!$admin_permissions) {
-                        if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+                        if ($field_details[7] == 0)    $form->freeze('extra_'.$field_details[1]);
                     }
                     break;
                 case self::USER_FIELD_TYPE_TEXTAREA:
@@ -3511,7 +3538,7 @@ class UserManager {
                     $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
                     $form->applyFilter('extra_'.$field_details[1], 'trim');
                     if (!$admin_permissions) {
-                        if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+                        if ($field_details[7] == 0)    $form->freeze('extra_'.$field_details[1]);
                     }
                     break;
                 case self::USER_FIELD_TYPE_RADIO:
@@ -3522,7 +3549,7 @@ class UserManager {
                     }
                     $form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '');
                     if (!$admin_permissions) {
-                        if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+                        if ($field_details[7] == 0)    $form->freeze('extra_'.$field_details[1]);
                     }
                     break;
                 case self::USER_FIELD_TYPE_SELECT:
@@ -3545,7 +3572,7 @@ class UserManager {
 
                     $form->addElement('select','extra_'.$field_details[1], $field_details[3], $options, array('class'=>'chzn-select', 'id'=>'extra_'.$field_details[1]));
                     if (!$admin_permissions) {
-                        if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+                        if ($field_details[7] == 0)    $form->freeze('extra_'.$field_details[1]);
                     }
                     break;
                 case self::USER_FIELD_TYPE_SELECT_MULTIPLE:
@@ -3555,7 +3582,7 @@ class UserManager {
                     }
                     $form->addElement('select','extra_'.$field_details[1], $field_details[3], $options, array('multiple' => 'multiple'));
                     if (!$admin_permissions) {
-                        if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+                        if ($field_details[7] == 0)    $form->freeze('extra_'.$field_details[1]);
                     }
                     break;
                 case self::USER_FIELD_TYPE_DATE:
@@ -3564,7 +3591,7 @@ class UserManager {
                     $defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
                     $form -> setDefaults($defaults);
                     if (!$admin_permissions) {
-                        if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+                        if ($field_details[7] == 0)    $form->freeze('extra_'.$field_details[1]);
                     }
                     $form->applyFilter('theme', 'trim');
                     break;
@@ -3574,7 +3601,7 @@ class UserManager {
                     $defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
                     $form -> setDefaults($defaults);
                     if (!$admin_permissions) {
-                        if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+                        if ($field_details[7] == 0)    $form->freeze('extra_'.$field_details[1]);
                     }
                     $form->applyFilter('theme', 'trim');
                     break;
@@ -3593,7 +3620,7 @@ class UserManager {
                     $form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], ' ');
 
                     if (!$admin_permissions) {
-                        if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+                        if ($field_details[7] == 0)    $form->freeze('extra_'.$field_details[1]);
                     }
 
                     // recoding the selected values for double : if the user has selected certain values, we have to assign them to the correct select form
@@ -3652,7 +3679,7 @@ EOF;
                     break;
                 case self::USER_FIELD_TYPE_TIMEZONE:
                     $form->addElement('select', 'extra_'.$field_details[1], $field_details[3], api_get_timezones(), '');
-                    if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+                    if ($field_details[7] == 0)    $form->freeze('extra_'.$field_details[1]);
                     break;
                 case self::USER_FIELD_TYPE_SOCIAL_PROFILE:
                     // get the social network's favicon
@@ -3663,7 +3690,7 @@ EOF;
                     $form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 60, 'style' => 'background-image: url(\''.$icon_path.'\'); background-repeat: no-repeat; background-position: 0.4em '.$top.'em; padding-left: '.$leftpad.'em; '));
                     $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
                     $form->applyFilter('extra_'.$field_details[1], 'trim');
-                    if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
+                    if ($field_details[7] == 0)    $form->freeze('extra_'.$field_details[1]);
                     break;
             }
         }

From e08f89ff8151b925b0235b783c16bd78a4aaa827 Mon Sep 17 00:00:00 2001
From: Julio Montoya 
Date: Tue, 18 Dec 2012 10:10:14 +0100
Subject: [PATCH 05/23] Fixing bug when inviting user to answer a survey see
 BT#5559

---
 main/survey/survey.lib.php    | 27 +++++++++++++++++++--------
 main/survey/survey_invite.php |  8 ++++++--
 2 files changed, 25 insertions(+), 10 deletions(-)

diff --git a/main/survey/survey.lib.php b/main/survey/survey.lib.php
index 7c1d51681f..f45a13363a 100644
--- a/main/survey/survey.lib.php
+++ b/main/survey/survey.lib.php
@@ -3823,7 +3823,7 @@ class SurveyUtil {
 				if (!array_key_exists($value, $survey_invitations)) {
 					$sql = "INSERT INTO $table_survey_invitation (c_id, user, survey_code, invitation_code, invitation_date) VALUES
 					($course_id,  '".Database::escape_string($value)."','".Database::escape_string($survey_data['code'])."','".Database::escape_string($invitation_code)."','".Database::escape_string(date('Y-m-d H:i:s'))."')";
-					$result = Database::query($sql);
+					Database::query($sql);
 				}
 			}
 			// Send the email if checkboxed
@@ -3927,7 +3927,7 @@ class SurveyUtil {
 
 		// Updating the field in the survey table
 		$sql = "UPDATE $table_survey SET invited = '".Database::escape_string($total_invited)."' WHERE c_id = $course_id AND code = '".Database::escape_string($survey_code)."'";
-		$result = Database::query($sql);
+		Database::query($sql);
 	}
 
 	/**
@@ -3940,6 +3940,7 @@ class SurveyUtil {
 	 * @todo consider making $defaults['additional_users'] also an array
 	 *
 	 * @author Patrick Cool , Ghent University
+     * @author Julio Montoya, adding c_id fixes - Dec 2012
 	 * @version January 2007
 	 */
 	static function get_invited_users($survey_code, $course_code = '') {
@@ -3951,15 +3952,13 @@ class SurveyUtil {
         }
 
 	    $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
-	 	$table_user = Database :: get_main_table(TABLE_MAIN_USER);
+        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
 
 		// Selecting all the invitations of this survey AND the additional emailaddresses (the left join)
 		$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
 		$sql = "SELECT user
 				FROM $table_survey_invitation as table_invitation
-				LEFT JOIN $table_user as table_user
-						ON table_invitation.user = table_user.user_id AND table_invitation.c_id = $course_id
-				WHERE survey_code='".Database::escape_string($survey_code)."'".$order_clause;
+				WHERE table_invitation.c_id = $course_id AND survey_code='".Database::escape_string($survey_code)."'";
 
 		$defaults = array();
 		$defaults['course_users'] = array();
@@ -3976,6 +3975,18 @@ class SurveyUtil {
 				}
 			}
 		}
+
+        if (!empty($defaults['course_users'])) {
+            $user_ids = implode("','", $defaults['course_users']);
+            $sql = "SELECT user_id FROM $table_user WHERE user_id IN ('$user_ids') $order_clause";
+            $result = Database::query($sql);
+            $fixed_users = array();
+            while ($row = Database::fetch_array($result)) {
+                $fixed_users[] = $row['user_id'];
+            }
+            $defaults['course_users'] = $fixed_users;
+        }
+
 		return $defaults;
 	}
 
@@ -4299,9 +4310,9 @@ class SurveyUtil {
 					survey.survey_id							AS col9,
 					survey.session_id							AS session_id
 				 FROM $table_survey survey
-                    LEFT JOIN $table_survey_question survey_question ON survey.survey_id = survey_question.survey_id
+                    LEFT JOIN $table_survey_question survey_question ON (survey.survey_id = survey_question.survey_id AND survey_question.c_id = $course_id)
                     INNER JOIN $table_user user ON (survey.author = user.user_id)
-				 WHERE  survey.c_id = $course_id AND survey_question.c_id = $course_id
+				 WHERE survey.c_id = $course_id
 				 $search_restriction
 				 $condition_session ";
 		$sql .= " GROUP BY survey.survey_id";
diff --git a/main/survey/survey_invite.php b/main/survey/survey_invite.php
index f36084a633..f1efb50135 100644
--- a/main/survey/survey_invite.php
+++ b/main/survey/survey_invite.php
@@ -119,15 +119,16 @@ $users->setElementTemplate('
 ');
 $users->setButtonAttributes('add', array('class' => 'btn arrowr'));
 $users->setButtonAttributes('remove', array('class' => 'btn arrowl'));
+
 // Additional users
-$form->addElement('textarea', 'additional_users', array(get_lang('AdditonalUsers'), get_lang('AdditonalUsersComment')), array('class' => 'span6', 'rows' => 2));
+$form->addElement('textarea', 'additional_users', array(get_lang('AdditonalUsers'), get_lang('AdditonalUsersComment')), array('class' => 'span6', 'rows' => 5));
 
-//$form->addElement('html', '

'.Display::return_icon('course.png', Security::remove_XSS(get_lang('SendMail')),'',ICON_SIZE_SMALL).' '.Security::remove_XSS(get_lang('SendMail')).'

'); $form->addElement('html', '
'); $form->addElement('checkbox', 'send_mail','', get_lang('SendMail')); $form->addElement('html', '
'); $form->addElement('html', '
'); + // The title of the mail $form->addElement('text', 'mail_title', get_lang('MailTitle'), array('class' => 'span6')); // The text of the mail @@ -169,6 +170,7 @@ if ($form->validate()) { Display :: display_error_message(get_lang('FormHasErrorsPleaseComplete')); // Getting the invited users $defaults = SurveyUtil::get_invited_users($survey_data['code']); + // Getting the survey mail text if (!empty($survey_data['reminder_mail'])) { $defaults['mail_text'] = $survey_data['reminder_mail']; @@ -216,6 +218,7 @@ if ($form->validate()) { } else { // Getting the invited users $defaults = SurveyUtil::get_invited_users($survey_data['code']); + // Getting the survey mail text if (!empty($survey_data['reminder_mail'])) { $defaults['mail_text'] = $survey_data['reminder_mail']; @@ -224,6 +227,7 @@ if ($form->validate()) { } $defaults['mail_title'] = $survey_data['mail_subject']; $defaults['send_mail'] = 1; + $form->setDefaults($defaults); $form->display(); } From 7c543328c3f86319cd8831c317ed79894108c49a Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 18 Dec 2012 14:55:44 +0100 Subject: [PATCH 06/23] Minor - adding api_get_cidreq + avoiding PHP notices see BT#5559 --- main/survey/survey.lib.php | 30 +++++++++++++++++++++--------- main/survey/survey_invite.php | 8 ++++---- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/main/survey/survey.lib.php b/main/survey/survey.lib.php index f45a13363a..28faeb4898 100644 --- a/main/survey/survey.lib.php +++ b/main/survey/survey.lib.php @@ -3816,7 +3816,8 @@ class SurveyUtil { } $new_user = false; // User not already invited // Store the invitation if user_id not in $already_invited['course_users'] OR email is not in $already_invited['additional_users'] - $addit_users_array = explode(';', $already_invited['additional_users']); + $addit_users_array = isset($already_invited['additional_users']) && !empty($already_invited['additional_users']) ? explode(';', $already_invited['additional_users']) : array(); + $my_alredy_invited = ($already_invited['course_users'] == null) ? array() : $already_invited['course_users']; if ((is_numeric($value) && !in_array($value, $my_alredy_invited)) || (!is_numeric($value) && !in_array($value, $addit_users_array))) { $new_user = true; @@ -3943,7 +3944,7 @@ class SurveyUtil { * @author Julio Montoya, adding c_id fixes - Dec 2012 * @version January 2007 */ - static function get_invited_users($survey_code, $course_code = '') { + static function get_invited_users($survey_code, $course_code = '', $session_id = 0) { if (!empty($course_code)) { $course_info = api_get_course_info($course_code); $course_id = $course_info['real_id']; @@ -3951,6 +3952,10 @@ class SurveyUtil { $course_id = api_get_course_int_id(); } + if (empty($session_id)) { + $session_id = api_get_session_id(); + } + $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION); $table_user = Database :: get_main_table(TABLE_MAIN_USER); @@ -3958,21 +3963,24 @@ class SurveyUtil { $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname'; $sql = "SELECT user FROM $table_survey_invitation as table_invitation - WHERE table_invitation.c_id = $course_id AND survey_code='".Database::escape_string($survey_code)."'"; + WHERE table_invitation.c_id = $course_id AND + survey_code='".Database::escape_string($survey_code)."' AND + session_id = $session_id + + "; $defaults = array(); $defaults['course_users'] = array(); - $defaults['additional_users'] = ''; + $defaults['additional_users'] = array(); + $result = Database::query($sql); while ($row = Database::fetch_array($result)) { if (is_numeric($row['user'])) { $defaults['course_users'][] = $row['user']; } else { - if (empty($defaults['additional_users'])) { - $defaults['additional_users'] = $row['user']; - } else { - $defaults['additional_users'] .= ';'.$row['user']; - } + if (!empty($row['user'])) { + $defaults['additional_users'][] = $row['user']; + } } } @@ -3987,6 +3995,10 @@ class SurveyUtil { $defaults['course_users'] = $fixed_users; } + if (!empty($defaults['additional_users'])) { + $defaults['additional_users'] = implode(';', $defaults['additional_users']); + } + error_log(print_r($defaults, 1)); return $defaults; } diff --git a/main/survey/survey_invite.php b/main/survey/survey_invite.php index f1efb50135..acdcea255c 100644 --- a/main/survey/survey_invite.php +++ b/main/survey/survey_invite.php @@ -94,14 +94,14 @@ if ($survey_data['invited'] > 0 && !isset($_POST['submit'])) { } // Building the form for publishing the survey -$form = new FormValidator('publish_form', 'post', api_get_self().'?survey_id='.$survey_id); +$form = new FormValidator('publish_form', 'post', api_get_self().'?survey_id='.$survey_id.'&'.api_get_cidReq()); $form->addElement('header', '', $tool_name); // Course users -$complete_user_list = CourseManager :: get_user_list_from_course_code($_course['id'], $_SESSION['id_session'], '', api_sort_by_first_name() ? 'ORDER BY firstname' : 'ORDER BY lastname'); +$complete_user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), api_get_session_id(), '', api_sort_by_first_name() ? 'ORDER BY firstname' : 'ORDER BY lastname'); $possible_users = array(); -foreach ($complete_user_list as $index => & $user) { +foreach ($complete_user_list as & $user) { $possible_users[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']); } $users = $form->addElement('advmultiselect', 'course_users', get_lang('CourseUsers'), $possible_users, 'style="width: 250px; height: 200px;"'); @@ -213,7 +213,7 @@ if ($form->validate()) { $message .= ''.$total_invited.' '; $message .= get_lang('WereInvited'); Display::display_normal_message($message, false); - Display :: display_confirmation_message($total_count.' '.get_lang('InvitationsSend')); + Display::display_confirmation_message($total_count.' '.get_lang('InvitationsSend')); } } else { // Getting the invited users From 531f5e71ccbafb45241470b3550f8fd12e03584d Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 18 Dec 2012 14:56:41 +0100 Subject: [PATCH 07/23] Minor - Removing error_log --- main/survey/survey.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main/survey/survey.lib.php b/main/survey/survey.lib.php index 28faeb4898..ae27ca8155 100644 --- a/main/survey/survey.lib.php +++ b/main/survey/survey.lib.php @@ -3998,7 +3998,7 @@ class SurveyUtil { if (!empty($defaults['additional_users'])) { $defaults['additional_users'] = implode(';', $defaults['additional_users']); } - error_log(print_r($defaults, 1)); + //error_log(print_r($defaults, 1)); return $defaults; } From 42434e8edc31f8e895c441051a1a7425431f632f Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 18 Dec 2012 15:32:18 +0100 Subject: [PATCH 08/23] Minor - Adding messages --- main/newscorm/learnpath.class.php | 7 +++---- main/newscorm/lp_add_item.php | 11 ++++++++++- main/newscorm/lp_controller.php | 10 ++++------ 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/main/newscorm/learnpath.class.php b/main/newscorm/learnpath.class.php index 975c119747..3384744604 100644 --- a/main/newscorm/learnpath.class.php +++ b/main/newscorm/learnpath.class.php @@ -4042,7 +4042,6 @@ class learnpath { } else { return false; } - } /** @@ -4367,7 +4366,7 @@ class learnpath { if ($this->debug > 2) { error_log('New LP - lp updated with new expired_on : ' . $this->modified_on, 0); } - $res = Database::query($sql); + Database::query($sql); return true; } @@ -5310,7 +5309,7 @@ class learnpath { $buttons = array( array( - 'title' => get_lang('SetPrerequisiteFoEachItem'), + 'title' => get_lang('SetPrerequisiteForEachItem'), 'href' => 'lp_controller.php?'.api_get_cidreq().'&action=set_previous_step_as_prerequisite&lp_id=' . $_SESSION['oLP']->lp_id, ), array( @@ -9244,7 +9243,7 @@ EOD; $sql = "UPDATE $tbl_lp_item SET prerequisite = '' WHERE c_id = ".$course_id." AND lp_id = '$lp_id'"; Database::query($sql); - + //Cleaning mastery score for exercises $sql = "UPDATE $tbl_lp_item SET mastery_score = '' WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND item_type = 'quiz'"; diff --git a/main/newscorm/lp_add_item.php b/main/newscorm/lp_add_item.php index 32f6715947..e4420bf366 100644 --- a/main/newscorm/lp_add_item.php +++ b/main/newscorm/lp_add_item.php @@ -248,10 +248,14 @@ echo '
'; echo $_SESSION['oLP']->return_new_tree(null, true); +$message = isset($_REQUEST['message']) ? $_REQUEST['message'] : null; + // Show the template list. if ($type == 'document' && !isset($_GET['file'])) { // Show the template list. - echo '
';} + echo '
'; +} + echo '
'; //hide bar div @@ -261,6 +265,11 @@ if ($action == 'add_item' && $type == 'document' && !isset($_GET['file'])) { echo '
'; +//@todo use session flash messages +if (in_array($message, array('ItemUpdated'))) { + echo Display::return_message(get_lang($message)); +} + if (isset($new_item_id) && is_numeric($new_item_id)) { switch ($type) { case 'chapter': diff --git a/main/newscorm/lp_controller.php b/main/newscorm/lp_controller.php index d3b0dfcb52..daacdd41fe 100644 --- a/main/newscorm/lp_controller.php +++ b/main/newscorm/lp_controller.php @@ -100,6 +100,7 @@ $lpfound = false; $myrefresh = 0; $myrefresh_id = 0; + if (!empty($_SESSION['refresh']) && $_SESSION['refresh'] == 1) { // Check if we should do a refresh of the oLP object (for example after editing the LP). // If refresh is set, we regenerate the oLP object from the database (kind of flush). @@ -223,8 +224,6 @@ if (isset($_GET['isStudentView']) && $_GET['isStudentView'] == 'true') { } } - - $action = (!empty($_REQUEST['action']) ? $_REQUEST['action'] : ''); switch ($action) { @@ -965,7 +964,7 @@ switch ($action) { require 'lp_list.php'; } else { if ($debug > 0) {error_log('New LP - Trying to impress this LP item to ' . $_REQUEST['item_id'], 0); } - if ( !empty($_REQUEST['item_id']) ) { + if (!empty($_REQUEST['item_id']) ) { $_SESSION['oLP']->set_current_item($_REQUEST['item_id']); } require 'lp_impress.php'; @@ -973,17 +972,16 @@ switch ($action) { break; case 'set_previous_step_as_prerequisite': $_SESSION['oLP']->set_previous_step_as_prerequisite_for_all_items(); - $url = api_get_self().'?action=add_item&type=step&lp_id='.intval($_SESSION['oLP']->lp_id); + $url = api_get_self().'?action=add_item&type=step&lp_id='.intval($_SESSION['oLP']->lp_id)."&message=ItemUpdated"; header('Location: '.$url); break; case 'clear_prerequisites': $_SESSION['oLP']->clear_prerequisites(); - $url = api_get_self().'?action=add_item&type=step&lp_id='.intval($_SESSION['oLP']->lp_id); + $url = api_get_self().'?action=add_item&type=step&lp_id='.intval($_SESSION['oLP']->lp_id)."&message=ItemUpdated"; header('Location: '.$url); break; default: if ($debug > 0) error_log('New LP - default action triggered', 0); - //$_SESSION['refresh'] = 1; require 'lp_list.php'; break; } From 7793ab672da4b81006b5e51640c8d500e2568497 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 18 Dec 2012 15:37:41 +0100 Subject: [PATCH 09/23] Updating lang vars --- main/lang/english/admin.inc.php | 2 ++ main/lang/english/learnpath.inc.php | 3 +++ main/lang/english/tracking.inc.php | 3 +++ main/lang/english/trad4all.inc.php | 2 ++ main/newscorm/learnpath.class.php | 2 +- 5 files changed, 11 insertions(+), 1 deletion(-) diff --git a/main/lang/english/admin.inc.php b/main/lang/english/admin.inc.php index 6d9ecafb5b..e29cf6fb53 100644 --- a/main/lang/english/admin.inc.php +++ b/main/lang/english/admin.inc.php @@ -1257,6 +1257,8 @@ $SessionStartDate = "Access start date"; $SessionDisplayEndDate = "End date to display"; $SessionDisplayStartDate = "Start date to display"; $UserHasNoCourse = "This user is not subscribed to any course"; +$SessionPageEnabledComment = "When this option is enabled, the session title is a link to a special session page. When disabled, it is only a text title, without link. The session page linked to might be confusing for some users, which is why you might want to disable it."; +$SessionPageEnabledTitle = "Enable session link in courses list"; $ThisValueIsUsedInTheCourseURL = "This value is used in the course URL"; $ThereAreUsersUsingThisLanguageYouWantToDisableThisLanguageAndSetUsersWithTheDefaultPortalLanguage = "There are users using this language. Do you want to disable this language and set all this users with the default portal language?"; $SessionTutorsCanSeeExpiredSessionsResultsComment = "Can session tutors see the reports for their session after it has expired?"; diff --git a/main/lang/english/learnpath.inc.php b/main/lang/english/learnpath.inc.php index a41afd05e3..cbd5f5c5b1 100644 --- a/main/lang/english/learnpath.inc.php +++ b/main/lang/english/learnpath.inc.php @@ -247,6 +247,9 @@ $ModifyHotPotatoes = "Modify hotpotatoes"; $SaveHotpotatoes = "Save hotpotatoes"; $ReturnToLPList = "Return to list"; $LpPrerequisiteDescription = "Selecting another learning path as a prerequisite will hide the current prerequisite until the one in prerequisite is fully completed (100%)"; +$PrerequisitesOptions = "Prerequisites options"; +$ClearAllPrerequisites = "Clear all prerequisites"; +$SetPrerequisiteForEachItem = "Set previous step as prerequisite for each step"; $ClickOnTheLearnerViewToSeeYourLearningPath = "Click on the [Learner view] button to see your learning path"; $ExerciseCantBeEditedAfterAddingToTheLP = "Exercise can't be edited after being added to the Learning Path"; $EnableTimeLimits = "Enable availability limits"; diff --git a/main/lang/english/tracking.inc.php b/main/lang/english/tracking.inc.php index d239616bfc..0a1c78bac8 100644 --- a/main/lang/english/tracking.inc.php +++ b/main/lang/english/tracking.inc.php @@ -269,6 +269,9 @@ $LinkInvisible = "Link made invisible"; $LinkAdded = "Link added"; $Minutes = "Minutes"; $BackupCreated = "Backup created"; +$TrainingHoursAccumulated = "Training hours accumulated"; +$ManHours = "Man hours"; +$NotesObtained = "Notes obtained"; $DisplayCourseOverview = "Courses overview"; $DisplaySessionOverview = "Sessions overview"; $TotalNumberOfMessages = "Total number of messages"; diff --git a/main/lang/english/trad4all.inc.php b/main/lang/english/trad4all.inc.php index a6b77c7504..ddea0c5b38 100644 --- a/main/lang/english/trad4all.inc.php +++ b/main/lang/english/trad4all.inc.php @@ -950,6 +950,7 @@ $SkillXWithCourseX = "%s with %s"; $ToGetToLearnXYouWillNeedToTakeOneOfTheFollowingCourses = "To get to learn %s you will need to take one of the following courses:"; $YourSkillRankingX = "Your skill ranking: %s"; $ManageSkills = "Manage skills"; +$StartDateMustBeBeforeTheEndDate = "Start date must be before the end date"; $SkillRoot = "Root"; $SkillInfo = "Skill info"; $GetNewSkills = "Get new skills"; @@ -976,6 +977,7 @@ $NumberOfCoursesPrivate = "Number of private courses"; $NumberOfCoursesClosed = "Number of closed courses"; $NumberOfCoursesTotal = "Total number of courses"; $NumberOfUsersActive = "Number of active users"; +$Approved = "Approved"; $EditSettings = "Edit settings"; $ThisValueCantBeChanged = "This value can't be changed."; $TotalAvailableUsers = "Total available users"; diff --git a/main/newscorm/learnpath.class.php b/main/newscorm/learnpath.class.php index 3384744604..342a76e97d 100644 --- a/main/newscorm/learnpath.class.php +++ b/main/newscorm/learnpath.class.php @@ -5313,7 +5313,7 @@ class learnpath { 'href' => 'lp_controller.php?'.api_get_cidreq().'&action=set_previous_step_as_prerequisite&lp_id=' . $_SESSION['oLP']->lp_id, ), array( - 'title' => get_lang('Clear all prerequisites'), + 'title' => get_lang('ClearAllPrerequisites'), 'href' => 'lp_controller.php?'.api_get_cidreq().'&action=clear_prerequisites&lp_id=' . $_SESSION['oLP']->lp_id, ), ); From f1ea1dca2477c102f15788eecfd40af594575ebf Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 12:06:40 +0100 Subject: [PATCH 10/23] Improving UI in stylesheets --- main/admin/settings.lib.php | 473 +++++++++++++++++++----------------- main/admin/settings.php | 7 - 2 files changed, 244 insertions(+), 236 deletions(-) diff --git a/main/admin/settings.lib.php b/main/admin/settings.lib.php index 26965d32a9..ae3523e77c 100644 --- a/main/admin/settings.lib.php +++ b/main/admin/settings.lib.php @@ -16,25 +16,25 @@ * @author Julio Montoya Beeznest 2012 */ function handle_regions() { - + if (isset($_POST['submit_plugins'])) { store_regions(); - // Add event to the system log. + // Add event to the system log. $user_id = api_get_user_id(); $category = $_GET['category']; event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id); Display :: display_confirmation_message(get_lang('SettingsStored')); } - + $plugin_obj = new AppPlugin(); $possible_plugins = $plugin_obj->read_plugins_from_path(); - $installed_plugins = $plugin_obj->get_installed_plugins(); + $installed_plugins = $plugin_obj->get_installed_plugins(); if (!empty($installed_plugins)) { $not_installed = array_diff($possible_plugins, $installed_plugins); } else { $not_installed = $possible_plugins; - } + } echo '
'; echo ''; echo ''; @@ -45,21 +45,21 @@ function handle_regions() { echo ''; echo ''; echo ''; - + /* We display all the possible plugins and the checkboxes */ - + $plugin_region_list = array(); $my_plugin_list = $plugin_obj->get_plugin_regions(); foreach ($my_plugin_list as $plugin_item) { $plugin_region_list[$plugin_item] = $plugin_item; } - + //Removing course tool unset($plugin_region_list['course_tool_plugin']); foreach ($installed_plugins as $plugin) { $plugin_info_file = api_get_path(SYS_PLUGIN_PATH).$plugin.'/plugin.php'; - + if (file_exists($plugin_info_file)) { $plugin_info = array(); require $plugin_info_file; @@ -68,30 +68,30 @@ function handle_regions() { } else { echo ''; } - echo ''; } } echo '
'; + echo ''; echo '

'.$plugin_info['title'].' v'.$plugin_info['version'].'

'; - echo '

'.$plugin_info['comment'].'

'; - echo '
'; + echo '

'.$plugin_info['comment'].'

'; + echo '
'; $selected_plugins = $plugin_obj->get_areas_by_plugin($plugin); - - if ($plugin_info['is_course_plugin']) { + + if ($plugin_info['is_course_plugin']) { $region_list = array('course_tool_plugin' => 'course_tool_plugin'); } else { $region_list = $plugin_region_list; - } - echo Display::select('plugin_'.$plugin.'[]', $region_list, $selected_plugins, array('multiple' => 'multiple', 'style' => 'width:500px'), true, get_lang('None')); + } + echo Display::select('plugin_'.$plugin.'[]', $region_list, $selected_plugins, array('multiple' => 'multiple', 'style' => 'width:500px'), true, get_lang('None')); echo '
'; echo '
'; - echo '
'; + echo ''; } -function handle_extensions() { +function handle_extensions() { echo Display::page_subheader(get_lang('ConfigureExtensions')); - echo ''.get_lang('Ppt2lp').''; - + echo ''.get_lang('Ppt2lp').''; + } /** * This function allows easy activating and inactivating of plugins @@ -101,18 +101,18 @@ function handle_extensions() { */ function handle_plugins() { $plugin_obj = new AppPlugin(); - + if (isset($_POST['submit_plugins'])) { store_plugins(); - // Add event to the system log. + // Add event to the system log. $user_id = api_get_user_id(); $category = $_GET['category']; event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id); Display :: display_confirmation_message(get_lang('SettingsStored')); } - - $all_plugins = $plugin_obj->read_plugins_from_path(); - $installed_plugins = $plugin_obj->get_installed_plugins(); + + $all_plugins = $plugin_obj->read_plugins_from_path(); + $installed_plugins = $plugin_obj->get_installed_plugins(); //Plugins NOT installed echo Display::page_subheader(get_lang('Plugins')); @@ -122,10 +122,10 @@ function handle_plugins() { echo ''; echo get_lang('Action'); echo ''; - echo get_lang('Description'); + echo get_lang('Description'); echo ''; echo ''; - + $plugin_list = array(); $my_plugin_list = $plugin_obj->get_plugin_regions(); foreach($my_plugin_list as $plugin_item) { @@ -134,7 +134,7 @@ function handle_plugins() { foreach ($all_plugins as $plugin) { $plugin_info_file = api_get_path(SYS_PLUGIN_PATH).$plugin.'/plugin.php'; - + if (file_exists($plugin_info_file)) { $plugin_info = array(); require $plugin_info_file; @@ -143,41 +143,39 @@ function handle_plugins() { } else { echo ''; } - //echo ''; echo ''; //Checkbox - if (in_array($plugin, $installed_plugins)) { + if (in_array($plugin, $installed_plugins)) { echo ''; - - } else { + + } else { echo ''; } echo ''; - + echo '

'.$plugin_info['title'].' v '.$plugin_info['version'].'

'; echo '

'.$plugin_info['comment'].'

'; echo '

'.get_lang('Author').': '.$plugin_info['author'].'

'; - + echo '
'; - if (in_array($plugin, $installed_plugins)) { + if (in_array($plugin, $installed_plugins)) { echo Display::url(get_lang('Configure'), 'configure_plugin.php?name='.$plugin, array('class' => 'btn')); echo Display::url(get_lang('Regions'), 'settings.php?category=Regions&name='.$plugin, array('class' => 'btn')); } - + if (file_exists(api_get_path(SYS_PLUGIN_PATH).$plugin.'/readme.txt')) { echo Display::url("readme.txt", api_get_path(WEB_PLUGIN_PATH).$plugin."/readme.txt", array('class' => 'btn ajax', '_target' => '_blank')); } echo '
'; - echo ''; + echo ''; } } echo ''; - - echo '
'; - echo ''; + + echo '
'; + echo ''; echo '
'; echo ''; - } /** @@ -187,9 +185,10 @@ function handle_plugins() { */ function handle_stylesheets() { global $_configuration; + // Current style. $currentstyle = api_get_setting('stylesheets'); - + $is_style_changeable = false; if ($_configuration['access_url'] != 1) { @@ -197,75 +196,71 @@ function handle_stylesheets() { $url_info = api_get_access_url($_configuration['access_url']); if ($style_info[0]['access_url_changeable'] == 1 && $url_info['active'] == 1) { $is_style_changeable = true; - echo '';*/ } } else { $is_style_changeable = true; - echo '';*/ } - $form = new FormValidator('stylesheet_upload', 'post', 'settings.php?category=Stylesheets&showuploadform=true'); + $form = new FormValidator('stylesheet_upload', 'post', 'settings.php?category=Stylesheets#tabs-2'); + //$form->addElement('header', get_lang('UploadNewStylesheet')); $form->addElement('text', 'name_stylesheet', get_lang('NameStylesheet'), array('size' => '40', 'maxlength' => '40')); $form->addRule('name_stylesheet', get_lang('ThisFieldIsRequired'), 'required'); $form->addElement('file', 'new_stylesheet', get_lang('UploadNewStylesheet')); $allowed_file_types = array('css', 'zip', 'jpeg', 'jpg', 'png', 'gif', 'ico'); - + $form->addRule('new_stylesheet', get_lang('InvalidExtension').' ('.implode(',', $allowed_file_types).')', 'filetype', $allowed_file_types); $form->addRule('new_stylesheet', get_lang('ThisFieldIsRequired'), 'required'); - $form->addElement('style_submit_button', 'stylesheet_upload', get_lang('Ok'), array('class'=>'save')); - if ($form->validate() && is_writable(api_get_path(SYS_CODE_PATH).'css/')) { - $values = $form->exportValues(); - $picture_element = $form->getElement('new_stylesheet'); - $picture = $picture_element->getValue(); - $result = upload_stylesheet($values, $picture); + $form->addElement('style_submit_button', 'stylesheet_upload', get_lang('Upload'), array('class'=>'save')); - // Add event to the system log. - $user_id = api_get_user_id(); - $category = $_GET['category']; - event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id); - - if ($result) { - Display::display_confirmation_message(get_lang('StylesheetAdded')); - } + $show_upload_form = false; + + if (!is_writable(api_get_path(SYS_CODE_PATH).'css/')) { + Display::display_error_message(api_get_path(SYS_CODE_PATH).'css/'.get_lang('IsNotWritable')); } else { - if (!is_writable(api_get_path(SYS_CODE_PATH).'css/')) { - Display::display_error_message(api_get_path(SYS_CODE_PATH).'css/'.get_lang('IsNotWritable')); + // Uploading a new stylesheet. + if ($_configuration['access_url'] == 1) { + //$form->display(); + $show_upload_form = true; } else { - if (!empty($_GET['showuploadform']) && $_GET['showuploadform'] == 'true') { - echo '
'; - } else { - echo ''; } } -?> - -'; - echo '
"; //echo ''.$show_name.''; } else { - echo ''.$show_name.''; + //echo ''.$show_name.''; } - echo '
'; $counter++; } } } @closedir($handle); } - + //Sort styles in alphabetical order asort($list_of_names); - foreach($list_of_names as $style_dir=>$item) { - echo $list_of_styles[$style_dir]; + $select_list = array(); + foreach ($list_of_names as $style_dir=>$item) { + $select_list[$style_dir] = strip_tags($list_of_styles[$style_dir]); } - //echo '
'; - echo '  '; - if ($is_style_changeable){ - echo ''; + $form_change->addElement('select', 'style', get_lang('NameStylesheet'), $select_list); + $form_change->setDefaults('style', $selected); + + if ($form_change->validate()) { + // Submit stylesheets. + if (isset($_POST['save'])) { + store_stylesheets(); + echo Display::display_normal_message(get_lang('Saved')); + } + } + + if ($is_style_changeable) { + $group[] = $form_change->createElement('button', 'save', get_lang('SaveSettings'), array('class' => 'btn btn-primary')); + $group[] = $form_change->createElement('button', 'preview', get_lang('Preview'), array('class' => 'btn')); + $form_change->addGroup($group); + + if ($show_upload_form) { + echo ''; + echo Display::tabs(array(get_lang('Update'), get_lang('UploadNewStylesheet')), array($form_change->return_form(), $form->return_form())); + } else { + $form_change->display(); + } + } else { + $form_change->freeze(); } } @@ -399,7 +418,7 @@ function upload_stylesheet($values, $picture) { } fclose($fp); - fclose($ofp); + fclose($ofp); } $result = true; } @@ -421,7 +440,7 @@ function store_regions() { // Get a list of all current 'Plugins' settings $installed_plugins = $plugin_obj->get_installed_plugins(); - + $shortlist_installed = array(); if (!empty($installed_plugins)) { foreach ($installed_plugins as $plugin) { @@ -431,12 +450,12 @@ function store_regions() { } } $shortlist_installed = array_flip(array_flip($shortlist_installed)); - + $plugin_list = $plugin_obj->read_plugins_from_path(); foreach ($plugin_list as $plugin) { if (isset($_POST['plugin_'.$plugin])) { - $areas_to_installed = $_POST['plugin_'.$plugin]; + $areas_to_installed = $_POST['plugin_'.$plugin]; if (!empty($areas_to_installed)) { $plugin_obj->remove_all_regions($plugin); foreach ($areas_to_installed as $region) { @@ -454,30 +473,28 @@ function store_regions() { * @author Patrick Cool , Ghent University */ function store_plugins() { - $plugin_obj = new AppPlugin(); // Get a list of all current 'Plugins' settings - $plugin_list = $plugin_obj->read_plugins_from_path(); - + $installed_plugins = array(); - + foreach ($plugin_list as $plugin) { if (isset($_POST['plugin_'.$plugin])) { $plugin_obj->install($plugin); $installed_plugins[] = $plugin; } } - + if (!empty($installed_plugins)) { $remove_plugins = array_diff($plugin_list, $installed_plugins); } else { $remove_plugins = $plugin_list; - } + } foreach ($remove_plugins as $plugin) { $plugin_obj->uninstall($plugin); - } + } } /** @@ -486,14 +503,12 @@ function store_plugins() { */ function store_stylesheets() { global $_configuration; - // Insert the stylesheet. $style = Database::escape_string($_POST['style']); if (is_style($style)) { api_set_setting('stylesheets', $style, null, 'stylesheets', $_configuration['access_url']); } - return true; } @@ -521,19 +536,19 @@ function is_style($style) { function handle_search() { global $SettingsStored, $_configuration; - require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php'; + require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php'; $search_enabled = api_get_setting('search_enabled'); - + $form = new FormValidator('search-options', 'post', api_get_self().'?category=Search'); - + //$renderer = & $form->defaultRenderer(); //$renderer->setHeaderTemplate('
{header}
'."\n"); //$renderer->setElementTemplate('
{label}
'."\n".'
{element}
'."\n"); //$renderer->setElementTemplate('
{label}
{element}{label_2}
'); - - $values = api_get_settings_options('search_enabled'); - $form->addElement('header', null, get_lang('SearchEnabledTitle')); - + + $values = api_get_settings_options('search_enabled'); + $form->addElement('header', null, get_lang('SearchEnabledTitle')); + $group = array (); if (is_array($values)) { foreach ($values as $key => $value) { @@ -548,9 +563,9 @@ function handle_search() { } //SearchEnabledComment $form->addGroup($group, 'search_enabled', array(get_lang('SearchEnabledTitle'), get_lang('SearchEnabledComment')), '
', false); - + $search_enabled = api_get_setting('search_enabled'); - + if ($form->validate()) { $formvalues = $form->exportValues(); $r = api_set_settings_category('Search', 'false', $_configuration['access_url']); @@ -562,9 +577,9 @@ function handle_search() { Display::display_confirmation_message($SettingsStored); } $specific_fields = get_specific_field_list(); - + if ($search_enabled == 'true') { - + // Search_show_unlinked_results. //$form->addElement('header', null, get_lang('SearchShowUnlinkedResultsTitle')); //$form->addElement('label', null, get_lang('SearchShowUnlinkedResultsComment')); @@ -576,74 +591,74 @@ function handle_search() { } $form->addGroup($group, 'search_show_unlinked_results', array(get_lang('SearchShowUnlinkedResultsTitle'),get_lang('SearchShowUnlinkedResultsComment')), '', false); $default_values['search_show_unlinked_results'] = api_get_setting('search_show_unlinked_results'); - + // Search_prefilter_prefix. //$form->addElement('header', null, get_lang('SearchPrefilterPrefix')); //$form->addElement('label', null, get_lang('SearchPrefilterPrefixComment')); - + $sf_values = array(); foreach ($specific_fields as $sf) { $sf_values[$sf['code']] = $sf['name']; } $group = array(); $url = Display::div(Display::url(get_lang('AddSpecificSearchField'), 'specific_fields.php'), array('class'=>'sectioncomment')); - if (empty($sf_values)) { + if (empty($sf_values)) { $form->addElement('html', get_lang('SearchPrefilterPrefix').$url); } else { - $form->addElement('select', 'search_prefilter_prefix', array(get_lang('SearchPrefilterPrefix'), $url), $sf_values, ''); + $form->addElement('select', 'search_prefilter_prefix', array(get_lang('SearchPrefilterPrefix'), $url), $sf_values, ''); $default_values['search_prefilter_prefix'] = api_get_setting('search_prefilter_prefix'); - } - + } + } $default_values['search_enabled'] = $search_enabled; //$form->addRule('search_show_unlinked_results', get_lang('ThisFieldIsRequired'), 'required'); $form->addElement('style_submit_button', 'submit', get_lang('Save'),'class="save"'); - $form->setDefaults($default_values); - + $form->setDefaults($default_values); + echo '
'; $form->display(); echo '
'; - + if ($search_enabled == 'true') { - require_once api_get_path(LIBRARY_PATH).'sortable_table.class.php'; + require_once api_get_path(LIBRARY_PATH).'sortable_table.class.php'; $xapian_path = api_get_path(SYS_PATH).'searchdb'; - + /* @todo Test the Xapian connection if (extension_loaded('xapian')) { require_once 'xapian.php'; - try { + try { $db = new XapianDatabase($xapian_path.'/'); - } catch (Exception $e) { - var_dump($e->getMessage()); + } catch (Exception $e) { + var_dump($e->getMessage()); } - + require_once api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php'; require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php'; require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php'; - + $indexable = new IndexableChunk(); $indexable->addValue("content", 'Test'); - - $di = new DokeosIndexer(); + + $di = new DokeosIndexer(); $di->connectDb(NULL, NULL, 'english'); $di->addChunk($indexable); $did = $di->index(); } */ - + $xapian_loaded = Display::return_icon('bullet_green.gif', get_lang('Ok')); $dir_exists = Display::return_icon('bullet_green.gif', get_lang('Ok')); - $dir_is_writable = Display::return_icon('bullet_green.gif', get_lang('Ok')); + $dir_is_writable = Display::return_icon('bullet_green.gif', get_lang('Ok')); $specific_fields_exists = Display::return_icon('bullet_green.gif', get_lang('Ok')); - + //Testing specific fields if (empty($specific_fields)) { $specific_fields_exists = Display::return_icon('bullet_red.gif', get_lang('AddSpecificSearchField')); } - //Testing xapian extension + //Testing xapian extension if (!extension_loaded('xapian')) { $xapian_loaded = Display::return_icon('bullet_red.gif', get_lang('Error')); } @@ -653,9 +668,9 @@ function handle_search() { } //Testing xapian searchdb path is writable if (!is_writable($xapian_path)) { - $dir_is_writable = Display::return_icon('bullet_red.gif', get_lang('Error')); + $dir_is_writable = Display::return_icon('bullet_red.gif', get_lang('Error')); } - + $data[] = array(get_lang('XapianModuleInstalled'),$xapian_loaded); $data[] = array(get_lang('DirectoryExists').' - '.$xapian_path,$dir_exists); $data[] = array(get_lang('IsWritable').' - '.$xapian_path,$dir_is_writable); @@ -665,21 +680,21 @@ function handle_search() { $table = new SortableTableFromArray($data); $table->set_header(0, get_lang('Setting'), false); $table->set_header(1, get_lang('Status'), false); - echo $table->display(); - + echo $table->display(); + //@todo windows support if (api_is_windows_os() == false) { $list_of_programs = array('pdftotext','ps2pdf', 'catdoc','html2text','unrtf', 'catppt', 'xls2csv'); - + foreach($list_of_programs as $program) { $output = $ret_val = null; exec("which $program", $output, $ret_val); $icon = Display::return_icon('bullet_red.gif', get_lang('NotInstalled')); if (!empty($output[0])) { - $icon = Display::return_icon('bullet_green.gif', get_lang('Installed')); + $icon = Display::return_icon('bullet_green.gif', get_lang('Installed')); } - $data2[]= array($program, $output[0], $icon); - } + $data2[]= array($program, $output[0], $icon); + } echo Display::tag('h3', get_lang('ProgramsNeededToConvertFiles')); $table = new SortableTableFromArray($data2); $table->set_header(0, get_lang('Program'), false); @@ -689,7 +704,7 @@ function handle_search() { } else { Display::display_warning_message(get_lang('YouAreUsingChamiloInAWindowsPlatformSadlyYouCantConvertDocumentsInOrderToSearchTheContentUsingThisTool')); } - } + } } /** @@ -718,7 +733,7 @@ function handle_templates() { if ($_GET['action'] == 'delete' && is_numeric($_GET['id'])) { delete_template($_GET['id']); - // Add event to the system log + // Add event to the system log $user_id = api_get_user_id(); $category = $_GET['category']; event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id); @@ -933,7 +948,7 @@ function add_edit_template() { } $new_height = round(($thumbwidth / $picture_info['width']) * $picture_info['height']); $temp->resize($thumbwidth, $new_height, 0); - } + } $temp->send_image($upload_dir.$new_file_name); } } @@ -1025,16 +1040,16 @@ function select_gradebook_number_decimals() { return array('0', '1', '2'); } -function select_gradebook_default_grade_model_id() { +function select_gradebook_default_grade_model_id() { $grade_model = new GradeModel(); $models = $grade_model->get_all(); - $options = array(); + $options = array(); $options[-1] = get_lang('None'); - if (!empty($models)) { + if (!empty($models)) { foreach ($models as $model) { $options[$model['id']] = $model['name']; } - } + } return $options; } @@ -1062,33 +1077,33 @@ function update_gradebook_score_display_custom_values($values) { $scoredisplay->update_custom_score_display_settings($final); } -function generate_settings_form($settings, $settings_by_access_list) { +function generate_settings_form($settings, $settings_by_access_list) { global $_configuration, $settings_to_avoid, $convert_byte_to_mega_list; $table_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT); - + $form = new FormValidator('settings', 'post', 'settings.php?category='.Security::remove_XSS($_GET['category'])); - + $form->addElement('hidden', 'search_field', (!empty($_GET['search_field'])?Security::remove_XSS($_GET['search_field']):null)); - + $url_id = api_get_current_access_url_id(); - + if (!empty($_configuration['multiple_access_urls']) && api_is_global_platform_admin() && $url_id == 1) { - $group = array(); + $group = array(); $group[] = $form->createElement('button', 'mark_all', get_lang('MarkAll')); - $group[] = $form->createElement('button', 'unmark_all', get_lang('UnmarkAll')); - $form->addGroup($group, 'buttons_in_action_right'); + $group[] = $form->createElement('button', 'unmark_all', get_lang('UnmarkAll')); + $form->addGroup($group, 'buttons_in_action_right'); } - - $default_values = array(); - + + $default_values = array(); + $url_info = api_get_access_url($url_id); - + $i = 0; - foreach ($settings as $row) { - if (in_array($row['variable'], array_keys($settings_to_avoid))) { continue; } - + foreach ($settings as $row) { + if (in_array($row['variable'], array_keys($settings_to_avoid))) { continue; } + if (!empty($_configuration['multiple_access_urls'])) { - if (api_is_global_platform_admin()) { + if (api_is_global_platform_admin()) { if ($row['access_url_locked'] == 0) { if ($url_id == 1) { if ($row['access_url_changeable'] == '1') { @@ -1107,19 +1122,19 @@ function generate_settings_form($settings, $settings_by_access_list) { Display::return_icon('shared_setting_na.png', get_lang('ChangeSharedSetting')).'
'); } } - } + } } } $hideme = array(); $hide_element = false; - + if ($_configuration['access_url'] != 1) { if ($row['access_url_changeable'] == 0) { // We hide the element in other cases (checkbox, radiobutton) we 'freeze' the element. $hide_element = true; $hideme = array('disabled'); - } elseif ($url_info['active'] == 1) { + } elseif ($url_info['active'] == 1) { // We show the elements. if (empty($row['variable'])) $row['variable'] = 0; @@ -1127,7 +1142,7 @@ function generate_settings_form($settings, $settings_by_access_list) { $row['subkey'] = 0; if (empty($row['category'])) $row['category'] = 0; - + if (is_array($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ] [ $row['category'] ])) { // We are sure that the other site have a selected value. if ($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ] [ $row['category'] ]['selected_value'] != '') @@ -1135,14 +1150,14 @@ function generate_settings_form($settings, $settings_by_access_list) { } // There is no else{} statement because we load the default $row['selected_value'] of the main Chamilo site. } - } - + } + switch ($row['type']) { case 'textfield': - if (in_array($row['variable'], $convert_byte_to_mega_list)) { + if (in_array($row['variable'], $convert_byte_to_mega_list)) { $form->addElement('text', $row['variable'], array(get_lang($row['title']), get_lang($row['comment']), get_lang('MB')), array('class' => 'span1', 'maxlength' => '8')); $form->applyFilter($row['variable'], 'html_filter'); - $default_values[$row['variable']] = round($row['selected_value']/1024/1024, 1); + $default_values[$row['variable']] = round($row['selected_value']/1024/1024, 1); } elseif ($row['variable'] == 'account_valid_duration') { $form->addElement('text', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])), array('maxlength' => '5')); $form->applyFilter($row['variable'], 'html_filter'); @@ -1168,20 +1183,20 @@ function generate_settings_form($settings, $settings_by_access_list) { foreach ($valid_encodings as $key => &$encoding) { if (api_is_encoding_supported($key) && Database::is_encoding_supported($key)) { $encoding = $key; - } else { + } else { unset($valid_encodings[$key]); } - } + } $form->addElement('select', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])), $valid_encodings); - $default_values[$row['variable']] = $current_system_encoding; - } else { + $default_values[$row['variable']] = $current_system_encoding; + } else { $hideme['class'] = 'span4'; - $form->addElement('text', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])), $hideme); + $form->addElement('text', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])), $hideme); $form->applyFilter($row['variable'],'html_filter'); $default_values[$row['variable']] = $row['selected_value']; } break; - case 'textarea': + case 'textarea': if ($row['variable'] == 'header_extra_content') { $file = api_get_path(SYS_PATH).api_get_home_path().'header_extra_content.txt'; $value = ''; @@ -1189,7 +1204,7 @@ function generate_settings_form($settings, $settings_by_access_list) { $value = file_get_contents($file); } $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('class'=>'span6','rows'=>'10'), $hideme); - $default_values[$row['variable']] = $value; + $default_values[$row['variable']] = $value; } elseif ($row['variable'] == 'footer_extra_content') { $file = api_get_path(SYS_PATH).api_get_home_path().'footer_extra_content.txt'; $value = ''; @@ -1197,7 +1212,7 @@ function generate_settings_form($settings, $settings_by_access_list) { $value = file_get_contents($file); } $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('rows'=>'10', 'class'=>'span6'), $hideme); - $default_values[$row['variable']] = $value; + $default_values[$row['variable']] = $value; } else { $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('rows'=>'10','class'=>'span6'), $hideme); $default_values[$row['variable']] = $row['selected_value']; @@ -1260,7 +1275,7 @@ function generate_settings_form($settings, $settings_by_access_list) { break; case 'link': $form->addElement('static', null, array(get_lang($row['title']), get_lang($row['comment'])), get_lang('CurrentValue').' : '.$row['selected_value'], $hideme); - break; + break; case 'select': /* * To populate the list of options, the select type dynamically calls a function that must be called select_ + the name of the variable being displayed. @@ -1269,23 +1284,23 @@ function generate_settings_form($settings, $settings_by_access_list) { $form->addElement('select', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])), call_user_func('select_'.$row['variable']), $hideme); $default_values[$row['variable']] = $row['selected_value']; break; - case 'custom': - break; + case 'custom': + break; } - + switch ($row['variable']) { - case 'pdf_export_watermark_enable': - $url = PDF::get_watermark(null); + case 'pdf_export_watermark_enable': + $url = PDF::get_watermark(null); $form->addElement('file', 'pdf_export_watermark_path', get_lang('AddWaterMark')); - - if ($url != false) { + + if ($url != false) { $delete_url = ''.Display::return_icon('delete.png',get_lang('DelImage')).''; $form->addElement('html', ''.$url.' '.$delete_url.''); - } - + } + $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif'); $form->addRule('pdf_export_watermark_path', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types); - + break; case 'timezone_value': $timezone = $row['selected_value']; @@ -1293,14 +1308,14 @@ function generate_settings_form($settings, $settings_by_access_list) { $timezone = _api_get_timezone(); } $form->addElement('html', sprintf(get_lang('LocalTimeUsingPortalTimezoneXIsY'), $timezone, api_get_local_time())); - break; - } + break; + } } // end for - - if (!empty($settings)) { - $form->setDefaults($default_values); - } - $form->addElement('button', 'submit_fixed_in_bottom', get_lang('SaveSettings'), 'class="save"'); + + if (!empty($settings)) { + $form->setDefaults($default_values); + } + $form->addElement('button', 'submit_fixed_in_bottom', get_lang('SaveSettings'), 'class="save"'); return $form; } @@ -1313,40 +1328,40 @@ function search_setting($search) { if (empty($search)) { return array(); } - $table_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT); + $table_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT); $sql = "SELECT * FROM $table_settings_current WHERE category <> 'Plugins' GROUP BY variable ORDER BY id ASC "; $result = Database::store_result(Database::query($sql), 'ASSOC'); $settings = array(); - + $search = api_strtolower($search); - + if (!empty($result)) { foreach ($result as $setting) { $found = false; - + $title = api_strtolower(get_lang($setting['title'])); //try the title - if (strpos($title, $search) === false) { + if (strpos($title, $search) === false) { $comment = api_strtolower(get_lang($setting['comment'])); //Try the comment if (strpos($comment, $search) === false) { //Try the variable name if (strpos($setting['variable'], $search) === false) { - continue; + continue; } else { - $found = true; - } + $found = true; + } } else { - $found = true; + $found = true; } - - } else { - $found = true; - } - if ($found) { + + } else { + $found = true; + } + if ($found) { $settings[] = $setting; } - } - } - return $settings; + } + } + return $settings; } diff --git a/main/admin/settings.php b/main/admin/settings.php index 55c19b2821..af0de6a924 100644 --- a/main/admin/settings.php +++ b/main/admin/settings.php @@ -47,13 +47,6 @@ $settings_to_avoid = array( $convert_byte_to_mega_list = array('dropbox_max_filesize', 'message_max_upload_filesize', 'default_document_quotum', 'default_group_quotum'); -// Submit stylesheets. -if (isset($_POST['submit_stylesheets'])) { - $message = store_stylesheets(); - header("Location: ".api_get_self()."?category=Stylesheets"); - exit; -} - if (isset($_POST['style'])) { Display::$preview_style = $_POST['style']; } From 79937d95ca3329671dd196c72aa2925100513187 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 12:29:24 +0100 Subject: [PATCH 11/23] Exercises: Should fix bug when loading long descriptions see #5831 --- main/exercice/exercise_submit.php | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/main/exercice/exercise_submit.php b/main/exercice/exercise_submit.php index e322844e68..0e59bc96d3 100644 --- a/main/exercice/exercise_submit.php +++ b/main/exercice/exercise_submit.php @@ -55,7 +55,6 @@ if (api_get_setting('show_glossary_in_extra_tools') == 'true') { $htmlHeadXtra[] = api_get_js('jquery.highlight.js'); //highlight } - //This library is necessary for the time control feature $htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/epiclock/stylesheet/jquery.epiclock.css'); $htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/epiclock/renderers/minute/epiclock.minute.css'); @@ -342,7 +341,6 @@ if ($time_control) { //Sends the exercice form when the expired time is finished // if the user has submitted the form $exercise_title = $objExercise->selectTitle(); -$exercise_description = $objExercise->selectDescription(); $exercise_sound = $objExercise->selectSound(); //in LP's is enabled the "remember question" feature? @@ -657,8 +655,20 @@ if ($time_control) { echo ''; } + if (!empty($objExercise->description)) { - echo Display::generate_accordion(array( array('title' => get_lang('ExerciseDescriptionLabel'), 'content' => $objExercise->description))); + echo ""; + echo Display::generate_accordion(array(array('title' => get_lang('ExerciseDescriptionLabel'), 'content' => null)), 'jquery', 'description_content'); } if ($origin != 'learnpath') { From c25b1999e5fe47aa1429ef47c034558769501cc2 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 13:05:30 +0100 Subject: [PATCH 12/23] Adding reply to instead of sending the email as the user see BT#5316 and #5738 --- main/inc/lib/mail.lib.inc.php | 4 ++++ main/inc/lib/notification.lib.php | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/main/inc/lib/mail.lib.inc.php b/main/inc/lib/mail.lib.inc.php index bb28f86005..94f674cc60 100644 --- a/main/inc/lib/mail.lib.inc.php +++ b/main/inc/lib/mail.lib.inc.php @@ -80,6 +80,10 @@ function api_mail_html($recipient_name, $recipient_email, $subject, $message, $s $mail->AddReplyTo($sender_email, $sender_name); } + if (isset($extra_headers['reply_to'])) { + $mail->AddReplyTo($extra_headers['reply_to']['mail'], $extra_headers['reply_to']['name']); + } + // Attachments // $mail->AddAttachment($path); // $mail->AddAttachment($path, $filename); diff --git a/main/inc/lib/notification.lib.php b/main/inc/lib/notification.lib.php index 867963aa05..74f6b8b152 100644 --- a/main/inc/lib/notification.lib.php +++ b/main/inc/lib/notification.lib.php @@ -146,7 +146,10 @@ class Notification extends Model { if (!empty($user_info['mail'])) { $name = api_get_person_name($user_info['firstname'], $user_info['lastname']); if (!empty($sender_info['complete_name']) && !empty($sender_info['email'])) { - api_mail_html($name, $user_info['mail'], Security::filter_terms($title), Security::filter_terms($content), $sender_info['complete_name'], $sender_info['email']); + $extra_headers = array(); + $extra_headers['reply_to']['mail'] = $sender_info['email']; + $extra_headers['reply_to']['name'] = $name; + api_mail_html($name, $user_info['mail'], Security::filter_terms($title), Security::filter_terms($content), $this->admin_name, $this->admin_email, $extra_headers); } else { api_mail_html($name, $user_info['mail'], Security::filter_terms($title), Security::filter_terms($content), $this->admin_name, $this->admin_email); } From 4744d98bbd294ca45b3317c4d304fbb67854a34e Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 14:06:55 +0100 Subject: [PATCH 13/23] No need to invalidate quiz because exercise_show.php is only loaded by teachers see #5814 --- main/exercice/exercise_show.php | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/main/exercice/exercise_show.php b/main/exercice/exercise_show.php index a8c4ef02f0..9059dda773 100644 --- a/main/exercice/exercise_show.php +++ b/main/exercice/exercise_show.php @@ -96,17 +96,6 @@ if (empty($objExercise)) { } $feedback_type = $objExercise->feedback_type; -if ($objExercise->exercise_was_added_in_lp && $learnpath_id != 0) { - //Display::display_normal_message(get_lang('ThisExerciseWasResolvedInsideALP')); -} - -//If is not valid -$session_control_key = get_session_time_control_key($exercise_id, $learnpath_id, $learnpath_item_id); -if (isset($session_control_key) && !exercise_time_control_is_valid($exercise_id, $learnpath_id, $learnpath_item_id) && !in_array($action, array('qualify','edit'))) { - $sql_fraud = "UPDATE $TBL_TRACK_ATTEMPT SET answer = 0, marks=0, position=0 WHERE exe_id = $id "; - Database::query($sql_fraud); -} - //Only users can see their own results if (!$is_allowedToEdit) { if ($student_id != $current_user_id) { @@ -114,9 +103,6 @@ if (!$is_allowedToEdit) { } } -//Unset session for clock time -exercise_time_control_delete($exercise_id, $learnpath_id, $learnpath_item_id); - if (isset($_SESSION['gradebook'])) { $gradebook= Security::remove_XSS($_SESSION['gradebook']); } From fb6396fb8d0d838ec6856d5d13e6db8d45bab9c0 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 14:16:09 +0100 Subject: [PATCH 14/23] Fixing exam URL sent to user see #5814 --- main/exercice/exercise_report.php | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/main/exercice/exercise_report.php b/main/exercice/exercise_report.php index 1a62816b35..5af294fe7c 100644 --- a/main/exercice/exercise_report.php +++ b/main/exercice/exercise_report.php @@ -80,7 +80,7 @@ if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') { if (isset($_REQUEST['extra_data']) && $_REQUEST['extra_data'] == 1) { $load_extra_data = true; } - + require_once 'exercise_result.class.php'; switch ($_GET['export_format']) { case 'xls' : @@ -113,14 +113,14 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G $lp_id = $track_exercise_info['orig_lp_id']; //$lp_item_id = $track_exercise_info['orig_lp_item_id']; $lp_item_view_id = $track_exercise_info['orig_lp_item_view_id']; - + $course_info = api_get_course_info(); // Teacher data - $teacher_info = api_get_user_info(api_get_user_id()); + $teacher_info = api_get_user_info(api_get_user_id()); $from_name = api_get_person_name($teacher_info['firstname'], $teacher_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS); - $url = api_get_path(WEB_CODE_PATH) . 'exercice/exercise_report.php?' . api_get_cidreq() . '&id_session='.$session_id.'&exerciseId='.$exercise_id; + $url = api_get_path(WEB_CODE_PATH) . 'exercice/result.php?id='.$track_exercise_info['exe_id'].'&'.api_get_cidreq().'&show_headers=1&id_session='.$session_id; $my_post_info = array(); $post_content_id = array(); @@ -174,7 +174,7 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G $totquery = "UPDATE $TBL_TRACK_EXERCICES SET exe_result = '".floatval($tot)."' WHERE exe_id = ".$id; Database::query($totquery); - + if (isset($_POST['send_notification'])) { //@todo move this somewhere else $subject = get_lang('ExamSheetVCC'); @@ -194,7 +194,7 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G $message = str_replace("#url#", $url, $message); MessageManager::send_message_simple($student_id, $subject, $message, api_get_user_id()); } - + //Updating LP score here if (in_array($origin, array ('tracking_course','user_course','correct_exercise_in_lp'))) { @@ -324,16 +324,16 @@ if (!empty($group_parameters)) { if ($is_allowedToEdit || $is_tutor) { //The order is important you need to check the the $column variable in the model.ajax.php file - $columns = array(get_lang('FirstName'), - get_lang('LastName'), + $columns = array(get_lang('FirstName'), + get_lang('LastName'), get_lang('LoginName'), - get_lang('Group'), - get_lang('Duration').' ('.get_lang('MinMinute').')', - get_lang('StartDate'), - get_lang('EndDate'), - get_lang('Score'), - get_lang('Status'), - get_lang('ToolLearnpath'), + get_lang('Group'), + get_lang('Duration').' ('.get_lang('MinMinute').')', + get_lang('StartDate'), + get_lang('EndDate'), + get_lang('Score'), + get_lang('Status'), + get_lang('ToolLearnpath'), get_lang('Actions') ); From f22303098fecb775c6702ec59dad1a92aaaa8a3d Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 14:38:09 +0100 Subject: [PATCH 15/23] Cleaning white spaces and changing button colors see #5832 --- main/exercice/exercise_reminder.php | 78 ++++++++++++++--------------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/main/exercice/exercise_reminder.php b/main/exercice/exercise_reminder.php index c9f460eb53..a40487390a 100644 --- a/main/exercice/exercise_reminder.php +++ b/main/exercice/exercise_reminder.php @@ -1,7 +1,7 @@ show_time_control_js($time_left); + $htmlHeadXtra[] = $objExercise->show_time_control_js($time_left); } @@ -107,48 +107,48 @@ if (api_is_course_admin() && $origin != 'learnpath') { echo Display::page_header(get_lang('QuestionsToReview')); if ($time_control) { - echo $objExercise->return_time_left_div(); + echo $objExercise->return_time_left_div(); } echo Display::div('', array('id'=>'message')); -echo ''; @@ -162,10 +162,10 @@ $exercise_result = array(); foreach ($attempt_list as $question_id => $options) { //echo $question_id.'
'; foreach($options as $item) { - + $question_obj = Question::read($item['question_id']); - - switch($question_obj->type) { + + switch($question_obj->type) { case FILL_IN_BLANKS: $item['answer'] = $objExercise->fill_in_blank_answer_to_string($item['answer']); break; @@ -173,12 +173,12 @@ foreach ($attempt_list as $question_id => $options) { //var_dump($item['answer']); break; } - - if ($item['answer'] != '0' && !empty($item['answer'])) { + + if ($item['answer'] != '0' && !empty($item['answer'])) { $exercise_result[] = $question_id; break; } - } + } } echo Display::label(get_lang('QuestionWithNoAnswer'), 'warning'); echo '

'; @@ -190,26 +190,26 @@ $counter = 0; foreach ($question_list as $questionId) { // destruction of the Question object unset($objQuestionTmp); - + // creates a temporary Question object $objQuestionTmp = Question :: read($questionId); // initialize question information - + $quesId = $objQuestionTmp->selectId(); $check_id = 'remind_list['.$questionId.']'; - $attributes = array('id'=>$check_id, 'onclick'=>"save_remind_item(this, '$questionId');"); - + $attributes = array('id'=>$check_id, 'onclick'=>"save_remind_item(this, '$questionId');"); + if (in_array($questionId, $remind_list)) { $attributes['checked'] = 1; } $label_attributes = array(); $label_attributes['class'] = 'checkbox'; - $label_attributes['for'] = $check_id; + $label_attributes['for'] = $check_id; $label_attributes['class'] = "checkbox"; - + $checkbox = Display::input('checkbox', 'remind_list['.$questionId.']', '', $attributes); $url = 'exercise_submit.php?exerciseId='.$objExercise->id.'&num='.$counter.'&reminder=1'; - + $counter++; if ($objExercise->type == ONE_PER_PAGE) { $question_title = Display::url($counter.'. '.cut($objQuestionTmp->selectTitle(), 40), $url); @@ -221,14 +221,14 @@ foreach ($question_list as $questionId) { if (!in_array($questionId, $exercise_result)) { $question_title = Display::label($question_title, 'warning'); } - $question_title = Display::tag('label', $checkbox.$question_title, $label_attributes); - $table .= Display::div($question_title, array('class'=>'exercise_reminder_item')); + $question_title = Display::tag('label', $checkbox.$question_title, $label_attributes); + $table .= Display::div($question_title, array('class'=>'exercise_reminder_item')); } // end foreach() block that loops over all questions echo Display::div($table, array('class'=>'span10')); -$exercise_actions = Display::url(get_lang('EndTest'), 'javascript://', array('onclick'=>'final_submit();', 'class'=>'btn btn-success')); -$exercise_actions .= ' '.Display::url(get_lang('ReviewQuestions'), 'javascript://', array('onclick'=>'review_questions();','class'=>'btn')); +$exercise_actions = Display::url(get_lang('EndTest'), 'javascript://', array('onclick'=>'final_submit();', 'class'=>'btn btn-warning')); +$exercise_actions .= ' '.Display::url(get_lang('ReviewQuestions'), 'javascript://', array('onclick'=>'review_questions();','class'=>'btn btn-success')); echo Display::div('', array('class'=>'clear')); echo Display::div($exercise_actions, array('class'=>'form-actions')); From 3e6220680ac9dc691d477e2bd1a06291a034283d Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 14:38:51 +0100 Subject: [PATCH 16/23] Fixing free_answer result when is empty (0 by default) --- main/exercice/exercise.class.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/main/exercice/exercise.class.php b/main/exercice/exercise.class.php index 84600065fb..56f69098d6 100644 --- a/main/exercice/exercise.class.php +++ b/main/exercice/exercise.class.php @@ -2365,6 +2365,9 @@ class Exercise { } else { $totalScore+= $questionScore; } + if ($questionScore == '') { + $questionScore = 0; + } $arrques = $questionName; $arrans = $choice; } else { From 1d5fc145849b6648a71c12010674d4fdaf101811 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 14:40:29 +0100 Subject: [PATCH 17/23] Fixing exercise link for students --- main/inc/lib/tracking.lib.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/main/inc/lib/tracking.lib.php b/main/inc/lib/tracking.lib.php index 1c44f06657..9d10bbcad7 100644 --- a/main/inc/lib/tracking.lib.php +++ b/main/inc/lib/tracking.lib.php @@ -2643,8 +2643,7 @@ class Tracking { $weighting = $exercise_stat['exe_weighting']; $exe_id = $exercise_stat['exe_id']; - //$latest_attempt_url .= ' '.Display::return_icon('quiz.gif', get_lang('Quiz')).' '; - $latest_attempt_url .= '../exercice/exercise_show.php?origin=myprogress&id='.$exe_id.'&cidReq='.$course_info['code'].'&id_session='.$session_id; + $latest_attempt_url .= api_get_path(WEB_CODE_PATH).'exercice/result.php?id='.$exe_id.'&cidReq='.$course_info['code'].'&show_headers=1&id_session='.$session_id; $percentage_score_result = Display::url(show_score($score, $weighting), $latest_attempt_url); $my_score = 0; if (!empty($weighting) && intval($weighting) != 0) { From 3d8d634c40d6fb3385fc2f7b0ac820efd9987c66 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 14:43:09 +0100 Subject: [PATCH 18/23] Adding options to the accordion jquery by default --- main/inc/lib/display.lib.php | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/main/inc/lib/display.lib.php b/main/inc/lib/display.lib.php index 005f3a0288..a6d36f7a0b 100644 --- a/main/inc/lib/display.lib.php +++ b/main/inc/lib/display.lib.php @@ -1511,17 +1511,21 @@ class Display { return self::span($text, array('class' => 'boot-tooltip', 'title' => strip_tags($tip))); } - public static function generate_accordion($items) { + public static function generate_accordion($items, $type = 'jquery', $id = null) { $html = null; if (!empty($items)) { - $id = api_get_unique_id(); - //$html = '
'; //using bootstrap - $html = '
'; //using jquery + if (empty($id)) { + $id = api_get_unique_id(); + } + if ($type == 'jquery') { + $html = '
'; //using jquery + } else { + $html = '
'; //using bootstrap + } $count = 1; foreach ($items as $item) { $html .= '
'; - $html .= '
'.$item['title'].' From af957a3de0cada0fdd0a416b6caa592237e5c0bb Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 14:43:29 +0100 Subject: [PATCH 19/23] Minor - removing white spaces --- main/exercice/result.php | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/main/exercice/result.php b/main/exercice/result.php index f3f96691e6..1f64b6f79b 100644 --- a/main/exercice/result.php +++ b/main/exercice/result.php @@ -1,10 +1,10 @@ read($exercise_id); } -//Only users can see their own results +//Only users can see their own results if (!$is_allowedToEdit) { if ($student_id != $current_user_id) { api_not_allowed(); @@ -70,12 +70,11 @@ if (!$is_allowedToEdit) { if ($show_headers) { $interbreadcrumb[] = array("url" => "exercice.php","name" => get_lang('Exercices')); $interbreadcrumb[] = array("url" => "#","name" => get_lang('Result')); - $this_section = SECTION_COURSES; + $this_section = SECTION_COURSES; Display::display_header(); } else { Display::display_reduced_header(); -} - +} display_question_list_by_attempt($objExercise, $id, false); if ($show_headers) { From 7015227f3628d7840d57c700d3ef39c444f9a179 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 14:43:44 +0100 Subject: [PATCH 20/23] Minor - removing white spaces --- main/exercice/exercise_report.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/main/exercice/exercise_report.php b/main/exercice/exercise_report.php index 5af294fe7c..9c8ad72f41 100644 --- a/main/exercice/exercise_report.php +++ b/main/exercice/exercise_report.php @@ -101,8 +101,8 @@ if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') { } //Send student email @todo move this code in a class, library -if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_GET['exeid']== strval(intval($_GET['exeid']))) { - $id = intval($_GET['exeid']); //filtered by post-condition +if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_GET['exeid'] == strval(intval($_GET['exeid']))) { + $id = intval($_GET['exeid']); //filtered by post-condition $track_exercise_info = get_exercise_track_exercise_info($id); if (empty($track_exercise_info)) { api_not_allowed(); @@ -119,7 +119,6 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G // Teacher data $teacher_info = api_get_user_info(api_get_user_id()); $from_name = api_get_person_name($teacher_info['firstname'], $teacher_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS); - $url = api_get_path(WEB_CODE_PATH) . 'exercice/result.php?id='.$track_exercise_info['exe_id'].'&'.api_get_cidreq().'&show_headers=1&id_session='.$session_id; $my_post_info = array(); @@ -134,16 +133,17 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G } } - $loop_in_track=($comments_exist===true) ? (count($_POST)/2) : count($_POST); + $loop_in_track = ($comments_exist===true) ? (count($_POST)/2) : count($_POST); + + $array_content_id_exe = array(); - $array_content_id_exe=array(); - if ($comments_exist===true) { - $array_content_id_exe = array_slice($post_content_id,$loop_in_track); + if ($comments_exist === true) { + $array_content_id_exe = array_slice($post_content_id, $loop_in_track); } else { $array_content_id_exe = $post_content_id; } - for ($i=0;$i<$loop_in_track;$i++) { + for ($i=0; $i < $loop_in_track; $i++) { $my_marks = Database::escape_string($_POST['marks_'.$array_content_id_exe[$i]]); $contain_comments = Database::escape_string($_POST['comments_'.$array_content_id_exe[$i]]); if (isset($contain_comments)) { @@ -153,6 +153,7 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G } $my_questionid = intval($array_content_id_exe[$i]); $sql = "SELECT question from $TBL_QUESTIONS WHERE c_id = $course_id AND id = '$my_questionid'"; + $result =Database::query($sql); Database::result($result,0,"question"); @@ -195,7 +196,6 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G MessageManager::send_message_simple($student_id, $subject, $message, api_get_user_id()); } - //Updating LP score here if (in_array($origin, array ('tracking_course','user_course','correct_exercise_in_lp'))) { $sql_update_score = "UPDATE $TBL_LP_ITEM_VIEW SET score = '" . floatval($tot) . "' WHERE c_id = ".$course_id." AND id = " .$lp_item_view_id; From 9a8376f35b062a0212abf4b895ba6af75c290679 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 14:43:54 +0100 Subject: [PATCH 21/23] Minor - removing white spaces --- main/exercice/exercise_show.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/main/exercice/exercise_show.php b/main/exercice/exercise_show.php index 9059dda773..ad59d63a0b 100644 --- a/main/exercice/exercise_show.php +++ b/main/exercice/exercise_show.php @@ -251,9 +251,6 @@ if (!empty($track_exercise_info['data_tracking'])) { if (empty($questionList)) { $questionList = $question_list_from_database; } - /*if (is_array($temp_question_list) && count($temp_question_list) == count($question_list_from_database)) { - $questionList = $tempquestionList; - }*/ } else { $questionList = $question_list_from_database; } @@ -288,7 +285,6 @@ foreach ($questionList as $questionId) { $questionWeighting = $objQuestionTmp->selectWeighting(); $answerType = $objQuestionTmp->selectType(); - // Start buffer ob_start(); @@ -455,7 +451,7 @@ foreach ($questionList as $questionId) { echo '

'.get_lang('Feedback').'

'; if ($answerType == HOT_SPOT_DELINEATION) { - if ($organs_at_risk_hit>0) { + if ($organs_at_risk_hit > 0) { $message='
'.get_lang('ResultIs').' '.$result_comment.'
'; $message.='

'.get_lang('OARHit').'

'; } else { From 9240efcb709b70e96c6d990f07681481583c60c5 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 14:59:42 +0100 Subject: [PATCH 22/23] Should fix bug when using "time limit" exercises see #5814 --- main/exercice/exercise.lib.php | 4 ++-- main/inc/lib/events.lib.inc.php | 42 ++++++++++++++++++++------------- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/main/exercice/exercise.lib.php b/main/exercice/exercise.lib.php index 9be6be97c5..2a44f64da7 100644 --- a/main/exercice/exercise.lib.php +++ b/main/exercice/exercise.lib.php @@ -2077,6 +2077,7 @@ function display_question_list_by_attempt($objExercise, $exe_id, $save_user_resu //Getting attempt info $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id($exe_id); + //Getting question list $question_list = array(); if (!empty($exercise_stat_info['data_tracking'])) { $question_list = explode(',', $exercise_stat_info['data_tracking']); @@ -2135,11 +2136,10 @@ function display_question_list_by_attempt($objExercise, $exe_id, $save_user_resu $objQuestionTmp = Question :: read($questionId); //this variable commes from exercise_submit_modal.php - ob_start(); // We're inside *one* question. Go through each possible answer for this question - $result = $objExercise->manage_answer($exercise_stat_info['exe_id'], $questionId, null ,'exercise_result', array(), false, true, $show_results, $objExercise->selectPropagateNeg(), $hotspot_delineation_result); + $result = $objExercise->manage_answer($exercise_stat_info['exe_id'], $questionId, null , 'exercise_result', array(), $save_user_result, true, $show_results, $objExercise->selectPropagateNeg(), $hotspot_delineation_result); $total_score += $result['score']; $total_weight += $result['weight']; diff --git a/main/inc/lib/events.lib.inc.php b/main/inc/lib/events.lib.inc.php index 623cf1b266..9893581360 100644 --- a/main/inc/lib/events.lib.inc.php +++ b/main/inc/lib/events.lib.inc.php @@ -485,24 +485,34 @@ function exercise_attempt($score, $answer, $question_id, $exe_id, $position, $ex $file = Database::escape_string(basename($nano->load_filename_if_exists(false))); } - $sql = "INSERT INTO $TBL_TRACK_ATTEMPT (exe_id, user_id, question_id, answer, marks, course_code, session_id, position, tms, filename) - VALUES ( - ".$exe_id.", - ".$user_id.", - '".$question_id."', - '".$answer."', - '".$score."', - '".api_get_course_id()."', - '".api_get_session_id()."', - '".$position."', - '".$now."', - '".$file."' - )"; - - if ($debug) error_log("Saving question attempt: "); - if ($debug) error_log($sql); if (!empty($question_id) && !empty($exe_id) && !empty($user_id)) { + + //Check if attempt exists + $sql = "SELECT exe_id FROM $TBL_TRACK_ATTEMPT WHERE exe_id = $exe_id AND user_id = $user_id AND question_id = $question_id"; + $result = Database::query($sql); + if (Database::num_rows($result)) { + if ($debug) error_log("Attempt already exist: exe_id: $exe_id - user_id:$user_id - question_id:$question_id"); + //The attempt already exist do not update use update_event_exercice() instead + return false; + } + $sql = "INSERT INTO $TBL_TRACK_ATTEMPT (exe_id, user_id, question_id, answer, marks, course_code, session_id, position, tms, filename) + VALUES ( + ".$exe_id.", + ".$user_id.", + '".$question_id."', + '".$answer."', + '".$score."', + '".api_get_course_id()."', + '".api_get_session_id()."', + '".$position."', + '".$now."', + '".$file."' + )"; + + if ($debug) error_log("Saving question attempt: "); + if ($debug) error_log($sql); + $res = Database::query($sql); if (defined('ENABLED_LIVE_EXERCISE_TRACKING')){ $recording_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); From 68adb5d12c6eb88d425c9defa0b4453241d88ea6 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 19 Dec 2012 14:59:55 +0100 Subject: [PATCH 23/23] Minor - cleaning white spaces --- main/exercice/exercise.class.php | 2 +- main/tracking/exams.php | 276 +++++++++++++++---------------- 2 files changed, 133 insertions(+), 145 deletions(-) diff --git a/main/exercice/exercise.class.php b/main/exercice/exercise.class.php index 56f69098d6..cb998ac42e 100644 --- a/main/exercice/exercise.class.php +++ b/main/exercice/exercise.class.php @@ -2744,7 +2744,7 @@ class Exercise { } else { if ($debug) error_log('Showing questions $from '.$from); - switch($answerType) { + switch ($answerType) { case UNIQUE_ANSWER : case UNIQUE_ANSWER_NO_OPTION: case MULTIPLE_ANSWER : diff --git a/main/tracking/exams.php b/main/tracking/exams.php index f79645937d..1aafe061b2 100644 --- a/main/tracking/exams.php +++ b/main/tracking/exams.php @@ -16,7 +16,7 @@ $this_section = SECTION_TRACKING; $is_allowedToTrack = $is_courseAdmin || $is_platformAdmin || $is_courseCoach || $is_sessionAdmin; -if(!$is_allowedToTrack) { +if(!$is_allowedToTrack) { api_not_allowed(); } @@ -27,25 +27,25 @@ if (isset($_GET['export'])) { $tbl_stats_exercices = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); -if (api_is_platform_admin() ) { +if (api_is_platform_admin() ) { $global = true; } else { $global = false; } if ($global) { - $temp_course_list = CourseManager :: get_courses_list(); + $temp_course_list = CourseManager :: get_courses_list(); foreach($temp_course_list as $temp_course_item) { - $course_item = CourseManager ::get_course_information($temp_course_item['code']); + $course_item = CourseManager ::get_course_information($temp_course_item['code']); $course_list[]= array( 'db_name' => $course_item['db_name'], 'code' => $course_item['code'], 'real_id' => $course_item['real_id'], - 'title' => $course_item['title']); + 'title' => $course_item['title']); } -} else { +} else { $current_course['db_name'] = $_course['dbName']; $current_course['real_id'] = $_course['real_id']; - $current_course['code'] = $_course['id']; + $current_course['code'] = $_course['id']; $course_list = array($current_course); } @@ -58,15 +58,15 @@ if ($global) { $t_quiz = Database::get_course_table(TABLE_QUIZ_TEST); $course_id = api_get_course_int_id(); $sqlExercices = " SELECT quiz.title,id FROM ".$t_quiz." AS quiz WHERE c_id = $course_id AND active='1' ORDER BY quiz.title ASC"; - $resultExercices = Database::query($sqlExercices); + $resultExercices = Database::query($sqlExercices); $exercise_list[0] = get_lang('All'); while($a_exercices = Database::fetch_array($resultExercices)) { $exercise_list[$a_exercices['id']] = $a_exercices['title']; - } - + } + $form->addElement('select', 'exercise_id', get_lang('Exercise'), $exercise_list); } - + //$form->addElement('submit','submit',get_lang('Filter')); $form->addElement('style_submit_button','submit', get_lang('Filter'),'class="search"' ); @@ -80,16 +80,16 @@ if (!$export_to_xls) { Display :: display_header(get_lang('Reporting')); echo '
'; if ($global) { - + echo ''. Display::return_icon('stats.png', get_lang('MyStats'),'',ICON_SIZE_MEDIUM); echo ''; - + echo ''; echo ''.Display::return_icon('export_excel.png',get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).''; - echo ''.Display::return_icon('printer.png',get_lang('Print'),'',ICON_SIZE_MEDIUM).''; + echo ''.Display::return_icon('printer.png',get_lang('Print'),'',ICON_SIZE_MEDIUM).''; echo ''; - + $menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('TeacherInterface'), array(), 32), api_get_path(WEB_CODE_PATH).'mySpace/?view=teacher'); if (api_is_platform_admin()) { $menu_items[] = Display::url(Display::return_icon('star.png', get_lang('AdminInterface'), array(), 32), api_get_path(WEB_CODE_PATH).'mySpace/?view=admin'); @@ -97,24 +97,24 @@ if (!$export_to_xls) { $menu_items[] = Display::url(Display::return_icon('star.png', get_lang('CoachInterface'), array(), 32), api_get_path(WEB_CODE_PATH).'mySpace/?view=coach'); } $menu_items[] = Display::return_icon('quiz_na.png', get_lang('ExamTracking'), array(), 32); - + $nb_menu_items = count($menu_items); if($nb_menu_items>1) { foreach($menu_items as $key=> $item) { - echo $item; + echo $item; } } } else { - echo ''.get_lang('StudentsTracking').' | + echo ''.get_lang('StudentsTracking').' | '.get_lang('CourseTracking').' | '; echo ''.get_lang('ResourcesTracking').''; echo ' | '.get_lang('ExamTracking').''; - echo ' '.get_lang('ExportAsXLS').''; - - } + echo ' '.get_lang('ExportAsXLS').''; + + } echo '
'; - - $form->display(); + + $form->display(); echo '

'.sprintf(get_lang('FilteringWithScoreX'), $filter_score).'%

'; } @@ -128,10 +128,10 @@ if ($global) { $html_result .= ''.get_lang('ExamFail').''; $html_result .= ''.get_lang('TotalStudents').''; $html_result .= ''; -} else { - $html_result .= ''; +} else { + $html_result .= '
'; $html_result .= ''; - $html_result .= ''; + $html_result .= ''; //$html_result .= ''; $html_result .= ''; $html_result .= ''; @@ -146,14 +146,14 @@ if(!empty($course_list) && is_array($course_list)) foreach ($course_list as $current_course) { $global_row = $row_not_global = array(); $course_id = $current_course['real_id']; - - $a_students = CourseManager :: get_student_list_from_course_code($current_course['code'], false); + + $a_students = CourseManager :: get_student_list_from_course_code($current_course['code'], false); $total_students = count($a_students); - + $sqlExercices = "SELECT count(id) as count FROM ".$t_quiz." AS quiz WHERE active='1' AND c_id = $course_id "; $resultExercices = Database::query($sqlExercices); $data_exercises = Database::store_result($resultExercices); - $exercise_count = $data_exercises[0]['count']; + $exercise_count = $data_exercises[0]['count']; if ($global) { if ($exercise_count == 0) { $exercise_count = 2; @@ -161,25 +161,25 @@ foreach ($course_list as $current_course) { $html_result .= ""; + $html_result .= ""; } - + $sql = "SELECT visibility FROM $table WHERE c_id = $course_id AND name='quiz'"; $resultVisibilityQuizz = Database::query($sql); - - if (Database::result($resultVisibilityQuizz, 0 ,'visibility') == 1) { - $sqlExercices = " SELECT quiz.title,id FROM ".$t_quiz." AS quiz WHERE c_id = $course_id AND active='1' ORDER BY quiz.title ASC"; + + if (Database::result($resultVisibilityQuizz, 0 ,'visibility') == 1) { + $sqlExercices = " SELECT quiz.title,id FROM ".$t_quiz." AS quiz WHERE c_id = $course_id AND active='1' ORDER BY quiz.title ASC"; //Getting the exam list if (!$global) { if (!empty($exercise_id)) { - $sqlExercices = " SELECT quiz.title,id FROM ".$t_quiz." AS quiz WHERE c_id = $course_id AND active='1' AND id = $exercise_id ORDER BY quiz.title ASC"; + $sqlExercices = " SELECT quiz.title,id FROM ".$t_quiz." AS quiz WHERE c_id = $course_id AND active='1' AND id = $exercise_id ORDER BY quiz.title ASC"; } - } + } $resultExercices = Database::query($sqlExercices); $i = 0; - if (Database::num_rows($resultExercices) > 0) { + if (Database::num_rows($resultExercices) > 0) { while($a_exercices = Database::fetch_array($resultExercices)) { - $global_row[]= $current_course['title']; + $global_row[]= $current_course['title']; if (!$global) { $html_result .= ""; } @@ -187,36 +187,36 @@ foreach ($course_list as $current_course) { $html_result .= ''; - + } + + $html_result .= $a_exercices['title']; + $html_result .= ''; + $global_row[]=$a_exercices['title']; $row_not_global['exercise']= $a_exercices['title']; - + $taken = 0; $total_with_parameter = 0; $fail = 0; $not_taken = 0; - + $total_with_parameter_score = 0; $total_with_parameter_porcentage = 0; - - $student_result = array(); - - foreach ($a_students as $student ) { + + $student_result = array(); + + foreach ($a_students as $student ) { $current_student_id = $student['user_id']; $sqlEssais = " SELECT COUNT(ex.exe_id) as essais FROM $tbl_stats_exercices AS ex WHERE ex.exe_cours_id = '".$current_course['code']."' AND ex.exe_exo_id = ".$a_exercices['id']." AND exe_user_id='".$current_student_id."'"; - - - $resultEssais = Database::query($sqlEssais); - $a_essais = Database::fetch_array($resultEssais); - + + + $resultEssais = Database::query($sqlEssais); + $a_essais = Database::fetch_array($resultEssais); + $sqlScore = "SELECT exe_id, exe_result,exe_weighting FROM $tbl_stats_exercices WHERE exe_user_id = ".$current_student_id." @@ -224,42 +224,42 @@ foreach ($course_list as $current_course) { AND exe_exo_id = ".$a_exercices['id']." ORDER BY exe_result DESC LIMIT 1"; // we take the higher value //ORDER BY exe_date DESC LIMIT 1"; - + $resultScore = Database::query($sqlScore); $score = 0; - + while($a_score = Database::fetch_array($resultScore)) { $score = $score + $a_score['exe_result']; $weighting = $weighting + $a_score['exe_weighting']; $exe_id = $a_score['exe_id']; } - + $pourcentageScore = 0; if ($weighting!=0) { $pourcentageScore = round(($score*100)/$weighting); } - - $weighting = 0; - + + $weighting = 0; + if($i%2==0){ $s_css_class="row_odd"; } else { $s_css_class="row_even"; - } + } $i++; - + /*echo " "; */ - + //var_dump($pourcentageScore); /* echo " "; - + echo "'; - $user_info = $user_info['firstName'].' '.$user_info['lastName']; - - //Best result + $user_info = $user_info['firstName'].' '.$user_info['lastName']; + + //Best result if (!empty($a_essais['essais'])) { $user_row .= ''; - + if ($pourcentageScore >= $filter_score ) { $user_row .= ''; @@ -317,34 +305,34 @@ foreach ($course_list as $current_course) { $user_row .= get_lang('ExamFail').''; $temp_array [] = get_lang('ExamFail'); } - - $user_row .= ''; + $user_row .= ''; } else { $score = '-'; $user_row .= ''; - - $user_row .= ''; - $user_row .= ''; - } + } $user_row .= ''; - $student_result[$current_student_id] = array('html'=>$user_row,'score'=>$score,'array'=>$temp_array,'user'=>$user_info); + $student_result[$current_student_id] = array('html'=>$user_row,'score'=>$score,'array'=>$temp_array,'user'=>$user_info); $temp_array = array(); } } - - if (!$global) { + + if (!$global) { if (!empty($student_result)) { $student_result_empty = $student_result_content = array(); foreach($student_result as $row) { @@ -357,11 +345,11 @@ foreach ($course_list as $current_course) { //Sort only users with content usort($student_result_content, 'sort_user'); $student_result = array_merge($student_result_content, $student_result_empty ); - + foreach($student_result as $row) { $html_result .=$row['html']; $row_not_global['results'][]= $row['array']; - $row_not_global['users'][] = $row['user']; + $row_not_global['users'][] = $row['user']; } $export_array[] = $row_not_global; $row_not_global = array(); @@ -369,69 +357,69 @@ foreach ($course_list as $current_course) { } if ($global) { //Exam taken - $html_result .= ''; - - //Exam NOT taken - $html_result .= ''; - + //Examn pass if (!empty($total_with_parameter_score)) { $html_result .= ''; - - //Exam fail + + //Exam fail $html_result .= ''; - + $html_result .= ''; - $html_result .= ''; + $html_result .= ''; + $html_result .= ''; $export_array_global[] = $global_row; - $global_row = array(); + $global_row = array(); } } } else { - $html_result .= " + $html_result .= " "; - } + } } else { - $html_result .= " + $html_result .= " "; - } + } } $html_result .= '
'.get_lang('Quiz').''.get_lang('User').''.get_lang('User').''.sprintf(get_lang('ExamPassX'), $filter_score).''.get_lang('Percentage').' %'.get_lang('Status').'
"; $html_result .= $current_course['title']; - $html_result .= "
'; } else { $html_result .= ''; - } - - $html_result .= $a_exercices['title']; - $html_result .= ' "; echo $current_student_id.' '; echo " "; echo $pourcentageScore.' %'; echo " "; /* @@ -267,47 +267,35 @@ foreach ($course_list as $current_course) { echo " ";*/ - + if ($a_essais['essais'] > 0 ) { - $taken++; + $taken++; } - + if ($pourcentageScore >= $parameter_porcentage) { $total_with_parameter_porcentage++; } if ($pourcentageScore >= $filter_score) { - $total_with_parameter_score++; - } - - /* - $sql_last_attempt='SELECT exe_id FROM '.$tbl_stats_exercices.' WHERE exe_exo_id="'.$a_exercices['id'].'" AND exe_user_id="'.$current_student_id.'" AND exe_cours_id="'.$current_course['code'].'" ORDER BY exe_date DESC LIMIT 1'; - $resultLastAttempt = Database::query($sql_last_attempt); - if(Database::num_rows($resultLastAttempt)>0) { - $id_last_attempt=Database::result($resultLastAttempt,0,0); - if($a_essais['essais']>0) { - /// echo ' '; - } - } - */ - - + $total_with_parameter_score++; + } + if (!$global) { - $user_info = api_get_user_info($current_student_id); - + $user_info = api_get_user_info($current_student_id); + //User - $user_row = ''; + $user_row = ''; $user_row .= $user_info['firstName'].' '.$user_info['lastName']; $user_row .= ''; - $user_row .= $pourcentageScore; - $temp_array [] = $pourcentageScore; + $user_row .= $pourcentageScore; + $temp_array [] = $pourcentageScore; $user_row .= ''; $user_row .= get_lang('PassExam').''; + + $user_row .= ''; $user_row .= $a_essais['essais']; $temp_array [] = $a_essais['essais']; - $user_row .= ''; $user_row .= '-'; $temp_array [] = '-'; $user_row .= ''; + + $user_row .= ''; $user_row .= get_lang('NoAttempt'); $temp_array [] = get_lang('NoAttempt'); $user_row .= ''; + $user_row .= ''; $user_row .= 0; $temp_array [] = 0; $user_row .= '
'; + $html_result .= ''; $html_result .= $taken; $global_row[]= $taken; //echo $total.' / '.$total_students; $html_result .= ''; + + //Exam NOT taken + $html_result .= ''; $html_result .= $not_taken = $total_students - $taken; $global_row[]= $not_taken; $html_result .= ''; } else { $html_result .= ''; } - + $html_result .= $total_with_parameter_score; $global_row[]= $total_with_parameter_score; $html_result .= ''; $html_result .= $fail = $taken - $total_with_parameter_score; $global_row[]= $fail; $html_result .= ''; $html_result .= $total_students; $global_row[]= $total_students; - + $global_counter++; - $html_result .= '
".get_lang('NoExercise')."
".get_lang('NoExercise')."
'; if (!$export_to_xls) { - echo $html_result; + echo $html_result; } $filename = 'exam-reporting-'.date('Y-m-d-h:i:s').'.xls'; if ($export_to_xls) { @@ -451,10 +439,10 @@ function sort_user($a, $b) { } return 0; } - return 1; + return 1; } -function export_complete_report_xls($filename, $array) { +function export_complete_report_xls($filename, $array) { global $charset, $global, $filter_score; $workbook = new Spreadsheet_Excel_Writer(); $workbook ->setTempDir(api_get_path(SYS_ARCHIVE_PATH)); @@ -462,18 +450,18 @@ function export_complete_report_xls($filename, $array) { $workbook->setVersion(8); // BIFF8 $worksheet =& $workbook->addWorksheet('Report'); //$worksheet->setInputEncoding(api_get_system_encoding()); - $worksheet->setInputEncoding($charset); - + $worksheet->setInputEncoding($charset); + $line = 0; $column = 0; //skip the first column (row titles) - + if ($global) { $worksheet->write($line,$column,get_lang('Courses')); $column++; $worksheet->write($line,$column,get_lang('Exercises')); $column++; $worksheet->write($line,$column,get_lang('ExamTaken')); - $column++; + $column++; $worksheet->write($line,$column,get_lang('ExamNotTaken')); $column++; $worksheet->write($line,$column,sprintf(get_lang('ExamPassX'), $filter_score).'%'); @@ -481,45 +469,45 @@ function export_complete_report_xls($filename, $array) { $worksheet->write($line,$column,get_lang('ExamFail')); $column++; $worksheet->write($line,$column,get_lang('TotalStudents')); - $column++; - $line++; + $column++; + $line++; foreach ($array as $row) { $column = 0; - foreach ($row as $item) { + foreach ($row as $item) { $worksheet->write($line,$column,html_entity_decode(strip_tags($item))); $column++; } $line++; - } - $line++; + } + $line++; } else { $worksheet->write($line,$column,get_lang('Exercises')); $column++; $worksheet->write($line,$column,get_lang('User')); $column++; $worksheet->write($line,$column,get_lang('Percentage')); - $column++; + $column++; $worksheet->write($line,$column,get_lang('Status')); $column++; $worksheet->write($line,$column,get_lang('Attempts')); - $column++; - $line++; - foreach ($array as $row) { + $column++; + $line++; + foreach ($array as $row) { $column = 0; $worksheet->write($line,$column,html_entity_decode(strip_tags($row['exercise']))); $column++; foreach ($row['users'] as $key=>$user) { - $column = 1; + $column = 1; $worksheet->write($line,$column,html_entity_decode(strip_tags($user))); - $column++; + $column++; foreach ($row['results'][$key] as $result_item) { $worksheet->write($line,$column,html_entity_decode(strip_tags($result_item))); - $column++; + $column++; } - $line++; - } - } - $line++; + $line++; + } + } + $line++; } $workbook->close(); exit;