* @param    int field id
     * @param    array list of user ids
     * @return    array
     * @since    Nov 2009
     * @version    1.8.6.2
     */
    public static function get_addtional_profile_information_of_field_by_user($field_id, $users)
    {
    	// Database table definition
    	$table_user                 = Database::get_main_table(TABLE_MAIN_USER);
    	$table_user_field_values     = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
    	$result_extra_field         = UserManager::get_extra_field_information($field_id);
    	if (!empty($users)) {
    		if ($result_extra_field['field_type'] == UserManager::USER_FIELD_TYPE_TAG ) {
    			foreach($users as $user_id) {
    				$user_result = UserManager::get_user_tags($user_id, $field_id);
    				$tag_list = array();
    				foreach($user_result as $item) {
    					$tag_list[] = $item['tag'];
    				}
    				$return[$user_id][] = implode(', ',$tag_list);
    			}
    		} else {
    			$new_user_array = array();
    			foreach($users as $user_id) {
    				$new_user_array[]= "'".$user_id."'";
    			}
    			$users = implode(',',$new_user_array);
    			//selecting only the necessary information NOT ALL the user list
    			$sql = "SELECT user.user_id, field.field_value FROM $table_user user INNER JOIN $table_user_field_values field
                        ON (user.user_id = field.user_id)
                        WHERE field.field_id=".intval($field_id)." AND user.user_id IN ($users)";
    			$result = Database::query($sql);
    			while($row = Database::fetch_array($result)) {
    				// get option value for field type double select by id
    				if (!empty($row['field_value'])) {
    					if ($result_extra_field['field_type'] == USER_FIELD_TYPE_DOUBLE_SELECT) {
    						$id_double_select = explode(';',$row['field_value']);
    						if (is_array($id_double_select)) {
    							$value1 = $result_extra_field['options'][$id_double_select[0]]['option_value'];
    							$value2 = $result_extra_field['options'][$id_double_select[1]]['option_value'];
    							$row['field_value'] = ($value1.';'.$value2);
    						}
    					}
    				}
    				// get other value from extra field
    				$return[$row['user_id']][] = $row['field_value'];
    			}
    		}
    	}
    	return $return;
    }
    /**
     * count the number of students in this course (used for SortableTable)
     * Deprecated
     */
    public function count_student_in_course()
    {
    	global $nbStudents;
    	return $nbStudents;
    }
    public function sort_users($a, $b)
    {
    	return strcmp(trim(api_strtolower($a[$_SESSION['tracking_column']])), trim(api_strtolower($b[$_SESSION['tracking_column']])));
    }
    public function sort_users_desc($a, $b)
    {
    	return strcmp( trim(api_strtolower($b[$_SESSION['tracking_column']])), trim(api_strtolower($a[$_SESSION['tracking_column']])));
    }
    /**
     * Get number of users for sortable with pagination
     * @return int
     */
    public static function get_number_of_users()
    {
    	global $user_ids;
    	return count($user_ids);
    }
    /**
     * Get data for users list in sortable with pagination
     * @param $from
     * @param $number_of_items
     * @param $column
     * @param $direction
     * @param $includeInvitedUsers boolean Whether include the invited users
     * @return array
     */
    public static function get_user_data($from, $number_of_items, $column, $direction, $includeInvitedUsers = false)
    {
        global $user_ids, $course_code, $additional_user_profile_info, $export_csv, $is_western_name_order, $csv_content, $session_id;
    	$course_code        = Database::escape_string($course_code);
    	$tbl_user           = Database::get_main_table(TABLE_MAIN_USER);
    	$tbl_url_rel_user   = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
    	$access_url_id      = api_get_current_access_url_id();
    	// get all users data from a course for sortable with limit
    	if (is_array($user_ids)) {
    		$user_ids = array_map('intval', $user_ids);
    		$condition_user = " WHERE user.user_id IN (".implode(',',$user_ids).") ";
    	} else {
    		$user_ids = intval($user_ids);
    		$condition_user = " WHERE user.user_id = $user_ids ";
    	}
    	if (!empty($_GET['user_keyword'])) {
    		$keyword = trim(Database::escape_string($_GET['user_keyword']));
    		$condition_user .=  " AND (
                user.firstname LIKE '%".$keyword."%' OR
                user.lastname LIKE '%".$keyword."%'  OR
                user.username LIKE '%".$keyword."%'  OR
                user.email LIKE '%".$keyword."%'
             ) ";
    	}
        $url_table = null;
        $url_condition = null;
    	if (api_is_multiple_url_enabled()) {
    		$url_table = ", ".$tbl_url_rel_user."as url_users";
    		$url_condition = " AND user.user_id = url_users.user_id AND access_url_id='$access_url_id'";
    	}
        $invitedUsersCondition = '';
        if (!$includeInvitedUsers) {
            $invitedUsersCondition = " AND user.status != " . INVITEE;
        }
    	$sql = "SELECT  user.user_id as user_id,
                    user.official_code  as col0,
                    user.lastname       as col1,
                    user.firstname      as col2,
                    user.username       as col3
                FROM $tbl_user as user $url_table
    	        $condition_user $url_condition $invitedUsersCondition";
    	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);
    	$users    = array();
        $course_info = api_get_course_info($course_code);
        $total_surveys = 0;
        $total_exercises = ExerciseLib::get_all_exercises(
            $course_info,
            $session_id,
            false,
            null,
            false,
            3
        );
        if (empty($session_id)) {
            $survey_user_list = array();
            $survey_list = survey_manager::get_surveys($course_code, $session_id);
            $total_surveys = count($survey_list);
            foreach ($survey_list as $survey) {
                $user_list = survey_manager::get_people_who_filled_survey(
                    $survey['survey_id'],
                    false,
                    $course_info['real_id']
                );
                foreach ($user_list as $user_id) {
                    isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id]++ : $survey_user_list[$user_id] = 1;
                }
            }
        }
    	while ($user = Database::fetch_array($res, 'ASSOC')) {
            $courseInfo = api_get_course_info($course_code);
            $courseId = $courseInfo['real_id'];
    		$user['official_code']  = $user['col0'];
            $user['lastname']       = $user['col1'];
            $user['firstname']      = $user['col2'];
    		$user['username']       = $user['col3'];
    		$user['time'] = api_time_to_hms(Tracking::get_time_spent_on_the_course($user['user_id'], $courseId, $session_id));
            $avg_student_score = Tracking::get_avg_student_score(
                $user['user_id'],
                $course_code,
                array(),
                $session_id
            );
            $avg_student_progress = Tracking::get_avg_student_progress(
                $user['user_id'],
                $course_code,
                array(),
                $session_id
            );
    		if (empty($avg_student_progress)) {
    			$avg_student_progress=0;
    		}
    		$user['average_progress']   = $avg_student_progress.'%';
            $total_user_exercise = Tracking::get_exercise_student_progress(
                $total_exercises,
                $user['user_id'],
                $courseId,
                $session_id
            );
            $user['exercise_progress']  = $total_user_exercise;
            $total_user_exercise = Tracking::get_exercise_student_average_best_attempt(
                $total_exercises,
                $user['user_id'],
                $courseId,
                $session_id
            );
            $user['exercise_average_best_attempt'] = $total_user_exercise;
    		if (is_numeric($avg_student_score)) {
    			$user['student_score']  = $avg_student_score.'%';
    		} else {
    			$user['student_score']  = $avg_student_score;
    		}
    		$user['count_assignments'] = Tracking::count_student_assignments($user['user_id'], $course_code, $session_id);
    		$user['count_messages'] = Tracking::count_student_messages($user['user_id'], $course_code, $session_id);
    		$user['first_connection'] = Tracking::get_first_connection_date_on_the_course($user['user_id'], $courseId, $session_id);
    		$user['last_connection'] = Tracking::get_last_connection_date_on_the_course($user['user_id'], $courseId, $session_id);
    		// we need to display an additional profile field
    		$user['additional'] = '';
    		if (isset($_GET['additional_profile_field']) AND is_numeric($_GET['additional_profile_field'])) {
    			if (isset($additional_user_profile_info[$user['user_id']]) &&
                    is_array($additional_user_profile_info[$user['user_id']])
                ) {
    				$user['additional'] = implode(', ', $additional_user_profile_info[$user['user_id']]);
    			}
    		}
            if (empty($session_id)) {
                $user['survey'] = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0) .' / '.$total_surveys;
            }
    		$user['link'] = '
