Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Fri, Jul 18, 3:27 AM

in-portal

Index: trunk/core/kernel/utility/formatters.php
===================================================================
--- trunk/core/kernel/utility/formatters.php (revision 3522)
+++ trunk/core/kernel/utility/formatters.php (revision 3523)
@@ -1,1063 +1,1063 @@
<?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 = adodb_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 adodb_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), adodb_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 adodb_mktime($hour, $minute, $second, $month, $day, $year);
}
function GetSample($field, &$options, &$object)
{
return $this->Format( adodb_mktime(), $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']);
}
if(getArrayValue($options, 'content_type_field'))
{
$object->SetDBField($options['content_type_field'], $value['type']);
}
$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 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' );
- $options_b = Array('type' => 'double','error_field' => $field_name,'master_field' => $field_name,'format' => '%0.1f' );
+ $options_b = Array('type' => 'double','error_field' => $field_name,'master_field' => $field_name,'format' => '%0.2f' );
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 = Pounds2Kg($major, $minor);
}
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
{
list($major,$minor) = Kg2Pounds($value);
/*$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;
}
}
class kSerializedFormatter extends kFormatter {
function Format($value, $field_name, $object, $format=null)
{
$data = unserialize($value);
return $data[$format];
}
}
?>
Property changes on: trunk/core/kernel/utility/formatters.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.28
\ No newline at end of property
+1.29
\ No newline at end of property
Index: trunk/core/kernel/globals.php
===================================================================
--- trunk/core/kernel/globals.php (revision 3522)
+++ trunk/core/kernel/globals.php (revision 3523)
@@ -1,398 +1,398 @@
<?php
if( !function_exists('array_merge_recursive2') )
{
/**
* array_merge_recursive2()
*
* Similar to array_merge_recursive but keyed-valued are always overwritten.
* Priority goes to the 2nd array.
*
* @static yes
* @param $paArray1 array
* @param $paArray2 array
* @return array
* @access public
*/
function array_merge_recursive2($paArray1, $paArray2)
{
if (!is_array($paArray1) or !is_array($paArray2)) { return $paArray2; }
foreach ($paArray2 AS $sKey2 => $sValue2)
{
$paArray1[$sKey2] = array_merge_recursive2( getArrayValue($paArray1,$sKey2), $sValue2);
}
return $paArray1;
}
}
/**
* @return int
* @param $array array
* @param $value mixed
* @desc Prepend a reference to an element to the beginning of an array. Renumbers numeric keys, so $value is always inserted to $array[0]
*/
function array_unshift_ref(&$array, &$value)
{
$return = array_unshift($array,'');
$array[0] =& $value;
return $return;
}
if (!function_exists('print_pre')) {
/**
* Same as print_r, budet designed for viewing in web page
*
* @param Array $data
* @param string $label
*/
function print_pre($data, $label='')
{
if( constOn('DEBUG_MODE') )
{
global $debugger;
if($label) $debugger->appendHTML('<b>'.$label.'</b>');
$debugger->dumpVars($data);
}
else
{
if($label) echo '<b>',$label,'</b><br>';
echo '<pre>',print_r($data,true),'</pre>';
}
}
}
if (!function_exists('getArrayValue')) {
/**
* Returns array value if key exists
*
* @param Array $array searchable array
* @param int $key array key
* @return string
* @access public
*/
//
function getArrayValue(&$array,$key)
{
$ret = isset($array[$key]) ? $array[$key] : false;
if ($ret && func_num_args() > 2) {
for ($i = 2; $i < func_num_args(); $i++) {
$cur_key = func_get_arg($i);
$ret = getArrayValue( $ret, $cur_key );
if ($ret === false) break;
}
}
return $ret;
}
}
/**
* Rename key in associative array, maintaining keys order
*
* @param Array $array Associative Array
* @param mixed $old Old key name
* @param mixed $new New key name
* @access public
*/
function array_rename_key(&$array, $old, $new)
{
foreach ($array as $key => $val)
{
$new_array[ $key == $old ? $new : $key] = $val;
}
$array = $new_array;
}
if( !function_exists('safeDefine') )
{
/**
* Define constant if it was not already defined before
*
* @param string $const_name
* @param string $const_value
* @access public
*/
function safeDefine($const_name, $const_value)
{
if(!defined($const_name)) define($const_name,$const_value);
}
}
if( !function_exists('parse_portal_ini') )
{
function parse_portal_ini($file, $parse_section = false)
{
if (!file_exists($file)) return false;
if( file_exists($file) && !is_readable($file) ) die('Could Not Open Ini File');
$contents = file($file);
$retval = Array();
$section = '';
$ln = 1;
$resave = false;
foreach($contents as $line) {
if ($ln == 1 && $line != '<'.'?'.'php die() ?'.">\n") {
$resave = true;
}
$ln++;
$line = trim($line);
$line = eregi_replace(';[.]*','',$line);
if(strlen($line) > 0) {
//echo $line . " - ";
if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) {
//echo 'section';
$section = substr($line,1,(strlen($line)-2));
if ($parse_section) {
$retval[$section] = array();
}
continue;
} elseif(eregi('=',$line)) {
//echo 'main element';
list($key,$val) = explode(' = ',$line);
if (!$parse_section) {
$retval[trim($key)] = str_replace('"', '', $val);
}
else {
$retval[$section][trim($key)] = str_replace('"', '', $val);
}
} //end if
//echo '<br />';
} //end if
} //end foreach
if($resave)
{
$fp = fopen($file, 'w');
reset($contents);
fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
foreach($contents as $line) fwrite($fp,"$line");
fclose($fp);
}
return $retval;
}
}
if( !function_exists('getmicrotime') )
{
function getmicrotime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
}
if( !function_exists('k4_include_once') )
{
function k4_include_once($file)
{
if ( constOn('DEBUG_MODE') && isset($debugger) && constOn('DBG_PROFILE_INCLUDES') )
{
if ( in_array($file, get_required_files()) ) return;
global $debugger;
$debugger->IncludeLevel++;
$before_time = getmicrotime();
$before_mem = memory_get_usage();
include_once($file);
$used_time = getmicrotime() - $before_time;
$used_mem = memory_get_usage() - $before_mem;
$debugger->IncludeLevel--;
$debugger->IncludesData['file'][] = str_replace(FULL_PATH, '', $file);
$debugger->IncludesData['mem'][] = $used_mem;
$debugger->IncludesData['time'][] = $used_time;
$debugger->IncludesData['level'][] = $debugger->IncludeLevel;
}
else
{
include_once($file);
}
}
}
/**
* Checks if string passed is serialized array
*
* @param string $string
* @return bool
*/
function IsSerialized($string)
{
if( is_array($string) ) return false;
return preg_match('/a:([\d]+):{/', $string);
}
if (!function_exists('makepassword4')){
function makepassword4($length=10)
{
$pass_length=$length;
$p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
$p2=array('a','e','i','o','u');
$p3=array('1','2','3','4','5','6','7','8','9');
$p4=array('(','&',')',';','%'); // if you need real strong stuff
// how much elements in the array
// can be done with a array count but counting once here is faster
$s1=21;// this is the count of $p1
$s2=5; // this is the count of $p2
$s3=9; // this is the count of $p3
$s4=5; // this is the count of $p4
// possible readable combinations
$c1='121'; // will be like 'bab'
$c2='212'; // will be like 'aba'
$c3='12'; // will be like 'ab'
$c4='3'; // will be just a number '1 to 9' if you dont like number delete the 3
// $c5='4'; // uncomment to active the strong stuff
$comb='4'; // the amount of combinations you made above (and did not comment out)
for ($p=0;$p<$pass_length;)
{
mt_srand((double)microtime()*1000000);
$strpart=mt_rand(1,$comb);
// checking if the stringpart is not the same as the previous one
if($strpart<>$previous)
{
$pass_structure.=${'c'.$strpart};
// shortcutting the loop a bit
$p=$p+strlen(${'c'.$strpart});
}
$previous=$strpart;
}
// generating the password from the structure defined in $pass_structure
for ($g=0;$g<strlen($pass_structure);$g++)
{
mt_srand((double)microtime()*1000000);
$sel=substr($pass_structure,$g,1);
$pass.=${'p'.$sel}[mt_rand(0,-1+${'s'.$sel})];
}
return $pass;
}
}
if( !function_exists('unhtmlentities') )
{
function unhtmlentities($string)
{
$trans_tbl = get_html_translation_table(HTML_ENTITIES);
$trans_tbl = array_flip ($trans_tbl);
return strtr($string, $trans_tbl);
}
}
if( !function_exists('curl_post') )
{
/**
* submits $url with $post as POST
*
* @param string $url
* @param unknown_type $post
* @return unknown
*/
function curl_post($url, $post)
{
if( is_array($post) )
{
$params_str = '';
foreach($post as $key => $value) $params_str .= $key.'='.urlencode($value).'&';
$post = $params_str;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_REFERER, PROTOCOL.SERVER_NAME);
curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, 0);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
}
if( !function_exists('memory_get_usage') )
{
function memory_get_usage(){ return -1; }
}
function &ref_call_user_func_array($callable, $args)
{
if( is_scalar($callable) )
{
// $callable is the name of a function
$call = $callable;
}
else
{
if( is_object($callable[0]) )
{
// $callable is an object and a method name
$call = "\$callable[0]->{$callable[1]}";
}
else
{
// $callable is a class name and a static method
$call = "{$callable[0]}::{$callable[1]}";
}
}
// Note because the keys in $args might be strings
// we do this in a slightly round about way.
$argumentString = Array();
$argumentKeys = array_keys($args);
foreach($argumentKeys as $argK)
{
$argumentString[] = "\$args[$argumentKeys[$argK]]";
}
$argumentString = implode($argumentString, ', ');
// Note also that eval doesn't return references, so we
// work around it in this way...
eval("\$result =& {$call}({$argumentString});");
return $result;
}
if( !function_exists('constOn') )
{
/**
* Checks if constant is defined and has positive value
*
* @param string $const_name
* @return bool
*/
function constOn($const_name)
{
return defined($const_name) && constant($const_name);
}
}
function Kg2Pounds($kg)
{
- $major = floor( round($kg / POUND_TO_KG, 2) );
+ $major = floor( round($kg / POUND_TO_KG, 3) );
$minor = abs(round(($kg - $major * POUND_TO_KG) / POUND_TO_KG * 16, 2));
return array($major, $minor);
}
function Pounds2Kg($pounds, $ounces=0)
{
- return round(($pounds + ($ounces / 16)) * POUND_TO_KG, 4);
+ return round(($pounds + ($ounces / 16)) * POUND_TO_KG, 5);
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/globals.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.18
\ No newline at end of property
+1.19
\ No newline at end of property

Event Timeline