Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sun, Feb 2, 1:03 AM

in-portal

Index: trunk/core/kernel/utility/formatters.php
===================================================================
--- trunk/core/kernel/utility/formatters.php (revision 2788)
+++ trunk/core/kernel/utility/formatters.php (revision 2789)
@@ -1,1048 +1,1048 @@
<?php
class kFormatter extends kBase {
/**
* Convert's value to match type from config
*
* @param mixed $value
* @param Array $options
* @return mixed
* @access protected
*/
function TypeCast($value, $options)
{
$ret = true;
if( isset($options['type']) )
{
$field_type = $options['type'];
$type_ok = preg_match('#int|integer|double|float|real|numeric|string#', $field_type);
if($field_type == 'string') return $value;
if ($value != '' && $type_ok)
{
$ret = is_numeric($value);
if($ret)
{
$f = 'is_'.$field_type;
settype($value, $field_type);
$ret = $f($value);
}
}
}
return $ret ? $value : false;
}
//function Format($value, $options, &$errors)
function Format($value, $field_name, &$object, $format=null)
{
if ( is_null($value) ) return '';
$options = $object->GetFieldOptions($field_name);
if ( isset($format) ) $options['format'] = $format;
$tc_value = $this->TypeCast($value,$options);
if( ($tc_value === false) || ($tc_value != $value) ) return $value; // for leaving badly formatted date on the form
if (isset($options['format'])) return sprintf($options['format'], $tc_value);
return $tc_value;
}
//function Parse($value, $options, &$errors)
function Parse($value, $field_name, &$object)
{
if ($value == '') return NULL;
$options = $object->GetFieldOptions($field_name);
$tc_value = $this->TypeCast($value,$options);
if($tc_value === false) return $value; // for leaving badly formatted date on the form
if( isset($options['type']) )
{
if( preg_match('#double|float|real|numeric#', $options['type']) ) $tc_value = str_replace(',', '.', $tc_value);
}
if( isset($options['regexp']) )
{
if( !preg_match($options['regexp'], $value) )
{
$object->FieldErrors[$field_name]['pseudo'] = 'invalid_format';
}
}
return $tc_value;
}
function HumanFormat($format)
{
return $format;
}
/**
* The method is supposed to alter config options or cofigure object in some way based on its usage of formatters
* The methods is called for every field with formatter defined when configuring item.
* Could be used for adding additional VirtualFields to an object required by some special Formatter
*
* @param string $field_name
* @param array $field_options
* @param kDBBase $object
*/
function PrepareOptions($field_name, &$field_options, &$object)
{
}
/**
* Used for split fields like timestamp -> date, time
* Called from DBItem to update sub fields values after loading item
*
* @param unknown_type $field
* @param unknown_type $value
* @param unknown_type $options
* @param unknown_type $object
*/
function UpdateSubFields($field, $value, &$options, &$object)
{
}
/**
* Used for split fields like timestamp -> date, time
* Called from DBItem Validate (before validation) to get back master field value from its sub_fields
*
* @param unknown_type $field
* @param unknown_type $value
* @param unknown_type $options
* @param unknown_type $object
*/
function UpdateMasterFields($field, $value, &$options, &$object)
{
}
/* function GetErrorMsg($pseudo_error, $options)
{
if ( isset($options['error_msgs'][$pseudo_error]) ) {
return $options['error_msgs'][$pseudo_error];
}
else {
return $this->ErrorMsgs[$pseudo_error];
}
}*/
function GetSample($field, &$options, &$object)
{
}
}
class kOptionsFormatter extends kFormatter {
//function Format($value, $options, &$errors)
function Format($value, $field_name, &$object, $format=null)
{
if ( is_null($value) ) return '';
$options = $object->GetFieldOptions($field_name);
if ( isset($format) ) $options['format'] = $format;
$label = getArrayValue($options['options'], $value);
if( $label !== false )
{
if( getArrayValue($options,'use_phrases') )
{
return $this->Application->Phrase($label);
}
else
{
return $label;
}
}
else
{
return $value;
}
}
}
/**
* Replacement for kOptionsFormatter in case if options
* should be selected from database. Use this formatter
* only in case if formatter attached field is in edit form.
*
* For usage in grid just use LEFT JOIN clause to table
* where requested options are located.
*/
class kLEFTFormatter extends kFormatter {
//function Format($value, $options, &$errors)
function Format($value, $field_name, &$object, $format=null)
{
if ( is_null($value) ) return '';
$options = $object->GetFieldOptions($field_name);
if ( isset($format) ) $options['format'] = $format;
if( !isset($options['options'][$value]) )
{
// required option is not defined in config => query for it
$db =& $this->Application->GetADODBConnection();
$sql = sprintf($options['left_sql'],$options['left_title_field'],$options['left_key_field'],$value);
$options['options'][$value] = $db->GetOne($sql);
}
return $options['options'][$value];
}
//function Parse($value, $options, &$errors)
function Parse($value, $field_name, &$object)
{
if ($value == '') return NULL;
$options = $object->GetFieldOptions($field_name);
if( !array_search($value,$options['options']) )
{
// required option is not defined in config => query for it
$db =& $this->Application->GetADODBConnection();
$sql = sprintf($options['left_sql'],$options['left_key_field'],$options['left_title_field'],$value);
$found = $db->GetOne($sql);
if($found !== false) $options['options'][$found] = $value;
}
else
{
$found = array_search($value,$options['options']);
}
if($found === false) $found = $options['default'];
return $found;
}
}
class kDateFormatter extends kFormatter {
/* function kDateFormatter()
{
parent::kFormatter();
$this->ErrorMsgs['bad_dformat'] = 'Please use correct date format (%s) ex. (%s)';
}
*/
function PrepareOptions($field_name, &$field_options, &$object)
{
$date_format = getArrayValue($field_options, 'date_format');
$time_format = getArrayValue($field_options, 'time_format');
$language =& $this->Application->recallObject('lang.current');
if ($date_format === false) $date_format = $language->GetDBField('DateFormat');
if ($time_format === false) $time_format = $language->GetDBField('TimeFormat');
if (!isset($field_options['date_time_separator'])) $field_options['date_time_separator'] = ' ';
$field_options['format'] = $date_format.$field_options['date_time_separator'].$time_format;
$field_options['sub_fields'] = Array('date' => $field_name.'_date', 'time' => $field_name.'_time');
$add_fields = Array();
$opts = Array('master_field' => $field_name, 'formatter'=>'kDateFormatter', 'format'=>$date_format);
if ( isset($field_options['default']) ) $opts['default'] = $field_options['default'];
if ( isset($field_options['required']) ) $opts['required'] = $field_options['required'];
$add_fields[$field_name.'_date'] = $opts;
$opts['format'] = $time_format;
$add_fields[$field_name.'_time'] = $opts;
$filter_type = getArrayValue($field_options, 'filter_type');
if($filter_type == 'range')
{
$opts['format'] = $field_options['format'];
$add_fields[$field_name.'_rangefrom'] = $opts;
$add_fields[$field_name.'_rangeto'] = $opts;
}
if ( !isset($object->VirtualFields[$field_name]) ) {
// adding caluclated field to format date directly in the query
if ( !isset($object->CalculatedFields) || !is_array($object->CalculatedFields) ) {
$object->CalculatedFields = Array();
}
$object->CalculatedFields[$field_name.'_formatted'] = 'FROM_UNIXTIME('.'`%1$s`.'.$field_name.', \''.$this->SQLFormat($field_options['format']).'\')';
$opts['format'] = $field_options['format'];
$opts['required'] = 0;
unset($opts['master_field']);
$add_fields[$field_name.'_formatted'] = $opts;
}
$add_fields = array_merge_recursive2($add_fields, $object->VirtualFields);
$object->setVirtualFields($add_fields);
}
function UpdateSubFields($field, $value, &$options, &$object)
{
if ( $sub_fields = getArrayValue($options, 'sub_fields') ) {
if( isset($value) && $value )
{
$object->SetDBField( $sub_fields['date'], $value );
$object->SetDBField( $sub_fields['time'], $value );
}
}
}
function UpdateMasterFields($field, $value, &$options, &$object)
{
// when in master field - set own value from sub_fields
if ( $sub_fields = getArrayValue($options, 'sub_fields') ) {
// if date is not empty, but time is empty - set time to 0, otherwise master field fomratter will complain
// when we have only date field on form, we need time hidden field always empty, don't ask me why!
if ( $object->GetDBField($sub_fields['date']) != '' && $object->GetDBField($sub_fields['time']) == '' ) {
$empty_time = getArrayValue($options,'empty_time');
if($empty_time === false) $empty_time = mktime(0,0,0);
$object->SetDBField($sub_fields['time'], $empty_time);
}
$object->SetField($field, $object->GetField($sub_fields['date']).$options['date_time_separator'].$object->GetField($sub_fields['time']));
}
// when in one of sub_fields - call update for master_field to update its value from sub_fields [are you following ? :) ]
elseif ($master_field = getArrayValue($options, 'master_field') ) {
$opt =& $object->GetFieldOptions($master_field);
$this->UpdateMasterFields($master_field, null, $opt, $object);
}
}
//function Format($value, $options, &$errors)
function Format($value, $field_name, &$object, $format=null)
{
if ( is_null($value) ) return '';
if ( !is_numeric($value) ) return $value; // for leaving badly formatted date on the form
settype($value, 'int');
if ( !is_int($value) ) return $value;
$options = $object->GetFieldOptions($field_name);
if ( isset($format) ) $options['format'] = $format;
return date($options['format'], $value);
}
function HumanFormat($format)
{
$patterns = Array('/m/',
'/n/',
'/d/',
'/j/',
'/y/',
'/Y/',
'/h|H/',
'/g|G/',
'/i/',
'/s/',
'/a|A/');
$replace = Array( 'mm',
'm',
'dd',
'd',
'yy',
'yyyy',
'hh',
'h',
'mm',
'ss',
'AM');
$res = preg_replace($patterns, $replace, $format);
return $res;
}
function SQLFormat($format)
{
$mapping = Array(
'/%/' => '%%',
'/(?<!%)a/' => '%p', // Lowercase Ante meridiem and Post meridiem => MySQL provides only uppercase
'/(?<!%)A/' => '%p', // Uppercase Ante meridiem and Post meridiem
'/(?<!%)d/' => '%d', // Day of the month, 2 digits with leading zeros
'/(?<!%)D/' => '%a', // A textual representation of a day, three letters
'/(?<!%)F/' => '%M', // A full textual representation of a month, such as January or March
'/(?<!%)g/' => '%l', // 12-hour format of an hour without leading zeros
'/(?<!%)G/' => '%k', // 24-hour format of an hour without leading zeros
'/(?<!%)h/' => '%h', // 12-hour format of an hour with leading zeros
'/(?<!%)H/' => '%H', // 24-hour format of an hour with leading zeros
'/(?<!%)i/' => '%i', // Minutes with leading zeros
'/(?<!%)I/' => 'N/A', // Whether or not the date is in daylights savings time
'/(?<!%)S/' => 'N/A', // English ordinal suffix for the day of the month, 2 characters, see below
'/jS/' => '%D', // MySQL can't return separate suffix, but could return date with suffix
'/(?<!%)j/' => '%e', // Day of the month without leading zeros
'/(?<!%)l/' => '%W', // A full textual representation of the day of the week
'/(?<!%)L/' => 'N/A', // Whether it's a leap year
'/(?<!%)m/' => '%m', // Numeric representation of a month, with leading zeros
'/(?<!%)M/' => '%b', // A short textual representation of a month, three letters
'/(?<!%)n/' => '%c', // Numeric representation of a month, without leading zeros
'/(?<!%)O/' => 'N/A', // Difference to Greenwich time (GMT) in hours
'/(?<!%)r/' => 'N/A', // RFC 2822 formatted date
'/(?<!%)s/' => '%s', // Seconds, with leading zeros
// S and jS moved before j - see above
'/(?<!%)t/' => 'N/A', // Number of days in the given month
'/(?<!%)T/' => 'N/A', // Timezone setting of this machine
'/(?<!%)U/' => 'N/A', // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
'/(?<!%)w/' => '%w', // Numeric representation of the day of the week
'/(?<!%)W/' => '%v', // ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)
'/(?<!%)Y/' => '%Y', // A full numeric representation of a year, 4 digits
'/(?<!%)y/' => '%y', // A two digit representation of a year
'/(?<!%)z/' => 'N/A', // The day of the year (starting from 0) => MySQL starts from 1
'/(?<!%)Z/' => 'N/A', // Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.
);
$patterns = array_keys($mapping);
$replacements = array_values($mapping);
$res = preg_replace($patterns, $replacements, $format);
return $res;
}
//function Parse($value, $options, &$errors)
function Parse($value, $field_name, &$object)
{
$options = $object->GetFieldOptions($field_name);
$dt_separator = getArrayValue($options,'date_time_separator');
if($dt_separator) $value = trim($value, $dt_separator);
if($value == '') return NULL;
//return strtotime($value);
$format = $options['format'];
if($dt_separator) $format = trim($format, $dt_separator);
$object->FieldErrors[$field_name]['params'] = Array( $this->HumanFormat($format), date($format) );
$object->FieldErrors[$field_name]['value'] = $value;
$hour = 0;
$minute = 0;
$second = 0;
$month = 1;
$day = 1;
$year = 1970;
$patterns['n'] = '([0-9]{1,2})';
$patterns['m'] = '([0-9]{1,2})';
$patterns['d'] = '([0-9]{1,2})';
$patterns['j'] = '([0-9]{1,2})';
$patterns['Y'] = '([0-9]{4})';
$patterns['y'] = '([0-9]{2})';
$patterns['G'] = '([0-9]{1,2})';
$patterns['g'] = '([0-9]{1,2})';
$patterns['H'] = '([0-9]{2})';
$patterns['h'] = '([0-9]{2})';
$patterns['i'] = '([0-9]{2})';
$patterns['s'] = '([0-9]{2})';
$patterns['a'] = '(am|pm)';
$patterns['A'] = '(AM|PM)';
$holders_mask = eregi_replace('[a-zA-Z]{1}', '([a-zA-Z]{1})', $format);
if (!ereg($holders_mask, $format, $holders)) {
$object->FieldErrors[$field_name]['pseudo'] = 'bad_date_format';
return $value;
}
$values_mask = '/^'.str_replace('/','\/',$format).'$/';
foreach ($patterns as $key => $val) {
$values_mask = ereg_replace($key, $val, $values_mask);
}
// echo " values_mask : $values_mask <br>";
if (!preg_match($values_mask, $value, $values)) {
$object->FieldErrors[$field_name]['pseudo'] = 'bad_date_format';
return $value;
}
for ($i = 1; $i < count($holders); $i++) {
switch ($holders[$i]) {
case 'n':
case 'm':
$month = $values[$i];
$month = ereg_replace("^0{1}", '', $month);
break;
case 'd':
$day = $values[$i];
$day = ereg_replace("^0{1}", '', $day);
break;
case 'Y':
$year = $values[$i];
break;
case 'y':
$year = $values[$i] >= 70 ? 1900 + $values[$i] : 2000 + $values[$i];
break;
case 'H':
case 'h':
case 'G':
case 'g':
$hour = $values[$i];
$hour = ereg_replace("^0{1}", '', $hour);
break;
case 'i':
$minute = $values[$i];
$minute = ereg_replace("^0{1}", '', $minute);
break;
case 's':
$second = $values[$i];
$second = ereg_replace("^0{1}", '', $second);
break;
case 'a':
case 'A':
if ($hour <= 12) { // if AM/PM used with 24-hour - could happen :)
if ($values[$i] == 'pm' || $values[$i] == 'PM') {
$hour += 12;
if ($hour == 24) $hour = 12;
}
elseif ($values[$i] == 'am' || $values[$i] == 'AM') {
if ($hour == 12) $hour = 0;
}
}
break;
}
}
//echo "day: $day, month: $month, year: $year, hour: $hour, minute: $minute<br>";
/*if (!($year >= 1970 && $year <= 2037)) {
$object->FieldErrors[$field_name]['pseudo'] = 'bad_date_format';
return $value;
}*/
if (!($month >= 1 && $month <= 12)) {
$object->FieldErrors[$field_name]['pseudo'] = 'bad_date_format';
return $value;
}
$months_days = Array ( 1 => 31,2 => 28, 3 => 31, 4 => 30,5 => 31,6 => 30, 7 => 31, 8 => 31,9 => 30,10 => 31,11 => 30,12 => 31);
if ($year % 4 == 0) $months_days[2] = 29;
if (!($day >=1 && $day <= $months_days[$month])) {
$object->FieldErrors[$field_name]['pseudo'] = 'bad_date_format';
return $value;
}
if (!($hour >=0 && $hour <= 23)) {
$object->FieldErrors[$field_name]['pseudo'] = 'bad_date_format';
return $value;
}
if (!($minute >=0 && $minute <= 59)) {
$object->FieldErrors[$field_name]['pseudo'] = 'bad_date_format';
return $value;
}
if (!($second >=0 && $second <= 59)) {
$object->FieldErrors[$field_name]['pseudo'] = 'bad_date_format';
return $value;
}
// echo "day: $day, month: $month, year: $year, hour: $hour, minute: $minute<br>";
return (mktime($hour, $minute, $second, $month, $day, $year));
}
function GetSample($field, &$options, &$object)
{
return $this->Format( time(), $field, $object);
}
}
class kUploadFormatter extends kFormatter
{
var $DestinationPath;
var $FullPath;
function kUploadFormatter()
{
if ($this->DestinationPath)
{
$this->FullPath = FULL_PATH.$this->DestinationPath;
}
parent::kBase();
}
//function Parse($value, $options, &$errors)
function Parse($value, $field_name, &$object)
{
$ret = '';
$options = $object->GetFieldOptions($field_name);
if(getArrayValue($options, 'upload_dir'))
{
$this->DestinationPath = $options['upload_dir'];
$this->FullPath = FULL_PATH.$this->DestinationPath;
}
if (getArrayValue($value, 'upload') && getArrayValue($value, 'error') == UPLOAD_ERR_NO_FILE)
{
return getArrayValue($value, 'upload');
}
if ( is_array($value) && $value['size'] )
{
if ( is_array($value) && $value['error'] === UPLOAD_ERR_OK )
{
if ( getArrayValue($options, 'allowed_types') && !in_array($value['type'], $options['allowed_types']) )
{
$object->FieldErrors[$field_name]['pseudo'] = 'bad_file_format';
}
elseif ( $value['size'] > ($options['max_size'] ? $options['max_size'] : MAX_UPLOAD_SIZE) )
{
$object->FieldErrors[$field_name]['pseudo'] = 'bad_file_size';
}
elseif ( !is_writable($this->FullPath) )
{
$object->FieldErrors[$field_name]['pseudo'] = 'cant_save_file';
}
else
{
$real_name = $this->ValidateFileName($this->FullPath, $value['name']);
$file_name = $this->FullPath.$real_name;
if ( !move_uploaded_file($value['tmp_name'], $file_name) )
{
$object->FieldErrors[$field_name]['pseudo'] = 'cant_save_file';
}
else
{
if(getArrayValue($options, 'size_field'))
{
$object->SetDBField($options['size_field'], $value['size']);
}
if(getArrayValue($options, 'orig_name_field'))
{
$object->SetDBField($options['orig_name_field'], $value['name']);
}
$ret = getArrayValue($options, 'upload_dir') ? $real_name : $this->DestinationPath.$real_name;
}
}
}
else
{
$object->FieldErrors[$field_name]['pseudo'] = 'cant_save_file';
}
}
else
{
if(getArrayValue($options, 'required'))
{
$object->FieldErrors[$field_name]['pseudo'] = 'required';
}
}
if ($value['error'] && !( $value['error'] == UPLOAD_ERR_NO_FILE ) && !$object->FieldErrors[$field_name]['pseudo'])
{
$object->FieldErrors[$field_name]['pseudo'] = 'cant_save_file';
}
return $ret;
}
function ValidateFileName($path, $name)
{
$parts = pathinfo($name);
$ext = '.'.$parts['extension'];
$filename = substr($parts['basename'], 0, -strlen($ext));
$new_name = $filename.$ext;
while ( file_exists($path.'/'.$new_name) )
{
if ( preg_match("/({$filename}_)([0-9]*)($ext)/", $new_name, $regs) ) {
$new_name = $regs[1].($regs[2]+1).$regs[3];
}
else {
$new_name = $filename.'_1'.$ext;
}
}
return $new_name;
}
}
class kPictureFormatter extends kUploadFormatter
{
function kPictureFormatter()
{
$this->NakeLookupPath = IMAGES_PATH;
$this->DestinationPath = IMAGES_PENDING_PATH;
parent::kUploadFormatter();
}
}
class kMultiLanguage extends kFormatter
{
function LangFieldName($field_name)
{
$lang = $this->Application->GetVar('m_lang');
return 'l'.$lang.'_'.$field_name;
}
function PrepareOptions($field_name, &$field_options, &$object)
{
if (getArrayValue($object->Fields, $field_name, 'master_field')) return;
$lang_field_name = $this->LangFieldName($field_name);
//substitude title field
$title_field = $this->Application->getUnitOption($object->Prefix, 'TitleField');
if ($title_field == $field_name) {
$this->Application->setUnitOption($object->Prefix, 'TitleField', $lang_field_name);
}
//substitude fields
$fields = $this->Application->getUnitOption($object->Prefix, 'Fields');
if ( isset($fields[$field_name]) ) {
$fields[$lang_field_name] = $fields[$field_name];
$fields[$lang_field_name]['master_field'] = $field_name;
$object->Fields[$lang_field_name] = $fields[$lang_field_name];
$fields[$field_name]['required'] = false;
$object->Fields[$field_name]['required'] = false;
$object->VirtualFields[$field_name] = $object->Fields[$field_name];
}
$this->Application->setUnitOption($object->Prefix, 'Fields', $fields);
//substitude virtual fields
$virtual_fields = $this->Application->getUnitOption($object->Prefix, 'VirtualFields');
if ( isset($virtual_fields[$field_name]) ) {
$virtual_fields[$lang_field_name] = $virtual_fields[$field_name];
$virtual_fields[$lang_field_name]['master_field'] = $field_name;
$object->VirtualFields[$lang_field_name] = $virtual_fields[$lang_field_name];
$virtual_fields[$field_name]['required'] = false;
$object->VirtualFields[$field_name]['required'] = false;
}
$this->Application->setUnitOption($object->Prefix, 'VirtualFields', $virtual_fields);
//substitude grid fields
$grids = $this->Application->getUnitOption($object->Prefix, 'Grids');
foreach ($grids as $name => $grid) {
if ( getArrayValue($grid, 'Fields', $field_name) ) {
array_rename_key($grids[$name]['Fields'], $field_name, $lang_field_name);
}
}
$this->Application->setUnitOption($object->Prefix, 'Grids', $grids);
//substitude default sortings
$sortings = $this->Application->getUnitOption($object->Prefix, 'ListSortings');
foreach ($sortings as $special => $the_sortings) {
if (isset($the_sortings['ForcedSorting'])) {
array_rename_key($sortings[$special]['ForcedSorting'], $field_name, $lang_field_name);
}
if (isset($the_sortings['Sorting'])) {
array_rename_key($sortings[$special]['Sorting'], $field_name, $lang_field_name);
}
}
$this->Application->setUnitOption($object->Prefix, 'ListSortings', $sortings);
//TODO: substitude possible language-fields sortings after changing language
}
/*function UpdateSubFields($field, $value, &$options, &$object)
{
}
function UpdateMasterFields($field, $value, &$options, &$object)
{
}*/
function Format($value, $field_name, &$object, $format=null)
{
$master_field = getArrayValue($object->Fields, $field_name, 'master_field');
if (!$master_field) { // if THIS field is master it does NOT have reference to it's master_field
$lang = $this->Application->GetVar('m_lang');
$value = $object->GetDBField('l'.$lang.'_'.$field_name); //getting value of current language
$master_field = $field_name; // THIS is master_field
}
if ( $value == '' && $format != 'no_default') { // try to get default language value
$def_lang_value = $object->GetDBField('l'.$this->Application->GetDefaultLanguageId().'_'.$master_field);
if ($def_lang_value == '') return NULL;
return $def_lang_value; //return value from default language
}
return $value;
}
function Parse($value, $field_name, &$object)
{
$lang = $this->Application->GetVar('m_lang');
$def_lang = $this->Application->GetDefaultLanguageId();
$master_field = getArrayValue($object->Fields, $field_name, 'master_field');
if ( getArrayValue($object->Fields, $field_name, 'required') && ( (string) $value == '' ) ) {
$object->FieldErrors[$master_field]['pseudo'] = 'required';
};
if (!$this->Application->GetVar('allow_translation') && $lang != $def_lang && getArrayValue($object->Fields, $field_name, 'required')) {
$def_lang_field = 'l'.$def_lang.'_'.$master_field;
if ( !$object->ValidateRequired($def_lang_field, $object->Fields[$field_name]) ) {
$object->FieldErrors[$master_field]['pseudo'] = 'primary_lang_required';
}
}
if ($value == '') return NULL;
return $value;
}
}
class kPasswordFormatter extends kFormatter
{
function PrepareOptions($field_name, &$field_options, &$object)
{
if( isset( $field_options['verify_field'] ) )
{
$add_fields = Array();
$options = Array('master_field' => $field_name, 'formatter'=>'kPasswordFormatter');
$add_fields[ $field_options['verify_field'] ] = $options;
$add_fields[$field_name.'_plain'] = Array('type'=>'string', 'error_field'=>$field_name);
$add_fields[ $field_options['verify_field'].'_plain' ] = Array('type'=>'string', 'error_field'=>$field_options['verify_field'] );
$add_fields = array_merge_recursive2($add_fields, $object->VirtualFields);
$object->setVirtualFields($add_fields);
}
}
function Format($value, $field_name, &$object, $format=null)
{
return $value;
}
function Parse($value, $field_name, &$object)
{
$options = $object->GetFieldOptions($field_name);
$fields = Array('master_field','verify_field');
$fields_set = true;
$flip_count = 0;
while($flip_count < 2)
{
if( getArrayValue($options,$fields[0]) )
{
$object->SetDBField($field_name.'_plain', $value);
if( !getArrayValue($object->Fields[ $options[ $fields[0] ] ], $fields[1].'_set') )
{
$object->Fields[ $options[ $fields[0] ] ][$fields[1].'_set'] = true;
}
$password_field = $options[ $fields[0] ];
$verify_field = $field_name;
}
$fields = array_reverse($fields);
$flip_count++;
}
if( getArrayValue($object->Fields[$password_field], 'verify_field_set') && getArrayValue($object->Fields[$verify_field], 'master_field_set') )
{
$new_password = $object->GetDBField($password_field.'_plain');
$verify_password = $object->GetDBField($verify_field.'_plain');
if($new_password == '' && $verify_password == '')
{
if( $object->GetDBField($password_field) != $this->EncryptPassword('') )
{
return $this->EncryptPassword($value);
}
else
{
$object->Fields[$password_field.'_plain']['required'] = true;
$object->Fields[$verify_field.'_plain']['required'] = true;
return null;
}
}
$min_length = $this->Application->ConfigValue('Min_Password');
if( strlen($new_password) >= $min_length )
{
if($new_password != $verify_password)
{
$object->ErrorMsgs['passwords_do_not_match'] = $this->Application->Phrase('lu_passwords_do_not_match');
$object->FieldErrors[$password_field]['pseudo'] = 'passwords_do_not_match';
$object->FieldErrors[$verify_field]['pseudo'] = 'passwords_do_not_match';
}
}
else
{
$object->ErrorMsgs['passwords_min_length'] = sprintf($this->Application->Phrase('lu_passwords_too_short'), $min_length);
$object->FieldErrors[$password_field]['pseudo'] = 'passwords_min_length';
$object->FieldErrors[$verify_field]['pseudo'] = 'passwords_min_length';
}
}
if($value == '') return $object->GetDBField($field_name);
return $this->EncryptPassword($value);
}
function EncryptPassword($value)
{
return md5($value);
}
}
/**
* Credit card expiration date formatter
*
*/
class kCCDateFormatter extends kFormatter
{
function PrepareOptions($field_name, &$field_options, &$object)
{
$add_fields = Array();
$i = 1;
$options = Array('00' => '');
while($i <= 12)
{
$options[ sprintf('%02d',$i) ] = sprintf('%02d',$i);
$i++;
}
$add_fields[ $field_options['month_field'] ] = Array('formatter'=>'kOptionsFormatter', 'options' => $options, 'not_null' => true, 'default' => '00');
$add_fields[ $field_options['year_field'] ] = Array('type' => 'string', 'default' => '');
$add_fields = array_merge_recursive2($add_fields, $object->VirtualFields);
$object->setVirtualFields($add_fields);
}
function UpdateSubFields($field, $value, &$options, &$object)
{
if(!$value) return false;
$date = explode('/', $value);
$object->SetDBField( $options['month_field'], $date[0] );
$object->SetDBField( $options['year_field'], $date[1] );
}
/**
* Will work in future if we could attach 2 formatters to one field
*
* @param string $value
* @param string $field_name
- * @param kBase $object
+ * @param kDBase $object
* @return string
*/
function Parse($value, $field_name, &$object)
{
// if ( is_null($value) ) return '';
$options = $object->GetFieldOptions($field_name);
$month = $object->GetDirtyField($options['month_field']);
$year = $object->GetDirtyField($options['year_field']);
if( !(int)$month && !(int)$year ) return NULL;
$is_valid = ($month >= 1 && $month <= 12) && ($year >= 0 && $year <= 99);
if(!$is_valid) $object->FieldErrors[$field_name]['pseudo'] = 'bad_type';
return $month.'/'.$year;
}
}
class kUnitFormatter extends kFormatter {
function PrepareOptions($field_name, &$field_options, &$object)
{
if( !isset($field_options['master_field']) )
{
$regional =& $this->Application->recallObject('lang.current');
$add_fields = Array();
$options_a = Array('type' => 'int','error_field' => $field_name,'master_field' => $field_name,'format' => '%d','min_value_inc' => 0 );
$options_b = Array('type' => 'double','error_field' => $field_name,'master_field' => $field_name,'format' => '%0.1f','min_value_inc' => 0);
switch( $regional->GetDBField('UnitSystem') )
{
case 2: // US/UK
$field_options_copy = $field_options;
unset($field_options_copy['min_value_exc']);
$add_fields[$field_name.'_a'] = array_merge_recursive2($field_options_copy, $options_a);
$add_fields[$field_name.'_b'] = array_merge_recursive2($field_options_copy, $options_b);
break;
default:
}
$add_fields = array_merge_recursive2($add_fields, $object->VirtualFields);
$object->setVirtualFields($add_fields);
}
}
function UpdateMasterFields($field, $value, &$options, &$object)
{
if( !isset($options['master_field']) )
{
$regional =& $this->Application->recallObject('lang.current');
switch( $regional->GetDBField('UnitSystem') )
{
case 2: // US/UK
$major = $object->GetDirtyField($field.'_a');
$minor = $object->GetDirtyField($field.'_b');
if($major === '' && $minor === '')
{
$value = null;
}
elseif($major === null && $minor === null)
{
unset($object->Fields[$field]);
return;
}
else
{
$value = $major / 2 + $minor / 32;
}
break;
default:
}
$object->SetDBField($field, $value);
}
}
function UpdateSubFields($field, $value, &$options, &$object)
{
if( !isset($options['master_field']) )
{
$regional =& $this->Application->recallObject('lang.current');
switch( $regional->GetDBField('UnitSystem') )
{
case 2: // US/UK
if($value === null)
{
$major = null;
$minor = null;
}
else
{
$major = floor( $value / 0.5 );
$minor = ($value - $major * 0.5) * 32;
}
$object->SetDBField($field.'_a', $major);
$object->SetDBField($field.'_b', $minor);
break;
default:
}
}
}
}
class kFilesizeFormatter extends kFormatter {
function Format($value, $field_name, &$object, $format=null)
{
if ($value >= 1099511627776) {
$return = round($value / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "Tb";
} elseif ($value >= 1073741824) {
$return = round($value / 1024 / 1024 / 1024, 2);
$suffix = "Gb";
} elseif ($value >= 1048576) {
$return = round($value / 1024 / 1024, 2);
$suffix = "Mb";
} elseif ($value >= 1024) {
$return = round($value / 1024, 2);
$suffix = "Kb";
} else {
$return = $value;
$suffix = "B";
}
$return .= ' '.$suffix;
return $return;
}
}
?>
Property changes on: trunk/core/kernel/utility/formatters.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.21
\ No newline at end of property
+1.22
\ No newline at end of property

Event Timeline