';
    		// store columns in array $users
    		$is_western_name_order = api_is_western_name_order();
            $user_row = array();
            $user_row[]= $user['official_code']; //0
            if ($is_western_name_order) {
                $user_row[]= $user['firstname'];
                $user_row[]= $user['lastname'];
            } else {
                $user_row[]= $user['lastname'];
                $user_row[]= $user['firstname'];
            }
            $user_row[]= $user['username'];
            $user_row[]= $user['time'];
            $user_row[]= $user['average_progress'];
            $user_row[]= $user['exercise_progress'];
            $user_row[]= $user['exercise_average_best_attempt'];
            $user_row[]= $user['student_score'];
            $user_row[]= $user['count_assignments'];
            $user_row[]= $user['count_messages'];
            if (empty($session_id)) {
                $user_row[]= $user['survey'];
            }
            $user_row[]= $user['first_connection'];
            $user_row[]= $user['last_connection'];
            if (isset($_GET['additional_profile_field']) AND is_numeric($_GET['additional_profile_field'])) {
                $user_row[]= $user['additional'];
            }
            $user_row[]= $user['link'];
            $users[] = $user_row;
    		if ($export_csv) {
    		    if (empty($session_id)) {
                    $user_row = array_map('strip_tags', $user_row);
    			    unset($user_row[14]);
    			    unset($user_row[15]);
                } else {
                    $user_row = array_map('strip_tags', $user_row);
                    unset($user_row[13]);
                    unset($user_row[14]);
                }
    			$csv_content[] = $user_row;
    		}
    	}
    	return $users;
    }
}
/**
 * @package chamilo.tracking
 */
