Enhancement: Date and time formats are now configurable in iTop !! (beta version, beware!)

SVN:trunk[4011]
This commit is contained in:
Denis Flaven
2016-04-22 09:26:27 +00:00
parent b318d27b19
commit 8eba9ae714
44 changed files with 3211 additions and 115 deletions

View File

@@ -34,7 +34,7 @@ class ExecAsyncTask implements iBackgroundProcess
public function Process($iTimeLimit)
{
$sNow = date('Y-m-d H:i:s');
$sNow = date(AttributeDateTime::GetSQLFormat());
// Criteria: planned, and expected to occur... ASAP or in the past
$sOQL = "SELECT AsyncTask WHERE (status = 'planned') AND (ISNULL(planned) OR (planned < '$sNow'))";
$iProcessed = 0;

View File

@@ -3537,9 +3537,353 @@ class AttributeMetaEnum extends AttributeEnum
*/
class AttributeDateTime extends AttributeDBField
{
static public function GetDateFormat()
static $sDateTimeFormat = null;
static $sTimeFormat = null;
static public function GetFormat()
{
return "Y-m-d H:i:s";
if (self::$sDateTimeFormat == null)
{
static::LoadFormatFromConfig();
}
return self::$sDateTimeFormat;
}
/**
* Load the 3 settings: date format, time format and data_time format from the configuration
*/
protected static function LoadFormatFromConfig()
{
$aFormats = MetaModel::GetConfig()->Get('date_and_time_format');
$sLang = Dict::GetUserLanguage();
$sDateFormat = isset($aFormats[$sLang]['date']) ? $aFormats[$sLang]['date'] : (isset($aFormats['default']['date']) ? $aFormats['default']['date'] : 'Y-m-d');
$sTimeFormat = isset($aFormats[$sLang]['time']) ? $aFormats[$sLang]['time'] : (isset($aFormats['default']['time']) ? $aFormats['default']['time'] : 'H:i:s');
$sDateAndTimeFormat = isset($aFormats[$sLang]['date_time']) ? $aFormats[$sLang]['date_time'] : (isset($aFormats['default']['date_time']) ? $aFormats['default']['date_time'] : '$date $time');
$sFormat = str_replace(array('$date', '$time'), array($sDateFormat, $sTimeFormat), $sDateAndTimeFormat);
self::SetFormat($sFormat);
self::SetTimeFormat($sTimeFormat);
AttributeDate::SetFormat($sDateFormat);
}
/**
* Returns the format string used for the date & time stored in memory
* @return string
*/
static public function GetInternalFormat()
{
return 'Y-m-d H:i:s';
}
/**
* Returns the format string used for the date & time written to MySQL
* @return string
*/
static public function GetSQLFormat()
{
return 'Y-m-d H:i:s';
}
static public function SetFormat($sDateTimeFormat)
{
self::$sDateTimeFormat = $sDateTimeFormat;
}
static public function GetTimeFormat()
{
if (self::$sTimeFormat == null)
{
static::LoadFormatFromConfig();
}
return self::$sTimeFormat;
}
static public function GetSQLTimeFormat()
{
return 'H:i:s';
}
static public function SetTimeFormat($sTimeFormat)
{
self::$sTimeFormat = $sTimeFormat;
}
/**
* Return the mapping table for converting between various convention for data formats
*/
public static function GetFormatMapping()
{
return array(
// Days
'd' => array('regexpr' => '(0[1-9]|[1-2][0-9]||3[0-1])', 'datepicker' => 'dd', 'usage' => 'day', 'excel' => 'dd'), // Day of the month: 2 digits (with leading zero)
'j' => array('regexpr' => '([1-9]|[1-2][0-9]||3[0-1])', 'datepicker' => 'd', 'usage' => 'day', 'excel' => '%d'), // Day of the month: 1 or 2 digits (without leading zero)
// Months
'm' => array('regexpr' => '(0[1-9]|1[0-2])', 'datepicker' => 'mm', 'usage' => 'month', 'excel' => 'MM'), // Month on 2 digits i.e. 01-12
'n' => array('regexpr' => '([1-9]|1[0-2])', 'datepicker' => 'm', 'usage' => 'month', 'excel' => '%M'), // Month on 1 or 2 digits 1-12
// Years
'Y' => array('regexpr' => '([0-9]{4})', 'datepicker' => 'yy', 'usage' => 'year', 'excel' => 'YYYY'), // Year on 4 digits
'y' => array('regexpr' => '([0-9]{2})', 'datepicker' => 'y', 'usage' => 'year', 'excel' => 'YY'), // Year on 2 digits
// Hours
'H' => array('regexpr' => '([0-1][0-9]|2[0-3])', 'datepicker' => 'HH', 'usage' => 'hour', 'excel' => 'HH'), // Hour 00..23
'h' => array('regexpr' => '(0[1-9]|1[0-2])', 'datepicker' => 'hh', 'usage' => 'hour', 'excel' => 'hh'), // Hour 01..12
'G' => array('regexpr' => '([1-9]|[1[0-9]|2[0-3])', 'datepicker' => 'H', 'usage' => 'hour', 'excel' => '%H'), // Hour 0..23
'g' => array('regexpr' => '([1-9]|1[0-2])', 'datepicker' => 'h', 'usage' => 'hour', 'excel' => '%h'), // Hour 1..12
'a' => array('regexpr' => '(am|pm)', 'datepicker' => 'tt', 'usage' => 'am/pm', 'excel' => 'am/pm'),
'A' => array('regexpr' => '(AM|PM)', 'datepicker' => 'TT', 'usage' => 'am/pm', 'excel' => 'AM/PM'),
// Minutes
'i' => array('regexpr' => '([0-5][0-9])', 'datepicker' => 'mm', 'usage' => 'minutes', 'excel' => 'mm'),
// Seconds
's' => array('regexpr' => '([0-5][0-9])', 'datepicker' => 'ss', 'usage' => 'seconds', 'excel' => 'ss'),
);
}
/**
* Format a date into the supplied format string
* @param mixed $date An int, string, DateTime object or null !!
* @param string $sFormat The format using PHP createFromFormat convention
* @throws Exception
* @return string The formatted date
*/
public static function Format($date, $sFormat = null)
{
if ($sFormat === null)
{
$sFormat = static::GetFormat();
}
if ($date == null)
{
$sDate = '';
}
else if (($date === '0000-00-00') || ($date === '0000-00-00 00:00:00'))
{
$sDate = '';
}
else if ($date instanceof DateTime)
{
// Parameter is a DateTime
$sDate = $date->format($sFormat);
}
else if (is_int($date))
{
// Parameter is a Unix timestamp
$oDate = new DateTime();
$oDate->setTimestamp($date);
$sDate = $oDate->format($sFormat);
}
else if (is_string($date))
{
$oDate = new DateTime($date);
$sDate = $oDate->format($sFormat);
}
else
{
throw new Exception("AttributeDateTime::Format: Unexpected date value: ".print_r($date, true));
}
return $sDate;
}
/**
* Parse a date in the supplied format and return the date as a string in the internal format
* @param string $sDate The string to parse
* @param string $sFormat The format, in PHP createFromFormat convention
* @throws Exception
* @return string
*/
public static function Parse($sDate, $sFormat)
{
if (($sDate == null) || ($sDate == '0000-00-00 00:00:00') || ($sDate == '0000-00-00'))
{
return null;
}
else
{
$sFormat = preg_replace('/\\?/', '', $sFormat); // replace escaped characters by a wildcard for parsing
$oDate = DateTime::createFromFormat($sFormat, $sDate);
if ($oDate === false)
{
throw new Exception("Unable to parse the date: '$sDate' using the format: '$sFormat'");
}
return $oDate->format(static::GetInternalFormat());
}
}
/**
* Get a date or datetime format string in the jQuery UI date picker format
* @param string $sFormat
* @return string The format string using the date picker convention
*/
static public function GetDatePickerFormat()
{
$sFormat = static::GetFormat();
$aMappings = static::GetFormatMapping();
$sResult = '';
$bEscaping = false;
for($i=0; $i < strlen($sFormat); $i++)
{
if (($sFormat[$i] == '\\'))
{
$bEscaping = true;
continue;
}
if ($bEscaping)
{
$sResult .= "'{$sFormat[$i]}'";
$bEscaping = false;
}
else if(array_key_exists($sFormat[$i], $aMappings))
{
// Not a litteral value, must be replaced by its regular expression pattern
$sResult .= $aMappings[$sFormat[$i]]['datepicker'];
}
else
{
// Normal char with no special meaning
$sResult .= $sFormat[$i];
}
}
return $sResult;
}
/**
* Get a date or datetime format string in the Excel format
* @param string $sFormat
* @return string The format string using the Excel convention
*/
static public function GetExcelFormat($sFormat = null)
{
$sFormat = ($sFormat == null) ? static::GetFormat() : $sFormat;
$aMappings = static::GetFormatMapping();
$sResult = '';
$bEscaping = false;
for($i=0; $i < strlen($sFormat); $i++)
{
if (($sFormat[$i] == '\\'))
{
$bEscaping = true;
continue;
}
if ($bEscaping)
{
$sResult .= $sFormat[$i]; // What's the way to escape characters in Excel format ??
$bEscaping = false;
}
else if(array_key_exists($sFormat[$i], $aMappings))
{
// Not a litteral value, must be replaced by its regular expression pattern
$sResult .= $aMappings[$sFormat[$i]]['excel'];
}
else
{
// Normal char with no special meaning
$sResult .= $sFormat[$i];
}
}
return $sResult;
}
/*
* Unused since the sorting of the tables is always performed server-side
*
public static function GetTableSorterRule()
{
$aOrder = array();
$aPos = array();
$sRegExpr = static::GetRegExpr($aOrder);
foreach(array('year', 'month', 'day', 'hour', 'minutes', 'seconds') as $sUsage)
{
$pos = array_search($sUsage, $aOrder);
if ($pos !== false)
{
$aPos[$sUsage] = '$'.(1+$pos);
}
}
$sIsoDate = "{$aPos['year']}/{$aPos['month']}/{$aPos['day']}";
if (array_key_exists('hour', $aPos))
{
$sIsoDate .= " {$aPos['hour']}:{$aPos['minutes']}:{$aPos['seconds']}";
}
return array('regexpr' => $sRegExpr, 'replacement' => $sIsoDate);
}
public static function InitTableSorter($oPage, $sRuleName)
{
$aDef = static::GetTableSorterRule();
$oPage->add_ready_script(
<<<EOF
$.tablesorter.addParser({
id: "$sRuleName",
is: function (s) {
return /^({$aDef['regexpr']})$/.test(s);
}, format: function (s) {
s = s.replace(/{$aDef['regexpr']}/, "{$aDef['replacement']}");
return $.tablesorter.formatFloat(new Date(s).getTime());
}, type: "numeric"
});
EOF
);
}
*/
/**
* Get the regular expression to (approximately) validate a date/time for the current format
* @param array $aOrder
* @return string The regular expression in PCRE syntax
*/
static public function GetRegExpr(&$aOrder = null)
{
$sFormat = static::GetFormat();
$aMappings = static::GetFormatMapping();
$sSpecialChars = '.?*$^()[]/'; // Characters having a special meaning in a regular expression, must be escaped by prepending a backslash
$sResult = '^';
$bEscaping = false;
for($i=0; $i < strlen($sFormat); $i++)
{
if (($sFormat[$i] == '\\') && !$bEscaping)
{
$bEscaping = true;
continue;
}
if (!$bEscaping && array_key_exists($sFormat[$i], $aMappings))
{
// Not a litteral value, must be replaced by its regular expression pattern
$sResult .= $aMappings[$sFormat[$i]]['regexpr'];
if ($aOrder !== null)
{
$aOrder[] = $aMappings[$sFormat[$i]]['usage'];
}
}
else
{
// Litteral value, take care of special characters in a RegExpr
if (strpos($sSpecialChars, $sFormat[$i]) !== false)
{
$sResult .= '\\'.$sFormat[$i];
}
else
{
// Normal char with no special meaning
$sResult .= $sFormat[$i];
}
}
if ($bEscaping)
{
$bEscaping = false;
}
}
$sResult .= '$';
return $sResult;
}
static public function ListExpectedParams()
@@ -3550,6 +3894,12 @@ class AttributeDateTime extends AttributeDBField
public function GetEditClass() {return "DateTime";}
public function GetEditValue($sValue, $oHostObj = null)
{
return (string)static::Format($sValue, static::GetFormat());
}
protected function GetSQLCol($bFullSpec = false) {return "DATETIME";}
public static function GetAsUnixSeconds($value)
{
@@ -3558,29 +3908,15 @@ class AttributeDateTime extends AttributeDBField
return $iUnixSeconds;
}
// This has been done at the time when itop was using TIMESTAMP columns,
// now that iTop is using DATETIME columns, it seems possible to have IsNullAllowed returning false... later when this is needed
public function IsNullAllowed() {return true;}
public function GetDefaultValue(DBObject $oHostObject = null)
{
$default = parent::GetDefaultValue($oHostObject);
if (!parent::IsNullAllowed())
{
if (empty($default))
{
$default = date($this->GetDateFormat());
}
}
return $default;
// null value will be replaced by the current date, if not already set, in DoComputeValues
return $this->GetNullValue();
}
// END OF THE WORKAROUND
///////////////////////////////////////////////////////////////
public function GetValidationPattern()
{
return "^(([0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30))))( (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])(:([0-5][0-9])){0,1}){0,1}|0000-00-00 00:00:00|0000-00-00)$";
return static::GetRegExpr();
}
public function GetBasicFilterOperators()
@@ -3654,7 +3990,7 @@ class AttributeDateTime extends AttributeDBField
return $proposedValue;
}
return date(self::GetDateFormat(), $proposedValue);
return date(self::GetInternalFormat(), $proposedValue);
}
public function ScalarToSQL($value)
@@ -3673,7 +4009,7 @@ class AttributeDateTime extends AttributeDBField
public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
{
return Str::pure2html($value);
return Str::pure2html(static::Format($value, static::GetFormat()));
}
public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
@@ -3683,6 +4019,19 @@ class AttributeDateTime extends AttributeDBField
public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
{
if (empty($sValue) || ($sValue === '0000-00-00 00:00:00') || ($sValue === '0000-00-00'))
{
return '';
}
else if (self::GetFormat() !== self::GetInternalFormat())
{
// Format conversion
$oDate = new DateTime($sValue);
if ($oDate !== false)
{
$sValue = $oDate->format(self::GetFormat());
}
}
$sFrom = array("\r\n", $sTextQualifier);
$sTo = array("\n", $sTextQualifier.$sTextQualifier);
$sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
@@ -3839,13 +4188,40 @@ class AttributeDuration extends AttributeInteger
*/
class AttributeDate extends AttributeDateTime
{
const MYDATEFORMAT = "Y-m-d";
static public function GetDateFormat()
static $sDateFormat = null;
static public function GetFormat()
{
return "Y-m-d";
if (self::$sDateFormat == null)
{
AttributeDateTime::LoadFormatFromConfig();
}
return self::$sDateFormat;
}
static public function SetFormat($sDateFormat)
{
self::$sDateFormat = $sDateFormat;
}
/**
* Returns the format string used for the date & time stored in memory
* @return string
*/
static public function GetInternalFormat()
{
return 'Y-m-d';
}
/**
* Returns the format string used for the date & time written to MySQL
* @return string
*/
static public function GetSQLFormat()
{
return 'Y-m-d';
}
static public function ListExpectedParams()
{
return parent::ListExpectedParams();
@@ -3854,11 +4230,6 @@ class AttributeDate extends AttributeDateTime
public function GetEditClass() {return "Date";}
protected function GetSQLCol($bFullSpec = false) {return "DATE";}
public function GetValidationPattern()
{
return "^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$";
}
}
/**

View File

@@ -258,7 +258,7 @@ class BulkChange
protected $m_aReconcilKeys; // attcode (attcode = 'id' for the pkey)
protected $m_sSynchroScope; // OQL - if specified, then the missing items will be reported
protected $m_aOnDisappear; // array of attcode => value, values to be set when an object gets out of scope (ignored if no scope has been defined)
protected $m_sDateFormat; // Date format specification, see utils::StringToTime()
protected $m_sDateFormat; // Date format specification, see DateTime::createFromFormat
protected $m_bLocalizedValues; // Values in the data set are localized (see AttributeEnum)
protected $m_aExtKeysMappingCache; // Cache for resolving external keys based on the given search criterias
@@ -800,16 +800,16 @@ class BulkChange
foreach ($this->m_aAttList as $sAttCode => $iCol)
{
if ($sAttCode == 'id') continue;
$oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
if ($oAttDef instanceof AttributeDateTime)
{
foreach($this->m_aData as $iRow => $aRowData)
{
$sNewDate = utils::StringToTime($this->m_aData[$iRow][$iCol], $this->m_sDateFormat);
if ($sNewDate !== false)
$oDate = DateTime::createFromFormat($this->m_sDateFormat, $this->m_aData[$iRow][$iCol]);
if ($oDate !== false)
{
// Todo - improve the reporting
$sNewDate = $oDate->format($oAttDef->GetInternalFormat());
$this->m_aData[$iRow][$iCol] = $sNewDate;
}
else

View File

@@ -95,7 +95,7 @@ class BulkExportResultGC implements iBackgroundProcess
public function Process($iTimeLimit)
{
$sDateLimit = date('Y-m-d H:i:s', time() - 24*3600); // Every BulkExportResult older than one day will be deleted
$sDateLimit = date(AttributeDateTime::GetSQLFormat(), time() - 24*3600); // Every BulkExportResult older than one day will be deleted
$sOQL = "SELECT BulkExportResult WHERE created < '$sDateLimit'";
$iProcessed = 0;

View File

@@ -898,6 +898,14 @@ class Config
'source_of_value' => '',
'show_in_conf_sample' => true,
),
'date_and_time_format' => array(
'type' => 'array',
'description' => 'Format for date and time display (per language)',
'default' => array('default' => array('date' => 'Y-m-d', 'time' => 'H:i:s', 'date_time' => '$date $time')),
'value' => false,
'source_of_value' => '',
'show_in_conf_sample' => true,
),
);
public function IsProperty($sPropCode)

View File

@@ -34,6 +34,7 @@ class CSVBulkExport extends TabularBulkExport
$oP->p(" *\ttext-qualifier: (optional) character to be used around text strings (default is '\"').");
$oP->p(" *\tno_localize: set to 1 to retrieve non-localized values (for instance for ENUM values). Default is 0 (= localized values)");
$oP->p(" *\tformatted_text: set to 1 to export case logs and formatted text fields with their HTML markup. Default is 0 (= plain text)");
$oP->p(" *\tdate_format: the format to use when exporting date and time fields (default = the format used in the user interface). Example: 'm/d/Y H:i:s'");
}
public function ReadParameters()
@@ -57,6 +58,16 @@ class CSVBulkExport extends TabularBulkExport
$this->aStatusInfo['charset'] = strtoupper(utils::ReadParam('charset', 'UTF-8', true, 'raw_data'));
$this->aStatusInfo['formatted_text'] = (bool)utils::ReadParam('formatted_text', 0, true);
$sDateFormatRadio = utils::ReadParam('date_format_radio', 'custom');
if ($sDateFormatRadio == 'default')
{
$this->aStatusInfo['date_format'] = AttributeDateTime::GetFormat();
}
else
{
$this->aStatusInfo['date_format'] = utils::ReadParam('date_format', AttributeDateTime::GetFormat(), true, 'raw_data');
}
}
@@ -97,6 +108,7 @@ class CSVBulkExport extends TabularBulkExport
$oP->add('<table class="export_parameters"><tr><td style="vertical-align:top">');
$oP->add('<h3>'.Dict::S('UI:CSVImport:SeparatorCharacter').'</h3>');
$sRawSeparator = utils::ReadParam('separator', ',', true, 'raw_data');
$sCustomDateTimeFormat = utils::ReadParam('', ',', true, 'raw_data');
$aSep = array(
';' => Dict::S('UI:CSVImport:SeparatorSemicolon+'),
',' => Dict::S('UI:CSVImport:SeparatorComma+'),
@@ -162,10 +174,28 @@ class CSVBulkExport extends TabularBulkExport
$sChecked = (utils::ReadParam('formatted_text', 0) == 1) ? ' checked ' : '';
$oP->add('<h3>'.Dict::S('Core:BulkExport:TextFormat').'</h3>');
$oP->add('<input type="checkbox" id="csv_formatted_text" name="formatted_text" value="1"'.$sChecked.'><label for="csv_formatted_text"> '.Dict::S('Core:BulkExport:OptionFormattedText').'</label>');
$oP->add('</td><td style="vertical-align:top">');
$sDateTimeFormat = utils::ReadParam('date_format', AttributeDateTime::GetFormat(), true, 'raw_data');
$sDefaultChecked = ($sDateTimeFormat == AttributeDateTime::GetFormat()) ? ' checked' : '';
$sCustomChecked = ($sDateTimeFormat !== AttributeDateTime::GetFormat()) ? ' checked' : '';
$oP->add('<h3>'.Dict::S('Core:BulkExport:DateTimeFormat').'</h3>');
$sDefaultFormat = htmlentities(AttributeDateTime::GetFormat(), ENT_QUOTES, 'UTF-8');
$sExample = htmlentities(date(AttributeDateTime::GetFormat()), ENT_QUOTES, 'UTF-8');
$oP->add('<input type="radio" id="csv_date_time_format_default" name="date_format_radio" value="default"'.$sDefaultChecked.'><label for="csv_date_time_format_default"> '.Dict::Format('Core:BulkExport:DateTimeFormatDefault_Example', $sDefaultFormat, $sExample).'</label><br/>');
$sFormatInput = '<input type="text" size="15" name="date_format" id="csv_custom_date_time_format" title="" value="'.htmlentities($sDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>';
$oP->add('<input type="radio" id="csv_date_time_format_custom" name="date_format_radio" value="custom"'.$sCustomChecked.'><label for="csv_date_time_format_custom"> '.Dict::Format('Core:BulkExport:DateTimeFormatCustom_Format', $sFormatInput).'</label>');
$oP->add('</td></tr></table>');
$oP->add('</fieldset>');
$sJSTooltip = json_encode('<div class="date_format_tooltip">'.Dict::S('UI:CSVImport:CustomDateTimeFormatTooltip').'</div>');
$oP->add_ready_script(
<<<EOF
$('#csv_custom_date_time_format').tooltip({content: function() { return $sJSTooltip; } });
$('#csv_custom_date_time_format').on('click', function() { $('#csv_date_time_format_custom').prop('checked', true); });
EOF
);
break;
@@ -257,7 +287,10 @@ class CSVBulkExport extends TabularBulkExport
break;
default:
$sPrevFormat = AttributeDateTime::GetFormat();
AttributeDateTime::SetFormat($this->aStatusInfo['date_format']);
$sField = $oObj->GetAsCSV($sAttCode, $this->aStatusInfo['separator'], $this->aStatusInfo['text_qualifier'], $this->bLocalizeOutput, !$this->aStatusInfo['formatted_text']);
AttributeDateTime::SetFormat($sPrevFormat);
}
}
if ($this->aStatusInfo['charset'] != 'UTF-8')

View File

@@ -705,6 +705,17 @@ abstract class DBObject implements iDisplay
if ($aCallInfo["function"] != "ComputeValues") continue;
return; //skip!
}
// Set the "null-not-allowed" datetimes (and dates) whose value is not initialized
foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
{
// AttributeDate is derived from AttributeDateTime
if (($oAttDef instanceof AttributeDateTime) && (!$oAttDef->IsNullAllowed()) && ($this->Get($sAttCode) == $oAttDef->GetNullValue()))
{
$this->Set($sAttCode, date($oAttDef->GetFormat()));
}
}
$this->ComputeValues();
}
@@ -3300,8 +3311,8 @@ abstract class DBObject implements iDisplay
}
$aContext['current_contact_id'] = UserRights::GetContactId();
$aContext['current_contact_friendlyname'] = UserRights::GetUserFriendlyName();
$aContext['current_date'] = date('Y-m-d');
$aContext['current_time'] = date('H:i:s');
$aContext['current_date'] = date(AttributeDate::GetSQLFormat());
$aContext['current_time'] = date(AttributeDateTime::GetSQLTimeFormat());
$sValue = MetaModel::ApplyParams($sRawValue, $aContext);
$this->Set($sAttCode, $sValue);
break;
@@ -3328,8 +3339,8 @@ abstract class DBObject implements iDisplay
}
$aContext['current_contact_id'] = UserRights::GetContactId();
$aContext['current_contact_friendlyname'] = UserRights::GetUserFriendlyName();
$aContext['current_date'] = date('Y-m-d');
$aContext['current_time'] = date('H:i:s');
$aContext['current_date'] = date(AttributeDate::GetSQLFormat());
$aContext['current_time'] = date(AttributeDateTime::GetSQLTimeFormat());
$sAddendum = MetaModel::ApplyParams($sRawAddendum, $aContext);
$this->Set($sAttCode, $this->Get($sAttCode).$sAddendum);
break;

View File

@@ -47,12 +47,23 @@ class ExcelBulkExport extends TabularBulkExport
$oP->p(" * xlsx format options:");
$oP->p(" *\tfields: the comma separated list of field codes to export (e.g: name,org_id,service_name...).");
$oP->p(" *\tformatted_text: set to 1 to export case logs and formatted text fields with their HTML markup. Default is 0 (= plain text)");
$oP->p(" *\tdate_format: the format to use when exporting date and time fields (default = the format used in the user interface). Example: 'm/d/Y H:i:s'");
}
public function ReadParameters()
{
parent::ReadParameters();
$this->aStatusInfo['formatted_text'] = (bool)utils::ReadParam('formatted_text', 0, true);
$sDateFormatRadio = utils::ReadParam('date_format_radio', 'custom');
if ($sDateFormatRadio == 'default')
{
$this->aStatusInfo['date_format'] = AttributeDateTime::GetFormat();
}
else
{
$this->aStatusInfo['date_format'] = utils::ReadParam('date_format', AttributeDateTime::GetFormat(), true, 'raw_data');
}
}
public function EnumFormParts()
@@ -76,9 +87,28 @@ class ExcelBulkExport extends TabularBulkExport
$oP->add('<h3>'.Dict::S('Core:BulkExport:TextFormat').'</h3>');
$oP->add('<input type="checkbox" id="xlsx_formatted_text" name="formatted_text" value="1"'.$sChecked.'><label for="xlsx_formatted_text"> '.Dict::S('Core:BulkExport:OptionFormattedText').'</label>');
$oP->add('</td><td style="vertical-align:top">');
$sDateTimeFormat = utils::ReadParam('date_format', AttributeDateTime::GetFormat(), true, 'raw_data');
$sDefaultChecked = ($sDateTimeFormat == AttributeDateTime::GetFormat()) ? ' checked' : '';
$sCustomChecked = ($sDateTimeFormat !== AttributeDateTime::GetFormat()) ? ' checked' : '';
$oP->add('<h3>'.Dict::S('Core:BulkExport:DateTimeFormat').'</h3>');
$sDefaultFormat = htmlentities(AttributeDateTime::GetFormat(), ENT_QUOTES, 'UTF-8');
$sExample = htmlentities(date(AttributeDateTime::GetFormat()), ENT_QUOTES, 'UTF-8');
$oP->add('<input type="radio" id="excel_date_time_format_default" name="date_format_radio" value="default"'.$sDefaultChecked.'><label for="excel_date_time_format_default"> '.Dict::Format('Core:BulkExport:DateTimeFormatDefault_Example', $sDefaultFormat, $sExample).'</label><br/>');
$sFormatInput = '<input type="text" size="15" name="date_format" id="excel_custom_date_time_format" title="" value="'.htmlentities($sDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>';
$oP->add('<input type="radio" id="excel_date_time_format_custom" name="date_format_radio" value="custom"'.$sCustomChecked.'><label for="excel_date_time_format_custom"> '.Dict::Format('Core:BulkExport:DateTimeFormatCustom_Format', $sFormatInput).'</label>');
$oP->add('</td></tr></table>');
$oP->add('</fieldset>');
$sJSTooltip = json_encode('<div class="date_format_tooltip">'.Dict::S('UI:CSVImport:CustomDateTimeFormatTooltip').'</div>');
$oP->add_ready_script(
<<<EOF
$('#excel_custom_date_time_format').tooltip({content: function() { return $sJSTooltip; } });
$('#excel_custom_date_time_format').on('click', function() { $('#excel_date_time_format_custom').prop('checked', true); });
EOF
);
break;
default:
@@ -141,14 +171,19 @@ class ExcelBulkExport extends TabularBulkExport
else
{
$oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text'])
{
if ($oAttDef instanceof AttributeDateTime)
{
// Date and times are formatted using the ISO encoding, not the localized format
$sRet = $value;
}
else if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text'])
{
$sRet = $oAttDef->GetEditValue($value, $oObj);
}
else
{
$sRet = $oAttDef->GetAsPlainText($value, $oObj);
}
}
else
{
$sRet = $oAttDef->GetAsPlainText($value, $oObj);
}
}
}
return $sRet;
@@ -269,6 +304,7 @@ class ExcelBulkExport extends TabularBulkExport
$fStartExcel = microtime(true);
$writer = new XLSXWriter();
$writer->setDateTimeFormat(AttributeDateTime::GetExcelFormat($this->aStatusInfo['date_format']));
$writer->setAuthor(UserRights::GetUserFriendlyName());
$aHeaderTypes = array();
$aHeaderNames = array();

View File

@@ -488,7 +488,7 @@ class InlineImageGC implements iBackgroundProcess
public function Process($iTimeLimit)
{
$sDateLimit = date('Y-m-d H:i:s', time()); // Every temporary InlineImage/Attachment expired will be deleted
$sDateLimit = date(AttributeDateTime::GetSQLFormat(), time()); // Every temporary InlineImage/Attachment expired will be deleted
$iProcessed = 0;
$sOQL = "SELECT InlineImage WHERE (item_id = 0) AND (expire < '$sDateLimit')";

View File

@@ -115,14 +115,14 @@ class ormCaseLog {
if (is_int($this->m_aIndex[$index]['date']))
{
// Unix timestamp
$sDate = date(Dict::S('UI:CaseLog:DateFormat'),$this->m_aIndex[$index]['date']);
$sDate = date(AttributeDateTime::GetInternalFormat(),$this->m_aIndex[$index]['date']);
}
elseif (is_object($this->m_aIndex[$index]['date']))
{
if (version_compare(phpversion(), '5.3.0', '>='))
{
// DateTime
$sDate = $this->m_aIndex[$index]['date']->format(Dict::S('UI:CaseLog:DateFormat'));
$sDate = $this->m_aIndex[$index]['date']->format(AttributeDateTime::GetInternalFormat());
}
else
{
@@ -234,14 +234,14 @@ class ormCaseLog {
if (is_int($aIndex[$index]['date']))
{
// Unix timestamp
$sDate = date(Dict::S('UI:CaseLog:DateFormat'),$aIndex[$index]['date']);
$sDate = date(AttributeDateTime::GetFormat(), $aIndex[$index]['date']);
}
elseif (is_object($aIndex[$index]['date']))
{
if (version_compare(phpversion(), '5.3.0', '>='))
{
// DateTime
$sDate = $aIndex[$index]['date']->format(Dict::S('UI:CaseLog:DateFormat'));
$sDate = $aIndex[$index]['date']->format(AttributeDateTime::GetFormat());
}
else
{
@@ -322,14 +322,14 @@ class ormCaseLog {
if (is_int($aIndex[$index]['date']))
{
// Unix timestamp
$sDate = date(Dict::S('UI:CaseLog:DateFormat'),$aIndex[$index]['date']);
$sDate = date(AttributeDateTime::GetFormat(),$aIndex[$index]['date']);
}
elseif (is_object($aIndex[$index]['date']))
{
if (version_compare(phpversion(), '5.3.0', '>='))
{
// DateTime
$sDate = $aIndex[$index]['date']->format(Dict::S('UI:CaseLog:DateFormat'));
$sDate = $aIndex[$index]['date']->format(AttributeDateTime::GetFormat());
}
else
{
@@ -425,14 +425,14 @@ class ormCaseLog {
if (is_int($aIndex[$index]['date']))
{
// Unix timestamp
$sDate = date(Dict::S('UI:CaseLog:DateFormat'),$aIndex[$index]['date']);
$sDate = date(AttributeDateTime::GetFormat(),$aIndex[$index]['date']);
}
elseif (is_object($aIndex[$index]['date']))
{
if (version_compare(phpversion(), '5.3.0', '>='))
{
// DateTime
$sDate = $aIndex[$index]['date']->format(Dict::S('UI:CaseLog:DateFormat'));
$sDate = $aIndex[$index]['date']->format(AttributeDateTime::GetFormat());
}
else
{
@@ -498,7 +498,7 @@ class ormCaseLog {
{
$sText = HTMLSanitizer::Sanitize($sText);
$bMergeEntries = false;
$sDate = date(Dict::S('UI:CaseLog:DateFormat'));
$sDate = date(AttributeDateTime::GetInternalFormat());
if ($sOnBehalfOf == '')
{
$sOnBehalfOf = UserRights::GetUserFriendlyName();
@@ -612,7 +612,7 @@ class ormCaseLog {
$sFormat = 'html';
}
$sDate = date(Dict::S('UI:CaseLog:DateFormat'), $iDate);
$sDate = date(AttributeDateTime::GetInternalFormat(), $iDate);
$sSeparator = sprintf(CASELOG_SEPARATOR, $sDate, $sOnBehalfOf, $iUserId);
$iSepLength = strlen($sSeparator);

View File

@@ -490,7 +490,7 @@ class CheckStopWatchThresholds implements iBackgroundProcess
{
$iPercent = $aThresholdData['percent']; // could be different than the index !
$sNow = date('Y-m-d H:i:s');
$sNow = date(AttributeDateTime::GetSQLFormat());
$sExpression = "SELECT $sClass WHERE {$sAttCode}_laststart AND {$sAttCode}_{$iThreshold}_triggered = 0 AND {$sAttCode}_{$iThreshold}_deadline < '$sNow'";
$oFilter = DBObjectSearch::FromOQL($sExpression);
$oSet = new DBObjectSet($oFilter);

View File

@@ -239,7 +239,7 @@ class iTopOwnershipLock
{
if ($sToken === $this->oToken->Get('token'))
{
$this->oToken->Set('last_seen', date('Y-m-d H:i:s'));
$this->oToken->Set('last_seen', date(AttributeDateTime::GetSQLFormat()));
$this->oToken->DBUpdate();
$aResult['acquired'] = $this->oToken->Get('acquired');
}
@@ -327,9 +327,9 @@ class iTopOwnershipLock
$this->oToken->Set('obj_class', $this->sObjClass);
$this->oToken->Set('obj_key', $this->iObjKey);
}
$this->oToken->Set('acquired', date('Y-m-d H:i:s'));
$this->oToken->Set('acquired', date(AttributeDateTime::GetSQLFormat()));
$this->oToken->Set('user_id', UserRights::GetUserId());
$this->oToken->Set('last_seen', date('Y-m-d H:i:s'));
$this->oToken->Set('last_seen', date(AttributeDateTime::GetSQLFormat()));
if ($sToken === null)
{
$sToken = sprintf('%X', microtime(true));
@@ -342,7 +342,7 @@ class iTopOwnershipLock
protected static function DeleteExpiredLocks()
{
$sOQL = "SELECT iTopOwnershipToken WHERE last_seen < :last_seen_limit";
$oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL, array('last_seen_limit' => date('Y-m-d H:i:s', time() - MetaModel::GetConfig()->Get('concurrent_lock_expiration_delay')))));
$oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL, array('last_seen_limit' => date(AttributeDateTime::GetSQLFormat(), time() - MetaModel::GetConfig()->Get('concurrent_lock_expiration_delay')))));
while($oToken = $oSet->Fetch())
{
$oToken->DBDelete();

View File

@@ -31,6 +31,7 @@ class PDFBulkExport extends HTMLBulkExport
$oP->p(" *\tfields: (mandatory) the comma separated list of field codes to export (e.g: name,org_id,service_name...).");
$oP->p(" *\tpage_size: (optional) size of the page. One of A4, A3, Letter (default is 'A4').");
$oP->p(" *\tpage_orientation: (optional) the orientation of the page. Either Portrait or Landscape (default is 'Portrait').");
$oP->p(" *\tdate_format: the format to use when exporting date and time fields (default = the format used in the user interface). Example: 'm/d/Y H:i:s'");
}
public function EnumFormParts()
@@ -44,6 +45,8 @@ class PDFBulkExport extends HTMLBulkExport
{
case 'pdf_options':
$oP->add('<fieldset><legend>'.Dict::S('Core:BulkExport:PDFOptions').'</legend>');
$oP->add('<table class="export_parameters"><tr><td style="vertical-align:top">');
$oP->add('<h3>'.Dict::S('Core:PDFBulkExport:PageFormat').'</h3>');
$oP->add('<table>');
$oP->add('<tr>');
$oP->add('<td>'.Dict::S('Core:BulkExport:PDFPageSize').'</td>');
@@ -53,8 +56,30 @@ class PDFBulkExport extends HTMLBulkExport
$oP->add('<td>'.$this->GetSelectCtrl('page_orientation', array('P', 'L'), 'Core:BulkExport:PageOrientation-', 'L').'</td>');
$oP->add('</tr>');
$oP->add('</table>');
$oP->add('</td><td style="vertical-align:top">');
$sDateTimeFormat = utils::ReadParam('date_format', AttributeDateTime::GetFormat(), true, 'raw_data');
$sDefaultChecked = ($sDateTimeFormat == AttributeDateTime::GetFormat()) ? ' checked' : '';
$sCustomChecked = ($sDateTimeFormat !== AttributeDateTime::GetFormat()) ? ' checked' : '';
$oP->add('<h3>'.Dict::S('Core:BulkExport:DateTimeFormat').'</h3>');
$sDefaultFormat = htmlentities(AttributeDateTime::GetFormat(), ENT_QUOTES, 'UTF-8');
$sExample = htmlentities(date(AttributeDateTime::GetFormat()), ENT_QUOTES, 'UTF-8');
$oP->add('<input type="radio" id="pdf_date_time_format_default" name="date_format_radio" value="default"'.$sDefaultChecked.'><label for="pdf_date_time_format_default"> '.Dict::Format('Core:BulkExport:DateTimeFormatDefault_Example', $sDefaultFormat, $sExample).'</label><br/>');
$sFormatInput = '<input type="text" size="15" name="date_format" id="pdf_custom_date_time_format" title="" value="'.htmlentities($sDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>';
$oP->add('<input type="radio" id="pdf_date_time_format_custom" name="date_format_radio" value="custom"'.$sCustomChecked.'><label for="pdf_date_time_format_custom"> '.Dict::Format('Core:BulkExport:DateTimeFormatCustom_Format', $sFormatInput).'</label>');
$oP->add('</td></tr></table>');
$oP->add('</fieldset>');
$sJSTooltip = json_encode('<div id="date_format_tooltip">'.Dict::S('UI:CSVImport:CustomDateTimeFormatTooltip').'</div>');
$oP->add_ready_script(
<<<EOF
$('#pdf_custom_date_time_format').tooltip({content: function() { return $sJSTooltip; } });
$('#pdf_custom_date_time_format').on('click', function() { $('#pdf_date_time_format_custom').prop('checked', true); });
EOF
);
break;
default:
@@ -88,6 +113,16 @@ class PDFBulkExport extends HTMLBulkExport
parent::ReadParameters();
$this->aStatusInfo['page_size'] = utils::ReadParam('page_size', 'A4', true, 'raw_data');
$this->aStatusInfo['page_orientation'] = utils::ReadParam('page_orientation', 'L', true);
$sDateFormatRadio = utils::ReadParam('date_format_radio', 'custom');
if ($sDateFormatRadio == 'default')
{
$this->aStatusInfo['date_format'] = AttributeDateTime::GetFormat();
}
else
{
$this->aStatusInfo['date_format'] = utils::ReadParam('date_format', AttributeDateTime::GetFormat(), true, 'raw_data');
}
}
public function GetHeader()
@@ -106,7 +141,10 @@ class PDFBulkExport extends HTMLBulkExport
public function GetNextChunk(&$aStatus)
{
$sPrevFormat = AttributeDateTime::GetFormat();
AttributeDateTime::SetFormat($this->aStatusInfo['date_format']);
$sData = parent::GetNextChunk($aStatus);
AttributeDateTime::SetFormat($sPrevFormat);
$hFile = @fopen($this->aStatusInfo['tmp_file'], 'ab');
if ($hFile === false)
{