소스 검색

Dates refactoring - Chamilo - CT#696

Guillaume Viguier 15 년 전
부모
커밋
7afd8c72d2

+ 2 - 2
main/attendance/attendance_controller.php

@@ -224,7 +224,7 @@
 			if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST") {	
 				if (!isset($_POST['cancel'])) {												
 					$datetime = $attendance->build_datetime_from_array($_POST['date_time']);					
-					$datetimezone = api_get_utc_datetime(strtotime($datetime));					
+					$datetimezone = api_get_utc_datetime($datetime);					
 					if (!empty($datetime)) {						
 						$attendance->set_date_time($datetimezone);
 						$affected_rows = $attendance->attendant_calendar_add($attendance_id);
@@ -241,7 +241,7 @@
 			if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST") {					
 				if (!isset($_POST['cancel'])) {										
 					$datetime = $attendance->build_datetime_from_array($_POST['date_time']);									
-					$datetimezone = api_get_utc_datetime(strtotime($datetime));								
+					$datetimezone = api_get_utc_datetime($datetime);								
 					$attendance->set_date_time($datetimezone);					
 					$affected_rows = $attendance->attendant_calendar_edit($calendar_id, $attendance_id);
 					$data['calendar_id'] = 0;

+ 4 - 4
main/dropbox/index.php

@@ -433,8 +433,8 @@ if ($_GET['action'] != 'add') {
 				$dropbox_file_data[] = $dropbox_file->author;
 				//$dropbox_file_data[] = $dropbox_file->description;
 
-				$last_upload_date = api_get_local_time($dropbox_file->last_upload_date, 'Y-m-d H:i:s', null, date_default_timezone_get());
-				$dropbox_file_data[] = date_to_str_ago($last_upload_date).'<br /><span class="dropbox_date">'.api_format_date_time_long($last_upload_date).'</span>';
+				$last_upload_date = api_get_local_time($dropbox_file->last_upload_date, null, date_default_timezone_get());
+				$dropbox_file_data[] = date_to_str_ago($last_upload_date).'<br /><span class="dropbox_date">'.api_format_date($last_upload_date).'</span>';
 
 				$action_icons = check_number_feedback($dropbox_file->id, $number_feedback).' '.get_lang('Feedback').'
 									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=viewfeedback&amp;id='.$dropbox_file->id.'">'.Display::return_icon('comment_bubble.gif', get_lang('Comment')).'</a>
@@ -582,8 +582,8 @@ if ($_GET['action'] != 'add') {
 				}
 				$receivers_celldata = trim(trim($receivers_celldata), ','); // Removing the trailing comma.
 				$dropbox_file_data[] = $receivers_celldata;
-				$last_upload_date = api_get_local_time($dropbox_file->last_upload_date, 'Y-m-d H:i:s', null, date_default_timezone_get());
-				$dropbox_file_data[] = date_to_str_ago($last_upload_date).'<br /><span class="dropbox_date">'.api_format_date_time_long($last_upload_date).'</span>';
+				$last_upload_date = api_get_local_time($dropbox_file->last_upload_date, null, date_default_timezone_get());
+				$dropbox_file_data[] = date_to_str_ago($last_upload_date).'<br /><span class="dropbox_date">'.api_format_date($last_upload_date).'</span>';
 
 				//$dropbox_file_data[] = $dropbox_file->author;
 				$receivers_celldata = '';

+ 2 - 2
main/gradebook/gradebook_flatview.php

@@ -133,7 +133,7 @@ if (isset ($_GET['exportpdf']))	{
 		$html .= '<h1 align="center">'.get_lang('FlatView').'</h1>';
 
 		$html .= '<p><strong>'.$report_name.'</strong></p>';
-		$html .= '<p><strong>'.api_format_date(DATE_TIME_FORMAT_LONG, $time).'</strong></p>';
+		$html .= '<p><strong>'.api_convert_and_format_date().'</strong></p>';
 		$html .= '<p><strong>'.get_lang('By').': '.$creator.'</strong></p>';
 
 		$columns = count($printable_data[0]);
@@ -320,4 +320,4 @@ if (isset($_GET['isStudentView']) && $_GET['isStudentView'] == 'false') {
 	echo '</div>';
 }
 
-Display :: display_footer();
+Display :: display_footer();

+ 3 - 4
main/inc/lib/attendance.lib.php

@@ -611,8 +611,7 @@ class Attendance
 				$res = Database::query($sql);
 				if (Database::num_rows($res) > 0) {
 					while ($row = Database::fetch_array($res)) {
-						$row['date_time'] = api_get_local_time($row['date_time'], $dateTimeFormatLong, null, date_default_timezone_get());
-						//$row['date_time'] = api_format_date($dateTimeFormatLong, strtotime($row['date_time']));
+						$row['date_time'] = api_convert_and_format_date($row['date_time'], null, date_default_timezone_get());
 						$data[$user_id][] = $row;
 					}
 				}
@@ -694,8 +693,8 @@ class Attendance
 		if (Database::num_rows($rs) > 0) {
 			while ($row = Database::fetch_array($rs)) {				
 				$row['date_time'] = api_get_local_time($row['date_time']);				
-				$row['date'] = api_format_date($dateFormatShort, strtotime($row['date_time']));
-				$row['time'] = api_format_date($timeNoSecFormat, strtotime($row['date_time']));
+				$row['date'] = api_format_date($row['date_time'], DATE_FORMAT_SHORT);
+				$row['time'] = api_format_date($row['date_time'], TIME_NO_SEC_FORMAT);
 				$data[] = $row;
 			}
 		}

+ 64 - 48
main/inc/lib/internationalization.lib.php

@@ -22,6 +22,7 @@ define('TIME_NO_SEC_FORMAT', 0);	// 15:23
 define('DATE_FORMAT_SHORT', 1);		// 25.08.2009
 define('DATE_FORMAT_LONG', 2);		// Aug 25, 09
 define('DATE_TIME_FORMAT_LONG', 3);	// August 25, 2009 at 03:28 PM
+define('DATE_FORMAT_LONG_WITHOUT_DAY', 4);
 
 // Formatting person's name.
 define('PERSON_NAME_COMMON_CONVENTION', 0);	// Formatting a person's name using the pattern as it has been
@@ -386,83 +387,98 @@ function api_detect_language(&$string, $encoding = null) {
 
 /**
  * Returns formated date/time, correspondent to a given language.
+ * The given date should be in the timezone chosen by the administrator and/or user. Use api_get_local_time to get it.
+ * 
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  * @author Christophe Gesche<gesche@ipm.ucl.ac.be>
  *         originally inspired from from PhpMyAdmin
  * @author Ivan Tcholakov, 2009, code refactoring, adding support for predefined date/time formats.
- * @param string/int $date_format			The date pattern. See the php-manual about the function strftime().
- * Note: For $date_format the following integer constants may be used for using predefined date/time
- * formats in the Chamilo system: TIME_NO_SEC_FORMAT, DATE_FORMAT_SHORT, DATE_FORMAT_LONG, DATE_TIME_FORMAT_LONG.
- * @param int/string $time_stamp (optional)	Time as an integer value. The default value -1 means now, the function time() is called internally.
- * 											This parameter also could be a string, 'Y-m-d H:i:s' formatted.
+ * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
+ * 
+ * @param mixed Timestamp or datetime string
+ * @param mixed Date format (string or int; see date formats in the Chamilo system: TIME_NO_SEC_FORMAT, DATE_FORMAT_SHORT, DATE_FORMAT_LONG, DATE_TIME_FORMAT_LONG, DATE_FORMAT_LONG_WITHOUT_DAY)
  * @param string $language (optional)		Language indentificator. If it is omited, the current interface language is assumed.
  * @return string							Returns the formatted date.
+ * 
  * @link http://php.net/manual/en/function.strftime.php
  */
-function api_format_date($date_format, $time_stamp = -1, $language = null) {
-	if ($time_stamp == -1) {
-		$time_stamp = time();
-	}
-	if (is_string($time_stamp)) {
-		$time_stamp = strtotime($time_stamp);
-	}
-	if (is_int($date_format)) {
-		switch ($date_format) {
+function api_format_date($time, $format = null, $language = null) {
+	
+	$system_timezone = date_default_timezone_get();
+	date_default_timezone_set(_api_get_timezone());
+	
+	if (is_string($time)) {
+		$time = strtotime($time);
+	}
+	
+	if (is_null($format)) {
+		$format = DATE_TIME_FORMAT_LONG;
+	}
+	
+	$datetype = null;
+	$timetype = null;
+	if(is_int($format)) {
+		switch ($format) {
 			case TIME_NO_SEC_FORMAT:
 				$date_format = get_lang('timeNoSecFormat', '', $language);
+				if (IS_PHP_53) {
+					$datetype = IntlDateFormatter::NONE;
+					$timetype = IntlDateFormatter::SHORT;
+				}
 				break;
 			case DATE_FORMAT_SHORT:
 				$date_format = get_lang('dateFormatShort', '', $language);
+				if (IS_PHP_53) {
+					$datetype = IntlDateFormatter::LONG;
+					$timetype = IntlDateFormatter::NONE;
+				}
 				break;
 			case DATE_FORMAT_LONG:
-				$date_format = get_lang('dateFormatShort', '', $language);
+				$date_format = get_lang('dateFormatLong', '', $language);
+				if (IS_PHP_53) {
+					$datetype = IntlDateFormatter::FULL;
+					$timetype = IntlDateFormatter::NONE;
+				}
 				break;
 			case DATE_TIME_FORMAT_LONG:
 				$date_format = get_lang('dateTimeFormatLong', '', $language);
+				if (IS_PHP_53) {
+					$datetype = IntlDateFormatter::FULL;
+					$timetype = IntlDateFormatter::SHORT;
+				}
+				break;
+			case DATE_FORMAT_LONG_WITHOUT_DAY:
+				$date_format = get_lang('DateFormatLongWithoutDay', '', $language);
 				break;
 			default:
 				$date_format = get_lang('dateTimeFormatLong', '', $language);
+				if (IS_PHP_53) {
+					$datetype = IntlDateFormatter::FULL;
+					$timetype = IntlDateFormatter::SHORT;
+				}
 		}
 	}
-	// We replace %a %A %b %B masks of date format with translated strings.
-	$translated = &_api_get_day_month_names($language);
-	$date_format = str_replace(array('%A', '%a', '%B', '%b'),
+	
+	if (IS_PHP_53 && INTL_INSTALLED && $datetype !== null && $timetype !== null) {
+		// Use ICU
+		if (is_null($language)) {
+			$language = api_get_language_isocode();
+		}
+		$date_formatter = datefmt_create($language, $datetype, $timetype, date_default_timezone_get());
+		$formatted_date = api_to_system_encoding(datefmt_format($date_formatter, $time), 'UTF-8');
+	} else {
+		// We replace %a %A %b %B masks of date format with translated strings.
+		$translated = &_api_get_day_month_names($language);
+		$date_format = str_replace(array('%A', '%a', '%B', '%b'),
 		array($translated['days_long'][(int)strftime('%w', $time_stamp)],
 			$translated['days_short'][(int)strftime('%w', $time_stamp)],
 			$translated['months_long'][(int)strftime('%m', $time_stamp) - 1],
 			$translated['months_short'][(int)strftime('%m', $time_stamp) - 1]),
 		$date_format);
-	return strftime($date_format, $time_stamp);
-}
-
-/**
- * Returns date and time with long format correspondent to a given language.
- * This function is a workaround, it is designed to work for PHP 5.2.x and PHP 5.3+.
- * @author Ivan Tcholakov, 2010
- * @param int/string $time_stamp (optional)	Time as an integer value. The default value -1 means now, the function time() is called internally.
- * 											This parameter also could be a string, 'Y-m-d H:i:s' formatted.
- * @param string $language (optional)		Language indentificator. If it is omited, the current interface language is assumed.
- * @return string							Returns the formatted date.
- */
-function api_format_date_time_long($time_stamp = -1, $language = null) {
-	static $date_formatter; // Holds the IntlDateFormatter object that should be created only once, for performance.
-	if ($time_stamp == -1) {
-		$time_stamp = time();
-	}
-	if (is_string($time_stamp)) {
-		$time_stamp = strtotime($time_stamp);
-	}
-	if (IS_PHP_53 && INTL_INSTALLED && !isset($date_formatter)) {
-		$locale = _api_get_locale_from_language($language);
-		$date_formatter = datefmt_create($locale, IntlDateFormatter::FULL, IntlDateFormatter::SHORT);
-		if (!is_object($date_formatter)) {
-			$date_formatter = false;
-		}
-	}
-	if ($date_formatter) {
-		return api_to_system_encoding(datefmt_format($date_formatter, $time_stamp), 'UTF-8');
+		$formatted_date = api_to_system_encoding(strftime($date_format, $time_stamp), 'UTF-8');
 	}
-	return api_format_date(DATE_FORMAT_LONG, $time_stamp).'&nbsp;&nbsp;&nbsp;&nbsp;'.api_format_date(TIME_NO_SEC_FORMAT, $time_stamp);
+	date_default_timezone_set($system_timezone);
+	return $formatted_date;
 }
 
 /**

+ 34 - 31
main/inc/lib/main_api.lib.php

@@ -4324,12 +4324,15 @@ function _api_get_timezone() {
  *
  * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  */
-function api_get_utc_datetime($time) {
+function api_get_utc_datetime($time = null) {
 	$from_timezone = _api_get_timezone();
 	$to_timezone = 'UTC';
-	// If time is a timestamp, convert it to a string
+	if (is_null($time)) {
+		return gmdate("Y-m-d H:i:s");
+	}
+	// If time is a timestamp, return directly in utc
 	if (is_int($time)) {
-		$time = date("Y-m-d H:i:s", $time);
+		return gmdate("Y-m-d H:i:s", $time);
 	}
 	try {
 		$date = new DateTime($time, new DateTimezone($from_timezone));
@@ -4341,56 +4344,56 @@ function api_get_utc_datetime($time) {
 }
 
 /**
- * Returns the local time in a format given as an argument
- * @param string The time to be converted
- * @param string The format to be used. The default format is DATETIME
+ * Returns a DATETIME string converted to the right timezone
+ * @param mixed The time to be converted
  * @param string The timezone to be converted to. If null, the timezone will be determined based on user preference, or timezone chosen by the admin for the platform.
  * @param string The timezone to be converted from. If null, UTC will be assumed.
- * @return string The converted time
+ * @return string The converted time formatted as Y-m-d H:i:s
  *
  * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  */
-function api_get_local_time($time, $format=null, $to_timezone=null, $from_timezone=null) {
+function api_get_local_time($time = null, $to_timezone=null, $from_timezone=null) {
 	// Determining the timezone to be converted from
-	if ($from_timezone === null) {
+	if (is_null($from_timezone)) {
 		$from_timezone = 'UTC';
 	}
 	// Determining the timezone to be converted to
-	if ($to_timezone === null) {
+	if (is_null($to_timezone)) {
 		$to_timezone = _api_get_timezone();
 	}
-	// Determine the format
-	$format_null = false;
-	if ($format === null) {
-		$format_null = true;
-		$format = 'Y-m-d H:i:s';
-	}
 	// If time is a timestamp, convert it to a string
+	if (is_null($time)) {
+		$from_timezone = 'UTC';
+		$time = gmdate('Y-m-d H:i:s');
+	}
 	if (is_int($time)) {
-		$time = date('Y-m-d H:i:s', $time);
+		$from_timezone = 'UTC';
+		$time = gmdate('Y-m-d H:i:s', $time);
 	}
 	try {
 		$date = new DateTime($time, new DateTimezone($from_timezone));
 		$date->setTimezone(new DateTimeZone($to_timezone));
-		// In the following case, the format is an internal Chamilo format, so we are using api_format_date
-		if (is_int($format) || strpos($format, '%') !== false) {
-			return api_format_date($format, strtotime($date->format('Y-m-d H:i:s')));
-		} else {
-			if ($format_null && IS_PHP_53) {
-				// use IntlDateFormatter to localize the date in the language of the user
-				$locale = api_get_language_isocode();
-				// TODO: This instance of IntlDateFormatter is better to be cached for each locale. It is for speed, api_get_local_time() is called repetitively in tables.
-				$date_formatter = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::SHORT);
-				return api_to_system_encoding($date_formatter->format(strtotime($date->format('Y-m-d H:i:s'))), 'UTF-8');
-			} else {
-				return $date->format($format);
-			}
-		}
+		return $date->format('Y-m-d H:i:s');
 	} catch (Exception $e) {
 		return null;
 	}
 }
 
+/**
+ * Converts a date to the right timezone and localizes it in the format given as an argument
+ * @param mixed The time to be converted
+ * @param mixed Format to be used
+ * @param string Timezone to be converted from. If null, UTC will be assumed.
+ * @return string Converted and localized date
+ * 
+ * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
+ */
+function api_convert_and_format_date($time = null, $format = null, $from_timezone = null) {
+	// First, convert the datetime to the right timezone
+	$datetime = api_get_local_time($time, null, $from_timezone);
+	// Second, localize the date
+	return api_format_date($time, $format);
+}
 
 /*	DEPRECATED FUNCTIONS */
 

+ 10 - 1
main/inc/lib/text.lib.php

@@ -55,7 +55,10 @@ function make_clickable($string) {
  */
 
 function format_locale_date($date_format, $time_stamp = -1, $language = null) {
-	return api_format_date($date_format, $time_stamp, $language);
+	if ($time_stamp == -1) {
+		$time_stamp = time();
+	}
+	return api_format_date($time_stamp, $date_format, $language);
 }
 
 /**
@@ -213,6 +216,7 @@ function latex_gif_renderer($latex_code) {
  * Returns the difference between the current date (date(now)) with the parameter $date in a string format like "2 days, 1 hour"
  * Example: $date="2008-03-07 15:44:08";
  * 			date_to_str($date) it will return 3 days, 20 hours
+ * The given date should be in the timezone chosen by the user or administrator. Use api_get_local_time() to get it...
  *
  * @param  string The string has to be the result of a date function in this format -> date("Y-m-d H:i:s",time());
  * @return string The difference between the current date and the parameter in a literal way "3 days, 2 hour" *
@@ -226,6 +230,9 @@ function date_to_str_ago($date) {
 	static $min_decade, $min_year, $min_month, $min_week, $min_day, $min_hour, $min_minute;
 	static $min_decades, $min_years, $min_months, $min_weeks, $min_days, $min_hours, $min_minutes;
 	static $sec_time_time, $sec_time_sing, $sec_time_plu;
+	
+	$system_timezone = date_default_timezone_get();
+	date_default_timezone_set(_api_get_timezone());
 
 	if (!$initialized) {
 		$today = api_ucfirst(get_lang('Today'));
@@ -328,6 +335,8 @@ function date_to_str_ago($date) {
 	} else {
 		$str = $str_result[0];
 	}
+	
+	date_default_timezone_set($system_timezone);
 	return $str;
 }
 

+ 4 - 4
main/work/work.lib.php

@@ -693,8 +693,8 @@ function display_student_publications_list($work_dir, $sub_course_dir, $currentC
 			}
 
 			if ($direc_date != '' && $direc_date != '0000-00-00 00:00:00') {
-				$direc_date = api_get_local_time($direc_date, 'Y-m-d H:i:s', null, date_default_timezone_get());
-				$row[] = date_to_str_ago($direc_date).'<br /><span class="dropbox_date">'.api_format_date_time_long($direc_date).'</span>'.'<!--uts='.strtotime($direc_date).'-->';
+				$direc_date_local = api_get_local_time($direc_date, null, date_default_timezone_get());
+				$row[] = date_to_str_ago($direc_date_local).'<br /><span class="dropbox_date">'.api_format_date($direc_date_local).'</span>'.'<!--uts='.strtotime($direc_date).'-->';
 			} else {
 				$row[] = '';
 			}
@@ -754,8 +754,8 @@ function display_student_publications_list($work_dir, $sub_course_dir, $currentC
 				$row[] = '<a href="download.php?file='.$url.'"'.$class.'><img src="../img/filesave.gif" style="float:right;" alt="'.get_lang('Save').'" title="'.get_lang('Save').'" />'.$work->title.'</a><br />'.$work->description;
 				$row[] = display_user_link_work($row2['insert_user_id'], $work->author).$qualification_string; // $work->author;
 
-				$work_sent_date = api_get_local_time($work->sent_date, 'Y-m-d H:i:s', null, date_default_timezone_get());
-				$row[] = date_to_str_ago($work_sent_date).$add_string.'<br /><span class="dropbox_date">'.api_format_date_time_long($work_sent_date).'</span>'.'<!--uts='.strtotime($work_sent_date).'-->';
+				$work_sent_date_local = api_get_local_time($work->sent_date, null, date_default_timezone_get());
+				$row[] = date_to_str_ago($work_sent_date_local).$add_string.'<br /><span class="dropbox_date">'.api_format_date($work_sent_date_local).'</span>'.'<!--uts='.strtotime($work_sent_date).'-->';
 
 				if ($is_allowed_to_edit) {
 

+ 4 - 4
main/work/work.php

@@ -1117,11 +1117,11 @@ if ($is_special > 0) {
 			define('ASSIGNMENT_EXPIRES', $time_expires);
 		}
 
-		$ends_on_datetime = api_get_local_time($homework['ends_on'], 'Y-m-d H:i:s', null, date_default_timezone_get());
-		$ends_on = api_format_date_time_long($ends_on_datetime);
+		$ends_on_datetime = api_get_local_time($homework['ends_on'], null, date_default_timezone_get());
+		$ends_on = api_format_date($ends_on_datetime);
 
-		$expires_on_datetime = api_get_local_time($homework['expires_on'], 'Y-m-d H:i:s', null, date_default_timezone_get());
-		$expires_on = api_format_date_time_long($expires_on_datetime);
+		$expires_on_datetime = api_get_local_time($homework['expires_on'], null, date_default_timezone_get());
+		$expires_on = api_format_date($expires_on_datetime);
 
 		if ($has_ended) {
 			display_action_links($cur_dir_path, $always_show_tool_options, true);