class TrackingUserLog
{
    /**
     * Displays the number of logins every month for a specific user in a specific course.
     * @param $view
     * @param int $user_id
     * @param int $course_id
     * @param int $session_id
     */
    public function display_login_tracking_info($view, $user_id, $course_id, $session_id = 0)
    {
    	$MonthsLong = $GLOBALS['MonthsLong'];
    	// protected data
    	$user_id = intval($user_id);
    	$session_id = intval($session_id);
    	$course_id = Database::escape_string($course_id);
    	$track_access_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
    	$tempView = $view;
    	if(substr($view,0,1) == '1') {
    		$new_view = substr_replace($view,'0',0,1);
    		echo "
                
                    | 
                    -   " .
                    "".get_lang('LoginsAndAccessTools')."   [".get_lang('Close')."]   [".get_lang('ExportAsCSV')."]
                     | 
                
                ";
    		echo "".get_lang('LoginsDetails')." ";
    		$sql = "SELECT UNIX_TIMESTAMP(access_date), count(access_date)
                        FROM $track_access_table
                        WHERE access_user_id = $user_id
                        AND c_id = $course_id
                        AND access_session_id = $session_id
                        GROUP BY YEAR(access_date),MONTH(access_date)
                        ORDER BY YEAR(access_date),MONTH(access_date) ASC";
    		echo " | 
";
    		//$results = getManyResults2Col($sql);
    		$results = getManyResults3Col($sql);
    		echo "";
    		echo "
                    | 
                    ".get_lang('LoginsTitleMonthColumn')."
                     | 
                    
                    ".get_lang('LoginsTitleCountColumn')."
                     | 
                 ";
    		$total = 0;
    		if (is_array($results)) {
    			for($j = 0 ; $j < count($results) ; $j++) {
    				echo "";
    				echo "| ".$MonthsLong[date('n', $results[$j][0])-1].' '.date('Y', $results[$j][0])." | ";
    				echo "".$results[$j][1]." | ";
    				echo" ";
    				$total = $total + $results[$j][1];
    			}
    			echo "";
    			echo "| ".get_lang('Total')." | ";
    			echo "".$total." | ";
    			echo" ";
    		} else {
    			echo "";
    			echo "| ".get_lang('NoResult')." | ";
    			echo" ";
    		}
    		echo " ";
    		echo " | 
";
    	} else {
    		$new_view = substr_replace($view,'1',0,1);
    		echo "
                
                    | 
                    +  ".get_lang('LoginsAndAccessTools')."
                     | 
                
            ";
    	}
    }
    /**
     * Displays the exercise results for a specific user in a specific course.
     * @param   string $view
     * @param   int $user_id    User ID
     * @param   string  $courseCode Course code
     * @return array
     * @todo remove globals
     */
    public function display_exercise_tracking_info($view, $user_id, $courseCode)
    {
    	global $TBL_TRACK_HOTPOTATOES, $TABLECOURSE_EXERCICES, $TABLETRACK_EXERCICES, $dateTimeFormatLong;
        $courseId = api_get_course_int_id($courseCode);
    	if(substr($view,1,1) == '1') {
    		$new_view = substr_replace($view,'0',1,1);
    		echo "
                    | 
                        -   ".get_lang('ExercicesResults')."   [".get_lang('Close')."]   [".get_lang('ExportAsCSV')."]
                     | 
                
";
    		echo "".get_lang('ExercicesDetails')." ";
    		$sql = "SELECT ce.title, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
                FROM $TABLECOURSE_EXERCICES AS ce , $TABLETRACK_EXERCICES AS te
                WHERE te.c_id = $courseId
                    AND te.exe_user_id = ".intval($user_id)."
                    AND te.exe_exo_id = ce.id
                ORDER BY ce.title ASC, te.exe_date ASC";
    		$hpsql = "SELECT te.exe_name, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
                FROM $TBL_TRACK_HOTPOTATOES AS te
                WHERE te.exe_user_id = '".intval($user_id)."' AND te.c_id = $courseId
                ORDER BY te.c_id ASC, te.exe_date ASC";
    		$hpresults = StatsUtils::getManyResultsXCol($hpsql, 4);
    		$NoTestRes = 0;
    		$NoHPTestRes = 0;
    		echo " | 
\n\n";
    		$results = StatsUtils::getManyResultsXCol($sql, 4);
    		echo "\n";
    		echo "
                
                    | 
                    ".get_lang('ExercicesTitleExerciceColumn')."
                     | 
                    
                    ".get_lang('Date')."
                     | 
                    
                    ".get_lang('ExercicesTitleScoreColumn')."
                     | 
                 ";
    		if (is_array($results)) {
    			for($i = 0; $i < sizeof($results); $i++) {
    				$display_date = api_convert_and_format_date($results[$i][3], null, date_default_timezone_get());
    				echo "\n";
    				echo "| ".$results[$i][0]." | \n";
    				echo "".$display_date." | \n";
    				echo "".$results[$i][1]." / ".$results[$i][2]." | \n";
    				echo " \n";
    			}
    		} else {
    			// istvan begin
    			$NoTestRes = 1;
    		}
    		// The Result of Tests
    		if(is_array($hpresults)) {
    			for($i = 0; $i < sizeof($hpresults); $i++) {
    				$title = GetQuizName($hpresults[$i][0],'');
    				if ($title == '')
    				$title = basename($hpresults[$i][0]);
    				$display_date = api_convert_and_format_date($hpresults[$i][3], null, date_default_timezone_get());
    				?>
     | 
     | 
     / 
     | 
 
\n";
    			echo "".get_lang('NoResult')." | \n";
    			echo "\n";
    		}
    		echo " ";
    		echo " | \n
\n";
    	} else {
    		$new_view = substr_replace($view,'1',1,1);
    		echo "
                
                    | 
                        +  ".get_lang('ExercicesResults')."
                     | 
                
";
    	}
    }
    /**
     * Displays the student publications for a specific user in a specific course.
     * @todo remove globals
     */
    public function display_student_publications_tracking_info($view, $user_id, $course_id)
    {
    	global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK, $dateTimeFormatLong, $_course;
    	if (substr($view,2,1) == '1') {
    		$new_view = substr_replace($view,'0',2,1);
    		echo "
                        | 
                        -   ".get_lang('WorkUploads')."   [".get_lang('Close')."]   [".get_lang('ExportAsCSV')."]
                         | 
                
";
    		echo "".get_lang('WorksDetails')." ";
    		$sql = "SELECT u.upload_date, w.title, w.author,w.url
                    FROM $TABLETRACK_UPLOADS u , $TABLECOURSE_WORK w
                    WHERE u.upload_work_id = w.id
                        AND u.upload_user_id = '".intval($user_id)."'
                        AND u.c_id = '".intval($course_id)."'
                    ORDER BY u.upload_date DESC";
    		echo " | 
";
    		$results = StatsUtils::getManyResultsXCol($sql,4);
    		echo "";
    		echo "
                    | 
                    ".get_lang('WorkTitle')."
                     | 
                    
                    ".get_lang('WorkAuthors')."
                     | 
                    
                    ".get_lang('Date')."
                     | 
                 ";
    		if (is_array($results)) {
    			for($j = 0 ; $j < count($results) ; $j++) {
    				$pathToFile = api_get_path(WEB_COURSE_PATH).$_course['path']."/".$results[$j][3];
    				$beautifulDate = api_convert_and_format_date($results[$j][0], null, date_default_timezone_get());
    				echo "";
    				echo "| "
    				."".$results[$j][1].""
    				." | ";
    				echo "".$results[$j][2]." | ";
    				echo "".$beautifulDate." | ";
    				echo" ";
    			}
    		} else {
    			echo "";
    			echo "| ".get_lang('NoResult')." | ";
    			echo" ";
    		}
    		echo " ";
    		echo " | 
";
    	} else {
    		$new_view = substr_replace($view,'1',2,1);
    		echo "
                
                        | 
                        +  ".get_lang('WorkUploads')."
                         | 
                
            ";
    	}
    }
    /**
     * Displays the links followed for a specific user in a specific course.
     * @todo remove globals
     */
    public function display_links_tracking_info($view, $user_id, $courseCode)
    {
    	global $TABLETRACK_LINKS, $TABLECOURSE_LINKS;
        $courseId = api_get_course_int_id($courseCode);
    	if (substr($view,3,1) == '1') {
    		$new_view = substr_replace($view,'0',3,1);
    		echo "
                
                        | 
                        -   ".get_lang('LinksAccess')."   [".get_lang('Close')."]   [".get_lang('ExportAsCSV')."]
                         | 
                
            ";
    		echo "".get_lang('LinksDetails')." ";
    		$sql = "SELECT cl.title, cl.url
                        FROM $TABLETRACK_LINKS AS sl, $TABLECOURSE_LINKS AS cl
                        WHERE sl.links_link_id = cl.id
                            AND sl.c_id = $courseId
                            AND sl.links_user_id = ".intval($user_id)."
                        GROUP BY cl.title, cl.url";
    		echo " | 
";
    		$results = StatsUtils::getManyResults2Col($sql);
    		echo "";
    		echo "
                    | 
                    ".get_lang('LinksTitleLinkColumn')."
                     | 
                 ";
    		if (is_array($results)) {
    			for($j = 0 ; $j < count($results) ; $j++) {
    				echo "";
    				echo "| ".$results[$j][0]." | ";
    				echo" ";
    			}
    		} else {
    			echo "";
    			echo "| ".get_lang('NoResult')." | ";
    			echo" ";
    		}
    		echo " ";
    		echo " | 
";
    	} else {
    		$new_view = substr_replace($view,'1',3,1);
    		echo "
                
                        | 
                        +  ".get_lang('LinksAccess')."
                         | 
                
            ";
    	}
    }
    /**
     * Displays the documents downloaded for a specific user in a specific course.
     * @param     string    kind of view inside tracking info
     * @param    int        User id
     * @param    string    Course code
     * @param    int        Session id (optional, default = 0)
     * @return     void
     */
    public static function display_document_tracking_info($view, $user_id, $course_code, $session_id = 0) {
    	// protect data
    	$user_id     = intval($user_id);
        $courseId = api_get_course_int_id($course_code);
    	$session_id = intval($session_id);
    	$downloads_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
    	if(substr($view,4,1) == '1') {
    		$new_view = substr_replace($view,'0',4,1);
    		echo "
                
                        | 
                        -   ".get_lang('DocumentsAccess')."   [".get_lang('Close')."]   [".get_lang('ExportAsCSV')."]
                         | 
                
            ";
    		echo "".get_lang('DocumentsDetails')." ";
    		$sql = "SELECT down_doc_path
                        FROM $downloads_table
                        WHERE c_id = $courseId
                            AND down_user_id = $user_id
                            AND down_session_id = $session_id
                        GROUP BY down_doc_path";
    		echo " | 
";
    		$results = StatsUtils::getManyResults1Col($sql);
    		echo "";
    		echo "
                    | 
                    ".get_lang('DocumentsTitleDocumentColumn')."
                     | 
                 ";
    		if (is_array($results)) {
    			for($j = 0 ; $j < count($results) ; $j++) {
    				echo "";
    				echo "| ".$results[$j]." | ";
    				echo" ";
    			}
    		} else {
    			echo "";
    			echo "| ".get_lang('NoResult')." | ";
    			echo" ";
    		}
    		echo " ";
    		echo " | 
";
    	} else {
    		$new_view = substr_replace($view,'1',4,1);
    		echo "
                
                        | 
                        +  ".get_lang('DocumentsAccess')."
                         | 
                
            ";
    	}
    }
    /**
     * Gets the IP of a given user, using the last login before the given date
     * @param int User ID
     * @param string Datetime
     * @param bool Whether to return the IP as a link or just as an IP
     * @param string If defined and return_as_link if true, will be used as the text to be shown as the link
     * @return string IP address (or false on error)
     * @assert (0,0) === false
     */
    public static function get_ip_from_user_event($user_id, $event_date, $return_as_link = false, $body_replace = null) {
        if (empty($user_id) or empty($event_date)) {
            return false;
        }
        $table_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
        $sql_ip = "SELECT login_date, user_ip FROM $table_login WHERE login_user_id = $user_id AND login_date < '$event_date' ORDER BY login_date DESC LIMIT 1";
        $ip = '';
        $res_ip = Database::query($sql_ip);
        if ($res_ip !== false && Database::num_rows($res_ip)>0) {
            $row_ip = Database::fetch_row($res_ip);
            if ($return_as_link) {
                $ip = Display::url((empty($body_replace)?$row_ip[1]:$body_replace), 'http://www.whatsmyip.org/ip-geo-location/?ip='.$row_ip[1], array('title'=>get_lang('TraceIP'), 'target'=>'_blank'));
            } else {
                $ip = $row_ip[1];
            }
        }
        return $ip;
    }
}
/**
 * @package chamilo.tracking
 */
class TrackingUserLogCSV
{
    /**
     * Displays the number of logins every month for a specific user in a specific course.
     * @param $view
     * @param int $user_id
     * @param int $course_id
     * @param int $session_id
     * @return array
     */
    public function display_login_tracking_info($view, $user_id, $course_id, $session_id = 0)
    {
    	$MonthsLong = $GLOBALS['MonthsLong'];
    	$track_access_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
    	// protected data
    	$user_id    = intval($user_id);
    	$session_id = intval($session_id);
    	$course_id  = intval($course_id);
    	$tempView = $view;
    	if (substr($view,0,1) == '1') {
    		$new_view = substr_replace($view,'0',0,1);
    		$title[1]= get_lang('LoginsAndAccessTools').get_lang('LoginsDetails');
    		$sql = "SELECT UNIX_TIMESTAMP(access_date), count(access_date)
                    FROM $track_access_table
                    WHERE access_user_id = $user_id
                    AND c_id = $course_id
                    AND access_session_id = $session_id
                    GROUP BY YEAR(access_date),MONTH(access_date)
                    ORDER BY YEAR(access_date),MONTH(access_date) ASC";
    		//$results = getManyResults2Col($sql);
    		$results = getManyResults3Col($sql);
    		$title_line= get_lang('LoginsTitleMonthColumn').';'.get_lang('LoginsTitleCountColumn')."\n";
    		$line='';
    		$total = 0;
    		if (is_array($results)) {
    			for($j = 0 ; $j < count($results) ; $j++) {
    				$line .= $results[$j][0].';'.$results[$j][1]."\n";
    				$total = $total + $results[$j][1];
    			}
    			$line .= get_lang('Total').";".$total."\n";
    		} else {
    			$line= get_lang('NoResult')."";
    		}
    	} else {
    		$new_view = substr_replace($view,'1',0,1);
    	}
    	return array($title_line, $line);
    }
    /**
     * Displays the exercise results for a specific user in a specific course.
     * @param   string $view
     * @param   int $user_id    User ID
     * @param   string  $courseCode Course code
     * @return array
     * @todo remove globals
     */
    public function display_exercise_tracking_info($view, $userId, $courseCode)
    {
    	global $TABLECOURSE_EXERCICES, $TABLETRACK_EXERCICES, $TABLETRACK_HOTPOTATOES, $dateTimeFormatLong;
        $courseId = api_get_course_int_id($courseCode);
        $userId = intval($userId);
    	if (substr($view,1,1) == '1') {
    		$new_view = substr_replace($view,'0',1,1);
    		$title[1] = get_lang('ExercicesDetails');
    		$line = '';
    		$sql = "SELECT ce.title, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
                FROM $TABLECOURSE_EXERCICES AS ce , $TABLETRACK_EXERCICES AS te
                WHERE te.c_id = $courseId
                    AND te.exe_user_id = $userId
                    AND te.exe_exo_id = ce.id
                ORDER BY ce.title ASC, te.exe_date ASC";
    		$hpsql = "SELECT te.exe_name, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
                FROM $TABLETRACK_HOTPOTATOES AS te
                WHERE te.exe_user_id = '$userId' AND te.c_id = $courseId
                ORDER BY te.c_id ASC, te.exe_date ASC";
    		$hpresults = StatsUtils::getManyResultsXCol($hpsql, 4);
    		$NoTestRes = 0;
    		$NoHPTestRes = 0;
    		$results = StatsUtils::getManyResultsXCol($sql, 4);
    		$title_line = get_lang('ExercicesTitleExerciceColumn').";".get_lang('Date').';'.get_lang('ExercicesTitleScoreColumn')."\n";
    		if (is_array($results)) {
    			for($i = 0; $i < sizeof($results); $i++)
    			{
    				$display_date = api_convert_and_format_date($results[$i][3], null, date_default_timezone_get());
    				$line .= $results[$i][0].";".$display_date.";".$results[$i][1]." / ".$results[$i][2]."\n";
    			}
    		} else {
                // istvan begin
    			$NoTestRes = 1;
    		}
    		// The Result of Tests
    		if (is_array($hpresults)) {
    			for($i = 0; $i < sizeof($hpresults); $i++) {
    				$title = GetQuizName($hpresults[$i][0],'');
    				if ($title == '')
    				$title = basename($hpresults[$i][0]);
    				$display_date = api_convert_and_format_date($hpresults[$i][3], null, date_default_timezone_get());
    				$line .= $title.';'.$display_date.';'.$hpresults[$i][1].'/'.$hpresults[$i][2]."\n";
    			}
    		} else {
    			$NoHPTestRes = 1;
    		}
    		if ($NoTestRes == 1 && $NoHPTestRes == 1) {
    			$line=get_lang('NoResult');
    		}
    	} else {
    		$new_view = substr_replace($view,'1',1,1);
    	}
    	return array($title_line, $line);
    }
    /**
     * Displays the student publications for a specific user in a specific course.
     * @todo remove globals
     */
    public function display_student_publications_tracking_info($view, $user_id, $course_id)
    {
    	global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK, $dateTimeFormatLong, $_course;
        $user_id = intval($user_id);
        $course_id = intval($course_id);
    	if (substr($view,2,1) == '1') {
    		$sql = "SELECT u.upload_date, w.title, w.author, w.url
                    FROM $TABLETRACK_UPLOADS u , $TABLECOURSE_WORK w
                    WHERE
                        u.upload_work_id = w.id AND
                        u.upload_user_id = '$user_id' AND
                        u.c_id = '$course_id'
                    ORDER BY u.upload_date DESC";
    		$results = StatsUtils::getManyResultsXCol($sql,4);
    		$title[1]=get_lang('WorksDetails');
    		$line='';
    		$title_line=get_lang('WorkTitle').";".get_lang('WorkAuthors').";".get_lang('Date')."\n";
    		if (is_array($results)) {
    			for($j = 0 ; $j < count($results) ; $j++) {
    				$pathToFile = api_get_path(WEB_COURSE_PATH).$_course['path']."/".$results[$j][3];
    				$beautifulDate = api_convert_and_format_date($results[$j][0], null, date_default_timezone_get());
    				$line .= $results[$j][1].";".$results[$j][2].";".$beautifulDate."\n";
    			}
    		} else {
    			$line= get_lang('NoResult');
    		}
    	}
    	return array($title_line, $line);
    }
    /**
     * Displays the links followed for a specific user in a specific course.
     * @todo remove globals
     */
    public function display_links_tracking_info($view, $userId, $courseCode)
    {
    	global $TABLETRACK_LINKS, $TABLECOURSE_LINKS;
        $courseId = api_get_course_int_id($courseCode);
        $userId = intval($userId);
        $line = null;
    	if (substr($view,3,1) == '1') {
    		$new_view = substr_replace($view,'0',3,1);
    		$title[1]=get_lang('LinksDetails');
    		$sql = "SELECT cl.title, cl.url
                        FROM $TABLETRACK_LINKS AS sl, $TABLECOURSE_LINKS AS cl
                        WHERE sl.links_link_id = cl.id
                            AND sl.c_id = $courseId
                            AND sl.links_user_id = $userId
                        GROUP BY cl.title, cl.url";
    		$results = StatsUtils::getManyResults2Col($sql);
    		$title_line= get_lang('LinksTitleLinkColumn')."\n";
    		if (is_array($results)) {
    			for ($j = 0 ; $j < count($results) ; $j++) {
    				$line .= $results[$j][0]."\n";
    			}
    		} else {
    			$line=get_lang('NoResult');
    		}
    	} else {
    		$new_view = substr_replace($view,'1',3,1);
    	}
    	return array($title_line, $line);
    }
    /**
     * Displays the documents downloaded for a specific user in a specific course.
     * @param     string    kind of view inside tracking info
     * @param    int        User id
     * @param    string    Course code
     * @param    int        Session id (optional, default = 0)
     * @return     void
     */
    public function display_document_tracking_info($view, $user_id, $courseCode, $session_id = 0)
    {
    	// protect data
    	$user_id     = intval($user_id);
        $courseId = api_get_course_int_id($courseCode);
    	$session_id = intval($session_id);
    	$downloads_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
    	if (substr($view,4,1) == '1') {
    		$new_view = substr_replace($view,'0',4,1);
    		$title[1]= get_lang('DocumentsDetails');
    		$sql = "SELECT down_doc_path
                        FROM $downloads_table
                        WHERE c_id = $courseId
                            AND down_user_id = $user_id
                            AND down_session_id = $session_id
                        GROUP BY down_doc_path";
    		$results = StatsUtils::getManyResults1Col($sql);
    		$title_line = get_lang('DocumentsTitleDocumentColumn')."\n";
            $line = null;
    		if (is_array($results)) {
    			for ($j = 0 ; $j < count($results) ; $j++) {
    				$line .= $results[$j]."\n";
    			}
    		} else {
    			$line = get_lang('NoResult');
    		}
    	} else {
    		$new_view = substr_replace($view,'1',4,1);
    	}
    	return array($title_line, $line);
    }
    /**
     * @param $userId
     * @param $courseInfo
     * @param int $sessionId
     * @return array
     */
    public static function getToolInformation(
        $userId,
        $courseInfo,
        $sessionId = 0
    ) {
        $csvContent = array();
        $courseToolInformation = null;
        $headerTool = array(
            array(get_lang('Title')),
            array(get_lang('CreatedAt')),
            array(get_lang('UpdatedAt')),
        );
        $headerListForCSV = array();
        foreach ($headerTool as $item) {
            $headerListForCSV[] = $item[0];
        }
        $courseForumInformationArray = getForumCreatedByUser(
            $userId,
            $courseInfo['real_id'],
            $sessionId
        );
        if (!empty($courseForumInformationArray)) {
            $csvContent[] = array();
            $csvContent[] = get_lang('Forums');
            $csvContent[] = $headerListForCSV;
            foreach ($courseForumInformationArray as $row) {
                $csvContent[] = $row;
            }
            $courseToolInformation .= Display::page_subheader2(
                get_lang('Forums')
            );
            $courseToolInformation .= Display::return_sortable_table(
                $headerTool,
                $courseForumInformationArray
            );
        }
        $courseWorkInformationArray = getWorkCreatedByUser(
            $userId,
            $courseInfo['real_id'],
            $sessionId
        );
        if (!empty($courseWorkInformationArray)) {
            $csvContent[] = null;
            $csvContent[] = get_lang('Works');
            $csvContent[] = $headerListForCSV;
            foreach ($courseWorkInformationArray as $row) {
                $csvContent[] = $row;
            }
            $csvContent[] = null;
            $courseToolInformation .= Display::page_subheader2(
                get_lang('Works')
            );
            $courseToolInformation .= Display::return_sortable_table(
                $headerTool,
                $courseWorkInformationArray
            );
        }
        $courseToolInformationTotal = null;
        if (!empty($courseToolInformation)) {
            $sessionTitle = null;
            if (!empty($sessionId)) {
                $sessionTitle = ' ('.api_get_session_name($sessionId).')';
            }
            $courseToolInformationTotal .= Display::page_subheader(
                $courseInfo['title'].$sessionTitle
            );
            $courseToolInformationTotal .= $courseToolInformation;
        }
        return array(
            'array' => $csvContent,
            'html' => $courseToolInformationTotal
        );
    }
}