Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sun, Jan 5, 7:31 PM

in-portal

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: branches/RC/kernel/units/files/file_tp.php
===================================================================
--- branches/RC/kernel/units/files/file_tp.php (revision 10097)
+++ branches/RC/kernel/units/files/file_tp.php (revision 10098)
@@ -1,25 +1,25 @@
<?php
class FileTagProcessor extends kDBTagProcessor {
function DownloadFileLink($params)
{
$params[$this->getPrefixSpecial().'_event'] = 'OnDownloadFile';
$params['pass'] = 'm,'.$this->Application->getUnitOption($this->Prefix, 'ParentPrefix').','.$this->getPrefixSpecial();
return $this->ItemLink($params);
}
function FileIcon($params)
{
$object =& $this->getObject($params);
/* @var $object kDBItem */
- $last_dot = strrpos($object->GetDBField('FilePath'), '.');
- $ext = ($last_dot !== false) ? substr($object->GetDBField('FilePath'), $last_dot + 1).'.gif' : '';
+ $last_dot = mb_strrpos($object->GetDBField('FilePath'), '.');
+ $ext = ($last_dot !== false) ? mb_substr($object->GetDBField('FilePath'), $last_dot + 1).'.gif' : '';
return $ext ? $ext : $params['default'];
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/kernel/units/files/file_tp.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1.2.2
\ No newline at end of property
+1.1.2.3
\ No newline at end of property
Index: branches/RC/kernel/units/images/image_tag_processor.php
===================================================================
--- branches/RC/kernel/units/images/image_tag_processor.php (revision 10097)
+++ branches/RC/kernel/units/images/image_tag_processor.php (revision 10098)
@@ -1,331 +1,331 @@
<?php
class ImageTagProcessor extends kDBTagProcessor {
/**
* Prepares all image parameters as list block parameters (for easy usage)
*
* @param kDBList $object
* @param Array $block_params
* @author Alex
*/
function PrepareListElementParams(&$object, &$block_params)
{
$image_url = $this->ImageSrc($block_params);
if (!$image_url) {
return ;
}
$parent_prefix = $this->Application->getUnitOption($object->Prefix, 'ParentPrefix');
$parent_item =& $this->Application->recallObject($parent_prefix);
$block_params['img_path'] = $image_url;
$image_dimensions = $this->ImageSize($block_params);
$block_params['img_size'] = $image_dimensions ? $image_dimensions : ' width="'.$block_params['DefaultWidth'].'"';
$block_params['alt'] = htmlspecialchars($this->getItemTitle($parent_item)); // $object->GetField('AltName') really used ?
$block_params['align'] = array_key_exists('align', $block_params) ? $block_params['align'] : 'left';
}
/**
* Returns value of object's title field
*
* @param kDBItem $object
* @return string
*/
function getItemTitle(&$object)
{
$title_field = $this->Application->getUnitOption($object->Prefix, 'TitleField');
return $object->GetField($title_field);
}
/**
* [AGGREGATED TAGS] works as <inp2:CatalogItemPrefix_Image, ImageSize, ImageSrc ..../>
*
* @param Array $params
* @return string
*/
function ItemImageTag($params)
{
$this->LoadItemImage($params);
return $this->$params['original_tag']($params);
}
function LargeImageExists($params)
{
$object =& $this->getObject($params);
if ($object->GetDBField('SameImages') == null || $object->GetDBField('SameImages') == 1) {
return false;
}
else {
return true;
}
}
function LoadItemImage($params)
{
$parent_item =& $this->Application->recallObject($params['PrefixSpecial']);
/* @var $parent_item kCatDBItem */
$object =& $this->Application->recallObject($this->getPrefixSpecial(), null, Array('skip_autoload' => true));
/* @var $object kDBItem */
$object->Clear();
// if we need primary thumbnail which is preloaded with category item's list
$is_primary = $this->SelectParam($params, 'primary,Primary');
$image_id = $this->Application->GetVar($this->Prefix.'_id');
if (
// is primary, when primary mark set OR name & field not given
($is_primary || !(isset($params['name']) || isset($params['field']))) &&
// primary image is preloaded AND direct id not given
isset($parent_item->Fields['ThumbPath']) && !$image_id
) {
$object->SetDefaultValues();
$object->SetDBField('Url', $parent_item->GetDBField('FullUrl'));
$object->SetDBField('AltName', $this->getItemTitle($parent_item));
$object->SetDBFieldsFromHash($parent_item->GetFieldValues(), Array('SameImages', 'LocalThumb', 'ThumbPath', 'ThumbUrl', 'LocalImage', 'LocalPath'));
$object->Loaded = true;
}
else { // if requested image is not primary thumbnail - load it directly
$id_field = $this->Application->getUnitOption($this->Prefix, 'ForeignKey');
$parent_table_key = $this->Application->getUnitOption($this->Prefix, 'ParentTableKey');
$keys[$id_field] = $parent_item->GetDBField($parent_table_key);
// which image to load?
if ($is_primary) {
// by PrimaryImage mark
$keys['DefaultImg'] = 1;
}
elseif (getArrayValue($params, 'name')) {
// by ImageName
$keys['Name'] = $params['name'];
}
elseif (getArrayValue($params, 'field')) {
// by virtual field name in main object
$field_options = $parent_item->GetFieldOptions($params['field']);
$keys['Name'] = isset($field_options['original_field']) ? $field_options['original_field'] : $params['field'];
}
elseif ($image_id) {
// by ID
$keys['ImageId'] = $image_id;
}
else {
// by PrimaryImage if no other criteria given
$keys['DefaultImg'] = 1;
}
$object->Load($keys);
if (isset($params['field'])) {
$image_src = $parent_item->GetDBField($params['field']);
// when image is uploaded to virtual field in main item, but not saved to db
$object->SetDBField('ThumbPath', $image_src);
if (!$object->isLoaded()) {
// set fields for displaing new image during main item suggestion with errors
$fields_hash = Array (
'Url' => '',
'ThumbUrl' => '',
'LocalPath' => '',
'SameImages' => 1,
'LocalThumb' => 1,
'LocalImage' => 1,
);
$object->SetDBFieldsFromHash($fields_hash);
$object->Loaded = true;
}
}
}
}
function getImageDimension($type, $params)
{
$ret = isset($params['Max'.$type]) ? $params['Max'.$type] : false;
if (!$ret) {
return $ret;
}
$parent_prefix = $this->Application->getUnitOption($this->Prefix, 'ParentPrefix');
if ($ret == 'thumbnail') {
$ret = $this->Application->ConfigValue($parent_prefix.'_ThumbnailImage'.$type);
}
if ($ret == 'fullsize') {
$ret = $this->Application->ConfigValue($parent_prefix.'_FullImage'.$type);
}
return $ret;
}
/**
* Appends "/" to beginning of image path (in case when missing)
*
* @param kDBItem $object
* @todo old in-portal doesn't append first slash, but we do => append first slash for him :)
*/
function makeRelativePaths(&$object)
{
$thumb_path = $object->GetDBField('ThumbPath');
if ($thumb_path && substr($thumb_path, 0, 1) != '/') {
$object->SetDBField('ThumbPath', '/'.$thumb_path);
}
$local_path = $object->GetDBField('LocalPath');
if ($local_path && substr($local_path, 0, 1) != '/') {
$object->SetDBField('LocalPath', '/'.$local_path);
}
}
function ImageSrc($params)
{
$object =& $this->getObject($params);
$this->makeRelativePaths($object);
$base_url = rtrim($this->Application->BaseURL(), '/');
if ($object->GetDBField('SameImages') && $object->GetDBField('ThumbPath')) {
// we can auto-resize image, when source image available & we use same image for thumbnail & full image in admin
$max_width = $this->getImageDimension('Width', $params);
$max_height = $this->getImageDimension('Height', $params);
// user watermarks from format param
if (!$max_width) {
$max_width = $params['format'];
if ($max_width) {
$max_height = null;
}
}
if ($max_width > 0 || $max_height > 0 || $params['format']) {
$image_helper =& $this->Application->recallObject('ImageHelper');
/* @var $image_helper ImageHelper */
$src_image = FULL_PATH.$object->GetDBField('ThumbPath');
return $image_helper->ResizeImage($src_image, $max_width, $max_height);
}
}
$ret = '';
// if we need thumbnail, or full image is same as thumbnail
$show_thumbnail = $this->SelectParam($params, 'thumbnail,Thumbnail') || // old style
(isset($params['MaxWidth']) && $params['MaxWidth'] == 'thumbnail') || // new style
(isset($params['MaxHeight']) && $params['MaxHeight'] == 'thumbnail');
if ($show_thumbnail || $object->GetDBField('SameImages')) {
// return local image or url
$ret = $object->GetDBField('LocalThumb') ? $base_url.$object->GetDBField('ThumbPath') : $object->GetDBField('ThumbUrl');
if ($object->GetDBField('LocalThumb') && !file_exists(FULL_PATH.$object->GetDBField('ThumbPath')) && !constOn('DBG_IMAGE_RECOVERY')) {
// local thumbnail file is missing
$ret = '';
}
}
else { // if we need full which is not the same as thumb
$ret = $object->GetDBField('LocalImage') ? $base_url.$object->GetDBField('LocalPath') : $object->GetDBField('Url');
if ($object->GetDBField('LocalImage') && !file_exists(FULL_PATH.$object->GetDBField('LocalPath'))) {
// local full image file is missing
$ret = '';
}
}
$default_image = $this->SelectParam($params, 'default_image,DefaultImage');
return ($ret && $ret != $base_url) ? $ret : ($default_image ? $base_url.THEMES_PATH.'/'.$default_image : false);
}
function getFullPath($path)
{
if (!$path) {
return $path;
}
// absolute url
if (preg_match('/^(.*):\/\/(.*)$/U', $path)) {
return preg_replace('/^'.preg_quote($this->Application->BaseURL(), '/').'(.*)/', FULL_PATH.'/\\1', $path);
}
// relative url
- return FULL_PATH.'/'.substr(THEMES_PATH, 1).'/'.$path;
+ return FULL_PATH.'/'.mb_substr(THEMES_PATH, 1).'/'.$path;
}
/**
* Makes size clause for img tag, such as
* ' width="80" height="100"' according to max_width
* and max_heght limits.
*
* @param array $params
* @return string
*/
function ImageSize($params)
{
$img_path = $this->getFullPath($params['img_path']);
$image_helper =& $this->Application->recallObject('ImageHelper');
/* @var $image_helper ImageHelper */
$max_width = $this->getImageDimension('Width', $params);
$max_height = $this->getImageDimension('Height', $params);
$image_dimensions = $image_helper->GetImageDimensions($img_path, $max_width, $max_height);
if (!$image_dimensions) {
return false;
}
return ' width="'.$image_dimensions[0].'" height="'.$image_dimensions[1].'"';
}
/**
* Prepares image parameters & parses block with them (for admin)
*
* @param Array $params
* @return string
*/
function Image($params)
{
$image_url = $this->ImageSrc($params);
if (!$image_url) {
return ;
}
$object =& $this->getObject($params);
$params['img_path'] = $image_url;
$image_dimensions = $this->ImageSize($params);
$params['img_size'] = $image_dimensions ? $image_dimensions : ' width="'.$params['DefaultWidth'].'"';
$params['alt'] = htmlspecialchars($object->GetField('AltName')); // really used ?
$params['name'] = $this->SelectParam($params, 'block,render_as');
$params['align'] = array_key_exists('align', $params) ? $params['align'] : 'left';
if (!$object->isLoaded() && !$this->SelectParam($params, 'default_image,DefaultImage')) {
return false;
}
return $this->Application->ParseBlock($params);
}
/**
* Returns url for image in case when image source is url (for admin)
*
* @param Array $params
* @return string
*/
function ImageUrl($params)
{
$object =& $this->getObject($params);
if ($object->GetDBField('SameImages') ? $object->GetDBField('LocalThumb') : $object->GetDBField('LocalImage') ) {
$ret = $this->Application->Phrase(getArrayValue($params,'local_phrase'));
}
else {
$ret = $object->GetDBField('SameImages') ? $object->GetDBField('ThumbUrl') : $object->GetDBField('Url');
}
return $ret;
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/kernel/units/images/image_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.13.2.5
\ No newline at end of property
+1.13.2.6
\ No newline at end of property
Index: branches/RC/kernel/units/images/image_event_handler.php
===================================================================
--- branches/RC/kernel/units/images/image_event_handler.php (revision 10097)
+++ branches/RC/kernel/units/images/image_event_handler.php (revision 10098)
@@ -1,350 +1,350 @@
<?php
class ImageEventHandler extends kDBEventHandler {
function mapEvents()
{
parent::mapEvents(); // ensure auto-adding of approve/decine and so on events
$image_events = Array(
'OnAfterCopyToTemp'=>'ImageAction',
'OnBeforeDeleteFromLive'=>'ImageAction',
'OnBeforeCopyToLive'=>'ImageAction',
'OnBeforeItemDelete'=>'ImageAction',
'OnAfterClone'=>'ImageAction',
);
$this->eventMethods = array_merge($this->eventMethods, $image_events);
}
/**
* Get's special of main item for linking with subitem
*
* @param kEvent $event
* @return string
*/
function getMainSpecial(&$event)
{
if ($event->Special == 'list' && !$this->Application->IsAdmin()) {
// ListImages aggregated tag uses this special
return '';
}
-
+
return parent::getMainSpecial($event);
}
-
+
function customProcessing(&$event, $type)
{
$object =& $event->GetObject();
switch ($type)
{
case 'before' :
if ($object->GetDBField('LocalImage'))
{
$object->SetDBField('Url', '');
}
else
{
$object->SetDBField('LocalPath', '');
}
if ($object->GetDBField('LocalThumb'))
{
$object->SetDBField('ThumbUrl', '');
}
else
{
$object->SetDBField('ThumbPath', '');
}
if ($object->GetDBField('SameImages'))
{
$object->SetDBField('LocalImage', 1);
$object->SetDBField('LocalPath', '');
$object->SetDBField('Url', '');
}
break;
case 'after' :
if ($object->GetDBField('DefaultImg') )
{
$sql = 'UPDATE '.$object->TableName.' SET DefaultImg=0 WHERE ResourceId='.
$object->GetDBField('ResourceId').' AND ImageId<>'.
$object->GetId();
$res = $this->Conn->Query($sql);
}
break;
default:
}
}
function ImageAction(&$event)
{
$id = $event->getEventParam('id');
$object =& $this->Application->recallObject($event->Prefix.'.-item', $event->Prefix);
if (in_array($event->Name, Array('OnBeforeDeleteFromLive','OnAfterClone')) ) {
$object->SwitchToLive();
}
elseif ($event->Name == 'OnBeforeItemDelete') {
// keep current table
}
else {
$object->SwitchToTemp();
}
$object->Load($id);
$fields = Array('LocalPath' => 'LocalImage', 'ThumbPath' => 'LocalThumb');
foreach ($fields as $a_field => $mode_field) {
$file = $object->GetField($a_field);
if (!$file) continue;
$source_file = FULL_PATH.$file;
switch ($event->Name) {
// Copy image files to pending dir and update corresponding fields in temp record
// Checking for existing files and renaming if nessessary - two users may upload same pending files at the same time!
case 'OnAfterCopyToTemp':
$new_file = IMAGES_PENDING_PATH . $this->ValidateFileName(FULL_PATH.IMAGES_PENDING_PATH, basename($file));
$dest_file = FULL_PATH.$new_file;
copy($source_file, $dest_file);
$object->Fields[$a_field]['skip_empty'] = false;
$object->SetDBField($a_field, $new_file);
break;
// Copy image files to live dir (checking if fileexists and renameing if nessessary)
// and update corresponding fields in temp record (which gets copied to live automatically)
case 'OnBeforeCopyToLive':
if ( $object->GetDBField($mode_field) ) { // if image is local
// rename file if it exists in live folder
$new_file = IMAGES_PATH . $this->ValidateFileName(FULL_PATH.IMAGES_PATH, basename($file));
$dest_file = FULL_PATH.$new_file;
rename($source_file, $dest_file);
}
else { // if image is remote url - remove local file (if any), update local file field with empty value
if (file_exists($source_file)) @unlink($source_file);
$new_file = '';
}
$object->Fields[$a_field]['skip_empty'] = false;
$object->SetDBField($a_field, $new_file);
break;
case 'OnBeforeDeleteFromLive': // Delete image files from live folder before copying over from temp
case 'OnBeforeItemDelete': // Delete image files when deleteing Image object
@unlink(FULL_PATH.$file);
break;
case 'OnAfterClone': // Copy files when cloning objects, renaming it on the fly
$path_info = pathinfo($file);
$new_file = $path_info['dirname'].'/'.$this->ValidateFileName(FULL_PATH.$path_info['dirname'], $path_info['basename']);
$dest_file = FULL_PATH . $new_file;
copy($source_file, $dest_file);
$object->Fields[$a_field]['skip_empty'] = false;
$object->SetDBField($a_field, $new_file);
break;
}
}
if ( in_array($event->Name, Array('OnAfterClone', 'OnBeforeCopyToLive', 'OnAfterCopyToTemp')) ) {
$object->Update(null, true);
}
}
function ValidateFileName($path, $name)
{
$parts = pathinfo($name);
$ext = '.'.$parts['extension'];
- $filename = substr($parts['basename'], 0, -strlen($ext));
+ $filename = mb_substr($parts['basename'], 0, -mb_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;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
$object =& $event->getObject();
$object->SetDBField('DefaultImg', 1);
$object->Update();
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnBeforeItemUpdate(&$event)
{
$object =& $event->getObject();
// $parent_info = $object->getLinkedInfo();
$id = $object->GetDBField('ResourceId');
// $id = $parent_info['ParentId'] ? $parent_info['ParentId'] : $this->Application->GetVar('p_id');
$sql = 'SELECT ImageId FROM '.$object->TableName.' WHERE ResourceId='.$id.' AND DefaultImg=1';
if(!$this->Conn->GetOne($sql))
{
$object->SetDBField('DefaultImg', 1);
}
if($object->GetDBField('DefaultImg') && $object->Validate())
{
$sql = 'UPDATE '.$object->TableName.'
SET DefaultImg = 0
WHERE ResourceId = '.$id.' AND ImageId <> '.$object->GetDBField('ImageId');
$this->Conn->Query($sql);
$object->SetDBField('Enabled', 1);
}
}
function OnAfterItemCreate(&$event)
{
$event->CallSubEvent('OnBeforeItemUpdate');
$object =& $event->getObject();
$object->Update();
}
/**
* Deletes all selected items.
* Automatically recurse into sub-items using temp handler, and deletes sub-items
* by calling its Delete method if sub-item has AutoDelete set to true in its config file
*
* @param kEvent $event
*/
function OnMassDelete(&$event)
{
$event->status=erSUCCESS;
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$event->setEventParam('ids', $this->StoreSelectedIDs($event) );
$this->customProcessing($event, 'before');
$ids = $event->getEventParam('ids');
$object =& $event->getObject();
$sql = 'SELECT ImageId FROM '.$object->TableName.' WHERE DefaultImg=1';
$primary = $this->Conn->GetOne($sql);
if( $primary && ($key = array_search($primary, $ids)) )
{
$sql = 'SELECT ImageId FROM '.$object->TableName.' WHERE DefaultImg=0';
$res = $this->Conn->Query($sql);
if($res)
{
unset($ids[$key]);
}
}
if($ids)
{
$temp->DeleteItems($event->Prefix, $event->Special, $ids);
}
$this->clearSelectedIDs($event);
}
/*function OnAfterItemLoad(&$event)
{
$object =& $event->getObject();
if ( $object->GetDBField('ThumbPath') || $object->GetDBField('SameImages') )
{
// return local image or url
$path = $object->GetDBField('LocalThumb') ? PROTOCOL.SERVER_NAME.BASE_PATH.$object->GetDBField('ThumbPath') : $object->GetDBField('ThumbUrl');
if ( $object->GetDBField('LocalThumb') && !file_exists(FULL_PATH.$object->GetDBField('ThumbPath')) ) $path = '';
}
else { // if we need full which is not the same as thumb
$path = $object->GetDBField('LocalImage') ? PROTOCOL.SERVER_NAME.BASE_PATH.$object->GetDBField('LocalPath') : $object->GetDBField('Url');
if ( $object->GetDBField('LocalImage') && !file_exists(FULL_PATH.$object->GetDBField('LocalPath')) ) $path = '';
}
$object->SetDBField('ImageUrl', $path);
}*/
function SetCustomQuery(&$event)
{
parent::SetCustomQuery($event);
$types=$event->getEventParam('types');
$except_types=$event->getEventParam('except');
$object =& $event->getObject();
$type_clauses = Array();
if( !$this->Application->IsAdmin() )
{
$object->addFilter('active', '%1$s.Enabled = 1');
}
if($product_id = $event->getEventParam('product_id'))
{
$object->removeFilter('parent_filter');
$sql = 'SELECT ResourceId FROM '.$this->Application->getUnitOption('p', 'TableName').'
WHERE ProductId = '.$product_id;
$resource_id = (int) $this->Conn->GetOne($sql);
$object->addFilter('product_images', '%1$s.ResourceId = '.$resource_id);
}
$type_clauses['additional']['include'] = '%1$s.DefaultImg != 1';
$type_clauses['additional']['except'] = '%1$s.DefaultImg = 1';
$type_clauses['additional']['having_filter'] = false;
/********************************************/
$includes_or_filter =& $this->Application->makeClass('kMultipleFilter');
$includes_or_filter->setType(FLT_TYPE_OR);
$excepts_and_filter =& $this->Application->makeClass('kMultipleFilter');
$excepts_and_filter->setType(FLT_TYPE_AND);
$includes_or_filter_h =& $this->Application->makeClass('kMultipleFilter');
$includes_or_filter_h->setType(FLT_TYPE_OR);
$excepts_and_filter_h =& $this->Application->makeClass('kMultipleFilter');
$excepts_and_filter_h->setType(FLT_TYPE_AND);
$except_types_array=explode(',', $types);
if ($types){
$types_array=explode(',', $types);
for ($i=0; $i<sizeof($types_array); $i++){
$type=trim($types_array[$i]);
if (isset($type_clauses[$type])){
if ($type_clauses[$type]['having_filter']){
$includes_or_filter_h->removeFilter('filter_'.$type);
$includes_or_filter_h->addFilter('filter_'.$type, $type_clauses[$type]['include']);
}else{
$includes_or_filter->removeFilter('filter_'.$type);
$includes_or_filter->addFilter('filter_'.$type, $type_clauses[$type]['include']);
}
}
}
}
if ($except_types){
$except_types_array=explode(',', $except_types);
for ($i=0; $i<sizeof($except_types_array); $i++){
$type=trim($except_types_array[$i]);
if (isset($type_clauses[$type])){
if ($type_clauses[$type]['having_filter']){
$excepts_and_filter_h->removeFilter('filter_'.$type);
$excepts_and_filter_h->addFilter('filter_'.$type, $type_clauses[$type]['except']);
}else{
$excepts_and_filter->removeFilter('filter_'.$type);
$excepts_and_filter->addFilter('filter_'.$type, $type_clauses[$type]['except']);
}
}
}
}
$object->addFilter('includes_filter', $includes_or_filter);
$object->addFilter('excepts_filter', $excepts_and_filter);
$object->addFilter('includes_filter_h', $includes_or_filter_h, HAVING_FILTER);
$object->addFilter('excepts_filter_h', $excepts_and_filter_h, HAVING_FILTER);
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/kernel/units/images/image_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.4
\ No newline at end of property
+1.4.2.1
\ No newline at end of property
Index: branches/RC/kernel/units/stylesheets/stylesheets_item.php
===================================================================
--- branches/RC/kernel/units/stylesheets/stylesheets_item.php (revision 10097)
+++ branches/RC/kernel/units/stylesheets/stylesheets_item.php (revision 10098)
@@ -1,43 +1,43 @@
<?php
class StylesheetsItem extends kDBItem
{
function Compile()
{
$selector_item =& $this->Application->recallObject('selectors.item', 'selectors', Array('live_table'=>true, 'skip_autoload' => true) );
$parent_field = $this->Application->getUnitOption($selector_item->Prefix, 'ForeignKey');
$sql_template = 'SELECT '.$selector_item->IDField.' FROM '.$selector_item->TableName.' WHERE '.$parent_field.' = %s ORDER BY SelectorName ASC';
$selectors_ids = $this->Conn->GetCol( sprintf($sql_template, $this->GetID() ) );
$ret = '/* This file is generated automatically. Don\'t edit it manually ! */'."\n\n";
foreach($selectors_ids as $selector_id)
{
$selector_item->Load($selector_id);
$ret .= $selector_item->CompileStyle()."\n";
}
$ret .= $this->GetDBField('AdvancedCSS');
$compile_ts = adodb_mktime();
$css_path = FULL_PATH.'/kernel/stylesheets/';
- $css_file = $css_path.strtolower($this->GetDBField('Name')).'-'.$compile_ts.'.css';
+ $css_file = $css_path.mb_strtolower($this->GetDBField('Name')).'-'.$compile_ts.'.css';
$fp = fopen($css_file,'w');
if($fp)
{
- $prev_css = $css_path.strtolower($this->GetDBField('Name')).'-'.$this->GetDBField('LastCompiled').'.css';
+ $prev_css = $css_path.mb_strtolower($this->GetDBField('Name')).'-'.$this->GetDBField('LastCompiled').'.css';
if( file_exists($prev_css) ) unlink($prev_css);
fwrite($fp, $ret);
fclose($fp);
$sql = 'UPDATE '.$this->TableName.' SET LastCompiled = '.$compile_ts.' WHERE '.$this->IDField.' = '.$this->GetID();
$this->Conn->Query($sql);
}
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/kernel/units/stylesheets/stylesheets_item.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.6
\ No newline at end of property
+1.6.2.1
\ No newline at end of property
Index: branches/RC/core/kernel/processors/main_processor.php
===================================================================
--- branches/RC/core/kernel/processors/main_processor.php (revision 10097)
+++ branches/RC/core/kernel/processors/main_processor.php (revision 10098)
@@ -1,1115 +1,1115 @@
<?php
class kMainTagProcessor extends TagProcessor {
function Init($prefix, $special, $event_params = null)
{
parent::Init($prefix, $special, $event_params);
$actions =& $this->Application->recallObject('kActions');
$actions->Set('t', $this->Application->GetVar('t'));
$actions->Set('sid', $this->Application->GetSID());
$actions->Set('m_opener', $this->Application->GetVar('m_opener') );
}
/**
* Used to handle calls where tag name
* match with existing php function name
*
* @param Tag $tag
* @return string
*/
function ProcessTag(&$tag)
{
if ($tag->Tag=='include') $tag->Tag='MyInclude';
return parent::ProcessTag($tag);
}
/**
* Base folder for all template includes
*
* @param Array $params
* @return string
*/
function TemplatesBase($params)
{
if ($this->Application->IsAdmin()) {
$module = isset($params['module']) ? $params['module'] : 'core';
if ($module == 'in-portal') {
$module = 'kernel';
}
$path = preg_replace('/\/(.*?)\/(.*)/', $module.'/\\2', THEMES_PATH); // remove leading slash + substitute module
}
else {
- $path = substr(THEMES_PATH, 1);
+ $path = mb_substr(THEMES_PATH, 1);
$module = isset($params['module']) ? $params['module'] : 'core';
- if (strtolower($module) == 'in-portal') {
+ if (mb_strtolower($module) == 'in-portal') {
$module_folder = 'platform';
}
else {
$module_folder = $this->Application->findModule('Name', $module, 'TemplatePath');
}
$path .= '/'.trim($module_folder, '/').'/';
}
return $this->Application->BaseURL().$path;
}
/**
* Creates <base href ..> HTML tag for all templates
* affects future css, js files and href params of links
*
* @return string
* @access public
*/
function Base_Ref($params)
{
return '<base href="'.$this->TemplatesBase($params).'/" />';
}
/**
* Returns base url for web-site
*
* @return string
* @access public
*/
function BaseURL()
{
return $this->Application->BaseURL();
}
//for compatability with K3 tags
function Base($params)
{
return $this->TemplatesBase($params).'/';
}
function ProjectBase($params)
{
return $this->Application->BaseURL();
}
/*function Base($params)
{
return $this->Application->BaseURL().$params['add'];
}*/
/**
* Used to create link to any template.
* use "pass" paramter if "t" tag to specify
* prefix & special of object to be represented
* in resulting url
*
* @param Array $params
* @return string
* @access public
*/
function T($params)
{
//by default link to current template
$t = $this->SelectParam($params, 't,template');
unset($params['t']);
unset($params['template']);
$prefix=isset($params['prefix']) ? $params['prefix'] : ''; unset($params['prefix']);
$index_file = isset($params['index_file']) ? $params['index_file'] : null; unset($params['index_file']);
return $this->Application->HREF($t, $prefix, $params, $index_file);
}
function Link($params)
{
if (isset($params['template'])) {
$params['t'] = $params['template'];
unset($params['template']);
}
if (!isset($params['pass']) && !isset($params['no_pass'])) $params['pass'] = 'm';
if (isset($params['no_pass'])) unset($params['no_pass']);
if( $this->Application->GetVar('admin') ) $params['admin'] = 1;
return $this->T($params);
}
function Env($params)
{
$t = $params['template'];
unset($params['template']);
return $this->Application->BuildEnv($t, $params, 'm', null, false);
}
function FormAction($params)
{
$params['pass'] = 'all,m';
$params['pass_category'] = 1;
return $this->Application->HREF('', '', $params);
}
/*// NEEDS TEST
function Config($params)
{
return $this->Application->ConfigOption($params['var']);
}
function Object($params)
{
$name = $params['name'];
$method = $params['method'];
$tmp =& $this->Application->recallObject($name);
if ($tmp != null) {
if (method_exists($tmp, $method))
return $tmp->$method($params);
else
echo "Method $method does not exist in object ".get_class($tmp)." named $name<br>";
}
else
echo "Object $name does not exist in the appliaction<br>";
}*/
/**
* Tag, that always returns true.
* For parser testing purposes
*
* @param Array $params
* @return bool
* @access public
*/
function True($params)
{
return true;
}
/**
* Tag, that always returns false.
* For parser testing purposes
*
* @param Array $params
* @return bool
* @access public
*/
function False($params)
{
return false;
}
/**
* Returns block parameter by name
*
* @param Array $params
* @return stirng
* @access public
*/
function Param($params)
{
//$parser =& $this->Application->recallObject('TemplateParser');
$name = $params['name'];
if (isset($this->Application->LateParsed[$name])) {
$f = $this->Application->PreParsedBlocks['capture_'.$name.$this->Application->LateParsed[$name]];
$this->Application->Parser->SetParam($name, $f(array()));
}
$res = $this->Application->Parser->GetParam($params['name']);
if ($res === false) $res = '';
if (isset($params['plus']))
$res += $params['plus'];
return $res;
}
function DefaultParam($params)
{
foreach ($params as $key => $val) {
if ($this->Application->Parser->GetParam($key) === false) {
$this->Application->Parser->SetParam($key, $val);
}
}
}
/**
* Gets value of specified field from specified prefix_special and set it as parser param
*
* @param Array $params
*/
/*function SetParam($params)
{
// <inp2:m_SetParam param="custom_name" src="cf:FieldName"/>
list($prefix_special, $field_name) = explode(':', $params['src']);
$object =& $this->Application->recallObject($prefix_special);
$name = $this->SelectParam($params, 'param,name,var');
$this->Application->Parser->SetParam($name, $object->GetField($field_name) );
}*/
/**
* Compares block parameter with value specified
*
* @param Array $params
* @return bool
* @access public
*/
function ParamEquals($params)
{
//$parser =& $this->Application->recallObject('TemplateParser');
$name = $this->SelectParam($params, 'name,var,param');
$value = $params['value'];
return ($this->Application->Parser->GetParam($name) == $value);
}
/*function PHP_Self($params)
{
return $HTTP_SERVER_VARS['PHP_SELF'];
}
*/
/**
* Returns session variable value by name
*
* @param Array $params
* @return string
* @access public
*/
function Recall($params)
{
$var_name = $this->SelectParam($params,'name,var,param');
if (isset($params['persistent']) && $params['persistent']) {
$ret = $this->Application->RecallPersistentVar($var_name);
}
else {
$ret = $this->Application->RecallVar($var_name);
}
$ret = ($ret === false && isset($params['no_null'])) ? '' : $ret;
if (getArrayValue($params, 'special') || getArrayValue($params, 'htmlchars')) {
$ret = htmlspecialchars($ret);
}
if (getArrayValue($params, 'urlencode')) {
$ret = urlencode($ret);
}
return $ret;
}
function RemoveVar($params)
{
$this->Application->RemoveVar( $this->SelectParam($params,'name,var,param') );
}
// bad style to store something from template to session !!! (by Alex)
// Used here only to test how session works, nothing more
function Store($params)
{
//echo"Store $params[name]<br>";
$name = $params['name'];
$value = $params['value'];
$this->Application->StoreVar($name,$value);
}
/**
* Sets application variable value(-s)
*
* @param Array $params
* @access public
*/
function Set($params)
{
foreach ($params as $param => $value) {
$this->Application->SetVar($param, $value);
}
}
/**
* Increment application variable
* specified by number specified
*
* @param Array $params
* @access public
*/
function Inc($params)
{
$this->Application->SetVar($params['param'], $this->Application->GetVar($params['param']) + $params['by']);
}
/**
* Retrieves application variable
* value by name
*
* @param Array $params
* @return string
* @access public
*/
function Get($params)
{
$ret = $this->Application->GetVar($this->SelectParam($params, 'name,var,param'), '');
return getArrayValue($params, 'htmlchars') ? htmlspecialchars($ret) : $ret;
}
/**
* Retrieves application constant
* value by name
*
* @param Array $params
* @return string
* @access public
*/
function GetConst($params)
{
return defined($this->SelectParam($params, 'name,const')) ? constant($this->SelectParam($params, 'name,const,param')) : '';
}
/**
* Retrieves configuration variable value by name
*
* @param Array $params
* @return string
* @access public
*/
function GetConfig($params)
{
$config_name = $this->SelectParam($params, 'name,var');
$ret = $this->Application->ConfigValue($config_name);
if( getArrayValue($params, 'escape') ) $ret = addslashes($ret);
return $ret;
}
function ConfigEquals($params)
{
$option = $this->SelectParam($params, 'name,option,var');
return $this->Application->ConfigValue($option) == getArrayValue($params, 'value');
}
/**
* Creates all hidden fields
* needed for kernel_form
*
* @param Array $params
* @return string
* @access public
*/
function DumpSystemInfo($params)
{
$actions =& $this->Application->recallObject('kActions');
$actions->Set('t', $this->Application->GetVar('t') );
$params = $actions->GetParams();
$o='';
foreach ($params AS $name => $val)
{
$o .= "<input type='hidden' name='$name' id='$name' value='$val'>\n";
}
return $o;
}
/**
* Used for search sidebox on front-end only
*
* @param Array $params
* @return string
* @author Alex
*/
function GetFormHiddens($params)
{
$t = $this->SelectParam($params, 'template,t');
unset($params['template']);
$form_fields = Array ();
if ($this->Application->RewriteURLs()) {
$session =& $this->Application->recallObject('Session');
if ($session->NeedQueryString()) {
$form_fields['sid'] = $this->Application->GetSID();
}
}
else {
$form_fields['env'] = $this->Application->BuildEnv($t, $params, 'm', null, false);
}
if ($this->Application->GetVar('admin') == 1) {
$form_fields['admin'] = 1;
}
$ret = '';
$field_tpl = '<input type="hidden" name="%1$s" id="%1$s" value="%2$s"/>'."\n";
foreach ($form_fields as $form_field => $field_value) {
$ret .= sprintf($field_tpl, $form_field, $field_value);
}
return $ret;
}
function Odd_Even($params)
{
$odd = $params['odd'];
$even = $params['even'];
if (!isset($params['var'])) {
$var = 'odd_even';
}
else {
$var = $params['var'];
}
if ($this->Application->GetVar($var) == 'even') {
if (!isset($params['readonly']) || !$params['readonly']) {
$this->Application->SetVar($var, 'odd');
}
return $even;
}
else {
if (!isset($params['readonly']) || !$params['readonly']) {
$this->Application->SetVar($var, 'even');
}
return $odd;
}
}
/**
* Returns phrase translation by name
*
* @param Array $params
* @return string
* @access public
*/
function Phrase($params)
{
// m:phrase name="phrase_name" default="Tr-alala" updated="2004-01-29 12:49"
$phrase_name = $this->SelectParam($params, 'label,name,title');
if (isset($params['source']) && $params['source']) {
$phrase_name = $this->Application->GetVar($phrase_name);
if (array_key_exists('default', $params) && !$phrase_name) {
$phrase_name = $params['default'];
}
}
$translation = $this->Application->Phrase($phrase_name);
if (isset($params['escape']) && $params['escape']) {
$translation = htmlspecialchars($translation, ENT_QUOTES);
$translation = addslashes($translation);
}
return $translation;
}
// for tabs
function is_active($params)
{
$test_templ = $this->SelectParam($params, 'templ,template,t');
if ( !getArrayValue($params,'allow_empty') )
{
$if_true=getArrayValue($params,'true') ? $params['true'] : 1;
$if_false=getArrayValue($params,'false') ? $params['false'] : 0;
}
else
{
$if_true=$params['true'];
$if_false=$params['false'];
}
if ( preg_match("/^".str_replace('/', '\/', $test_templ)."/i", $this->Application->GetVar('t'))) {
return $if_true;
}
else {
return $if_false;
}
}
function IsNotActive($params)
{
return !$this->is_active($params);
}
function IsActive($params)
{
return $this->is_active($params);
}
function is_t_active($params)
{
return $this->is_active($params);
}
function CurrentTemplate($params)
{
return $this->is_active($params);
}
/**
* Checks if session variable
* specified by name value match
* value passed as parameter
*
* @param Array $params
* @return string
* @access public
*/
function RecallEquals($params)
{
$name = $this->SelectParam($params, 'name,var');
$value = $params['value'];
if (isset($params['persistent']) && $params['persistent']) {
return $this->Application->RecallPersistentVar($name) == $value;
}
return ($this->Application->RecallVar($name) == $value);
}
/**
* Checks if application variable
* specified by name value match
* value passed as parameter
*
* @param Array $params
* @return bool
* @access public
*/
function GetEquals($params)
{
$name = $this->SelectParam($params, 'var,name,param');
$value = $params['value'];
if ($this->Application->GetVar($name) == $value) {
return 1;
}
}
/**
* Includes template
* and returns it's
* parsed version
*
* @param Array $params
* @return string
* @access public
*/
function MyInclude($params)
{
if (defined('NPARSER') && NPARSER) {
return $this->Application->Parser->IncludeTemplate($params, isset($params['is_silent']) ? 1 : 0);
}
$BlockParser =& $this->Application->makeClass('TemplateParser');
/* @var $BlockParser TemplateParser */
// $BlockParser->SetParams($params);
$parser =& $this->Application->Parser;
$this->Application->Parser =& $BlockParser;
// this is for the parser to know the master template in case an error occurs,
// ParseTemplate will reset it anyway, but this will allow error handler to display the tempalte
// which tries to include missing template for example
$this->Application->Parser->TemplateName = $parser->TemplateName;
$t = $this->SelectParam($params, 't,template,block,name');
$t = eregi_replace("\.tpl$", '', $t);
if (!$t) {
trigger_error('Template name not specified in <b>&lt;inp2:m_include .../&gt;</b> tag', E_USER_ERROR);
}
if (isset($this->Application->PreParsedBlocks[$t]) ) {
$params['name'] = $t;
$res = $this->Application->ParseBlock($params);
}
else {
$res = $BlockParser->ParseTemplate($t, 1, $params, isset($params['is_silent']) ? 1 : 0 );
}
if (!$BlockParser->DataExists && ((isset($params['data_exists']) && $params['data_exists']) || isset($params['block_no_data']))) {
if ($block_no_data = getArrayValue($params, 'block_no_data')) {
if (isset($this->Application->PreParsedBlocks[$block_no_data]) ) {
// block_no_data is another block name
$res = $this->Application->ParseBlock(Array('name' => $block_no_data));
}
else {
// block_no_data is template name (only looks through real templates)
$res = $BlockParser->ParseTemplate($block_no_data, 1, Array(), getArrayValue($params, 'is_silent'));
}
}
else {
$res = '';
}
}
$this->Application->Parser =& $parser;
$this->Application->Parser->DataExists = $this->Application->Parser->DataExists || $BlockParser->DataExists;
if (isset($params['return_params']) && $params['return_params']) {
$new_params = array_merge($this->Application->Parser->Params, $BlockParser->ParamsStack[0]);
$this->Application->Parser->SetParams($new_params, false);
}
return $res;
}
function ModuleInclude($params)
{
$ret = '';
$block_params = array_merge($params, Array('is_silent' => 2)); // don't make fatal errors in case if template is missing
$current_template = $this->Application->GetVar('t');
$skip_prefixes = isset($params['skip_prefixes']) ? explode(',', $params['skip_prefixes']) : Array();
foreach ($this->Application->ModuleInfo as $module_name => $module_data) {
- $module_key = strtolower($module_name);
+ $module_key = mb_strtolower($module_name);
if ($module_name == 'In-Portal') {
$module_prefix = $this->Application->IsAdmin() ? 'in-portal/' : $module_data['TemplatePath'];
}
else {
$module_prefix = $this->Application->IsAdmin() ? $module_key.'/' : rtrim($module_data['TemplatePath'], '/').'/';
}
$block_params['t'] = $module_prefix.$this->SelectParam($params, $module_key.'_template,'.$module_key.'_t,template,t');
if ($block_params['t'] == $current_template || in_array($module_data['Var'], $skip_prefixes)) continue;
$no_data = $this->SelectParam($params, $module_key.'_block_no_data,block_no_data');
if ($no_data) {
$block_params['block_no_data'] = $module_prefix.'/'.$no_data;
}
$ret .= $this->MyInclude($block_params);
}
return $ret;
}
function ModuleEnabled($params)
{
return $this->Application->isModuleEnabled( $params['module'] );
}
/*function Kernel_Scripts($params)
{
return '<script type="text/javascript" src="'.PROTOCOL.SERVER_NAME.BASE_PATH.'/kernel3/js/grid.js"></script>';
}*/
/*function GetUserPermission($params)
{
// echo"GetUserPermission $params[name]";
if ($this->Application->RecallVar('user_type') == 1)
return 1;
else {
$perm_name = $params[name];
$aPermissions = unserialize($this->Application->RecallVar('user_permissions'));
if ($aPermissions)
return $aPermissions[$perm_name];
}
}*/
/**
* Set's parser block param value
*
* @param Array $params
* @access public
*/
function AddParam($params)
{
$parser =& $this->Application->Parser; // recallObject('TemplateParser');
foreach ($params as $param => $value) {
$this->Application->SetVar($param, $value);
$parser->SetParam($param, $value);
$parser->AddParam('/\$'.$param.'/', $value);
}
}
/*function ParseToVar($params)
{
$var = $params['var'];
$tagdata = $params['tag'];
$parser =& $this->Application->Parser; //recallObject('TemplateParser');
$res = $this->Application->ProcessTag($tagdata);
$parser->SetParam($var, $res);
$parser->AddParam('/\$'.$var.'/', $res);
return '';
}*/
/*function TagNotEmpty($params)
{
$tagdata = $params['tag'];
$res = $this->Application->ProcessTag($tagdata);
return $res != '';
}*/
/*function TagEmpty($params)
{
return !$this->TagNotEmpty($params);
}*/
/**
* Parses block and returns result
*
* @param Array $params
* @return string
* @access public
*/
function ParseBlock($params)
{
$parser =& $this->Application->Parser; // recallObject('TemplateParser');
return $parser->ParseBlock($params);
}
function RenderElement($params)
{
if (isset($params['design']) && $params['design']) {
$block_name = $params['name'];
if ($block_name != '__this__') {
// prepare content
$block_params = $params;
$block_params['template'] = $block_name;
$block_params['return_params'] = 1;
$block_params['strip_nl'] = 2;
$block_content = $this->MyInclude($block_params);
if (isset($params['data_exists']) && $params['data_exists'] && !$block_content) {
return '';
}
// prepare design
$block_params = Array (
'content' => $block_content,
);
}
$block_params['name'] = $params['design'];
return $this->Application->ParseBlock($block_params, 1);
}
return $this->ParseBlock($params);
}
function RenderElements($params)
{
if (!isset($params['elements']) || !$params['elements']) return;
$elements = explode(',', $params['elements']);
if (isset($params['skip']) && $params['skip']) {
$tmp_skip = explode(',', $params['skip']);
foreach ($tmp_skip as $elem) {
$skip[] = trim($elem);
}
}
else {
$skip = array();
}
unset($params['elements']);
$o = '';
foreach ($elements as $an_element)
{
$cur = trim($an_element);
if (in_array($cur,$skip) || !$cur) continue;
$pass_params = $params;
$pass_params['name'] = $cur;
$o .= $this->RenderElement($pass_params);
}
return $o;
}
/**
* Checks if debug mode is on
*
* @param Array $params
* @return bool
* @access public
*/
function IsDebugMode($params)
{
return $this->Application->isDebugMode();
}
function MassParse($params)
{
$qty = $params['qty'];
$block = $params['block'];
$mode = $params['mode'];
$o = '';
if ($mode == 'func') {
$func = create_function('$params', '
$o = \'<tr>\';
$o.= \'<td>a\'.$params[\'param1\'].\'</td>\';
$o.= \'<td>a\'.$params[\'param2\'].\'</td>\';
$o.= \'<td>a\'.$params[\'param3\'].\'</td>\';
$o.= \'<td>a\'.$params[\'param4\'].\'</td>\';
$o.= \'</tr>\';
return $o;
');
for ($i=1; $i<$qty; $i++) {
$block_params['param1'] = rand(1, 10000);
$block_params['param2'] = rand(1, 10000);
$block_params['param3'] = rand(1, 10000);
$block_params['param4'] = rand(1, 10000);
$o .= $func($block_params);
}
return $o;
}
$block_params['name'] = $block;
for ($i=0; $i<$qty; $i++) {
$block_params['param1'] = rand(1, 10000);
$block_params['param2'] = rand(1, 10000);
$block_params['param3'] = rand(1, 10000);
$block_params['param4'] = rand(1, 10000);
$block_params['passed'] = $params['passed'];
$block_params['prefix'] = 'm';
$o.= $this->Application->ParseBlock($block_params, 1);
}
return $o;
}
function LoggedIn($params)
{
return $this->Application->LoggedIn();
}
/**
* Allows to check if permission exists directly in template and perform additional actions if required
*
* @param Array $params
* @return bool
*/
function CheckPermission($params)
{
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
return $perm_helper->TagPermissionCheck($params);
}
/**
* Checks if user is logged in and if not redirects it to template passed
*
* @param Array $params
*/
function RequireLogin($params)
{
$t = $this->Application->GetVar('t');
if ($next_t = getArrayValue($params, 'next_template')) {
$t = $next_t;
}
// check by permissions: begin
if ((isset($params['perm_event']) && $params['perm_event']) ||
(isset($params['perm_prefix']) && $params['perm_prefix']) ||
(isset($params['permissions']) && $params['permissions'])) {
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
$perm_status = $perm_helper->TagPermissionCheck($params);
if (!$perm_status) {
list($redirect_template, $redirect_params) = $perm_helper->getPermissionTemplate($params);
$this->Application->Redirect($redirect_template, $redirect_params);
}
else {
return ;
}
}
// check by permissions: end
// check by configuration value: begin
$condition = getArrayValue($params, 'condition');
if (!$condition) {
$condition = true;
}
else {
if (substr($condition, 0, 1) == '!') {
$condition = !$this->Application->ConfigValue(substr($condition, 1));
}
else {
$condition = $this->Application->ConfigValue($condition);
}
}
// check by configuration value: end
// check by belonging to group: begin
$group = $this->SelectParam($params, 'group');
$group_access = true;
if ($group) {
$conn =& $this->Application->GetADODBConnection();
$group_id = $conn->GetOne('SELECT GroupId FROM '.TABLE_PREFIX.'PortalGroup WHERE Name = '.$conn->qstr($group));
if ($group_id) {
$groups = explode(',', $this->Application->RecallVar('UserGroups'));
$group_access = in_array($group_id, $groups);
}
}
// check by belonging to group: end
if ((!$this->Application->LoggedIn() || !$group_access) && $condition) {
$redirect_params = $this->Application->HttpQuery->getRedirectParams();
$redirect_params['next_template'] = $t;
if (array_key_exists('pass_category', $params)) {
$redirect_params['pass_category'] = $params['pass_category'];
}
if ( $this->Application->LoggedIn() && !$group_access) {
$this->Application->Redirect( $params['no_group_perm_template'], $redirect_params);
}
$redirect_params['lang_mode'] = ''; // if expiration happens while editing language it will be in temp mode
$redirect_params['m_wid'] = ''; // remove wid, otherwise parent window may add wid to its name breaking all the frameset (for <a> targets)
$this->Application->Redirect($params['login_template'], $redirect_params);
}
}
function IsMember($params)
{
$group = getArrayValue($params, 'group');
$conn =& $this->Application->DB;
$group_id = $conn->GetOne('SELECT GroupId FROM '.TABLE_PREFIX.'PortalGroup WHERE Name = '.$conn->qstr($group));
if ($group_id) {
$groups = explode(',', $this->Application->RecallVar('UserGroups'));
$group_access = in_array($group_id, $groups);
}
return $group_access;
}
/**
* Checks if SSL is on and redirects to SSL URL if needed
* If SSL_URL is not defined in config - the tag does not do anything
* If for_logged_in_only="1" exits if user is not logged in.
* If called without params forces https right away. If called with by_config="1" checks the
* Require SSL setting from General Config and if it is ON forces https
*
* @param unknown_type $params
*/
function CheckSSL($params)
{
$ssl = $this->Application->ConfigValue('SSL_URL');
if (!$ssl) return; //SSL URL is not set - no way to require SSL
$require = false;
if (isset($params['mode']) && $params['mode'] == 'required') {
$require = true;
if (isset($params['for_logged_in_only']) && $params['for_logged_in_only'] && !$this->Application->LoggedIn()) {
$require = false;
}
if (isset($params['condition'])) {
if (!$this->Application->ConfigValue($params['condition'])) {
$require = false;
}
}
}
$http_query =& $this->Application->recallObject('HTTPQuery');
$pass = $http_query->getRedirectParams();
if ($require) {
if (PROTOCOL == 'https://') {
$this->Application->SetVar('__KEEP_SSL__', 1);
return;
}
$this->Application->Redirect('', array_merge_recursive2($pass, Array('__SSL__' => 1)));
}
else {
if (PROTOCOL == 'https://' && $this->Application->ConfigValue('Force_HTTP_When_SSL_Not_Required')) {
if ($this->Application->GetVar('__KEEP_SSL__')) return;
$pass = array('pass'=>'m', 'm_cat_id'=>0);
$this->Application->Redirect('', array_merge_recursive2($pass, Array('__SSL__' => 0)));
}
}
}
function ConstOn($params)
{
$name = $this->SelectParam($params,'name,const');
return constOn($name);
}
function SetDefaultCategory($params)
{
$category_id = $this->Application->findModule('Name', $params['module'], 'RootCat');
$this->Application->SetVar('m_cat_id', $category_id);
}
function XMLTemplate($params)
{
safeDefine('DBG_SKIP_REPORTING', 1);
if (isset($params['cache']) && $params['cache']) {
$nextyear = intval(date('Y') + 1);
$format = "D, d M Y H:i:s";
$expiration = gmdate($format, mktime() + $params['cache']).' GMT';
$last_modified = mktime();
header ('Cache-Control: public, cache, max-age='.$params['cache']);
header ("Expires: $expiration");
header ('Pragma: public');
// Getting headers sent by the client.
$headers = request_headers();
// Checking if the client is validating his cache and if it is current.
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) > $last_modified-$params['cache'])) {
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.date($format, strtotime($headers['If-Modified-Since'])).' GMT', true, 304);
exit();
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate($format, $last_modified).' GMT', true, 200);
}
}
return $this->Application->XMLHeader(getArrayValue($params, 'xml_version'));
}
function Header($params)
{
header($params['data']);
}
function NoDebug($params)
{
define('DBG_SKIP_REPORTING', 1);
}
function RootCategoryName($params)
{
$root_phrase = $this->Application->ConfigValue('Root_Name');
return $this->Application->Phrase($root_phrase);
}
/**
* Allows to attach file directly from email event template
*
* @param Array $params
*/
function AttachFile($params)
{
$esender =& $application->recallObject('EmailSender'.(isset($params['special']) ? '.'.$params['special'] : ''));
/* @var $esender kEmailSendingHelper */
$path = FULL_PATH.'/'.$params['path'];
if (file_exists($path)) {
$esender->AddAttachment($path);
}
}
function CaptchaImage($params){
$captcha_helper =& $this->Application->recallObject('CaptchaHelper');
/* @var $captcha_helper kCaptchaHelper */
$captcha_helper->GenerateCaptchaImage(
$this->Application->RecallVar($this->Application->GetVar('var')),
$this->Application->GetVar('w'),
$this->Application->GetVar('h'),
true
);
}
function SID($params)
{
return $this->Application->GetSID();
}
function ModuleInfo($params)
{
return $this->Application->findModule($params['key'], $params['value'], $params['return']);
}
function Random($params)
{
return rand(1, 100000000);
}
}
Property changes on: branches/RC/core/kernel/processors/main_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.80.2.7
\ No newline at end of property
+1.80.2.8
\ No newline at end of property
Index: branches/RC/core/kernel/session/session.php
===================================================================
--- branches/RC/core/kernel/session/session.php (revision 10097)
+++ branches/RC/core/kernel/session/session.php (revision 10098)
@@ -1,1011 +1,1011 @@
<?php
/*
The session works the following way:
1. When a visitor loads a page from the site the script checks if cookies_on varibale has been passed to it as a cookie.
2. If it has been passed, the script tries to get Session ID (SID) from the request:
3. Depending on session mode the script is getting SID differently.
The following modes are available:
smAUTO - Automatic mode: if cookies are on at the client side, the script relays only on cookies and
ignore all other methods of passing SID.
If cookies are off at the client side, the script relays on SID passed through query string
and referal passed by the client. THIS METHOD IS NOT 100% SECURE, as long as attacker may
get SID and substitude referal to gain access to user' session. One of the faults of this method
is that the session is only created when the visitor clicks the first link on the site, so
there is NO session at the first load of the page. (Actually there is a session, but it gets lost
after the first click because we do not use SID in query string while we are not sure if we need it)
smCOOKIES_ONLY - Cookies only: in this mode the script relays solely on cookies passed from the browser
and ignores all other methods. In this mode there is no way to use sessions for clients
without cookies support or cookies support disabled. The cookies are stored with the
full domain name and path to base-directory of script installation.
smGET_ONLY - GET only: the script will not set any cookies and will use only SID passed in
query string using GET, it will also check referal. The script will set SID at the
first load of the page
smCOOKIES_AND_GET - Combined mode: the script will use both cookies and GET right from the start. If client has
cookies enabled, the script will check SID stored in cookie and passed in query string, and will
use this SID only if both cookie and query string matches. However if cookies are disabled on the
client side, the script will work the same way as in GET_ONLY mode.
4. After the script has the SID it tries to load it from the Storage (default is database)
5. If such SID is found in the database, the script checks its expiration time. If session is not expired, it updates
its expiration, and resend the cookie (if applicable to session mode)
6. Then the script loads all the data (session variables) pertaining to the SID.
Usage:
$session = new Session(smAUTO); //smAUTO is default, you could just leave the brackets empty, or provide another mode
$session->SetCookieDomain('my.domain.com');
$session->SetCookiePath('/myscript');
$session->SetCookieName('my_sid_cookie');
$session->SetGETName('sid');
$session->InitSession();
...
//link output:
echo "<a href='index.php?'". ( $session->NeedQueryString() ? 'sid='.$session->SID : '' ) .">My Link</a>";
*/
//Implements session storage in the database
class SessionStorage extends kDBBase {
var $Expiration;
var $SessionTimeout=0;
var $DirectVars = Array();
var $ChangedDirectVars = Array();
var $PersistentVars = Array ();
var $OriginalData=Array();
var $TimestampField;
var $SessionDataTable;
var $DataValueField;
var $DataVarField;
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$this->setTableName('sessions');
$this->setIDField('sid');
$this->TimestampField = 'expire';
$this->SessionDataTable = 'SessionData';
$this->DataValueField = 'value';
$this->DataVarField = 'var';
}
function setSessionTimeout($new_timeout)
{
$this->SessionTimeout = $new_timeout;
}
function StoreSession(&$session, $additional_fields = Array())
{
if (defined('IS_INSTALL') && IS_INSTALL && !$this->Application->TableFound($this->TableName)) {
return false;
}
$fields_hash = Array (
$this->IDField => $session->SID,
$this->TimestampField => $session->Expiration
);
$this->Conn->doInsert($fields_hash, $this->TableName);
foreach ($additional_fields as $field_name => $field_value) {
$this->SetField($session, $field_name, $field_value);
}
}
function DeleteSession(&$session)
{
$query = ' DELETE FROM '.$this->TableName.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
$query = ' DELETE FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
$this->OriginalData = Array();
}
function UpdateSession(&$session, $timeout=0)
{
$this->SetField($session, $this->TimestampField, $session->Expiration);
$query = ' UPDATE '.$this->TableName.' SET '.$this->TimestampField.' = '.$session->Expiration.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
}
function LocateSession($sid)
{
$query = ' SELECT * FROM '.$this->TableName.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($sid);
$result = $this->Conn->GetRow($query);
if($result===false) return false;
$this->DirectVars = $result;
$this->Expiration = $result[$this->TimestampField];
return true;
}
function GetExpiration()
{
return $this->Expiration;
}
function LoadData(&$session)
{
$query = 'SELECT '.$this->DataValueField.','.$this->DataVarField.' FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->OriginalData = $this->Conn->GetCol($query, $this->DataVarField);
return $this->OriginalData;
}
/**
* Enter description here...
*
* @param Session $session
* @param string $var_name
* @param mixed $default
*/
function GetField(&$session, $var_name, $default = false)
{
return isset($this->DirectVars[$var_name]) ? $this->DirectVars[$var_name] : $default;
//return $this->Conn->GetOne('SELECT '.$var_name.' FROM '.$this->TableName.' WHERE `'.$this->IDField.'` = '.$this->Conn->qstr($session->GetID()) );
}
function SetField(&$session, $var_name, $value)
{
$value_changed = !isset($this->DirectVars[$var_name]) || ($this->DirectVars[$var_name] != $value);
if ($value_changed) {
$this->DirectVars[$var_name] = $value;
$this->ChangedDirectVars[] = $var_name;
$this->ChangedDirectVars = array_unique($this->ChangedDirectVars);
}
//return $this->Conn->Query('UPDATE '.$this->TableName.' SET '.$var_name.' = '.$this->Conn->qstr($value).' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->GetID()) );
}
function SaveData(&$session)
{
if(!$session->SID) return false; // can't save without sid
$ses_data = $session->Data->GetParams();
$replace = '';
foreach ($ses_data as $key => $value)
{
if ( isset($this->OriginalData[$key]) && $this->OriginalData[$key] == $value)
{
continue; //skip unchanged session data
}
else
{
$replace .= sprintf("(%s, %s, %s),",
$this->Conn->qstr($session->SID),
$this->Conn->qstr($key),
$this->Conn->qstr($value));
}
}
$replace = rtrim($replace, ',');
if ($replace != '') {
$query = ' REPLACE INTO '.$this->SessionDataTable. ' ('.$this->IDField.', '.$this->DataVarField.', '.$this->DataValueField.') VALUES '.$replace;
$this->Conn->Query($query);
}
if ($this->ChangedDirectVars) {
$changes = array();
foreach ($this->ChangedDirectVars as $var) {
$changes[] = $var.' = '.$this->Conn->qstr($this->DirectVars[$var]);
}
$query = 'UPDATE '.$this->TableName.' SET '.implode(',', $changes).' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->GetID());
$this->Conn->Query($query);
}
}
function RemoveFromData(&$session, $var)
{
$query = 'DELETE FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID).
' AND '.$this->DataVarField.' = '.$this->Conn->qstr($var);
$this->Conn->Query($query);
unset($this->OriginalData[$var]);
}
function GetFromData(&$session, $var)
{
return getArrayValue($this->OriginalData, $var);
}
function GetExpiredSIDs()
{
$query = ' SELECT '.$this->IDField.' FROM '.$this->TableName.' WHERE '.$this->TimestampField.' > '.adodb_mktime();
return $this->Conn->GetCol($query);
}
function DeleteExpired()
{
$expired_sids = $this->GetExpiredSIDs();
if ($expired_sids) {
$where_clause=' WHERE '.$this->IDField.' IN ("'.implode('","',$expired_sids).'")';
$sql = 'DELETE FROM '.$this->SessionDataTable.$where_clause;
$this->Conn->Query($sql);
$sql = 'DELETE FROM '.$this->TableName.$where_clause;
$this->Conn->Query($sql);
// delete debugger ouputs left of expired sessions
foreach ($expired_sids as $expired_sid) {
$debug_file = KERNEL_PATH.'/../cache/debug_@'.$expired_sid.'@.txt';
if (file_exists($debug_file)) {
@unlink($debug_file);
}
}
}
return $expired_sids;
}
function LoadPersistentVars(&$session)
{
$user_id = $session->RecallVar('user_id');
if ($user_id != -2) {
// root & normal users
$sql = 'SELECT VariableValue, VariableName
FROM '.TABLE_PREFIX.'PersistantSessionData
WHERE PortalUserId = '.$user_id;
$this->PersistentVars = $this->Conn->GetCol($sql, 'VariableName');
}
else {
$this->PersistentVars = Array ();
}
}
/**
* Stores variable to persistent session
*
* @param Session $session
* @param string $var_name
* @param mixed $var_value
*/
function StorePersistentVar(&$session, $var_name, $var_value)
{
$user_id = $session->RecallVar('user_id');
if ($user_id == -2 || $user_id === false) {
// -2 (when not logged in), false (when after u:OnLogout event)
$session->StoreVar($var_name, $var_value);
return ;
}
$this->PersistentVars[$var_name] = $var_value;
$key_clause = 'PortalUserId = '.$user_id.' AND VariableName = '.$this->Conn->qstr($var_name);
$sql = 'SELECT VariableName
FROM '.TABLE_PREFIX.'PersistantSessionData
WHERE '.$key_clause;
$record_found = $this->Conn->GetOne($sql);
$fields_hash = Array (
'PortalUserId' => $user_id,
'VariableName' => $var_name,
'VariableValue' => $var_value,
);
if ($record_found) {
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX.'PersistantSessionData', $key_clause);
}
else {
$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'PersistantSessionData');
}
}
/**
* Gets persistent variable
*
* @param Session $session
* @param string $var_name
* @param mixed $default
* @return mixed
*/
function RecallPersistentVar(&$session, $var_name, $default = false)
{
if ($session->RecallVar('user_id') == -2) {
if ($default == '_USE_DEFAULT_USER_DATA_') {
$default = null;
}
return $session->RecallVar($var_name, $default);
}
if (array_key_exists($var_name, $this->PersistentVars)) {
return $this->PersistentVars[$var_name];
}
elseif ($default == '_USE_DEFAULT_USER_DATA_') {
$default_user_id = $this->Application->ConfigValue('DefaultSettingsUserId');
if (!$default_user_id) {
$default_user_id = -1;
}
$sql = 'SELECT VariableValue, VariableName
FROM '.TABLE_PREFIX.'PersistantSessionData
WHERE VariableName = '.$this->Conn->qstr($var_name).' AND PortalUserId = '.$default_user_id;
$value = $this->Conn->GetOne($sql);
$this->PersistentVars[$var_name] = $value;
if ($value !== false) {
$this->StorePersistentVar($session, $var_name, $value); //storing it, so next time we don't load default user setting
}
return $value;
}
else {
return $default;
}
}
function RemovePersistentVar(&$session, $var_name)
{
unset($this->PersistentVars[$var_name]);
$user_id = $session->RecallVar('user_id');
if ($user_id != -2) {
$sql = 'DELETE FROM '.TABLE_PREFIX.'PersistantSessionData
WHERE PortalUserId = '.$user_id.' AND VariableName = '.$this->Conn->qstr($var_name);
$this->Conn->Query($sql);
}
}
}
define('smAUTO', 1);
define('smCOOKIES_ONLY', 2);
define('smGET_ONLY', 3);
define('smCOOKIES_AND_GET', 4);
class Session extends kBase {
var $Checkers;
var $Mode;
var $OriginalMode = null;
var $GETName = 'sid';
var $CookiesEnabled = true;
var $CookieName = 'sid';
var $CookieDomain;
var $CookiePath;
var $CookieSecure = 0;
var $SessionTimeout = 3600;
var $Expiration;
var $SID;
/**
* Enter description here...
*
* @var SessionStorage
*/
var $Storage;
var $CachedNeedQueryString = null;
var $Data;
function Session($mode=smAUTO)
{
parent::kBase();
$this->SetMode($mode);
}
function SetMode($mode)
{
$this->Mode = $mode;
$this->CachedNeedQueryString = null;
$this->CachedSID = null;
}
function SetCookiePath($path)
{
$this->CookiePath = $path;
}
function SetCookieDomain($domain)
{
$this->CookieDomain = '.'.ltrim($domain, '.');
}
function SetGETName($get_name)
{
$this->GETName = $get_name;
}
function SetCookieName($cookie_name)
{
$this->CookieName = $cookie_name;
}
function InitStorage($special)
{
$this->Storage =& $this->Application->recallObject('SessionStorage.'.$special);
$this->Storage->setSessionTimeout($this->SessionTimeout);
}
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$this->CheckIfCookiesAreOn();
if ($this->CookiesEnabled) $_COOKIE['cookies_on'] = 1;
$this->Checkers = Array();
$this->InitStorage($special);
$this->Data = new Params();
$tmp_sid = $this->GetPassedSIDValue();
$check = $this->Check();
if( !(defined('IS_INSTALL') && IS_INSTALL) )
{
$expired_sids = $this->DeleteExpired();
if ( ( $expired_sids && in_array($tmp_sid,$expired_sids) ) || ( $tmp_sid && !$check ) ) {
$this->SetSession();
$this->Application->HandleEvent($event, 'u:OnSessionExpire');
return ;
}
}
if ($check) {
$this->SID = $this->GetPassedSIDValue();
$this->Refresh();
$this->LoadData();
}
else {
$this->SetSession();
}
if (!is_null($this->OriginalMode)) $this->SetMode($this->OriginalMode);
}
function IsHTTPSRedirect()
{
$http_referer = getArrayValue($_SERVER, 'HTTP_REFERER');
return (
( PROTOCOL == 'https://' && preg_match('#http:\/\/#', $http_referer) )
||
( PROTOCOL == 'http://' && preg_match('#https:\/\/#', $http_referer) )
);
}
function CheckReferer($for_cookies=0)
{
if (!$for_cookies) {
if ( !$this->Application->ConfigValue('SessionReferrerCheck') || $_SERVER['REQUEST_METHOD'] != 'POST') {
return true;
}
}
$path = preg_replace('/admin[\/]{0,1}$/', '', $this->CookiePath); // removing /admin for compatability with in-portal (in-link/admin/add_link.php)
$reg = '#^'.preg_quote(PROTOCOL.ltrim($this->CookieDomain, '.').$path).'#';
return preg_match($reg, getArrayValue($_SERVER, 'HTTP_REFERER') ) || (defined('IS_POPUP') && IS_POPUP);
}
/*function CheckDuplicateCookies()
{
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookie_str = $_SERVER['HTTP_COOKIE'];
$cookies = explode('; ', $cookie_str);
$all_cookies = array();
foreach ($cookies as $cookie) {
list($name, $value) = explode('=', $cookie);
if (isset($all_cookies[$name])) {
//double cookie name!!!
$this->RemoveCookie($name);
}
else $all_cookies[$name] = $value;
}
}
}
function RemoveCookie($name)
{
$path = $_SERVER['PHP_SELF'];
$path_parts = explode('/', $path);
$cur_path = '';
setcookie($name, false, null, $cur_path);
foreach ($path_parts as $part) {
$cur_path .= $part;
setcookie($name, false, null, $cur_path);
$cur_path .= '/';
setcookie($name, false, null, $cur_path);
}
}*/
function CheckIfCookiesAreOn()
{
// $this->CheckDuplicateCookies();
if ($this->Mode == smGET_ONLY)
{
//we don't need to bother checking if we would not use it
$this->CookiesEnabled = false;
return;
}
$http_query =& $this->Application->recallObject('HTTPQuery');
$cookies_on = isset($http_query->Cookie['cookies_on']); // not good here
$get_sid = getArrayValue($http_query->Get, $this->GETName);
if ($this->IsHTTPSRedirect() && $get_sid) { //Redirect from http to https on different domain
$this->OriginalMode = $this->Mode;
$this->SetMode(smGET_ONLY);
}
if (!$cookies_on || $this->IsHTTPSRedirect()) {
//If referer is our server, but we don't have our cookies_on, it's definetly off
$is_install = defined('IS_INSTALL') && IS_INSTALL;
if (!$is_install && $this->CheckReferer(1) && !$this->Application->GetVar('admin') && !$this->IsHTTPSRedirect()) {
$this->CookiesEnabled = false;
}
else {
//Otherwise we still suppose cookies are on, because may be it's the first time user visits the site
//So we send cookies on to get it next time (when referal will tell us if they are realy off
$this->SetCookie('cookies_on', 1, adodb_mktime() + 31104000); //one year should be enough
}
}
else
$this->CookiesEnabled = true;
return $this->CookiesEnabled;
}
/**
* Sets cookie for current site using path and domain
*
* @param string $name
* @param mixed $value
* @param int $expires
*/
function SetCookie($name, $value, $expires = null)
{
setcookie($name, $value, $expires, $this->CookiePath, $this->CookieDomain, $this->CookieSecure);
}
function Check()
{
// we should check referer if cookies are disabled, and in combined mode
// auto mode would detect cookies, get only mode would turn it off - so we would get here
// and we don't care about referal in cookies only mode
if ( $this->Mode != smCOOKIES_ONLY && (!$this->CookiesEnabled || $this->Mode == smCOOKIES_AND_GET) ) {
if (!$this->CheckReferer())
return false;
}
$sid = $this->GetPassedSIDValue();
if (empty($sid)) return false;
//try to load session by sid, if everything is fine
$result = $this->LoadSession($sid);
return $result;
}
function LoadSession($sid)
{
if( $this->Storage->LocateSession($sid) ) {
//if we have session with such SID - get its expiration
$this->Expiration = $this->Storage->GetExpiration();
//If session has expired
if ($this->Expiration < adodb_mktime()) return false;
//Otherwise it's ok
return true;
}
else //fake or deleted due to expiration SID
return false;
}
function GetPassedSIDValue($use_cache = 1)
{
if (!empty($this->CachedSID) && $use_cache) return $this->CachedSID;
$http_query =& $this->Application->recallObject('HTTPQuery');
$get_sid = getArrayValue($http_query->Get, $this->GETName);
if ($this->Application->GetVar('admin') == 1 && $get_sid) {
$sid = $get_sid;
}
else {
switch ($this->Mode) {
case smAUTO:
//Cookies has the priority - we ignore everything else
$sid = $this->CookiesEnabled ? $this->GetSessionCookie() : $get_sid;
break;
case smCOOKIES_ONLY:
$sid = $this->GetSessionCookie();
break;
case smGET_ONLY:
$sid = $get_sid;
break;
case smCOOKIES_AND_GET:
$cookie_sid = $this->GetSessionCookie();
//both sids should match if cookies are enabled
if (!$this->CookiesEnabled || ($cookie_sid == $get_sid))
{
$sid = $get_sid; //we use get here just in case cookies are disabled
}
else
{
$sid = '';
}
break;
}
}
$this->CachedSID = $sid;
return $this->CachedSID;
}
/**
* Returns session id
*
* @return int
* @access public
*/
function GetID()
{
return $this->SID;
}
/**
* Generates new session id
*
* @return int
* @access private
*/
function GenerateSID()
{
list($usec, $sec) = explode(" ",microtime());
$sid_part_1 = substr($usec, 4, 4);
$sid_part_2 = mt_rand(1,9);
$sid_part_3 = substr($sec, 6, 4);
$digit_one = substr($sid_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$sid_part_1 = ereg_replace("^0","",$sid_part_1);
$sid_part_1=$digit_one.$sid_part_1;
}
$this->setSID($sid_part_1.$sid_part_2.$sid_part_3);
return $this->SID;
}
/**
* Set's new session id
*
* @param int $new_sid
* @access private
*/
function setSID($new_sid)
{
$this->SID=$new_sid;
$this->Application->SetVar($this->GETName,$new_sid);
}
function SetSession()
{
$this->GenerateSID();
$this->Expiration = adodb_mktime() + $this->SessionTimeout;
switch ($this->Mode) {
case smAUTO:
if ($this->CookiesEnabled) {
$this->SetSessionCookie();
}
break;
case smGET_ONLY:
break;
case smCOOKIES_ONLY:
case smCOOKIES_AND_GET:
$this->SetSessionCookie();
break;
}
$this->Storage->StoreSession($this);
if ($this->Application->IsAdmin() || $this->Special == 'admin') {
$this->StoreVar('admin', 1);
}
if ($this->Special != '') {
// front-session called from admin or otherwise, then save it's data
$this->SaveData();
}
$this->Application->resetCounters('UserSession');
}
/**
* Returns SID from cookie
*
* @return int
*/
function GetSessionCookie()
{
$keep_session_on_browser_close = $this->Application->ConfigValue('KeepSessionOnBrowserClose');
if (isset($this->Application->HttpQuery->Cookie[$this->CookieName]) &&
( $keep_session_on_browser_close ||
(
!$keep_session_on_browser_close &&
isset($this->Application->HttpQuery->Cookie[$this->CookieName.'_live'])
&&
$this->Application->HttpQuery->Cookie[$this->CookieName] == $this->Application->HttpQuery->Cookie[$this->CookieName.'_live']
)
)
) {
return $this->Application->HttpQuery->Cookie[$this->CookieName];
}
return false;
}
/**
* Updates SID in cookie with new value
*
*/
function SetSessionCookie()
{
$this->SetCookie($this->CookieName, $this->SID, $this->Expiration);
$this->SetCookie($this->CookieName.'_live', $this->SID);
$_COOKIE[$this->CookieName] = $this->SID; // for compatibility with in-portal
}
/**
* Refreshes session expiration time
*
* @access private
*/
function Refresh()
{
if ($this->CookiesEnabled) $this->SetSessionCookie(); //we need to refresh the cookie
$this->Storage->UpdateSession($this);
}
function Destroy()
{
$this->Storage->DeleteSession($this);
$this->Data = new Params();
$this->SID = '';
if ($this->CookiesEnabled) $this->SetSessionCookie(); //will remove the cookie due to value (sid) is empty
$this->SetSession(); //will create a new session
}
function NeedQueryString($use_cache = 1)
{
if ($this->CachedNeedQueryString != null && $use_cache) return $this->CachedNeedQueryString;
$result = false;
switch ($this->Mode)
{
case smAUTO:
if (!$this->CookiesEnabled) $result = true;
break;
/*case smCOOKIES_ONLY:
break;*/
case smGET_ONLY:
case smCOOKIES_AND_GET:
$result = true;
break;
}
$this->CachedNeedQueryString = $result;
return $result;
}
function LoadData()
{
$this->Data->AddParams($this->Storage->LoadData($this));
}
function PrintSession($comment='')
{
if($this->Application->isDebugMode() && constOn('DBG_SHOW_SESSIONDATA')) {
// dump session data
$this->Application->Debugger->appendHTML('SessionStorage ('.$comment.'):');
$session_data = $this->Data->GetParams();
ksort($session_data);
foreach ($session_data as $session_key => $session_value) {
if (IsSerialized($session_value)) {
$session_data[$session_key] = unserialize($session_value);
}
}
$this->Application->Debugger->dumpVars($session_data);
}
if ($this->Application->isDebugMode() && constOn('DBG_SHOW_PERSISTENTDATA')) {
// dump persistent session data
if ($this->Storage->PersistentVars) {
$this->Application->Debugger->appendHTML('Persistant Session:');
$session_data = $this->Storage->PersistentVars;
ksort($session_data);
foreach ($session_data as $session_key => $session_value) {
if (IsSerialized($session_value)) {
$session_data[$session_key] = unserialize($session_value);
}
}
$this->Application->Debugger->dumpVars($session_data);
}
}
}
function SaveData()
{
if (!$this->Application->GetVar('skip_last_template') && $this->Application->GetVar('ajax') != 'yes') {
$this->SaveLastTemplate( $this->Application->GetVar('t') );
}
$this->PrintSession('after save');
$this->Storage->SaveData($this);
}
function SaveLastTemplate($t)
{
// save last_template
$wid = $this->Application->GetVar('m_wid');
$last_env = $this->getLastTemplateENV($t, Array('m_opener' => 'u'));
- $last_template = basename($_SERVER['PHP_SELF']).'|'.substr($last_env, strlen(ENV_VAR_NAME) + 1);
+ $last_template = basename($_SERVER['PHP_SELF']).'|'.mb_substr($last_env, mb_strlen(ENV_VAR_NAME) + 1);
$this->StoreVar(rtrim('last_template_'.$wid, '_'), $last_template);
$last_env = $this->getLastTemplateENV($t, null, false);
- $last_template = basename($_SERVER['PHP_SELF']).'|'.substr($last_env, strlen(ENV_VAR_NAME) + 1);
+ $last_template = basename($_SERVER['PHP_SELF']).'|'.mb_substr($last_env, mb_strlen(ENV_VAR_NAME) + 1);
$this->StoreVar(rtrim('last_template_popup_'.$wid, '_'), $last_template);
// save other last... variables for mistical purposes (customizations may be)
$this->StoreVar('last_url', $_SERVER['REQUEST_URI']); // needed by ord:StoreContinueShoppingLink
- $this->StoreVar('last_env', substr($last_env, strlen(ENV_VAR_NAME)+1));
+ $this->StoreVar('last_env', mb_substr($last_env, mb_strlen(ENV_VAR_NAME)+1));
// save last_template in persistant session
if (!$wid) {
if ($this->Application->IsAdmin()) {
// only for main window, not popups, not login template, not temp mode (used in adm:MainFrameLink tag)
$temp_mode = false;
$passed = explode(',', $this->Application->GetVar('passed'));
foreach ($passed as $passed_prefix) {
if ($this->Application->GetVar($passed_prefix.'_mode')) {
$temp_mode = true;
break;
}
}
if (!$temp_mode) {
if (isset($this->Application->HttpQuery->Get['section'])) {
// check directly in GET, bacause LinkVar (session -> request) used on these vars
$last_template .= '&section='.$this->Application->GetVar('section').'&module='.$this->Application->GetVar('module');
}
$this->StorePersistentVar('last_template_popup', $last_template);
}
}
elseif ($this->Application->GetVar('admin') == 1) {
$admin_session =& $this->Application->recallObject('Session.admin');
/* @var $admin_ses Session */
$admin_session->StorePersistentVar('last_template_popup', '../'.$last_template);
}
}
}
function getLastTemplateENV($t, $params = null, $encode = true)
{
if (!isset($params)) {
$params = Array ();
}
$params['__URLENCODE__'] = 1; // uses "&" instead of "&amp;" for url part concatenation + replaces "\" to "%5C" (works in HTML)
$ret = $this->Application->BuildEnv($t, $params, 'all');
if (!$encode) {
// cancels 2nd part of replacements, that URLENCODE does
$ret = str_replace('%5C', '\\', $ret);
}
return $ret;
}
function StoreVar($name, $value)
{
$this->Data->Set($name, $value);
}
function StorePersistentVar($name, $value)
{
$this->Storage->StorePersistentVar($this, $name, $value);
}
function LoadPersistentVars()
{
$this->Storage->LoadPersistentVars($this);
}
function StoreVarDefault($name, $value)
{
$tmp = $this->RecallVar($name);
if($tmp === false || $tmp == '')
{
$this->StoreVar($name, $value);
}
}
function RecallVar($name, $default = false)
{
$ret = $this->Data->Get($name);
return ($ret === false) ? $default : $ret;
}
function RecallPersistentVar($name, $default = false)
{
return $this->Storage->RecallPersistentVar($this, $name, $default);
}
function RemoveVar($name)
{
$this->Storage->RemoveFromData($this, $name);
$this->Data->Remove($name);
}
function RemovePersistentVar($name)
{
return $this->Storage->RemovePersistentVar($this, $name);
}
/**
* Ignores session varible value set before
*
* @param string $name
*/
function RestoreVar($name)
{
return $this->StoreVar($name, $this->Storage->GetFromData($this, $name));
}
function GetField($var_name, $default = false)
{
return $this->Storage->GetField($this, $var_name, $default);
}
function SetField($var_name, $value)
{
$this->Storage->SetField($this, $var_name, $value);
}
/**
* Deletes expired sessions
*
* @return Array expired sids if any
* @access private
*/
function DeleteExpired()
{
return $this->Storage->DeleteExpired();
}
/**
* Allows to check if user in this session is logged in or not
*
* @return bool
*/
function LoggedIn()
{
$user_id = $this->RecallVar('user_id');
$ret = $user_id > 0;
if ($this->RecallVar('admin') == 1 && ($user_id == -1)) {
$ret = true;
}
return $ret;
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/session/session.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.59.2.7
\ No newline at end of property
+1.59.2.8
\ No newline at end of property
Index: branches/RC/core/kernel/utility/multibyte.php
===================================================================
--- branches/RC/core/kernel/utility/multibyte.php (nonexistent)
+++ branches/RC/core/kernel/utility/multibyte.php (revision 10098)
@@ -0,0 +1,54 @@
+<?php
+
+ if (!function_exists('mb_internal_encoding')) {
+ function mb_internal_encoding ($encoding = null) {
+
+ }
+
+ // substr|substr_count|strtoupper|strtolower|strstr|strrpos|strpos|strlen
+
+ function mb_substr ($str, $start, $length = null, $encoding = null)
+ {
+ return substr($str, $start, $length);
+ }
+
+ function mb_substr_count ($haystack, $needle, $encoding = null)
+ {
+ return substr_count($haystack, $needle);
+ }
+
+ function mb_strtoupper ($str, $encoding = null)
+ {
+ return strtoupper($str);
+ }
+
+ function mb_strtolower ($str, $encoding = null)
+ {
+ return strtolower($str);
+ }
+
+ function mb_strstr ($haystack, $needle, $part = false, $encoding = null)
+ {
+ return strstr($haystack, $needle);
+ }
+
+ function mb_strrpos ($haystack, $needle, $offset = null, $encoding = null)
+ {
+ return strrpos($haystack, $needle, $offset);
+ }
+
+ function mb_strpos ($haystack, $needle, $offset = null, $encoding = null)
+ {
+ return strpos($haystack, $needle, $offset);
+ }
+
+ function mb_strlen ($str, $encoding = null)
+ {
+ return strlen($str);
+ }
+
+
+
+ }
+
+?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/utility/multibyte.php
___________________________________________________________________
Added: cvs2svn:cvs-rev
## -0,0 +1 ##
+1.1.4.1
\ No newline at end of property
Index: branches/RC/core/kernel/utility/email_send.php
===================================================================
--- branches/RC/core/kernel/utility/email_send.php (revision 10097)
+++ branches/RC/core/kernel/utility/email_send.php (revision 10098)
@@ -1,1968 +1,1968 @@
<?php
/**
* Class used to compose email message (using MIME standarts) and send it via mail function or via SMTP server
*
*/
class kEmailSendingHelper extends kHelper {
/**
* headers of main header part
*
* @var Array
*/
var $headers = Array ();
/**
* Tells if all message parts were combined together
*
* @var int
*/
var $bodyPartNumber = false;
/**
* Composed message parts
*
* @var Array
*/
var $parts = Array();
/**
* Lines separator by MIME standart
*
* @var string
*/
var $line_break = "\n";
/**
* Charset used for message composing
*
* @var string
*/
var $charset = 'utf-8';
/**
* Name of mailer program (X-Mailer header)
*
* @var string
*/
var $mailerName = '';
/**
* Options used for message content-type & structure guessing
*
* @var Array
*/
var $guessOptions = Array ();
/**
* Send messages using selected method
*
* @var string
*/
var $sendMethod = 'Mail';
/**
* Parameters used to initiate SMTP server connection
*
* @var Array
*/
var $smtpParams = Array ();
/**
* List of supported authentication methods, in preferential order.
* @var array
* @access public
*/
var $smtpAuthMethods = Array('CRAM-MD5', 'LOGIN', 'PLAIN');
/**
* The socket resource being used to connect to the SMTP server.
* @var kSocket
* @access private
*/
var $smtpSocket = null;
/**
* The most recent server response code.
* @var int
* @access private
*/
var $smtpResponceCode = -1;
/**
* The most recent server response arguments.
* @var array
* @access private
*/
var $smtpRespoceArguments = Array();
/**
* Stores detected features of the SMTP server.
* @var array
* @access private
*/
var $smtpFeatures = Array();
function kEmailSendingHelper()
{
parent::kHelper();
// set default guess options
$this->guessOptions = Array (
'attachments' => Array (),
'inline_attachments' => Array (),
'text_part' => false,
'html_part' => false,
);
// read SMTP server connection params from config
$smtp_mapping = Array ('server' => 'Smtp_Server', 'port' => 'Smtp_Port');
if ($this->Application->ConfigValue('Smtp_Authenticate')) {
$smtp_mapping['username'] = 'Smtp_User';
$smtp_mapping['password'] = 'Smtp_Pass';
}
foreach ($smtp_mapping as $smtp_name => $config_name) {
$this->smtpParams[$smtp_name] = $this->Application->ConfigValue($config_name);
}
$this->smtpParams['use_auth'] = isset($this->smtpParams['username']) ? true : false;
$this->smtpParams['localhost'] = 'localhost'; // The value to give when sending EHLO or HELO.
$this->sendMethod = $this->smtpParams['server'] && $this->smtpParams['port'] ? 'SMTP' : 'Mail';
if ($this->sendMethod == 'SMTP') {
// create connection object if we will use SMTP
$this->smtpSocket =& $this->Application->makeClass('Socket');
}
$this->SetCharset(null, true);
}
/**
* Returns new message id header by sender's email address
*
* @param string $email_address email address
* @return string
*/
function GenerateMessageID($email_address)
{
list ($micros, $seconds) = explode(' ', microtime());
list ($user, $domain) = explode('@', $email_address, 2);
$message_id = strftime('%Y%m%d%H%M%S', $seconds).substr($micros, 1, 5).'.'.preg_replace('/[^A-Za-z]+/', '-', $user).'@'.$domain;
$this->SetHeader('Message-ID', '<'.$message_id.'>');
}
/**
* Returns extension of given filename
*
* @param string $filename
* @return string
*/
function GetFilenameExtension($filename)
{
- $last_dot = strrpos($filename, '.');
- return $last_dot !== false ? substr($filename, $last_dot + 1) : '';
+ $last_dot = mb_strrpos($filename, '.');
+ return $last_dot !== false ? mb_substr($filename, $last_dot + 1) : '';
}
/**
* Creates boundary for part by number (only if it's missing)
*
* @param int $part_number
*
*/
function CreatePartBoundary($part_number)
{
$part =& $this->parts[$part_number];
if (!isset($part['BOUNDARY'])) {
$part['BOUNDARY'] = md5(uniqid($part_number.time()));
}
}
/**
* Returns ready to use headers associative array of any message part by it's number
*
* @param int $part_number
* @return Array
*/
function GetPartHeaders($part_number)
{
$part =& $this->parts[$part_number];
if (!isset($part['Content-Type'])) {
return $this->SetError('MISSING_CONTENT_TYPE');
}
$full_type = strtolower($part['Content-Type']);
list ($type, $sub_type) = explode('/', $full_type);
$headers['Content-Type'] = $full_type;
switch ($type) {
case 'text':
case 'image':
case 'audio':
case 'video':
case 'application':
case 'message':
// 1. update content-type header
if (isset($part['CHARSET'])) {
$headers['Content-Type'] .= '; charset='.$part['CHARSET'];
}
if (isset($part['NAME'])) {
$headers['Content-Type'] .= '; name="'.$part['NAME'].'"';
}
// 2. set content-transfer-encoding header
if (isset($part['Content-Transfer-Encoding'])) {
$headers['Content-Transfer-Encoding'] = $part['Content-Transfer-Encoding'];
}
// 3. set content-disposition header
if (isset($part['DISPOSITION']) && $part['DISPOSITION']) {
$headers['Content-Disposition'] = $part['DISPOSITION'];
if (isset($part['NAME'])) {
$headers['Content-Disposition'] .= '; filename="'.$part['NAME'].'"';
}
}
break;
case 'multipart':
switch ($sub_type) {
case 'alternative':
case 'related':
case 'mixed':
case 'parallel':
$this->CreatePartBoundary($part_number);
$headers['Content-Type'] .= '; boundary="'.$part['BOUNDARY'].'"';
break;
default:
return $this->SetError('INVALID_MULTIPART_SUBTYPE', Array($sub_type));
}
break;
default:
return $this->SetError('INVALID_CONTENT_TYPE', Array($full_type));
}
// set content-id if any
if (isset($part['Content-ID'])) {
$headers['Content-ID'] = '<'.$part['Content-ID'].'>';
}
return $headers;
}
function GetPartBody($part_number)
{
$part =& $this->parts[$part_number];
if (!isset($part['Content-Type'])) {
return $this->SetError('MISSING_CONTENT_TYPE');
}
$full_type = strtolower($part['Content-Type']);
list ($type, $sub_type) = explode('/', $full_type);
$body = '';
switch ($type) {
// compose text/binary content
case 'text':
case 'image':
case 'audio':
case 'video':
case 'application':
case 'message':
// 1. get content of part
if (isset($part['FILENAME'])) {
// content provided via absolute path to content containing file
$filename = $part['FILENAME'];
$file_size = filesize($filename);
$body = file_get_contents($filename);
if ($body === false) {
return $this->SetError('FILE_PART_OPEN_ERROR', Array($filename));
}
$actual_size = strlen($body);
if (($file_size === false || $actual_size > $file_size) && get_magic_quotes_runtime()) {
$body = stripslashes($body);
}
if ($file_size !== false && $actual_size != $file_size) {
return $this->SetError('FILE_PART_DATA_ERROR', Array($filename));
}
}
else {
// content provided directly as one of part keys
if (!isset($part['DATA'])) {
return $this->SetError('FILE_PART_DATA_MISSING');
}
$body =& $part['DATA'];
}
// 2. get part transfer encoding
$encoding = isset($part['Content-Transfer-Encoding']) ? strtolower($part['Content-Transfer-Encoding']) : '';
if (!in_array($encoding, Array ('', 'base64', 'quoted-printable', '7bit'))) {
return $this->SetError('INVALID_ENCODING', Array($encoding));
}
if ($encoding == 'base64') {
// split base64 encoded text by 76 symbols at line (MIME requirement)
$body = chunk_split( base64_encode($body) );
}
break;
case 'multipart':
// compose multipart message
switch ($sub_type) {
case 'alternative':
case 'related':
case 'mixed':
case 'parallel':
$this->CreatePartBoundary($part_number);
$boundary = $this->line_break.'--'.$part['BOUNDARY'];
foreach ($part['PARTS'] as $multipart_number) {
$body .= $boundary.$this->line_break;
$part_headers = $this->GetPartHeaders($multipart_number);
if ($part_headers === false) {
// some of sub-part headers were invalid
return false;
}
foreach ($part_headers as $header_name => $header_value) {
$body .= $header_name.': '.$header_value.$this->line_break;
}
$part_body = $this->GetPartBody($multipart_number);
if ($part_body === false) {
// part body was invalid
return false;
}
$body .= $this->line_break.$part_body;
}
$body .= $boundary.'--'.$this->line_break;
break;
default:
return $this->SetError('INVALID_MULTIPART_SUBTYPE', Array($sub_type));
}
break;
default:
return $this->SetError('INVALID_CONTENT_TYPE', Array($full_type));
}
return $body;
}
/**
* Applies quoted-printable encoding to specified text
*
* @param string $text
* @param string $header_charset
* @param int $break_lines
* @return unknown
*/
function QuotedPrintableEncode($text, $header_charset = '', $break_lines = 1)
{
$ln = strlen($text);
$h = strlen($header_charset) > 0;
if ($h) {
$s = Array (
'=' => 1,
'?' => 1,
'_' => 1,
'(' => 1,
')' => 1,
'<' => 1,
'>' => 1,
'@' => 1,
',' => 1,
';' => 1,
'"' => 1,
'\\' => 1,
/*
'/' => 1,
'[' => 1,
']' => 1,
':' => 1,
'.' => 1,
*/
);
$b = $space = $break_lines = 0;
for ($i = 0; $i < $ln; $i++) {
if (isset($s[$text[$i]])) {
$b = 1;
break;
}
switch ($o = ord($text[$i])) {
case 9:
case 32:
$space = $i + 1;
$b = 1;
break 2;
case 10:
case 13:
break 2;
default:
if ($o < 32 || $o > 127) {
$b = 1;
break 2;
}
}
}
if($i == $ln) {
return $text;
}
if ($space > 0) {
return substr($text, 0, $space).($space < $ln ? $this->QuotedPrintableEncode(substr($text, $space), $header_charset, 0) : '');
}
}
for ($w = $e = '', $n = 0, $l = 0, $i = 0; $i < $ln; $i++) {
$c = $text[$i];
$o = ord($c);
$en = 0;
switch ($o) {
case 9:
case 32:
if (!$h) {
$w = $c;
$c = '';
}
else {
if ($b) {
if ($o == 32) {
$c = '_';
}
else {
$en = 1;
}
}
}
break;
case 10:
case 13:
if (strlen($w)) {
if ($break_lines && $l + 3 > 75) {
$e .= '='.$this->line_break;
$l = 0;
}
$e .= sprintf('=%02X', ord($w));
$l += 3;
$w = '';
}
$e .= $c;
if ($h) {
$e .= "\t";
}
$l = 0;
continue 2;
case 46:
case 70:
case 102:
$en = (!$h && ($l == 0 || $l + 1 > 75));
break;
default:
if ($o > 127 || $o < 32 || !strcmp($c, '=')) {
$en = 1;
}
elseif ($h && isset($s[$c])) {
$en = 1;
}
break;
}
if (strlen($w)) {
if ($break_lines && $l + 1 > 75) {
$e .= '='.$this->line_break;
$l = 0;
}
$e .= $w;
$l++;
$w = '';
}
if (strlen($c)) {
if ($en) {
$c = sprintf('=%02X', $o);
$el = 3;
$n = 1;
$b = 1;
}
else {
$el = 1;
}
if ($break_lines && $l + $el > 75) {
$e .= '='.$this->line_break;
$l = 0;
}
$e .= $c;
$l += $el;
}
}
if (strlen($w)) {
if ($break_lines && $l + 3 > 75) {
$e .= '='.$this->line_break;
}
$e .= sprintf('=%02X', ord($w));
}
return $h && $n ? '=?'.$header_charset.'?q?'.$e.'?=' : $e;
}
/**
* Sets message header + encodes is by quoted-printable using charset specified
*
* @param string $name
* @param string $value
* @param string $encoding_charset
*/
function SetHeader($name, $value, $encoding_charset = '')
{
if ($encoding_charset) {
// actually for headers base64 method may give shorter result
$value = $this->QuotedPrintableEncode($value, $encoding_charset);
}
$this->headers[$name] = $value;
}
/**
* Sets header + automatically encodes it using default charset
*
* @param string $name
* @param string $value
*/
function SetEncodedHeader($name, $value)
{
$this->SetHeader($name, $value, $this->charset);
}
/**
* Sets header which value is email and username +autoencode
*
* @param string $header
* @param string $address
* @param string $name
*/
function SetEncodedEmailHeader($header, $address, $name)
{
$this->SetHeader($header, $this->QuotedPrintableEncode($name, $this->charset).' <'.$address.'>');
}
function SetMultipleEncodedEmailHeader($header, $addresses)
{
$value = '';
foreach ($addresses as $name => $address) {
$value .= $this->QuotedPrintableEncode($name, $this->charset).' <'.$address.'>, ';
}
$value = preg_replace('/(.*),$/', '\\1', $value);
$this->SetHeader($header, $value);
}
/**
* Adds new part to message and returns it's number
*
* @param Array $part_definition
* @param int $part_number number of new part
* @return int
*/
function AddPart(&$part_definition, $part_number = false)
{
$part_number = $part_number !== false ? $part_number : count($this->parts);
$this->parts[$part_number] =& $part_definition;
return $part_number;
}
/**
* Returns text version of HTML document
*
* @param string $html
* @return string
*/
function ConvertToText($html)
{
$search = Array (
"'(<\/td>.*)[\r\n]+(.*<td)'i",//formating text in tables
"'(<br[ ]?[\/]?>[\r\n]{0,2})|(<\/p>)|(<\/div>)|(<\/tr>)'i",
"'<head>(.*?)</head>'si",
"'<style(.*?)</style>'si",
"'<title>(.*?)</title>'si",
"'<script(.*?)</script>'si",
// "'^[\s\n\r\t]+'", //strip all spacers & newlines in the begin of document
// "'[\s\n\r\t]+$'", //strip all spacers & newlines in the end of document
"'&(quot|#34);'i",
"'&(amp|#38);'i",
"'&(lt|#60);'i",
"'&(gt|#62);'i",
"'&(nbsp|#160);'i",
"'&(iexcl|#161);'i",
"'&(cent|#162);'i",
"'&(pound|#163);'i",
"'&(copy|#169);'i",
"'&#(\d+);'e"
);
$replace = Array (
"\\1\t\\2",
"\n",
"",
"",
"",
"",
// "",
// "",
"\"",
"&",
"<",
">",
" ",
chr(161),
chr(162),
chr(163),
chr(169),
"chr(\\1)"
);
return strip_tags( preg_replace ($search, $replace, $html) );
}
/**
* Add text OR html part to message (optionally encoded)
*
* @param string $text part's text
* @param bool $is_html this html part or not
* @param bool $encode encode message using quoted-printable encoding
*
* @return int number of created part
*/
function CreateTextHtmlPart($text, $is_html = false, $encode = true)
{
if ($is_html) {
// if adding HTML part, then create plain-text part too
$this->CreateTextHtmlPart($this->ConvertToText($text));
}
// in case if text is from $_REQUEST, then line endings are "\r\n", but we need "\n" here
$text = str_replace("\r\n", "\n", $text); // possible case
$text = str_replace("\r", "\n", $text); // impossible case, but just in case replace this too
$definition = Array (
'Content-Type' => $is_html ? 'text/html' : 'text/plain',
'CHARSET' => $this->charset,
'DATA' => $encode ? $this->QuotedPrintableEncode($text) : $text,
);
if ($encode) {
$definition['Content-Transfer-Encoding'] = 'quoted-printable';
}
$guess_name = $is_html ? 'html_part' : 'text_part';
$part_number = $this->guessOptions[$guess_name] !== false ? $this->guessOptions[$guess_name] : false;
$part_number = $this->AddPart($definition, $part_number);
$this->guessOptions[$guess_name] = $part_number;
return $part_number;
}
/**
* Adds attachment part to message
*
* @param string $file name of the file with attachment body
* @param string $attach_name name for attachment (name of file is used, when not specified)
* @param string $content_type content type for attachment
* @param string $content body of file to be attached
* @param bool $inline is attachment inline or not
*
* @return int number of created part
*/
function AddAttachment($file = '', $attach_name = '', $content_type = '', $content = '', $inline = false)
{
$definition = Array (
'Disposition' => $inline ? 'inline' : 'attachment',
'Content-Type' => $content_type ? $content_type : 'automatic/name',
);
if ($file) {
// filename of attachment given
$definition['FileName'] = $file;
}
if ($attach_name) {
// name of attachment given
$definition['Name'] = $attach_name;
}
if ($content) {
// attachment data is given
$definition['Data'] = $content;
}
$definition =& $this->GetFileDefinition($definition);
$part_number = $this->AddPart($definition);
if ($inline) {
// it's inline attachment and needs content-id to be addressed by in message
$this->parts[$part_number]['Content-ID'] = md5(uniqid($part_number.time())).'.'.$this->GetFilenameExtension($attach_name ? $attach_name : $file);
}
$this->guessOptions[$inline ? 'inline_attachments' : 'attachments'][] = $part_number;
return $part_number;
}
/**
* Adds another MIME message as attachment to message being composed
*
* @param string $file name of the file with attachment body
* @param string $attach_name name for attachment (name of file is used, when not specified)
* @param string $content body of file to be attached
*
* @return int number of created part
*/
function AddMessageAttachment($file = '', $attach_name = '', $content = '')
{
$part_number = $this->AddAttachment($file, $attach_name, 'message/rfc822', $content, true);
unset($this->parts[$part_number]['Content-ID']); // messages don't have content-id, but have inline disposition
return $part_number;
}
/**
* Creates multipart of specified type and returns it's number
*
* @param Array $part_numbers
* @param string $multipart_type = {alternative,related,mixed,paralell}
* @return int
*/
function CreateMultipart($part_numbers, $multipart_type)
{
$types = Array ('alternative', 'related' , 'mixed', 'paralell');
if (!in_array($multipart_type, $types)) {
return $this->SetError('INVALID_MULTIPART_SUBTYPE', Array($multipart_type));
}
$definition = Array (
'Content-Type' => 'multipart/'.$multipart_type,
'PARTS' => $part_numbers,
);
return $this->AddPart($definition);
}
/**
* Creates missing content-id header for inline attachments
*
* @param int $part_number
*/
function CreateContentID($part_number)
{
$part =& $this->parts[$part_number];
if (!isset($part['Content-ID']) && $part['DISPOSITION'] == 'inline') {
$part['Content-ID'] = md5(uniqid($part_number.time())).'.'.$this->GetFilenameExtension($part['NAME']);
}
}
/**
* Returns attachment part based on file used in attachment
*
* @param Array $file
* @return Array
*/
function &GetFileDefinition ($file)
{
$name = '';
if (isset($file['Name'])) {
// if name is given directly, then use it
$name = $file['Name'];
}
else {
// auto-guess attachment name based on source filename
$name = isset($file['FileName']) ? basename($file['FileName']) : '';
}
if (!$name || (!isset($file['FileName']) && !isset($file['Data']))) {
// filename not specified || no filename + no direct file content
return $this->SetError('MISSING_FILE_DATA');
}
$encoding = 'base64';
if (isset($file['Content-Type'])) {
$content_type = $file['Content-Type'];
list ($type, $sub_type) = explode('/', $content_type);
switch ($type) {
case 'text':
case 'image':
case 'audio':
case 'video':
case 'application':
break;
case 'message':
$encoding = '7bit';
break;
case 'automatic':
if (!$name) {
return $this->SetError('MISSING_FILE_NAME');
}
$this->guessContentType($name, $content_type, $encoding);
break;
default:
return $this->SetError('INVALID_CONTENT_TYPE', Array($content_type));
}
}
else {
// encoding not passed in file part, then assume, that it's binary
$content_type = 'application/octet-stream';
}
$definition = Array (
'Content-Type' => $content_type,
'Content-Transfer-Encoding' => $encoding,
'NAME' => $name, // attachment name
);
if (isset($file['Disposition'])) {
$disposition = strtolower($file['Disposition']);
if ($disposition == 'inline' || $disposition == 'attachment') {
// valid disposition header value
$definition['DISPOSITION'] = $file['Disposition'];
}
else {
return $this->SetError('INVALID_DISPOSITION', Array($file['Disposition']));
}
}
if (isset($file['FileName'])) {
$definition['FILENAME'] = $file['FileName'];
}
elseif (isset($file['Data'])) {
$definition['DATA'] =& $file['Data'];
}
return $definition;
}
/**
* Returns content-type based on filename extension
*
* @param string $filename
* @param string $content_type
* @param string $encoding
*
* @todo Regular expression used is not completely finished, that's why if extension used for
* comparing in some other extension (from list) part, that partial match extension will be returned.
* Because of two extension that begins with same 2 letters always belong to same content type
* this unfinished regular expression still gives correct result in any case.
*/
function guessContentType($filename, &$content_type, &$encoding)
{
- $file_extension = strtolower( $this->GetFilenameExtension($filename) );
+ $file_extension = mb_strtolower( $this->GetFilenameExtension($filename) );
$mapping = '(xls:application/excel)(hqx:application/macbinhex40)(doc,dot,wrd:application/msword)(pdf:application/pdf)
(pgp:application/pgp)(ps,eps,ai:application/postscript)(ppt:application/powerpoint)(rtf:application/rtf)
(tgz,gtar:application/x-gtar)(gz:application/x-gzip)(php,php3:application/x-httpd-php)(js:application/x-javascript)
(ppd,psd:application/x-photoshop)(swf,swc,rf:application/x-shockwave-flash)(tar:application/x-tar)(zip:application/zip)
(mid,midi,kar:audio/midi)(mp2,mp3,mpga:audio/mpeg)(ra:audio/x-realaudio)(wav:audio/wav)(bmp:image/bitmap)(bmp:image/bitmap)
(gif:image/gif)(iff:image/iff)(jb2:image/jb2)(jpg,jpe,jpeg:image/jpeg)(jpx:image/jpx)(png:image/png)(tif,tiff:image/tiff)
(wbmp:image/vnd.wap.wbmp)(xbm:image/xbm)(css:text/css)(txt:text/plain)(htm,html:text/html)(xml:text/xml)
(mpg,mpe,mpeg:video/mpeg)(qt,mov:video/quicktime)(avi:video/x-ms-video)(eml:message/rfc822)';
if (preg_match('/[\(,]'.$file_extension.'[,]{0,1}.*?:(.*?)\)/s', $mapping, $regs)) {
if ($file_extension == 'eml') {
$encoding = '7bit';
}
$content_type = $regs[1];
}
else {
$content_type = 'application/octet-stream';
}
}
/**
* Using guess options combines all added parts together and returns combined part number
*
* @return int
*/
function PrepareMessageBody()
{
if ($this->bodyPartNumber === false) {
$part_number = false; // number of generated body part
// 1. set text content of message
if ($this->guessOptions['text_part'] !== false && $this->guessOptions['html_part'] !== false) {
// text & html parts present -> compose into alternative part
$parts = Array (
$this->guessOptions['text_part'],
$this->guessOptions['html_part'],
);
$part_number = $this->CreateMultipart($parts, 'alternative');
}
elseif ($this->guessOptions['text_part'] !== false) {
// only text part is defined, then leave as is
$part_number = $this->guessOptions['text_part'];
}
if ($part_number === false) {
return $this->SetError('MESSAGE_TEXT_MISSING');
}
// 2. if inline attachments found, then create related multipart from text & inline attachments
if ($this->guessOptions['inline_attachments']) {
$parts = array_merge(Array($part_number), $this->guessOptions['inline_attachments']);
$part_number = $this->CreateMultipart($parts, 'related');
}
// 3. if normal attachments found, then create mixed multipart from text & attachments
if ($this->guessOptions['attachments']) {
$parts = array_merge(Array($part_number), $this->guessOptions['attachments']);
$part_number = $this->CreateMultipart($parts, 'mixed');
}
$this->bodyPartNumber = $part_number;
}
return $this->bodyPartNumber;
}
/**
* Returns message headers and body part (by reference in parameters)
*
* @param Array $message_headers
* @param string $message_body
* @return bool
*/
function GetHeadersAndBody(&$message_headers, &$message_body)
{
$part_number = $this->PrepareMessageBody();
if ($part_number === false) {
return $this->SetError('MESSAGE_COMPOSE_ERROR');
}
$message_headers = $this->GetPartHeaders($part_number);
// join message headers and body headers
$message_headers = array_merge_recursive2($this->headers, $message_headers);
$message_headers['MIME-Version'] = '1.0';
if ($this->mailerName) {
$message_headers['X-Mailer'] = $this->mailerName;
}
$this->GenerateMessageID($message_headers['From']);
$valid_headers = $this->ValidateHeaders($message_headers);
if ($valid_headers) {
// set missing headers from existing
$from_headers = Array ('Reply-To', 'Errors-To');
foreach ($from_headers as $header_name) {
if (!isset($message_headers[$header_name])) {
$message_headers[$header_name] = $message_headers['From'];
}
}
$message_body = $this->GetPartBody($part_number);
return true;
}
return false;
}
/**
* Checks that all required headers are set and not empty
*
* @param Array $message_headers
* @return bool
*/
function ValidateHeaders($message_headers)
{
$from = isset($message_headers['From']) ? $message_headers['From'] : '';
if (!$from) {
return $this->SetError('HEADER_MISSING', Array('From'));
}
if (!isset($message_headers['To'])) {
return $this->SetError('HEADER_MISSING', Array('To'));
}
if (!isset($message_headers['Subject'])) {
return $this->SetError('HEADER_MISSING', Array('Subject'));
}
return true;
}
/**
* Returns full message source (headers + body) for sending to SMTP server
*
* @return string
*/
function GetMessage()
{
$composed = $this->GetHeadersAndBody($message_headers, $message_body);
if ($composed) {
// add headers to resulting message
$message = '';
foreach ($message_headers as $header_name => $header_value) {
$message .= $header_name.': '.$header_value.$this->line_break;
}
// add message body
$message .= $this->line_break.$message_body;
return $message;
}
return false;
}
/**
* Sets just happened error code
*
* @param string $code
* @param Array $params additional error params
* @return bool
*/
function SetError($code, $params = null, $fatal = true)
{
$error_msgs = Array (
'MAIL_NOT_FOUND' => 'the mail() function is not available in this PHP installation',
'MISSING_CONTENT_TYPE' => 'it was added a part without Content-Type: defined',
'INVALID_CONTENT_TYPE' => 'Content-Type: %s not yet supported',
'INVALID_MULTIPART_SUBTYPE' => 'multipart Content-Type sub_type %s not yet supported',
'FILE_PART_OPEN_ERROR' => 'could not open part file %s',
'FILE_PART_DATA_ERROR' => 'the length of the file that was read does not match the size of the part file %s due to possible data corruption',
'FILE_PART_DATA_MISSING' => 'it was added a part without a body PART',
'INVALID_ENCODING' => '%s is not yet a supported encoding type',
'MISSING_FILE_DATA' => 'file part data is missing',
'MISSING_FILE_NAME' => 'it is not possible to determine content type from the name',
'INVALID_DISPOSITION' => '%s is not a supported message part content disposition',
'MESSAGE_TEXT_MISSING' => 'text part of message was not defined',
'MESSAGE_COMPOSE_ERROR' => 'unknown message composing error',
'HEADER_MISSING' => 'header %s is required',
// SMTP errors
'INVALID_COMMAND' => 'Commands cannot contain newlines',
'CONNECTION_TERMINATED' => 'Connection was unexpectedly closed',
'HELO_ERROR' => 'HELO was not accepted: %s',
'AUTH_METHOD_NOT_SUPPORTED' => '%s is not a supported authentication method',
'AUTH_METHOD_NOT_IMPLEMENTED' => '%s is not a implemented authentication method',
);
if (!is_array($params)) {
$params = Array ();
}
trigger_error('mail error: '.vsprintf($error_msgs[$code], $params), $fatal ? E_USER_ERROR : E_USER_WARNING);
return false;
}
/**
* Simple method of message sending
*
* @param string $from_email
* @param string $to_email
* @param string $subject
* @param string $from_name
* @param string $to_name
*/
function Send($from_email, $to_email, $subject, $from_name = '', $to_name = '')
{
$this->SetSubject($subject);
$this->SetFrom($from_email, trim($from_name) ? trim($from_name) : $from_email);
if (!isset($this->headers['Return-Path'])) {
$this->SetReturnPath($from_email);
}
$this->SetEncodedEmailHeader('To', $to_email, $to_name ? $to_name : $to_email);
return $this->Deliver();
}
/**
* Prepares class for sending another message
*
*/
function Clear()
{
$this->headers = Array ();
$this->bodyPartNumber = false;
$this->parts = Array();
$this->guessOptions = Array (
'attachments' => Array(),
'inline_attachments' => Array (),
'text_part' => false,
'html_part' => false,
);
$this->SetCharset(null, true);
}
/**
* Sends message via php mail function
*
* @param Array $message_headers
* @param string $body
*
* @return bool
*/
function SendMail($message_headers, &$body)
{
if (!function_exists('mail')) {
return $this->SetError('MAIL_NOT_FOUND');
}
$to = $message_headers['To'];
$subject = $message_headers['Subject'];
$return_path = $message_headers['Return-Path'];
unset($message_headers['To'], $message_headers['Subject']);
$headers = '';
$header_separator = $this->Application->ConfigValue('MailFunctionHeaderSeparator') == 1 ? "\n" : "\r\n";
foreach ($message_headers as $header_name => $header_value) {
$headers .= $header_name.': '.$header_value.$header_separator;
}
if ($return_path) {
if (constOn('SAFE_MODE') || (defined('PHP_OS') && substr(PHP_OS, 0, 3) == 'WIN')) {
// safe mode restriction OR is windows
$return_path = '';
}
}
return mail($to, $subject, $body, $headers, $return_path ? '-f'.$return_path : null);
}
/**
* Sends message via SMTP server
*
* @param Array $message_headers
* @param string $body
*
* @return bool
*/
function SendSMTP($message_headers, &$message_body)
{
if (!$this->SmtpConnect()) {
return false;
}
$from = $this->ExtractRecipientEmail($message_headers['From']);
if (!$this->SmtpSetFrom($from)) {
return false;
}
$recipients = '';
$recipient_headers = Array ('To', 'Cc', 'Bcc');
foreach ($recipient_headers as $recipient_header) {
if (isset($message_headers[$recipient_header])) {
$recipients .= ' '.$message_headers[$recipient_header];
}
}
$recipients_accepted = 0;
$recipients = $this->ExtractRecipientEmail($recipients, true);
foreach ($recipients as $recipient) {
if ($this->SmtpAddTo($recipient)) {
$recipients_accepted++;
}
}
if ($recipients_accepted == 0) {
// none of recipients were accepted
return false;
}
$headers = '';
foreach ($message_headers as $header_name => $header_value) {
$headers .= $header_name.': '.$header_value.$this->line_break;
}
if (!$this->SmtpSendMessage($headers . "\r\n" . $message_body)) {
return false;
}
$this->SmtpDisconnect();
return true;
}
/**
* Send a command to the server with an optional string of
* arguments. A carriage return / linefeed (CRLF) sequence will
* be appended to each command string before it is sent to the
* SMTP server.
*
* @param string $command The SMTP command to send to the server.
* @param string $args A string of optional arguments to append to the command.
*
* @return bool
*
*/
function SmtpSendCommand($command, $args = '')
{
if (!empty($args)) {
$command .= ' ' . $args;
}
if (strcspn($command, "\r\n") !== strlen($command)) {
return $this->SetError('INVALID_COMMAND');
}
return $this->smtpSocket->write($command . "\r\n") === false ? false : true;
}
/**
* Read a reply from the SMTP server. The reply consists of a response code and a response message.
*
* @param mixed $valid The set of valid response codes. These may be specified as an array of integer values or as a single integer value.
*
* @return bool
*
*/
function SmtpParseResponse($valid)
{
$this->smtpResponceCode = -1;
$this->smtpRespoceArguments = array();
while ($line = $this->smtpSocket->readLine()) {
// If we receive an empty line, the connection has been closed.
if (empty($line)) {
$this->SmtpDisconnect();
return $this->SetError('CONNECTION_TERMINATED', null, false);
}
// Read the code and store the rest in the arguments array.
$code = substr($line, 0, 3);
$this->smtpRespoceArguments[] = trim(substr($line, 4));
// Check the syntax of the response code.
if (is_numeric($code)) {
$this->smtpResponceCode = (int)$code;
} else {
$this->smtpResponceCode = -1;
break;
}
// If this is not a multiline response, we're done.
if (substr($line, 3, 1) != '-') {
break;
}
}
// Compare the server's response code with the valid code.
if (is_int($valid) && ($this->smtpResponceCode === $valid)) {
return true;
}
// If we were given an array of valid response codes, check each one.
if (is_array($valid)) {
foreach ($valid as $valid_code) {
if ($this->smtpResponceCode === $valid_code) {
return true;
}
}
}
return false;
}
/**
* Attempt to connect to the SMTP server.
*
* @param int $timeout The timeout value (in seconds) for the socket connection.
* @param bool $persistent Should a persistent socket connection be used ?
*
* @return bool
*
*/
function SmtpConnect($timeout = null, $persistent = false)
{
$result = $this->smtpSocket->connect($this->smtpParams['server'], $this->smtpParams['port'], $persistent, $timeout);
if (!$result) {
return false;
}
if ($this->SmtpParseResponse(220) === false) {
return false;
}
elseif ($this->SmtpNegotiate() === false) {
return false;
}
if ($this->smtpParams['use_auth']) {
$result = $this->SmtpAuthentificate($this->smtpParams['username'], $this->smtpParams['password']);
if (!$result) {
// authentification failed
return false;
}
}
return true;
}
/**
* Attempt to disconnect from the SMTP server.
*
* @return bool
*/
function SmtpDisconnect()
{
if ($this->SmtpSendCommand('QUIT') === false) {
return false;
}
elseif ($this->SmtpParseResponse(221) === false) {
return false;
}
return $this->smtpSocket->disconnect();
}
/**
* Attempt to send the EHLO command and obtain a list of ESMTP
* extensions available, and failing that just send HELO.
*
* @return bool
*/
function SmtpNegotiate()
{
if (!$this->SmtpSendCommand('EHLO', $this->smtpParams['localhost'])) {
return false;
}
if (!$this->SmtpParseResponse(250)) {
// If we receive a 503 response, we're already authenticated.
if ($this->smtpResponceCode === 503) {
return true;
}
// If the EHLO failed, try the simpler HELO command.
if (!$this->SmtpSendCommand('HELO', $this->smtpParams['localhost'])) {
return false;
}
if (!$this->SmtpParseResponse(250)) {
return $this->SetError('HELO_ERROR', Array($this->smtpResponceCode), false);
}
return true;
}
foreach ($this->smtpRespoceArguments as $argument) {
$verb = strtok($argument, ' ');
$arguments = substr($argument, strlen($verb) + 1, strlen($argument) - strlen($verb) - 1);
$this->smtpFeatures[$verb] = $arguments;
}
return true;
}
/**
* Attempt to do SMTP authentication.
*
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
* @param string The requested authentication method. If none is specified, the best supported method will be used.
*
* @return bool
*/
function SmtpAuthentificate($uid, $pwd , $method = '')
{
if (empty($this->smtpFeatures['AUTH'])) {
// server doesn't understand AUTH command, then don't authentificate
return true;
}
$available_methods = explode(' ', $this->smtpFeatures['AUTH']); // methods supported by SMTP server
if (empty($method)) {
foreach ($this->smtpAuthMethods as $supported_method) {
// check if server supports methods, that we have implemented
if (in_array($supported_method, $available_methods)) {
$method = $supported_method;
break;
}
}
} else {
$method = strtoupper($method);
}
if (!in_array($method, $available_methods)) {
// coosen method is not supported by server
return $this->SetError('AUTH_METHOD_NOT_SUPPORTED', Array($method));
}
switch ($method) {
case 'CRAM-MD5':
$result = $this->_authCRAM_MD5($uid, $pwd);
break;
case 'LOGIN':
$result = $this->_authLogin($uid, $pwd);
break;
case 'PLAIN':
$result = $this->_authPlain($uid, $pwd);
break;
default:
return $this->SetError('AUTH_METHOD_NOT_IMPLEMENTED', Array($method));
break;
}
return $result;
}
/**
* Function which implements HMAC MD5 digest
*
* @param string $key The secret key
* @param string $data The data to protect
* @return string The HMAC MD5 digest
*/
function _HMAC_MD5($key, $data)
{
if (strlen($key) > 64) {
$key = pack('H32', md5($key));
}
if (strlen($key) < 64) {
$key = str_pad($key, 64, chr(0));
}
$k_ipad = substr($key, 0, 64) ^ str_repeat(chr(0x36), 64);
$k_opad = substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64);
$inner = pack('H32', md5($k_ipad . $data));
$digest = md5($k_opad . $inner);
return $digest;
}
/**
* Authenticates the user using the CRAM-MD5 method.
*
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
*
* @return bool
*/
function _authCRAM_MD5($uid, $pwd)
{
if (!$this->SmtpSendCommand('AUTH', 'CRAM-MD5')) {
return false;
}
// 334: Continue authentication request
if (!$this->SmtpParseResponse(334)) {
// 503: Error: already authenticated
return $this->smtpResponceCode === 503 ? true : false;
}
$challenge = base64_decode($this->smtpRespoceArguments[0]);
$auth_str = base64_encode($uid . ' ' . $this->_HMAC_MD5($pwd, $challenge));
if (!$this->SmtpSendCommand($auth_str)) {
return false;
}
// 235: Authentication successful
if (!$this->SmtpParseResponse(235)) {
return false;
}
return true;
}
/**
* Authenticates the user using the LOGIN method.
*
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
*
* @return bool
*/
function _authLogin($uid, $pwd)
{
if (!$this->SmtpSendCommand('AUTH', 'LOGIN')) {
return false;
}
// 334: Continue authentication request
if (!$this->SmtpParseResponse(334)) {
// 503: Error: already authenticated
return $this->smtpResponceCode === 503 ? true : false;
}
if (!$this->SmtpSendCommand(base64_encode($uid))) {
return false;
}
// 334: Continue authentication request
if (!$this->SmtpParseResponse(334)) {
return false;
}
if (!$this->SmtpSendCommand(base64_encode($pwd))) {
return false;
}
// 235: Authentication successful
if (!$this->SmtpParseResponse(235)) {
return false;
}
return true;
}
/**
* Authenticates the user using the PLAIN method.
*
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
*
* @return bool
*/
function _authPlain($uid, $pwd)
{
if (!$this->SmtpSendCommand('AUTH', 'PLAIN')) {
return false;
}
// 334: Continue authentication request
if (!$this->SmtpParseResponse(334)) {
// 503: Error: already authenticated
return $this->smtpResponceCode === 503 ? true : false;
}
$auth_str = base64_encode(chr(0) . $uid . chr(0) . $pwd);
if (!$this->SmtpSendCommand($auth_str)) {
return false;
}
// 235: Authentication successful
if (!$this->SmtpParseResponse(235)) {
return false;
}
return true;
}
/**
* Send the MAIL FROM: command.
*
* @param string $sender The sender (reverse path) to set.
* @param string $params String containing additional MAIL parameters, such as the NOTIFY flags defined by RFC 1891 or the VERP protocol.
*
* @return bool
*/
function SmtpSetFrom($sender, $params = null)
{
$args = "FROM:<$sender>";
if (is_string($params)) {
$args .= ' ' . $params;
}
if (!$this->SmtpSendCommand('MAIL', $args)) {
return false;
}
if (!$this->SmtpParseResponse(250)) {
return false;
}
return true;
}
/**
* Send the RCPT TO: command.
*
* @param string $recipient The recipient (forward path) to add.
* @param string $params String containing additional RCPT parameters, such as the NOTIFY flags defined by RFC 1891.
*
* @return bool
*/
function SmtpAddTo($recipient, $params = null)
{
$args = "TO:<$recipient>";
if (is_string($params)) {
$args .= ' ' . $params;
}
if (!$this->SmtpSendCommand('RCPT', $args)) {
return false;
}
if (!$this->SmtpParseResponse(array(250, 251))) {
return false;
}
return true;
}
/**
* Send the DATA command.
*
* @param string $data The message body to send.
*
* @return bool
*/
function SmtpSendMessage($data)
{
/* RFC 1870, section 3, subsection 3 states "a value of zero
* indicates that no fixed maximum message size is in force".
* Furthermore, it says that if "the parameter is omitted no
* information is conveyed about the server's fixed maximum
* message size". */
if (isset($this->smtpFeatures['SIZE']) && ($this->smtpFeatures['SIZE'] > 0)) {
if (strlen($data) >= $this->smtpFeatures['SIZE']) {
$this->SmtpDisconnect();
return $this->SetError('Message size excedes the server limit', null, false);
}
}
// Quote the data based on the SMTP standards
// Change Unix (\n) and Mac (\r) linefeeds into Internet-standard CRLF (\r\n) linefeeds.
$data = preg_replace(Array('/(?<!\r)\n/','/\r(?!\n)/'), "\r\n", $data);
// Because a single leading period (.) signifies an end to the data,
// legitimate leading periods need to be "doubled" (e.g. '..')
$data = str_replace("\n.", "\n..", $data);
if (!$this->SmtpSendCommand('DATA')) {
return false;
}
if (!$this->SmtpParseResponse(354)) {
return false;
}
if ($this->smtpSocket->write($data . "\r\n.\r\n") === false) {
return false;
}
if (!$this->SmtpParseResponse(250)) {
return false;
}
return true;
}
/**
* Sets global charset for every message part
*
* @param string $charset
* @param bool set charset to default for current langauge
*/
function SetCharset($charset, $is_system = false)
{
if ($is_system) {
$language =& $this->Application->recallObject('lang.current');
/* @var $language LanguagesItem */
$charset = $language->GetDBField('Charset') ? $language->GetDBField('Charset') : 'ISO-8859-1';
}
$this->charset = $charset;
}
/**
* Allows to extract recipient's name from text by specifying it's email
*
* @param string $text
* @param string $email
* @return string
*/
function ExtractRecipientName($text, $email = '')
{
- $lastspace = strrpos($text, ' ');
- $name = trim(substr($text, 0, $lastspace - strlen($text)), " \r\n\t\0\x0b\"'");
+ $lastspace = mb_strrpos($text, ' ');
+ $name = trim(mb_substr($text, 0, $lastspace - mb_strlen($text)), " \r\n\t\0\x0b\"'");
if (empty($name)) {
$name = $email;
}
return $name;
}
/**
* Takes $text and returns an email address from it
* Set $multiple to true to retrieve all found addresses
* Returns false if no addresses were found
*
* @param string $text
* @param bool $multiple
* @param bool $allowOnlyDomain
* @return string
*/
function ExtractRecipientEmail($text, $multiple = false, $allowOnlyDomain = false) {
if ($allowOnlyDomain) {
$pattern = '/(('.REGEX_EMAIL_USER.'@)?'.REGEX_EMAIL_DOMAIN.')/i';
} else {
$pattern = '/('.REGEX_EMAIL_USER.'@'.REGEX_EMAIL_DOMAIN.')/i';
}
if ($multiple) {
if (preg_match_all($pattern, $text, $findemail) >= 1) {
return $findemail[1];
} else {
return false;
}
} else {
if (preg_match($pattern, $text, $findemail) == 1) {
return $findemail[1];
} else {
return false;
}
}
}
/**
* Returns array of recipient names and emails
*
* @param string $list
* @param string $separator
* @return Array
*/
function GetRecipients($list, $separator = ';')
{
// by MIME specs recipients should be separated using "," symbol,
// but users can write ";" too (like in OutLook)
if (!trim($list)) {
return false;
}
$list = explode(',', str_replace($separator, ',', $list));
$ret = Array ();
foreach ($list as $recipient) {
$email = $this->ExtractRecipientEmail($recipient);
if (!$email) {
// invalid email format -> error
return false;
}
$name = $this->ExtractRecipientName($recipient, $email);
$ret[] = Array('Name' => $name, 'Email' => $email);
}
return $ret;
}
/* methods for nice header setting */
/**
* Sets "From" header.
*
* @param string $email
* @param string $first_last_name FirstName and LastName or just FirstName
* @param string $last_name LastName (if not specified in previous parameter)
*/
function SetFrom($email, $first_last_name, $last_name = '')
{
$name = rtrim($first_last_name.' '.$last_name, ' ');
$this->SetEncodedEmailHeader('From', $email, $name ? $name : $email);
if (!isset($this->headers['Return-Path'])) {
$this->SetReturnPath($email);
}
}
/**
* Sets "Return-Path" header (useful for spammers)
*
* @param string $email
*/
function SetReturnPath($email)
{
$this->SetHeader('Return-Path', $email);
}
/**
* Adds one more recipient into "To" header
*
* @param string $email
* @param string $first_last_name FirstName and LastName or just FirstName
* @param string $last_name LastName (if not specified in previous parameter)
*/
function AddTo($email, $first_last_name = '', $last_name = '')
{
$name = rtrim($first_last_name.' '.$last_name, ' ');
$this->AddRecipient('To', $email, $name);
}
/**
* Adds one more recipient into "Cc" header
*
* @param string $email
* @param string $first_last_name FirstName and LastName or just FirstName
* @param string $last_name LastName (if not specified in previous parameter)
*/
function AddCc($email, $first_last_name = '', $last_name = '')
{
$name = rtrim($first_last_name.' '.$last_name, ' ');
$this->AddRecipient('Cc', $email, $name);
}
/**
* Adds one more recipient into "Bcc" header
*
* @param string $email
* @param string $first_last_name FirstName and LastName or just FirstName
* @param string $last_name LastName (if not specified in previous parameter)
*/
function AddBcc($email, $first_last_name = '', $last_name = '')
{
$name = rtrim($first_last_name.' '.$last_name, ' ');
$this->AddRecipient('Bcc', $email, $name);
}
/**
* Adds one more recipient to specified header
*
* @param string $header_name
* @param string $email
* @param string $name
*/
function AddRecipient($header_name, $email, $name = '')
{
if (!$name) {
$name = $email;
}
$value = isset($this->headers[$header_name]) ? $this->headers[$header_name] : '';
$value .= ', '.$this->QuotedPrintableEncode($name, $this->charset).' <'.$email.'>';
$value = preg_replace('/^,(.*)/', '\\1', $value); // remove first comma
$this->SetHeader($header_name, $value);
}
/**
* Sets "Subject" header.
*
* @param string $subject message subject
*/
function SetSubject($subject)
{
$this->setEncodedHeader('Subject', $subject);
}
/**
* Sets HTML part of message
*
* @param string $html
*/
function SetHTML($html)
{
$this->CreateTextHtmlPart($html, true);
}
/**
* Sets Plain-Text part of message
*
* @param string $plain_text
*/
function SetPlain($plain_text)
{
$this->CreateTextHtmlPart($plain_text);
}
/**
* Sets HTML and optionally plain part of the message
*
* @param string $html
* @param string $plain_text
*/
function SetBody($html, $plain_text = '')
{
$this->SetHTML($html);
if ($plain_text) {
$this->SetPlain($plain_text);
}
}
/**
* Performs mail delivery (supports delayed delivery)
*
* @param string $mesasge message, if not given, then use composed one
* @param bool $immediate_send send message now
* @param bool $immediate_clear clear message parts after message is sent
*
*/
function Deliver($message = null, $immediate_send = true, $immediate_clear = true)
{
if (isset($message)) {
// if message is given directly, then use it
if (is_array($message)) {
$message_headers =& $message[0];
$message_body =& $message[1];
}
else {
$message_headers = Array ();
list ($headers, $message_body) = explode("\n\n", $message, 2);
$headers = explode("\n", $headers);
foreach ($headers as $header) {
$header = explode(':', $header, 2);
$message_headers[ trim($header[0]) ] = trim($header[1]);
}
}
$composed = true;
} else {
// direct message not given, then assemble message from available parts
$composed = $this->GetHeadersAndBody($message_headers, $message_body);
}
if ($composed) {
if ($immediate_send) {
$send_method = 'Send'.$this->sendMethod;
$result = $this->$send_method($message_headers, $message_body);
if ($immediate_clear) {
$this->Clear();
}
return $result;
}
else {
$fields_hash = Array (
'ToEmail' => $message_headers['To'],
'Subject' => $message_headers['Subject'],
'Queued' => adodb_mktime(),
'SendRetries' => 0,
'LastSendRetry' => 0,
);
$fields_hash['MessageHeaders'] = serialize($message_headers);
$fields_hash['MessageBody'] =& $message_body;
$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'EmailQueue');
if ($immediate_clear) {
$this->Clear();
}
}
}
// if not immediate send, then send result is positive :)
return !$immediate_send ? true : false;
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/utility/email_send.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3.2.1
\ No newline at end of property
+1.3.2.2
\ No newline at end of property
Index: branches/RC/core/kernel/utility/formatters/password_formatter.php
===================================================================
--- branches/RC/core/kernel/utility/formatters/password_formatter.php (revision 10097)
+++ branches/RC/core/kernel/utility/formatters/password_formatter.php (revision 10098)
@@ -1,118 +1,118 @@
<?php
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');
if (isset($field_options['encryption_method'])) {
$options['encryption_method'] = $field_options['encryption_method'];
}
if (isset($field_options['salt'])) {
$options['salt'] = $field_options['salt'];
}
if (isset($field_options['required'])) {
$options['required'] = $field_options['required'];
}
$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;
}
/**
* Performs password & verify password field validation
*
* @param mixed $value
* @param string $field_name
* @param kDBItem $object
* @return string
*/
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++;
}
$salt = isset($object->Fields[$password_field]['salt']) ? $object->Fields[$password_field]['salt'] : '';
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('', $salt) )
{
if ($options['encryption_method'] == 'plain') return $value;
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 (mb_strlen($new_password) >= $min_length) {
if ($new_password != $verify_password) {
$object->SetError($password_field, 'passwords_do_not_match', 'lu_passwords_do_not_match');
$object->SetError($verify_field, 'passwords_do_not_match', 'lu_passwords_do_not_match');
}
}
else {
$error_msg = '+'.sprintf($this->Application->Phrase('lu_passwords_too_short'), $min_length); // + -> not phrase
$object->SetError($password_field, 'passwords_min_length', $error_msg);
$object->SetError($verify_field, 'passwords_min_length', $error_msg);
}
}
if($value == '') return $object->GetDBField($field_name);
if ($options['encryption_method'] == 'plain') return $value;
return $this->EncryptPassword($value, $salt);
}
function EncryptPassword($value, $salt=null)
{
if (!isset($salt) || !$salt) {
// if empty salt, assume, that it's not passed at all
return md5($value);
}
return md5(md5($value).$salt);
}
}
\ No newline at end of file
Property changes on: branches/RC/core/kernel/utility/formatters/password_formatter.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.5
\ No newline at end of property
+1.5.2.1
\ No newline at end of property
Index: branches/RC/core/kernel/utility/formatters/upload_formatter.php
===================================================================
--- branches/RC/core/kernel/utility/formatters/upload_formatter.php (revision 10097)
+++ branches/RC/core/kernel/utility/formatters/upload_formatter.php (revision 10098)
@@ -1,309 +1,309 @@
<?php
class kUploadFormatter extends kFormatter
{
var $DestinationPath;
var $FullPath;
function kUploadFormatter()
{
parent::kBase();
if ($this->DestinationPath) {
$this->FullPath = FULL_PATH.$this->DestinationPath;
}
}
/**
* Processes file uploads from form
*
* @param mixed $value
* @param string $field_name
* @param kDBItem $object
* @return string
*/
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;
}
// SWF Uploader
if (is_array($value) && isset($value['tmp_ids'])) {
if ($value['tmp_deleted']) {
$deleted = explode('|', $value['tmp_deleted']);
$upload = explode('|', $value['upload']);
$n_upload = array();
// $n_ids = array();
foreach ($upload as $name) {
if (in_array($name, $deleted)) continue;
$n_upload[] = $name;
// $n_ids[] = $name;
}
$value['upload'] = implode('|', $n_upload);
// $value['tmp_ids'] = implode('|', $n_ids);
}
if (!$value['tmp_ids']) {
return getArrayValue($value, 'upload');
}
$swf_uploaded_ids = explode('|', $value['tmp_ids']);
$swf_uploaded_names = explode('|', $value['tmp_names']);
$existing = $value['upload'] ? explode('|', $value['upload']) : array();
if (isset($options['multiple'])) {
$max_files = $options['multiple'] == false ? 1 : $options['multiple'];
}
else {
$max_files = 1;
}
$fret = array();
// don't delete uploaded file, when it's name matches delete file name
$var_name = $object->getPrefixSpecial().'_file_pending_actions'.$this->Application->GetVar('m_wid');
$schedule = $this->Application->RecallVar($var_name);
$schedule = $schedule ? unserialize($schedule) : Array();
$files2delete = Array();
foreach ($schedule as $data) {
if ($data['action'] == 'delete') {
$files2delete[] = $data['file'];
}
}
for ($i=0; $i<min($max_files, count($swf_uploaded_ids)); $i++) {
$real_name = $swf_uploaded_names[$i];
$real_name = $this->ValidateFileName($this->FullPath, $real_name, $files2delete);
$file_name = $this->FullPath.$real_name;
$tmp_file = (defined('WRITEABLE') ? WRITEABLE.'/tmp/' : FULL_PATH.'/kernel/cache/').$swf_uploaded_ids[$i].'_'.$swf_uploaded_names[$i];
rename($tmp_file, $file_name);
@chmod($file_name, 0666);
$fret[] = getArrayValue($options, 'upload_dir') ? $real_name : $this->DestinationPath.$real_name;
}
$fret = array_merge($existing, $fret);
return implode('|', $fret);
}
// SWF Uploader END
if (getArrayValue($value, 'upload') && getArrayValue($value, 'error') == UPLOAD_ERR_NO_FILE) {
// file was not uploaded this time, but was uploaded before, then use previously uploaded file (from db)
return getArrayValue($value, 'upload');
}
if (is_array($value) && count($value) > 1 && $value['size']) {
if (is_array($value) && $value['error'] === UPLOAD_ERR_OK) {
$max_filesize = isset($options['max_size']) ? $options['max_size'] : MAX_UPLOAD_SIZE;
if (getArrayValue($options, 'allowed_types') && !in_array($value['type'], $options['allowed_types'])) {
$object->SetError($field_name, 'bad_file_format', 'la_error_InvalidFileFormat');
}
elseif ($value['size'] > $max_filesize) {
$object->SetError($field_name, 'bad_file_size', 'la_error_FileTooLarge');
}
elseif (!is_writable($this->FullPath)) {
$object->SetError($field_name, 'cant_save_file', 'la_error_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->SetError($field_name, 'cant_save_file', 'la_error_cant_save_file');
}
else {
@chmod($file_name, 0666);
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;
// delete previous file, when new file is uploaded under same field
/*$previous_file = isset($value['upload']) ? $value['upload'] : false;
if ($previous_file && file_exists($this->FullPath.$previous_file)) {
unlink($this->FullPath.$previous_file);
}*/
}
}
}
else {
$object->SetError($field_name, 'cant_save_file', 'la_error_cant_save_file');
}
}
else {
if (getArrayValue($options, 'required')) {
$object->SetError($field_name, 'required');
}
}
// && !$object->FieldErrors[$field_name]['pseudo'] - already implemented in kDBItem::SetError method
if ((count($value) > 1) && $value['error'] && ($value['error'] != UPLOAD_ERR_NO_FILE)) {
$object->SetError($field_name, 'cant_save_file', 'la_error_cant_save_file');
}
return $ret;
}
function getSingleFormat($format)
{
$single_mapping = Array (
'file_urls' => 'full_url',
'file_sizes' => 'file_size',
'files_resized' => 'resize',
'wms' => 'wm',
);
return $single_mapping[$format];
}
/**
* Return formatted file url,path or size (or same for multiple files)
*
* @param string $value
* @param string $field_name
* @param kDBItem $object
* @param string $format
* @return string
*/
function Format($value, $field_name, &$object, $format = null)
{
if (is_null($value)) {
return '';
}
$options = $object->GetFieldOptions($field_name);
if (!isset($format)) {
$format = isset($options['format']) ? $options['format'] : false;
}
if ($format && preg_match('/(file_urls|file_names|file_sizes|files_resized|wms)(.*)/', $format, $regs)) {
if (!$value || $format == 'file_names') {
// storage format matches display format OR no value
return $value;
}
$ret = Array ();
$files = explode('|', $value);
$format = $this->getSingleFormat($regs[1]).$regs[2];
foreach ($files as $a_file) {
$ret[] = $this->GetFormatted($a_file, $field_name, $object, $format);
}
return implode('|', $ret);
}
$tc_value = $this->TypeCast($value, $options);
if( ($tc_value === false) || ($tc_value != $value) ) return $value; // for leaving badly formatted date on the form
$object->Fields[$field_name]['direct_links'] = true; // for case, when non-swf uploader is used
return $this->GetFormatted($tc_value, $field_name, $object, $format);
}
/**
* Return formatted file url,path or size
*
* @param string $value
* @param string $field_name
* @param kDBItem $object
* @param string $format
* @return string
*/
function GetFormatted($value, $field_name, &$object, $format = null)
{
if (!$format) {
return $value;
}
$options = $object->GetFieldOptions($field_name);
$upload_dir = isset($options['upload_dir']) ? $options['upload_dir'] : $this->DestinationPath;
if (preg_match('/resize:([\d]*)x([\d]*)/', $format, $regs)) {
$image_helper =& $this->Application->recallObject('ImageHelper');
/* @var $image_helper ImageHelper */
return $image_helper->ResizeImage(FULL_PATH.$upload_dir.$value, $format);
}
switch ($format) {
case 'full_url':
if (isset($options['direct_links']) && $options['direct_links']) {
return rtrim($this->Application->BaseURL(), '/').$upload_dir.$value;
}
else {
$url_params = Array (
'no_amp' => 1, 'pass' => 'm,'.$object->Prefix,
$object->Prefix.'_event' => 'OnViewFile',
'file' => $value, 'field' => $field_name
);
return $this->Application->HREF('', '', $url_params);
}
break;
case 'full_path':
return FULL_PATH.$upload_dir.$value;
break;
case 'file_size':
return filesize(FULL_PATH.$upload_dir.$value);
break;
}
return sprintf($format, $value);
}
function ValidateFileName($path, $name, $forbidden_names = Array())
{
$parts = pathinfo($name);
$ext = '.'.$parts['extension'];
- $filename = substr($parts['basename'], 0, -strlen($ext));
+ $filename = mb_substr($parts['basename'], 0, -mb_strlen($ext));
$new_name = $filename.$ext;
while ( file_exists($path.'/'.$new_name) || in_array(rtrim($path, '/').'/'.$new_name, $forbidden_names) )
{
if ( preg_match('/('.preg_quote($filename, '/').'_)([0-9]*)('.preg_quote($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; // used ?
$this->DestinationPath = constOn('ADMIN') ? IMAGES_PENDING_PATH : IMAGES_PATH;
parent::kUploadFormatter();
}
function GetFormatted($value, $field_name, &$object, $format = null)
{
if ($format == 'img_size') {
$upload_dir = isset($options['upload_dir']) ? $options['upload_dir'] : $this->DestinationPath;
$img_path = FULL_PATH.'/'.$upload_dir.$value;
$image_info = @getimagesize($img_path);
return ' width="'.$image_info[0].'" height="'.$image_info[1].'"';
}
return parent::GetFormatted($value, $field_name, $object, $format);
}
}
\ No newline at end of file
Property changes on: branches/RC/core/kernel/utility/formatters/upload_formatter.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10.2.10
\ No newline at end of property
+1.10.2.11
\ No newline at end of property
Index: branches/RC/core/kernel/utility/debugger.php
===================================================================
--- branches/RC/core/kernel/utility/debugger.php (revision 10097)
+++ branches/RC/core/kernel/utility/debugger.php (revision 10098)
@@ -1,1309 +1,1309 @@
<?php
if( !class_exists('Debugger') ) {
class Debugger {
/**
* Set to true if fatal error occured
*
* @var bool
*/
var $IsFatalError = false;
/**
* Debugger data for building report
*
* @var Array
*/
var $Data = Array();
var $ProfilerData = Array();
var $ProfilerTotals = Array();
var $ProfilerTotalCount = Array();
var $ProfilePoints = Array();
/**
* Prevent recursion when processing debug_backtrace() function results
*
* @var Array
*/
var $RecursionStack = Array();
var $scrollbarWidth = 0;
/**
* Long errors are saved here, because trigger_error doesn't support error messages over 1KB in size
*
* @var Array
*/
var $longErrors = Array();
var $IncludesData = Array();
var $IncludeLevel = 0;
var $reportDone = false;
/**
* Transparent spacer image used in case of none spacer image defined via SPACER_URL contant.
* Used while drawing progress bars (memory usage, time usage, etc.)
*
* @var string
*/
var $dummyImage = '';
/**
* Temporary files created by debugger will be stored here
*
* @var string
*/
var $tempFolder = '';
/**
* Debug rows will be separated using this string before writing to debug file
*
* @var string
*/
var $rowSeparator = '@@';
/**
* Base URL for debugger includes
*
* @var string
*/
var $baseURL = '';
function Debugger()
{
global $start, $dbg_options;
// check if user haven't defined DEBUG_MODE contant directly
if (defined('DEBUG_MODE') && DEBUG_MODE) {
die('error: contant DEBUG_MODE defined directly, please use <strong>$dbg_options</strong> array instead');
}
// check IP before enabling debug mode
$ip_match = $this->ipMatch(isset($dbg_options['DBG_IP']) ? $dbg_options['DBG_IP'] : '');
if (!$ip_match) {
define('DEBUG_MODE', 0);
return ;
}
// debug is allowed for user, continue initialization
$this->InitDebugger();
$this->profileStart('kernel4_startup', 'Startup and Initialization of kernel4', $start);
$this->profileStart('script_runtime', 'Script runtime', $start);
error_reporting(E_ALL);
ini_set('display_errors', $this->constOn('DBG_ZEND_PRESENT') ? 0 : 1); // show errors on screen in case if not in Zend Studio debugging
$this->scrollbarWidth = $this->isGecko() ? 22 : 25; // vertical scrollbar width differs in Firefox and other browsers
$this->appendRequest();
}
/**
* Checks, that user IP address is within allowed range
*
* @param string $ip_list semi-column (by default) separated ip address list
* @param string $separator ip address separator (default ";")
*
* @return bool
*/
function ipMatch($ip_list, $separator = ';')
{
$ip_match = false;
$ip_addresses = $ip_list ? explode($separator, $ip_list) : Array ();
foreach ($ip_addresses as $ip_address) {
if ($this->netMatch($ip_address, $_SERVER['REMOTE_ADDR'])) {
$ip_match = true;
break;
}
}
return $ip_match;
}
/**
* Set's default values to constants debugger uses
*
*/
function InitDebugger()
{
global $dbg_options;
unset($_REQUEST['debug_host'], $_REQUEST['debug_fastfile'], $dbg_options['DBG_IP']); // this var messed up whole detection stuff :(
// Detect fact, that this session beeing debugged by Zend Studio
foreach ($_REQUEST as $rq_name => $rq_value) {
if (substr($rq_name, 0, 6) == 'debug_') {
$this->safeDefine('DBG_ZEND_PRESENT', 1);
break;
}
}
$this->safeDefine('DBG_ZEND_PRESENT', 0); // set this constant value to 0 (zero) to debug debugger using Zend Studio
// set default values for debugger constants
$dbg_constMap = Array(
'DBG_USE_HIGHLIGHT' => 1, // highlight output same as php code using "highlight_string" function
'DBG_WINDOW_WIDTH' => 700, // set width of debugger window (in pixels) for better viewing large amount of debug data
'DBG_USE_SHUTDOWN_FUNC' => DBG_ZEND_PRESENT ? 0 : 1, // use shutdown function to include debugger code into output
'DBG_HANDLE_ERRORS' => DBG_ZEND_PRESENT ? 0 : 1, // handle all allowed by php (see php manual) errors instead of default handler
'DBG_IGNORE_STRICT_ERRORS' => 1, // ignore PHP5 errors about private/public view modified missing in class declarations
'DBG_DOMVIEWER' => '/temp/domviewer.html', // path to DOMViewer on website
'DOC_ROOT' => str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT']) ), // windows hack
'DBG_LOCAL_BASE_PATH' => 'w:', // replace DOC_ROOT in filenames (in errors) using this path
);
// only for IE, in case if no windows php script editor defined
if (!defined('DBG_EDITOR')) {
// $dbg_constMap['DBG_EDITOR'] = 'c:\Program Files\UltraEdit\uedit32.exe %F/%L';
$dbg_constMap['DBG_EDITOR'] = 'c:\Program Files\Zend\ZendStudio-5.2.0\bin\ZDE.exe %F';
}
if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] && constOn('DBG_SKIP_AJAX')) {
$this->safeDefine('DBG_SKIP_REPORTING', 1);
}
// user defined options override debugger defaults
$dbg_constMap = $this->array_merge_recursive2($dbg_constMap, $dbg_options);
// when validation configs, don't show sqls for better validation error displaying
if (array_key_exists('DBG_VALIDATE_CONFIGS', $dbg_constMap) && $dbg_constMap['DBG_VALIDATE_CONFIGS']) {
$dbg_constMap['DBG_SQL_PROFILE'] = 0;
}
foreach ($dbg_constMap as $dbg_constName => $dbg_constValue) {
$this->safeDefine($dbg_constName, $dbg_constValue);
}
}
function constOn($const_name)
{
return defined($const_name) && constant($const_name);
}
function safeDefine($const_name, $const_value) {
if (!defined($const_name)) {
define($const_name, $const_value);
}
}
function array_merge_recursive2($paArray1, $paArray2)
{
if (!is_array($paArray1) or !is_array($paArray2)) {
return $paArray2;
}
foreach ($paArray2 AS $sKey2 => $sValue2) {
$paArray1[$sKey2] = isset($paArray1[$sKey2]) ? array_merge_recursive2($paArray1[$sKey2], $sValue2) : $sValue2;
}
return $paArray1;
}
function netMatch($network, $ip) {
$network = trim($network);
$ip = trim($ip);
if ($network == $ip) {
// comparing 2 ip addresses directly
return true;
}
$d = strpos($network, '-');
if ($d === false) {
// sigle subnet specified
$ip_arr = explode('/', $network);
if (!preg_match("@\d*\.\d*\.\d*\.\d*@", $ip_arr[0], $matches)) {
$ip_arr[0] .= '.0'; // Alternate form 194.1.4/24
}
$network_long = ip2long($ip_arr[0]);
$x = ip2long($ip_arr[1]);
$mask = long2ip($x) == $ip_arr[1] ? $x : (0xffffffff << (32 - $ip_arr[1]));
$ip_long = ip2long($ip);
return ($ip_long & $mask) == ($network_long & $mask);
}
else {
// ip address range specified
$from = ip2long(trim(substr($network, 0, $d)));
$to = ip2long(trim(substr($network, $d + 1)));
$ip = ip2long($ip);
return ($ip >= $from && $ip <= $to);
}
}
function InitReport()
{
if (!class_exists('kApplication')) return false;
$application =& kApplication::Instance();
// string used to separate debugger records while in file (used in debugger dump filename too)
$this->rowSeparator = '@'.(is_object($application->Factory) ? $application->GetSID() : 0).'@';
// include debugger files from this url
$reg_exp = '/^'.preg_quote(FULL_PATH, '/').'/';
$kernel_path = preg_replace($reg_exp, '', KERNEL_PATH, 1);
$this->baseURL = PROTOCOL.SERVER_NAME.rtrim(BASE_PATH, '/').$kernel_path.'/utility/debugger';
// save debug output in this folder
$this->tempFolder = defined('WRITEABLE') ? WRITEABLE.'/cache' : FULL_PATH.'/kernel/cache';
}
function mapLongError($msg)
{
$key = $this->generateID();
$this->longErrors[$key] = $msg;
return $key;
}
/**
* Appends all passed variable values (wihout variable names) to debug output
*
*/
function dumpVars()
{
$dump_mode = 'var_dump';
$dumpVars = func_get_args();
if ($dumpVars[count($dumpVars) - 1] === 'STRICT') {
$dump_mode = 'strict_var_dump';
array_pop($dumpVars);
}
foreach ($dumpVars as $varValue) {
$this->Data[] = Array('value' => $varValue, 'debug_type' => $dump_mode);
}
}
function prepareHTML($dataIndex)
{
$Data =& $this->Data[$dataIndex];
if ($Data['debug_type'] == 'html') {
return $Data['html'];
}
switch ($Data['debug_type']) {
case 'error':
$fileLink = $this->getFileLink($Data['file'], $Data['line']);
$ret = '<b class="debug_error">'.$this->getErrorNameByCode($Data['no']).'</b>: '.$Data['str'];
$ret .= ' in <b>'.$fileLink.'</b> on line <b>'.$Data['line'].'</b>';
return $ret;
break;
case 'var_dump':
return $this->highlightString( $this->print_r($Data['value'], true) );
break;
case 'strict_var_dump':
return $this->highlightString( var_export($Data['value'], true) );
break;
case 'trace':
ini_set('memory_limit', '500M');
$trace =& $Data['trace'];
$i = 0; $traceCount = count($trace);
$ret = '';
while ($i < $traceCount) {
$traceRec =& $trace[$i];
$argsID = 'trace_args_'.$dataIndex.'_'.$i;
$has_args = isset($traceRec['args']);
if (isset($traceRec['file'])) {
$func_name = isset($traceRec['class']) ? $traceRec['class'].$traceRec['type'].$traceRec['function'] : $traceRec['function'];
$args_link = $has_args ? '<a href="javascript:$Debugger.ToggleTraceArgs(\''.$argsID.'\');" title="Show/Hide Function Arguments"><b>Function</b></a>' : '<b>Function</b>';
$ret .= $args_link.': '.$this->getFileLink($traceRec['file'], $traceRec['line'], $func_name);
$ret .= ' in <b>'.basename($traceRec['file']).'</b> on line <b>'.$traceRec['line'].'</b><br>';
}
else {
$ret .= 'no file information available';
}
if ($has_args) {
// if parameter value is longer then 200 symbols, then leave only first 50
$args = $this->highlightString($this->print_r($traceRec['args'], true));
$ret .= '<div id="'.$argsID.'" style="display: none;">'.$args.'</div>';
}
$i++;
}
return $ret;
break;
case 'profiler':
$profileKey = $Data['profile_key'];
$Data =& $this->ProfilerData[$profileKey];
$runtime = ($Data['ends'] - $Data['begins']); // in seconds
$totals_key = getArrayValue($Data, 'totalsKey');
if ($totals_key) {
$total_before = $Data['totalsBefore'];
$total = $this->ProfilerTotals[$totals_key];
$div_width = Array();
$total_width = ($this->getWindowWidth() - 10);
$div_width['before'] = round(($total_before / $total) * $total_width);
$div_width['current'] = round(($runtime / $total) * $total_width);
$div_width['left'] = round((($total - $total_before - $runtime) / $total) * $total_width);
$ret = '<b>Name</b>: '.$Data['description'].'<br />';
$additional = isset($Data['additional']) ? $Data['additional'] : Array ();
if (isset($Data['file'])) {
array_unshift($additional, Array('name' => 'File', 'value' => $this->getFileLink($Data['file'], $Data['line'], basename($Data['file']).':'.$Data['line'])));
}
array_unshift($additional, Array('name' => 'Runtime', 'value' => $runtime.'s'));
foreach ($additional as $mixed_param) {
$ret .= '[<strong>'.$mixed_param['name'].'</strong>: '.$mixed_param['value'].'] ';
}
/*if (isset($Data['file'])) {
$ret .= '[<b>Runtime</b>: '.$runtime.'s] [<b>File</b>: '.$this->getFileLink($Data['file'], $Data['line'], basename($Data['file']).':'.$Data['line']).']<br />';
}
else {
$ret .= '<b>Runtime</b>: '.$runtime.'s<br />';
}*/
$ret .= '<div class="dbg_profiler" style="width: '.$div_width['before'].'px; border-right: 0px; background-color: #298DDF;"><img src="'.$this->dummyImage.'" width="1" height="1"/></div>';
$ret .= '<div class="dbg_profiler" style="width: '.$div_width['current'].'px; border-left: 0px; border-right: 0px; background-color: #EF4A4A;"><img src="'.$this->dummyImage.'" width="1" height="1"/></div>';
$ret .= '<div class="dbg_profiler" style="width: '.$div_width['left'].'px; border-left: 0px; background-color: #DFDFDF;"><img src="'.$this->dummyImage.'" width="1" height="1"/></div>';
return $ret;
}
else {
return '<b>Name</b>: '.$Data['description'].'<br><b>Runtime</b>: '.$runtime.'s';
}
break;
default:
return 'incorrect debug data';
break;
}
}
function getWindowWidth()
{
return DBG_WINDOW_WIDTH - $this->scrollbarWidth - 8;
}
/**
* Tells debugger to skip objects that are heavy in plan of memory usage while printing debug_backtrace results
*
* @param Object $object
* @return bool
*/
function IsBigObject(&$object)
{
$skip_classes = Array(
defined('APPLICATION_CLASS') ? APPLICATION_CLASS : 'kApplication',
'kFactory',
'kUnitConfigReader',
'TemplateParser',
);
foreach ($skip_classes as $class_name) {
if (strtolower(get_class($object)) == strtolower($class_name)) {
return true;
}
}
return false;
}
/**
* Advanced version of print_r (for debugger only). Don't print objects recursively
*
* @param Array $array
* @param bool $return_output return output or print it out
* @param int $tab_count offset in tabs
* @return string
*/
function print_r(&$array, $return_output = false, $tab_count = -1)
{
static $first_line = true;
// not an array at all
if (!is_array($array)) {
switch (gettype($array)) {
case 'NULL':
return 'NULL'."\n";
break;
case 'object':
return $this->processObject($array, $tab_count);
break;
default:
// number or string
- if (strlen($array) > 200) {
- $array = substr($array, 0, 50).' ...';
+ if (mb_strlen($array) > 200) {
+ $array = mb_substr($array, 0, 50).' ...';
}
return $array."\n";
break;
}
}
$output = '';
$tab_count++;
$output .= "Array\n".str_repeat(' ', $tab_count)."(\n";
$tab_count++;
$tabsign = $tab_count ? str_repeat(' ', $tab_count) : '';
$array_keys = array_keys($array);
foreach ($array_keys as $key) {
switch (gettype($array[$key])) {
case 'array':
$output .= $tabsign.'['.$key.'] = '.$this->print_r($array[$key], true, $tab_count);
break;
case 'boolean':
$output .= $tabsign.'['.$key.'] = '.($array[$key] ? 'true' : 'false')."\n";
break;
case 'integer':
case 'double':
case 'string':
- if (strlen($array[$key]) > 200) {
- $array[$key] = substr($array[$key], 0, 50).' ...';
+ if (mb_strlen($array[$key]) > 200) {
+ $array[$key] = mb_substr($array[$key], 0, 50).' ...';
}
$output .= $tabsign.'['.$key.'] = '.$array[$key]."\n";
break;
case 'NULL':
$output .= $tabsign.'['.$key."] = NULL\n";
break;
case 'object':
$output .= $tabsign.'['.$key."] = ";
$output .= "Object (".get_class($array[$key]).") = \n".str_repeat(' ', $tab_count + 1)."(\n";
$output .= $this->processObject($array[$key], $tab_count + 2);
$output .= str_repeat(' ', $tab_count + 1).")\n";
break;
default:
$output .= $tabsign.'['.$key.'] unknown = '.gettype($array[$key])."\n";
break;
}
}
$tab_count--;
$output .= str_repeat(' ', $tab_count).")\n";
if ($first_line) {
$first_line = false;
$output .= "\n";
}
$tab_count--;
if ($return_output) {
return $output;
}
else {
echo $output;
}
return true;
}
function processObject(&$object, $tab_count)
{
$object_class = get_class($object);
if (!in_array($object_class, $this->RecursionStack)) {
if ($this->IsBigObject($object)) {
return 'SKIPPED (class: '.$object_class.")\n";
}
$attribute_names = get_class_vars($object_class);
if (!$attribute_names) {
return "NO_ATTRIBUTES\n";
}
else {
$output = '';
array_push($this->RecursionStack, $object_class);
$tabsign = $tab_count ? str_repeat(' ', $tab_count) : '';
foreach ($attribute_names as $attribute_name => $attribute_value) {
if (is_object($object->$attribute_name)) {
// it is object
$output .= $tabsign.'['.$attribute_name.'] = '.$this->processObject($object->$attribute_name, $tab_count + 1);
}
else {
$output .= $tabsign.'['.$attribute_name.'] = '.$this->print_r($object->$attribute_name, true, $tab_count);
}
}
array_pop($this->RecursionStack);
return $output;
}
}
else {
// object [in recursion stack]
return '*** RECURSION *** (class: '.$object_class.")\n";
}
}
/**
* Format SQL Query using predefined formatting
* and highlighting techniques
*
* @param string $sql
* @return string
*/
function formatSQL($sql)
{
$sql = preg_replace('/(\n|\t| )+/is', ' ', $sql);
$sql = preg_replace('/(CREATE TABLE|DROP TABLE|SELECT|UPDATE|SET|REPLACE|INSERT|DELETE|VALUES|FROM|LEFT JOIN|INNER JOIN|LIMIT|WHERE|HAVING|GROUP BY|ORDER BY) /is', "\n\t$1 ", $sql);
return $this->highlightString($sql);
}
function highlightString($string)
{
if (!$this->constOn('DBG_USE_HIGHLIGHT')) {
return $string;
}
$string = str_replace( Array('\\', '/') , Array('_no_match_string_', '_n_m_s_'), $string);
$string = highlight_string('<?php'.$string.'?>', true);
$string = str_replace( Array('_no_match_string_', '_n_m_s_'), Array('\\', '/'), $string);
return preg_replace('/&lt;\?(.*)php(.*)\?&gt;/Us', '\\2', $string);
}
/**
* Determine by php type of browser used to show debugger
*
* @return bool
*/
function isGecko()
{
// we need isset because we may run scripts from shell with no user_agent at all
- return isset($_SERVER['HTTP_USER_AGENT']) && strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'firefox') !== false;
+ return isset($_SERVER['HTTP_USER_AGENT']) && mb_strpos(mb_strtolower($_SERVER['HTTP_USER_AGENT']), 'firefox') !== false;
}
/**
* Returns link for editing php file (from error) in external editor
*
* @param string $file filename with path from root folder
* @param int $lineno line number in file where error is found
* @param string $title text to show on file edit link
* @return string
*/
function getFileLink($file, $lineno = 1, $title = '')
{
if (!$title) {
$title = str_replace('/', '\\', $this->getLocalFile($file));
}
if ($this->isGecko()) {
return '<a href="file://'.$this->getLocalFile($file).'">'.$title.'</a>';
}
else {
return '<a href="javascript:$Debugger.editFile(\''.$this->getLocalFile($file).'\', '.$lineno.');" title="'.$file.'">'.$title.'</a>';
}
}
/**
* Converts filepath on server to filepath in mapped DocumentRoot on developer pc
*
* @param string $remoteFile
* @return string
*/
function getLocalFile($remoteFile)
{
return preg_replace('/^'.preg_quote(DOC_ROOT, '/').'/', DBG_LOCAL_BASE_PATH, $remoteFile, 1);
}
/**
* Appends call trace till this method call
*
*/
function appendTrace()
{
$trace = debug_backtrace();
array_shift($trace);
$this->Data[] = Array('trace' => $trace, 'debug_type' => 'trace');
}
function appendMemoryUsage($msg, $used = null)
{
if (!isset($used)) {
$used = round(memory_get_usage() / 1024);
}
$this->appendHTML('<b>Memory usage</b> '.$msg.' '.$used.'Kb');
}
/**
* Appends HTML code whithout transformations
*
* @param string $html
*/
function appendHTML($html)
{
$this->Data[] = Array('html' => $html, 'debug_type' => 'html');
}
/**
* Change debugger info that was already generated before.
* Returns true if html was set.
*
* @param int $index
* @param string $html
* @param string $type = {'append','prepend','replace'}
* @return bool
*/
function setHTMLByIndex($index, $html, $type = 'append')
{
if (!isset($this->Data[$index]) || $this->Data[$index]['debug_type'] != 'html') {
return false;
}
switch ($type) {
case 'append':
$this->Data[$index]['html'] .= '<br>'.$html;
break;
case 'prepend':
$this->Data[$index]['html'] = $this->Data[$index]['html'].'<br>'.$html;
break;
case 'replace':
$this->Data[$index]['html'] = $html;
break;
}
return true;
}
/**
* Move $debugLineCount lines of input from debug output
* end to beginning.
*
* @param int $debugLineCount
*/
function moveToBegin($debugLineCount)
{
$lines = array_splice($this->Data,count($this->Data)-$debugLineCount,$debugLineCount);
$this->Data = array_merge($lines,$this->Data);
}
function moveAfterRow($new_row, $debugLineCount)
{
$lines = array_splice($this->Data,count($this->Data)-$debugLineCount,$debugLineCount);
$rows_before = array_splice($this->Data,0,$new_row,$lines);
$this->Data = array_merge($rows_before,$this->Data);
}
function appendRequest()
{
if (isset($_SERVER['SCRIPT_FILENAME'])) {
$script = $_SERVER['SCRIPT_FILENAME'];
}
else {
$script = $_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF'];
}
$this->appendHTML('ScriptName: <b>'.$this->getFileLink($script, 1, basename($script)).'</b> (<b>'.dirname($script).'</b>)');
if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] == 'yes') {
- $this->appendHTML('RequestURI: '.$_SERVER['REQUEST_URI'].' (QS Length:'.strlen($_SERVER['QUERY_STRING']).')');
+ $this->appendHTML('RequestURI: '.$_SERVER['REQUEST_URI'].' (QS Length:'.mb_strlen($_SERVER['QUERY_STRING']).')');
}
$this->appendHTML('<a href="http://www.brainjar.com/dhtml/domviewer/" target="_blank">DomViewer</a>: <input id="dbg_domviewer" type="text" value="window" style="border: 1px solid #000000;"/>&nbsp;<button class="button" onclick="return $Debugger.OpenDOMViewer();">Show</button>');
ob_start();
?>
<table border="0" cellspacing="0" cellpadding="0" class="dbg_flat_table" style="width: <?php echo $this->getWindowWidth(); ?>px;">
<thead style="font-weight: bold;">
<td width="20">Src</td><td>Name</td><td>Value</td>
</thead>
<?php
foreach ($_REQUEST as $key => $value) {
if(!is_array($value) && trim($value) == '') {
$value = '<b class="debug_error">no value</b>';
}
else {
$value = htmlspecialchars($this->print_r($value, true));
}
$in_cookie = isset($_COOKIE[$key]);
$src = isset($_GET[$key]) && !$in_cookie ? 'GE' : (isset($_POST[$key]) && !$in_cookie ? 'PO' : ($in_cookie ? 'CO' : '?') );
echo '<tr><td>'.$src.'</td><td>'.$key.'</td><td>'.$value.'</td></tr>';
}
?>
</table>
<?php
$this->appendHTML(ob_get_contents());
ob_end_clean();
}
/**
* Appends php session content to debugger output
*
*/
function appendSession()
{
if (isset($_SESSION) && $_SESSION) {
$this->appendHTML('PHP Session: [<b>'.ini_get('session.name').'</b>]');
$this->dumpVars($_SESSION);
$this->moveToBegin(2);
}
}
function profileStart($key, $description = null, $timeStamp = null)
{
if (!isset($timeStamp)) {
$timeStamp = $this->getMoment();
}
$this->ProfilerData[$key] = Array('begins' => $timeStamp, 'ends' => 5000, 'debuggerRowID' => count($this->Data));
if (isset($description)) {
$this->ProfilerData[$key]['description'] = $description;
}
if (substr($key, 0, 4) == 'sql_') {
// append place from what was called
$trace_results = debug_backtrace();
$trace_count = count($trace_results);
$i = 0;
while ($i < $trace_count) {
$trace_file = basename($trace_results[$i]['file']);
if ($trace_file != 'db_connection.php' && $trace_file != 'adodb.inc.php') {
break;
}
$i++;
}
$this->ProfilerData[$key]['file'] = $trace_results[$i]['file'];
$this->ProfilerData[$key]['line'] = $trace_results[$i]['line'];
unset($trace_results);
}
$this->Data[] = Array('profile_key' => $key, 'debug_type' => 'profiler');
}
function profileFinish($key, $description = null, $timeStamp = null)
{
if (!isset($timeStamp)) {
$timeStamp = $this->getMoment();
}
$this->ProfilerData[$key]['ends'] = $timeStamp;
if (isset($description)) {
$this->ProfilerData[$key]['description'] = $description;
}
if (substr($key, 0, 4) == 'sql_') {
$func_arguments = func_get_args();
$rows_affected = $func_arguments[3];
if ($rows_affected > 0) {
$additional = Array (
Array ('name' => 'Affected Rows', 'value' => $rows_affected),
);
if (isset($func_arguments[4])) {
$additional[] = Array ('name' => 'Result', 'value' => $func_arguments[4]);
}
$this->ProfilerData[$key]['additional'] =& $additional;
}
}
}
function profilerAddTotal($total_key, $key = null, $value = null)
{
if (!isset($this->ProfilerTotals[$total_key])) {
$this->ProfilerTotals[$total_key] = 0;
$this->ProfilerTotalCount[$total_key] = 0;
}
if (!isset($value)) {
$value = $this->ProfilerData[$key]['ends'] - $this->ProfilerData[$key]['begins'];
}
if (isset($key)) {
$this->ProfilerData[$key]['totalsKey'] = $total_key;
$this->ProfilerData[$key]['totalsBefore'] = $this->ProfilerTotals[$total_key];
}
$this->ProfilerTotals[$total_key] += $value;
$this->ProfilerTotalCount[$total_key]++;
}
function getMoment()
{
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
function generateID()
{
list($usec, $sec) = explode(' ', microtime());
$id_part_1 = substr($usec, 4, 4);
$id_part_2 = mt_rand(1,9);
$id_part_3 = substr($sec, 6, 4);
$digit_one = substr($id_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$id_part_1 = ereg_replace("^0",'',$id_part_1);
$id_part_1=$digit_one.$id_part_1;
}
return $id_part_1.$id_part_2.$id_part_3;
}
function getErrorNameByCode($error_code)
{
$error_map = Array(
'Fatal Error' => Array(E_USER_ERROR),
'Warning' => Array(E_WARNING, E_USER_WARNING),
'Notice' => Array(E_NOTICE, E_USER_NOTICE),
);
if (defined('E_STRICT')) {
$error_map['PHP5 Strict'] = Array(E_STRICT);
}
if (defined('E_RECOVERABLE_ERROR')) {
$error_map['Fatal Error (recoverable)'] = Array(E_RECOVERABLE_ERROR);
}
foreach ($error_map as $error_name => $error_codes) {
if (in_array($error_code, $error_codes)) {
return $error_name;
}
}
return '';
}
/**
* Returns profile total key (check against unexisting key too)
*
* @param string $key
* @return int
*/
function getProfilerTotal($key)
{
if (isset($this->ProfilerTotalCount[$key])) {
return (int)$this->ProfilerTotalCount[$key];
}
return 0;
}
function ProfilePoint($title, $level=1)
{
$trace_results = debug_backtrace();
$level = min($level,count($trace_results)-1);
do {
$point = $trace_results[$level];
$location = $point['file'].':'.$point['line'];
$level++;
$has_more = isset($trace_results[$level]);
} while ($has_more && $point['function'] == $trace_results[$level]['function'] );
if ($location == ':') {
echo '';
}
if (!isset($this->ProfilePoints[$title])) {
$this->ProfilePoints[$title] = array();
}
if (!isset($this->ProfilePoints[$title][$location])) {
$this->ProfilePoints[$title][$location] = 0;
}
$this->ProfilePoints[$title][$location]++;
}
/**
* Generates report
*
*/
function printReport($returnResult = false, $clean_output_buffer = true)
{
if ($this->reportDone) {
// don't print same report twice (in case if shutdown function used + compression + fatal error)
return '';
}
$this->profileFinish('script_runtime');
$this->breakOutofBuffering();
$debugger_start = memory_get_usage();
if (defined('SPACER_URL')) {
$this->dummyImage = SPACER_URL;
}
$this->InitReport(); // set parameters required by AJAX
// defined here, because user can define this contant while script is running, not event before debugger is started
$this->safeDefine('DBG_RAISE_ON_WARNINGS', 0);
$this->safeDefine('DBG_TOOLBAR_BUTTONS', 1);
$this->appendSession(); // show php session if any
// ensure, that 1st line of debug output always is this one:
$top_line = '<table cellspacing="0" cellpadding="0" style="width: '.$this->getWindowWidth().'px; margin: 0px;"><tr><td align="left" width="50%">[<a href="javascript:window.location.reload();">Reload Frame</a>] [<a href="javascript:$Debugger.Toggle(27);">Hide Debugger</a>]</td><td align="right" width="50%">[Current Time: <b>'.date('H:i:s').'</b>] [File Size: <b>#DBG_FILESIZE#</b>]</td></tr></table>';
$this->appendHTML($top_line);
$this->moveToBegin(1);
if (count($this->ProfilePoints)>0) {
foreach($this->ProfilePoints as $point => $locations) {
arsort($this->ProfilePoints[$point]);
}
$this->appendHTML($this->highlightString($this->print_r($this->ProfilePoints, true)));
/*foreach ($this->ProfilePoints as $point => $locations) {
foreach ($locations as $location => $occurences) {
}
}*/
}
if ($this->constOn('DBG_SQL_PROFILE') && isset($this->ProfilerTotals['sql'])) {
// sql query profiling was enabled -> show totals
$this->appendHTML('<b>SQL Total time:</b> '.$this->ProfilerTotals['sql'].' <b>Number of queries</b>: '.$this->ProfilerTotalCount['sql']);
}
if ($this->constOn('DBG_PROFILE_INCLUDES') && isset($this->ProfilerTotals['includes'])) {
// included file profiling was enabled -> show totals
$this->appendHTML('<b>Included Files Total time:</b> '.$this->ProfilerTotals['includes'].' Number of includes: '.$this->ProfilerTotalCount['includes']);
}
if ($this->constOn('DBG_PROFILE_MEMORY')) {
// detailed memory usage reporting by objects was enabled -> show totals
$this->appendHTML('<b>Memory used by Objects:</b> '.round($this->ProfilerTotals['objects'] / 1024, 2).'Kb');
}
if ($this->constOn('DBG_INCLUDED_FILES')) {
$files = get_included_files();
$this->appendHTML('<b>Included files:</b>');
foreach ($files as $file) {
$this->appendHTML($this->getFileLink($this->getLocalFile($file)).' ('.round(filesize($file) / 1024, 2).'Kb)');
}
}
/*if ($this->constOn('DBG_PROFILE_INCLUDES')) {
$this->appendHTML('<b>Included files statistics:</b>'.( $this->constOn('DBG_SORT_INCLUDES_MEM') ? ' (sorted by memory usage)':''));
$totals = Array( 'mem' => 0, 'time' => 0);
$totals_configs = Array( 'mem' => 0, 'time' => 0);
if (is_array($this->IncludesData['mem'])) {
if ( $this->constOn('DBG_SORT_INCLUDES_MEM') ) {
array_multisort($this->IncludesData['mem'], SORT_DESC, $this->IncludesData['file'], $this->IncludesData['time'], $this->IncludesData['level']);
}
foreach ($this->IncludesData['file'] as $key => $file_name) {
$this->appendHTML( str_repeat('&nbsp;->&nbsp;', ($this->IncludesData['level'][$key] >= 0 ? $this->IncludesData['level'][$key] : 0)).$file_name.' Mem: '.sprintf("%.4f Kb", $this->IncludesData['mem'][$key]/1024).' Time: '.sprintf("%.4f", $this->IncludesData['time'][$key]));
if ($this->IncludesData['level'][$key] == 0) {
$totals['mem'] += $this->IncludesData['mem'][$key];
$totals['time'] += $this->IncludesData['time'][$key];
}
else if ($this->IncludesData['level'][$key] == -1) {
$totals_configs['mem'] += $this->IncludesData['mem'][$key];
$totals_configs['time'] += $this->IncludesData['time'][$key];
}
}
$this->appendHTML('<b>Sub-Total classes:</b> '.' Mem: '.sprintf("%.4f Kb", $totals['mem']/1024).' Time: '.sprintf("%.4f", $totals['time']));
$this->appendHTML('<b>Sub-Total configs:</b> '.' Mem: '.sprintf("%.4f Kb", $totals_configs['mem']/1024).' Time: '.sprintf("%.4f", $totals_configs['time']));
$this->appendHTML('<span class="error"><b>Grand Total:</b></span> '.' Mem: '.sprintf("%.4f Kb", ($totals['mem']+$totals_configs['mem'])/1024).' Time: '.sprintf("%.4f", $totals['time']+$totals_configs['time']));
}
}*/
$is_ajax = isset($_GET['ajax']) && $_GET['ajax'] == 'yes';
$skip_reporting = $this->constOn('DBG_SKIP_REPORTING') || $this->constOn('DBG_ZEND_PRESENT');
if (($is_ajax && !constOn('DBG_SKIP_AJAX')) || !$skip_reporting) {
$debug_file = $this->tempFolder.'/debug_'.$this->rowSeparator.'.txt';
if (file_exists($debug_file)) unlink($debug_file);
$i = 0;
$fp = fopen($debug_file, 'a');
$lineCount = count($this->Data);
while ($i < $lineCount) {
fwrite($fp, $this->prepareHTML($i).$this->rowSeparator);
$i++;
}
fclose($fp);
}
if ($skip_reporting) {
// let debugger write report and then don't output anything
$this->reportDone = true;
return '';
}
$dbg_path = str_replace(FULL_PATH, '', $this->tempFolder);
ob_start();
// the <script .. /script> and hidden div helps browser to break out of script tag or attribute esacped
// with " or ' in case fatal error (or user-error) occurs inside it in compiled template,
// otherwise it has no effect
?>
<div style="display: none" x='nothing'><script></script></div><html><body></body></html>
<script type="text/javascript" src="<?php echo $this->baseURL; ?>/debugger.js"></script>
<link rel="stylesheet" rev="stylesheet" href="<?php echo $this->baseURL; ?>/debugger.css" type="text/css" media="screen" />
<div id="debug_layer" class="debug_layer_container" style="display: none; width: <?php echo DBG_WINDOW_WIDTH; ?>px;">
<div class="debug_layer" style="width: <?php echo $this->getWindowWidth(); ?>px;">
<table width="100%" cellpadding="0" cellspacing="1" border="0" class="debug_layer_table" style="width: <?php echo $this->getWindowWidth(); ?>px;" align="left">
<tbody id="debug_table"></tbody>
</table>
</div>
</div>
<script type="text/javascript">
var $Debugger = new Debugger(<?php echo "'".$this->rowSeparator."', ".$this->getProfilerTotal('error_handling').', '.($this->IsFatalError ? 'true' : 'false').', '.$this->getProfilerTotal('sql'); ?>);
$Debugger.DOMViewerURL = '<?php echo constant('DBG_DOMVIEWER'); ?>';
$Debugger.EditorPath = '<?php echo defined('DBG_EDITOR') ? addslashes(DBG_EDITOR) : '' ?>';
$Debugger.DebugURL = '<?php echo $this->baseURL.'/debugger_responce.php?sid='.$this->rowSeparator.'&path='.urlencode($dbg_path); ?>';
<?php
if ($this->IsFatalError || DBG_RAISE_ON_WARNINGS) {
echo '$Debugger.Toggle();';
}
if (DBG_TOOLBAR_BUTTONS) {
echo '$Debugger.AddToolbar("$Debugger");';
}
?>
window.focus();
</script>
<?php
if (!isset($this->ProfilerTotals['error_handling'])) {
$memory_used = $debugger_start;
$this->ProfilerTotalCount['error_handling'] = 0;
}
else {
$memory_used = $debugger_start - $this->ProfilerTotals['error_handling'];
}
if ($returnResult) {
$ret = ob_get_contents();
if ($clean_output_buffer) {
ob_end_clean();
}
$ret .= $this->getShortReport($memory_used);
$this->reportDone = true;
return $ret;
}
else {
if (!$this->constOn('DBG_HIDE_FULL_REPORT')) {
$this->breakOutofBuffering();
}
elseif ($clean_output_buffer) {
ob_clean();
}
echo $this->getShortReport($memory_used);
$this->reportDone = true;
}
}
/**
* Format's memory usage report by debugger
*
* @return string
* @access private
*/
function getShortReport($memory_used)
{
if ($this->constOn('DBG_TOOLBAR_BUTTONS')) {
// we have sql & error count in toolbar, don't duplicate here
$info = Array(
'Script Runtime' => 'PROFILE:script_runtime',
'SQL\'s Runtime' => 'PROFILE_T:sql',
);
}
else {
// toolbar not visible, then show sql & error count too
$info = Array (
'Script Runtime' => 'PROFILE:script_runtime',
'SQL\'s Runtime' => 'PROFILE_T:sql',
'-' => 'SEP:-',
'Notice / Warning' => 'PROFILE_TC:error_handling',
'SQLs Count' => 'PROFILE_TC:sql',
);
}
$ret = '<tr><td>Application:</td><td><b>'.$this->formatSize($memory_used).'</b> ('.$memory_used.')</td></tr>';
foreach ($info as $title => $value_key) {
list ($record_type, $record_data) = explode(':', $value_key, 2);
switch ($record_type) {
case 'PROFILE': // profiler totals value
$Data =& $this->ProfilerData[$record_data];
$profile_time = ($Data['ends'] - $Data['begins']); // in seconds
$ret .= '<tr><td>'.$title.':</td><td><b>'.sprintf('%.5f', $profile_time).' s</b></td></tr>';
break;
case 'PROFILE_TC': // profile totals record count
$record_cell = '<td>';
if ($record_data == 'error_handling' && $this->ProfilerTotalCount[$record_data] > 0) {
$record_cell = '<td class="debug_error">';
}
$ret .= '<tr>'.$record_cell.$title.':</td>'.$record_cell.'<b>'.$this->ProfilerTotalCount[$record_data].'</b></td></tr>';
break;
case 'PROFILE_T': // profile total
$record_cell = '<td>';
$ret .= '<tr>'.$record_cell.$title.':</td>'.$record_cell.'<b>'.sprintf('%.5f', $this->ProfilerTotals[$record_data]).' s</b></td></tr>';
break;
case 'SEP':
$ret .= '<tr><td colspan="2" style="height: 1px; background-color: #000000; padding: 0px;"><img src="'.$this->dummyImage.'" height="1" alt=""/></td></tr>';
break;
}
}
return '<br /><table class="dbg_stats_table"><tr><td style="border-color: #FFFFFF;"><table class="dbg_stats_table" align="left">'.$ret.'</table></td></tr></table>';
}
/**
* User-defined error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param array $errcontext
*/
function saveError($errno, $errstr, $errfile = '', $errline = '', $errcontext = '')
{
$this->ProfilerData['error_handling']['begins'] = memory_get_usage();
$errorType = $this->getErrorNameByCode($errno);
if (!$errorType) {
trigger_error('Unknown error type ['.$errno.']', E_USER_ERROR);
return false;
}
if ($this->constOn('DBG_IGNORE_STRICT_ERRORS') && defined('E_STRICT') && ($errno == E_STRICT)) return;
if (preg_match('/(.*)#([\d]+)$/', $errstr, $rets) ) {
// replace short message with long one (due triger_error limitations on message size)
$long_id = $rets[2];
$errstr = $this->longErrors[$long_id];
unset($this->longErrors[$long_id]);
}
- if (strpos($errfile,'eval()\'d code') !== false) {
+ if (mb_strpos($errfile,'eval()\'d code') !== false) {
$errstr = '[<b>EVAL</b>, line <b>'.$errline.'</b>]: '.$errstr;
$tmpStr = $errfile;
- $pos = strpos($tmpStr,'(');
- $errfile = substr($tmpStr, 0, $pos);
+ $pos = mb_strpos($tmpStr,'(');
+ $errfile = mb_substr($tmpStr, 0, $pos);
$pos++;
- $errline = substr($tmpStr,$pos,strpos($tmpStr,')',$pos)-$pos);
+ $errline = mb_substr($tmpStr,$pos,mb_strpos($tmpStr,')',$pos)-$pos);
}
$this->Data[] = Array('no' => $errno, 'str' => $errstr, 'file' => $errfile, 'line' => $errline, 'context' => $errcontext, 'debug_type' => 'error');
$this->ProfilerData['error_handling']['ends'] = memory_get_usage();
$this->profilerAddTotal('error_handling', 'error_handling');
if (substr($errorType, 0, 5) == 'Fatal') {
$this->IsFatalError = true;
// append debugger report to data in buffer & clean buffer afterwards
die( $this->breakOutofBuffering(false) . $this->printReport(true) );
}
}
function breakOutofBuffering($flush = true)
{
$buffer_content = Array();
while (ob_get_level()) {
$buffer_content[] = ob_get_clean();
}
$ret = implode('', array_reverse($buffer_content));
if ($flush) {
echo $ret;
flush();
}
return $ret;
}
function saveToFile($msg)
{
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/vb_debug.txt', 'a');
fwrite($fp, $msg."\n");
fclose($fp);
}
/**
* Formats file/memory size in nice way
*
* @param int $bytes
* @return string
* @access public
*/
function formatSize($bytes)
{
if ($bytes >= 1099511627776) {
$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "TB";
} elseif ($bytes >= 1073741824) {
$return = round($bytes / 1024 / 1024 / 1024, 2);
$suffix = "GB";
} elseif ($bytes >= 1048576) {
$return = round($bytes / 1024 / 1024, 2);
$suffix = "MB";
} elseif ($bytes >= 1024) {
$return = round($bytes / 1024, 2);
$suffix = "KB";
} else {
$return = $bytes;
$suffix = "Byte";
}
$return .= ' '.$suffix;
return $return;
}
function printConstants($constants)
{
if (!is_array($constants)) {
$constants = explode(',', $constants);
}
$contant_tpl = '<tr><td>%s</td><td><b>%s</b></td></tr>';
$ret = '<table class="dbg_flat_table" style="width: '.$this->getWindowWidth().'px;">';
foreach ($constants as $constant_name) {
$ret .= sprintf($contant_tpl, $constant_name, constant($constant_name));
}
$ret .= '</table>';
$this->appendHTML($ret);
}
function AttachToApplication() {
if (!$this->constOn('DBG_HANDLE_ERRORS')) return true;
if (class_exists('kApplication')) {
restore_error_handler();
$application =& kApplication::Instance();
$application->Debugger =& $this;
$application->errorHandlers[] = Array(&$this, 'saveError');
}
else {
set_error_handler(Array(&$this, 'saveError'));
}
}
}
if (!function_exists('memory_get_usage')) {
function memory_get_usage(){ return -1; }
}
if (!Debugger::constOn('DBG_ZEND_PRESENT')) {
$debugger = new Debugger();
}
if (Debugger::constOn('DBG_USE_SHUTDOWN_FUNC')) {
register_shutdown_function( Array(&$debugger, 'printReport') );
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/utility/debugger.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.76.2.2
\ No newline at end of property
+1.76.2.3
\ No newline at end of property
Index: branches/RC/core/kernel/utility/unit_config_reader.php
===================================================================
--- branches/RC/core/kernel/utility/unit_config_reader.php (revision 10097)
+++ branches/RC/core/kernel/utility/unit_config_reader.php (revision 10098)
@@ -1,826 +1,826 @@
<?php
class kUnitConfigReader extends kBase {
/**
* Configs readed
*
* @var Array
* @access private
*/
var $configData = Array();
var $configFiles = Array();
var $CacheExpired = false;
var $prefixFiles = array();
var $ProcessAllConfigs = false;
var $FinalStage = false;
var $StoreCache = false;
var $AfterConfigProcessed = array();
/**
* Scan kernel and user classes
* for available configs
*
* @access protected
*/
function Init($prefix,$special)
{
parent::Init($prefix,$special);
}
function CacheParsedData()
{
$event_manager =& $this->Application->recallObject('EventManager');
$aggregator =& $this->Application->recallObject('TagsAggregator', 'kArray');
$config_vars = Array(
'SessionTimeout',
'SessionCookieName',
'SessionReferrerCheck',
'CookieSessions',
'UseCronForRegularEvent',
'User_GuestGroup',
'User_LoggedInGroup',
'SessionTimeout',
'UseModRewrite',
'UseOutputCompression',
'OutputCompressionLevel',
);
foreach ($config_vars as $var) {
$this->Application->ConfigValue($var);
}
$cache = Array(
'Factory.Files' => $this->Application->Factory->Files,
'Factory.realClasses' => $this->Application->Factory->realClasses,
'Factory.Dependencies' => $this->Application->Factory->Dependencies,
'ConfigReader.prefixFiles' => $this->prefixFiles,
'EventManager.buildEvents' => $event_manager->buildEvents,
'EventManager.beforeRegularEvents' => $event_manager->beforeRegularEvents,
'EventManager.afterRegularEvents' => $event_manager->afterRegularEvents,
'EventManager.beforeHooks' => $event_manager->beforeHooks,
'EventManager.afterHooks' => $event_manager->afterHooks,
'TagsAggregator.data' => $aggregator->_Array,
// the following caches should be reset based on admin interaction (adjusting config, enabling modules etc)
'Application.Caches.ConfigVariables' => $this->Application->Caches['ConfigVariables'],
'Application.ConfigCacheIds' => $this->Application->ConfigCacheIds,
'Application.ConfigHash' => $this->Application->ConfigHash,
'Application.ReplacementTemplates' => $this->Application->ReplacementTemplates,
'Application.ModuleInfo' => $this->Application->ModuleInfo,
);
$conn =& $this->Application->GetADODBConnection();
$conn->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("configs_parsed", '.$conn->qstr(serialize($cache)).', '.adodb_mktime().')');
$conn->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("config_files", '.$conn->qstr(serialize($this->configFiles)).', '.adodb_mktime().')');
unset($this->configFiles);
}
function RestoreParsedData()
{
$conn =& $this->Application->GetADODBConnection();
$data = $conn->GetRow('SELECT Data, Cached FROM '.TABLE_PREFIX.'Cache WHERE VarName = "configs_parsed"');
if ($data && $data['Cached'] > 0 ) {
$cache = unserialize($data['Data']);
$this->Application->Factory->Files = $cache['Factory.Files'];
$this->Application->Factory->realClasses = $cache['Factory.realClasses'];
$this->Application->Factory->Dependencies = $cache['Factory.Dependencies'];
$this->prefixFiles = $cache['ConfigReader.prefixFiles'];
$event_manager =& $this->Application->recallObject('EventManager');
$event_manager->buildEvents = $cache['EventManager.buildEvents'];
$event_manager->beforeRegularEvents = $cache['EventManager.beforeRegularEvents'];
$event_manager->afterRegularEvents = $cache['EventManager.afterRegularEvents'];
$event_manager->beforeHooks = $cache['EventManager.beforeHooks'];
$event_manager->afterHooks = $cache['EventManager.afterHooks'];
$aggregator =& $this->Application->recallObject('TagsAggregator', 'kArray');
$aggregator->_Array = $cache['TagsAggregator.data'];
$this->Application->ConfigHash = $cache['Application.ConfigHash'];
$this->Application->Caches['ConfigVariables'] = $cache['Application.ConfigCacheIds'];
$this->Application->ConfigCacheIds = $cache['Application.ConfigCacheIds'];
$this->Application->ReplacementTemplates = $cache['Application.ReplacementTemplates'];
$this->Application->ModuleInfo = $cache['Application.ModuleInfo'];
return true;
}
else return false;
}
function ResetParsedData($include_sections = false)
{
$conn =& $this->Application->GetADODBConnection();
$conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = "configs_parsed"');
if ($include_sections) {
$conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = "sections_parsed"');
}
}
function scanModules($folderPath, $cache = true)
{
if (defined('IS_INSTALL') && IS_INSTALL && !defined('FORCE_CONFIG_CACHE')) {
// disable config caching during installation
$cache = false;
}
if ($cache) {
$restored = $this->RestoreParsedData();
if ($restored) return;
}
$this->ProcessAllConfigs = true;
$this->includeConfigFiles($folderPath, $cache);
$this->ParseConfigs();
// tell AfterConfigRead to store cache if neede
// can't store it here beacuse AfterConfigRead needs ability to change config data
$this->StoreCache = $cache;
}
function findConfigFiles($folderPath)
{
// if FULL_PATH = "/" ensure, that all "/" in $folderPath are not deleted
$reg_exp = '/^'.preg_quote(FULL_PATH, '/').'/';
$folderPath = preg_replace($reg_exp, '', $folderPath, 1); // this make sense, since $folderPath may NOT contain FULL_PATH
$fh = opendir(FULL_PATH.$folderPath);
while (($sub_folder = readdir($fh))) {
$full_path = FULL_PATH.$folderPath.'/'.$sub_folder;
if ($this->isDir($full_path)) {
//the following is to exclude OLD, not removed files when upgrading to 'core'
if (preg_match('/^\/kernel\/kernel4\//', $folderPath) || ($folderPath == '/kernel/units' && file_exists(FULL_PATH.$this->getConfigName('/core/units/'.$sub_folder)))) {
continue;
}
if (file_exists(FULL_PATH.$this->getConfigName($folderPath.'/'.$sub_folder))) {
$this->configFiles[] = $this->getConfigName($folderPath.'/'.$sub_folder);
}
$this->findConfigFiles($full_path);
// if (filemtime($full_path) > $cached) { }
}
}
}
function includeConfigFiles($folderPath, $cache = true)
{
$this->Application->refreshModuleInfo();
$conn =& $this->Application->GetADODBConnection();
$data = $conn->GetRow('SELECT Data, Cached FROM '.TABLE_PREFIX.'Cache WHERE VarName = "config_files"');
if ($cache && $data) {
$this->configFiles = unserialize($data['Data']);
shuffle($this->configFiles);
$files_cached = $data['Cached'];
}
else {
$this->findConfigFiles($folderPath); // search from base directory
}
foreach ($this->configFiles as $filename)
{
$prefix = $this->PreloadConfigFile($filename);
if (!$prefix) {
trigger_error('Prefix not defined in config file '.$filename, E_USER_ERROR);
}
}
}
/**
* Process all read config files - called ONLY when there is no cache!
*
*/
function ParseConfigs()
{
// 1. process normal configs and their dependencies
$prioritized_configs = array();
foreach ($this->configData as $prefix => $config) {
if (isset($config['ConfigPriority'])) {
$prioritized_configs[$prefix] = $config['ConfigPriority'];
continue;
}
$this->parseConfig($prefix);
}
foreach ($this->configData as $prefix => $config) {
$this->ProcessDependencies($prefix);
$this->postProcessConfig($prefix, 'AggregateConfigs', 'sub_prefix');
$clones = $this->postProcessConfig($prefix, 'Clones', 'prefix');
}
// 2. process prioritized configs and their dependencies
asort($prioritized_configs);
foreach ($prioritized_configs as $prefix => $priority) {
$this->parseConfig($prefix);
}
foreach ($prioritized_configs as $prefix => $priority) {
$this->ProcessDependencies($prefix);
}
}
function AfterConfigRead($store_cache = null)
{
// if (!$this->ProcessAllConfigs) return ;
$this->FinalStage = true;
foreach ($this->configData as $prefix => $config) {
if (in_array($prefix, $this->AfterConfigProcessed)) continue;
$this->Application->HandleEvent( new kEvent($prefix.':OnAfterConfigRead') );
$this->AfterConfigProcessed[] = $prefix;
}
if (!isset($store_cache)) {
// store cache not overrided -> use global setting
$store_cache = $this->StoreCache;
}
if ($store_cache || (defined('IS_INSTALL') && IS_INSTALL)) {
// cache is not stored during install, but dynamic clones should be processed in any case
$this->processDynamicClones();
}
if ($store_cache) {
$this->CacheParsedData();
if ($this->Application->isDebugMode(false) && constOn('DBG_VALIDATE_CONFIGS')) {
// validate configs here to have changes from OnAfterConfigRead hooks to prefixes
foreach ($this->configData as $prefix => $config) {
if (!isset($config['TableName'])) continue;
$this->ValidateConfig($prefix);
}
}
}
}
/**
* Re-reads all configs
*
*/
function ReReadConfigs()
{
// clear restored cache (not in db)
$this->Application->Factory->Files = Array ();
$this->Application->Factory->realClasses = Array ();
$this->Application->Factory->Dependencies = Array ();
$this->Application->EventManager->beforeRegularEvents = Array ();
$this->Application->EventManager->afterRegularEvents = Array ();
$this->Application->EventManager->beforeHooks = Array ();
$this->Application->EventManager->afterHooks = Array ();
// otherwise ModulesHelper indirectly used from includeConfigFiles won't work
$this->Application->RegisterDefaultClasses();
// parse all configs
$this->ProcessAllConfigs = true;
$this->includeConfigFiles(MODULES_PATH, false);
$this->ParseConfigs();
$this->AfterConfigRead(false);
$this->processDynamicClones();
}
/**
* Process clones, that were defined via OnAfterConfigRead event
*
*/
function processDynamicClones()
{
$new_clones = Array();
foreach ($this->configData as $prefix => $config) {
$clones = $this->postProcessConfig($prefix, 'Clones', 'prefix');
if ($clones) {
$new_clones = array_merge($new_clones, $clones);
}
}
// call OnAfterConfigRead for cloned configs
$new_clones = array_unique($new_clones);
foreach ($new_clones as $prefix) {
if (in_array($prefix, $this->AfterConfigProcessed)) continue;
$this->Application->HandleEvent( new kEvent($prefix.':OnAfterConfigRead') );
$this->AfterConfigProcessed[] = $prefix;
}
}
/**
* Register nessasary classes
* This method should only process the data which is cached!
*
* @param string $prefix
* @access private
*/
function parseConfig($prefix)
{
$config =& $this->configData[$prefix];
$event_manager =& $this->Application->recallObject('EventManager');
$register_classes = getArrayValue($config,'RegisterClasses');
if (!$register_classes) $register_classes = Array();
$class_params=Array('ItemClass','ListClass','EventHandlerClass','TagProcessorClass');
foreach($class_params as $param_name)
{
if ( !(isset($config[$param_name]) ) ) continue;
$config[$param_name]['pseudo'] = $this->getPrefixByParamName($param_name,$prefix);
$register_classes[] = $config[$param_name];
}
foreach($register_classes as $class_info)
{
$require_classes = getArrayValue($class_info, 'require_classes');
if ($require_classes) {
if (!is_array($require_classes)) {
$require_classes = array($require_classes);
}
if (!isset($config['_Dependencies'][$class_info['class']])) {
$config['_Dependencies'][$class_info['class']] = array();
}
$config['_Dependencies'][$class_info['class']] = array_merge($config['_Dependencies'][$class_info['class']], $require_classes);
}
$this->Application->registerClass(
$class_info['class'],
$config['BasePath'].'/'.$class_info['file'],
$class_info['pseudo']/*,
getArrayValue($class_info, 'require_classes')*/
);
if (getArrayValue($class_info, 'build_event')) {
$event_manager->registerBuildEvent($class_info['pseudo'],$class_info['build_event']);
}
}
$regular_events = getArrayValue($config, 'RegularEvents');
if($regular_events)
{
foreach($regular_events as $short_name => $regular_event_info)
{
$event_manager->registerRegularEvent( $short_name, $config['Prefix'].':'.$regular_event_info['EventName'], $regular_event_info['RunInterval'], $regular_event_info['Type'] );
}
}
$hooks = getArrayValue($config, 'Hooks');
if (is_array($hooks) && count($hooks) > 0) {
foreach ($hooks as $hook) {
if (isset($config['ParentPrefix']) && $hook['HookToPrefix'] == $config['ParentPrefix']) {
trigger_error('Depricated Hook Usage [prefix: <b>'.$config['Prefix'].'</b>; do_prefix: <b>'.$hook['DoPrefix'].'</b>] use <b>#PARENT#</b> as <b>HookToPrefix</b> value, where HookToPrefix is same as ParentPrefix', E_USER_NOTICE);
}
if ($hook['HookToPrefix'] == '') {
$hook['HookToPrefix'] = $config['Prefix']; // new: set hooktoprefix to current prefix if not set
}
if (isset($config['ParentPrefix'])) {
// new: allow to set hook to parent prefix what ever it is
if ($hook['HookToPrefix'] == '#PARENT#') {
$hook['HookToPrefix'] = $config['ParentPrefix'];
}
if ($hook['DoPrefix'] == '#PARENT#') {
$hook['DoPrefix'] = $config['ParentPrefix'];
}
}
elseif ($hook['HookToPrefix'] == '#PARENT#' || $hook['DoPrefix'] == '#PARENT#') {
continue; // we need parent prefix but it's not set !
}
$do_prefix = $hook['DoPrefix'] == '' ? $config['Prefix'] : $hook['DoPrefix'];
if ( !is_array($hook['HookToEvent']) ) {
$hook_events = Array( $hook['HookToEvent'] );
}
else {
$hook_events = $hook['HookToEvent'];
}
foreach ($hook_events as $hook_event) {
$this->Application->registerHook($hook['HookToPrefix'], $hook['HookToSpecial'], $hook_event, $hook['Mode'], $do_prefix, $hook['DoSpecial'], $hook['DoEvent'], $hook['Conditional']);
}
}
}
if ( is_array(getArrayValue($config, 'AggregateTags')) ) {
foreach ($config['AggregateTags'] as $aggregate_tag) {
if (isset($config['ParentPrefix'])) {
if ($aggregate_tag['AggregateTo'] == $config['ParentPrefix']) {
trigger_error('Depricated Aggregate Tag Usage [prefix: <b>'.$config['Prefix'].'</b>; AggregateTo: <b>'.$aggregate_tag['AggregateTo'].'</b>] use <b>#PARENT#</b> as <b>AggregateTo</b> value, where AggregateTo is same as ParentPrefix', E_USER_NOTICE);
}
if ($aggregate_tag['AggregateTo'] == '#PARENT#') {
$aggregate_tag['AggregateTo'] = $config['ParentPrefix'];
}
}
$aggregate_tag['LocalPrefix'] = $config['Prefix'];
$this->Application->registerAggregateTag($aggregate_tag);
}
}
if (isset($config['ReplacementTemplates']) && $config['ReplacementTemplates']) {
// replacement templates defined in this config
$this->Application->ReplacementTemplates = array_merge_recursive2($this->Application->ReplacementTemplates, $config['ReplacementTemplates']);
}
}
function ValidateConfig($prefix)
{
global $debugger;
$config =& $this->configData[$prefix];
$tablename = $config['TableName'];
$float_types = Array ('float', 'double', 'numeric');
$conn =& $this->Application->GetADODBConnection();
$table_found = $conn->Query('SHOW TABLES LIKE "'.$tablename.'"');
if (!$table_found) {
// config present, but table missing, strange
$debugger->appendHTML("<b class='debug_error'>Config Warning: </b>Table <strong>$tablename</strong> missing, but prefix <b>".$config['Prefix']."</b> requires it!");
safeDefine('DBG_RAISE_ON_WARNINGS', 1);
return ;
}
$res = $conn->Query('DESCRIBE '.$tablename);
$config_link = $debugger->getFileLink(FULL_PATH.$this->prefixFiles[$config['Prefix']], 1, $config['Prefix']);
$error_messages = Array (
'field_not_found' => 'Field <strong>%s</strong> exists in the database, but <strong>is not defined</strong> in config',
'default_missing' => 'Default value for field <strong>%s</strong> not set in config',
'not_null_error1' => 'Field <strong>%s</strong> is NOT NULL in the database, but is not configured as not_null or required',
'not_null_error2' => 'Field <strong>%s</strong> is described as NOT NULL in config, but <strong>does not have DEFAULT value</strong>',
'not_null_error3' => 'Field <strong>%s</strong> is described as <strong>NOT NULL in config</strong>, but is <strong>NULL in db</strong>',
'invalid_default' => '<strong>Default value</strong> for field %s<strong>%s</strong> not sync. to db (in config = %s, in db = %s)',
'type_missing' => '<strong>Type definition</strong> for field <strong>%s</strong> missing in config',
);
$config_errors = Array ();
$tablename = preg_replace('/^'.preg_quote(TABLE_PREFIX, '/').'(.*)/', '\\1', $tablename); // remove table prefix
foreach ($res as $field) {
$f_name = $field['Field'];
if (getArrayValue($config, 'Fields')) {
if (preg_match('/l[\d]+_[\w]/', $f_name)) {
// skip multilingual fields
continue;
}
if (!array_key_exists ($f_name, $config['Fields'])) {
$config_errors[] = sprintf($error_messages['field_not_found'], $f_name);
}
else {
if (is_numeric($field['Default'])) {
$field['Default'] = preg_match('/[\.,]/', $field['Default']) ? (float)$field['Default'] : (int)$field['Default'];
}
$options = $config['Fields'][$f_name];
$default_missing = false;
if (!array_key_exists('default', $options)) {
$config_errors[] = sprintf($error_messages['default_missing'], $f_name);
$default_missing = true;
}
if ($field['Null'] != 'YES') {
// field is NOT NULL in database (MySQL5 for null returns "NO", but MySQL4 returns "")
if ( $f_name != $config['IDField'] && !isset($options['not_null']) && !isset($options['required']) ) {
$config_errors[] = sprintf($error_messages['not_null_error1'], $f_name);
}
if (isset($options['not_null']) && $options['not_null'] && !isset($options['default']) ) {
$config_errors[] = sprintf($error_messages['not_null_error2'], $f_name);
}
}
else {
if (isset($options['not_null']) && $options['not_null']) {
$config_errors[] = sprintf($error_messages['not_null_error3'], $f_name);
}
}
if (!array_key_exists('type', $options)) {
$config_errors[] = sprintf($error_messages['type_missing'], $f_name);
}
if (!$default_missing) {
if ($f_name == $config['IDField'] && $options['type'] != 'string' && $options['default'] !== 0) {
$config_errors[] = sprintf($error_messages['invalid_default'], '<span class="debug_error">IDField</span> ', $f_name, $this->varDump($options['default']), $this->varDump($field['Default']));
}
else if ($options['default'] != '#NOW#' && $field['Default'] !== $options['default'] && !in_array($options['type'], $float_types)) {
$config_errors[] = sprintf($error_messages['invalid_default'], '', $f_name, $this->varDump($options['default']), $this->varDump($field['Default']));
}
}
}
}
}
if ($config_errors) {
$error_prefix = '<strong class="debug_error">Config Error'.(count($config_errors) > 1 ? 's' : '').': </strong> for prefix <strong>'.$config_link.'</strong> ('.$tablename.') in unit config:<br />';
$config_errors = $error_prefix.'&nbsp;&nbsp;&nbsp;'.implode('<br />&nbsp;&nbsp;&nbsp;', $config_errors);
$debugger->appendHTML($config_errors);
safeDefine('DBG_RAISE_ON_WARNINGS', 1);
}
}
function varDump($value)
{
return '<strong>'.var_export($value, true).'</strong> of '.gettype($value);
}
function ProcessDependencies($prefix)
{
$config =& $this->configData[$prefix];
$deps = getArrayValue($config, '_Dependencies');
if (!$deps) return ;
foreach ($deps as $real_class => $requires) {
foreach ($requires as $class) {
$this->Application->registerDependency($real_class, $class);
}
}
unset($config['_Dependencies']);
}
function postProcessConfig($prefix, $config_key, $dst_prefix_var)
{
$main_config =& $this->configData[$prefix];
$sub_configs = isset($main_config[$config_key]) && $main_config[$config_key] ? $main_config[$config_key] : false; // getArrayValue($main_config, $config_key);
if (!$sub_configs) {
return array();
}
unset($main_config[$config_key]);
$processed = array();
foreach ($sub_configs as $sub_prefix => $sub_config) {
if ($config_key == 'AggregateConfigs' && !isset($this->configData[$sub_prefix])) {
$this->loadConfig($sub_prefix);
}
$sub_config['Prefix'] = $sub_prefix;
$this->configData[$sub_prefix] = array_merge_recursive2($this->configData[$$dst_prefix_var], $sub_config);
// when merging empty array to non-empty results non-empty array, but empty is required
foreach ($sub_config as $sub_key => $sub_value) {
if (!$sub_value) {
unset($this->configData[$sub_prefix][$sub_key]);
}
}
if ($config_key == 'Clones') {
$this->prefixFiles[$sub_prefix] = $this->prefixFiles[$prefix];
}
$this->postProcessConfig($sub_prefix, $config_key, $dst_prefix_var);
if ($config_key == 'AggregateConfigs') {
$processed = array_merge($this->postProcessConfig($sub_prefix, 'Clones', 'prefix'), $processed);
}
elseif ($this->ProcessAllConfigs) {
$this->parseConfig($sub_prefix);
}
array_push($processed, $sub_prefix);
}
if (!$prefix) {
// configs, that used only for cloning & not used ifself
unset($this->configData[$prefix]);
}
return array_unique($processed);
}
function PreloadConfigFile($filename)
{
$config_found = file_exists(FULL_PATH.$filename) && $this->configAllowed($filename);
if( defined('DEBUG_MODE') && DEBUG_MODE && constOn('DBG_PROFILE_INCLUDES') )
{
if ( in_array($filename, get_required_files()) ) return;
global $debugger;
if($config_found) {
$file = FULL_PATH.$filename;
$debugger->ProfileStart('inc_'.crc32($file), $file);
include_once($file);
$debugger->ProfileFinish('inc_'.crc32($file));
$debugger->profilerAddTotal('includes', 'inc_'.crc32($file));
}
}
else
{
if ($config_found) include_once(FULL_PATH.$filename);
}
if ($config_found) {
if (isset($config) && $config) {
// config file is included for 1st time -> save it's content for future processing
$prefix = isset($config['Prefix']) ? $config['Prefix'] : '';
preg_match('/\/(.*)\//U', $filename, $rets);
$config['ModuleFolder'] = $rets[1];
$config['BasePath'] = dirname(FULL_PATH.$filename);
if (isset($config['AdminTemplatePath'])) {
// append template base folder for admin templates path of this prefix
$module_templates = $rets[1] == 'core' ? 'in-portal/' : $rets[1].'/';
$config['AdminTemplatePath'] = $module_templates.$config['AdminTemplatePath'];
}
$this->configData[$prefix] = $config;
$this->prefixFiles[$prefix] = $filename;
return $prefix;
}
elseif ($prefix = array_search($filename, $this->prefixFiles)) {
// attempt is made to include config file twice or more, but include_once prevents that,
// but file exists on hdd, then it is already saved to all required arrays, just return it's prefix
return $prefix;
}
}
return 'dummy';
}
function loadConfig($prefix)
{
if (!isset($this->prefixFiles[$prefix])) {
if ($this->Application->isDebugMode()) $this->Application->Debugger->appendTrace();
trigger_error('Configuration file for prefix <b>'.$prefix.'</b> is unknown', E_USER_ERROR);
return ;
}
$file = $this->prefixFiles[$prefix];
$prefix = $this->PreloadConfigFile($file);
$clones = $this->postProcessConfig($prefix, 'AggregateConfigs', 'sub_prefix');
$clones = array_merge($this->postProcessConfig($prefix, 'Clones', 'prefix'), $clones);
if ($this->FinalStage) {
array_unshift($clones, $prefix);
$clones = array_unique($clones);
foreach ($clones as $a_prefix) {
$this->Application->HandleEvent( new kEvent($a_prefix.':OnAfterConfigRead') );
}
}
}
/**
* Reads unit (specified by $prefix)
* option specified by $option
*
* @param string $prefix
* @param string $name
* @param mixed $default
* @return string
* @access public
*/
function getUnitOption($prefix, $name, $default = false)
{
if (preg_match('/(.*)\.(.*)/', $prefix, $rets)) {
if (!isset($this->configData[$rets[1]])) {
$this->loadConfig($rets[1]);
}
$ret = isset($this->configData[$rets[1]][$name][$rets[2]]) ? $this->configData[$rets[1]][$name][$rets[2]] : false;
// $ret = getArrayValue($this->configData, $rets[1], $name, $rets[2]);
}
else {
if (!isset($this->configData[$prefix])) {
$this->loadConfig($prefix);
}
$ret = isset($this->configData[$prefix][$name]) ? $this->configData[$prefix][$name] : false;
// $ret = getArrayValue($this->configData, $prefix, $name);
}
return $ret === false ? $default : $ret;
}
/**
* Read all unit with $prefix options
*
* @param string $prefix
* @return Array
* @access public
*/
function getUnitOptions($prefix)
{
if (!isset($this->configData[$prefix])) {
$this->loadConfig($prefix);
}
return $this->configData[$prefix];
}
/**
* Set's new unit option value
*
* @param string $prefix
* @param string $name
* @param string $value
* @access public
*/
function setUnitOption($prefix, $name, $value)
{
if (preg_match('/(.*)\.(.*)/', $prefix, $rets)) {
if (!isset($this->configData[$rets[1]])) {
$this->loadConfig($rets[1]);
}
$this->configData[$rets[1]][$name][$rets[2]] = $value;
}
else {
if (!isset($this->configData[$prefix])) {
$this->loadConfig($prefix);
}
$this->configData[$prefix][$name] = $value;
}
}
function getPrefixByParamName($paramName,$prefix)
{
$pseudo_class_map=Array(
'ItemClass'=>'%s',
'ListClass'=>'%s_List',
'EventHandlerClass'=>'%s_EventHandler',
'TagProcessorClass'=>'%s_TagProcessor'
);
return sprintf($pseudo_class_map[$paramName],$prefix);
}
/**
* Get's config file name based
* on folder name supplied
*
* @param string $folderPath
* @return string
* @access private
*/
function getConfigName($folderPath)
{
return $folderPath.'/'.basename($folderPath).'_config.php';
}
/**
* is_dir ajustment to work with
* directory listings too
*
* @param string $folderPath
* @return bool
* @access private
*/
function isDir($folderPath)
{
$base_name = basename($folderPath);
$ret = !( $base_name == '.' || $base_name == '..' );
return $ret && is_dir($folderPath);
}
/**
* Checks if config file is allowed for includion (if module of config is installed)
*
* @param string $config_path relative path from in-portal directory
*/
function configAllowed($config_path)
{
if (defined('IS_INSTALL') && IS_INSTALL) {
// at installation start no modules in db and kernel configs could not be read
return true;
}
if (preg_match('#/plugins/|/core#', $config_path)) {
return true;
}
$module_found = false;
if (!$this->Application->ModuleInfo) return false;
foreach($this->Application->ModuleInfo as $module_name => $module_info)
{
$module_path = '/'.$module_info['Path'];
if (preg_match('/^'.preg_quote($module_path, '/').'/', $config_path)) {
- // if (substr($config_path, 0, strlen($module_path)) == $module_path) {
+ // if (mb_substr($config_path, 0, mb_strlen($module_path)) == $module_path) {
// config file path starts with module folder path
$module_found = true;
break;
}
}
return $module_found;
}
/**
* Returns true if config exists and is allowed for reading
*
* @param string $prefix
* @return bool
*/
function prefixRegistred($prefix)
{
return isset($this->prefixFiles[$prefix]) ? true : false;
}
function iterateConfigs($callback_function, $params)
{
$this->includeConfigFiles(MODULES_PATH); //make sure to re-read all configs
$this->AfterConfigRead();
foreach ($this->configData as $prefix => $config_data) {
$callback_function[0]->$callback_function[1]($prefix, $config_data, $params);
}
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/utility/unit_config_reader.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.78.2.3
\ No newline at end of property
+1.78.2.4
\ No newline at end of property
Index: branches/RC/core/kernel/utility/filters.php
===================================================================
--- branches/RC/core/kernel/utility/filters.php (revision 10097)
+++ branches/RC/core/kernel/utility/filters.php (revision 10098)
@@ -1,118 +1,118 @@
<?php
class kMultipleFilter
{
var $type = FLT_TYPE_AND;
var $filters = Array();
/**
* Creates new instance of kMultipleFilter class
*
* @param int $type
* @return kMultipleFilter
*/
function &makeClass($type=null)
{
$result = new kMultipleFilter($type);
return $result;
}
/**
* Creates empty multiple filter
*
* @param int $type
* @return MultipleFilter
* @access public
*/
function kMultipleFilter($type = FLT_TYPE_AND)
{
$this->setType($type);
}
/**
* Enter description here...
*
* @param int $new_type
*/
function setType($new_type)
{
$this->type = $new_type;
}
/**
* Adds new or replaces old filter with same name
*
* @param string $name
* @param mixed $clause kMultipleFilter object or where clause ifself
* @access public
*/
function addFilter($name, $clause)
{
if( is_object($clause) && $clause->hasFilters() )
{
$this->filters[$name] = $clause->getSQL();
}
elseif( !is_object($clause) && strlen($clause) )
{
$this->filters[$name] = $clause;
}
}
/**
* Returns filter by name
*
* @param string $name
* @return string
*/
function getFilter($name)
{
return isset($this->filters[$name]) ? $this->filters[$name] : false;
}
-
+
/**
* Removes specified filter from filters list
*
* @param string $name
* @access public
*/
function removeFilter($name)
{
unset($this->filters[$name]);
}
/**
* Remove all added filters
*
* @access public
*/
function clearFilters()
{
$this->filters = Array();
}
/**
* Build where clause based on added filters and multiple filter type
*
* @return string
* @access public
*/
function getSQL()
{
$filter_count = count($this->filters);
if(!$filter_count) return '';
return '('.implode(') '.$this->type.' (',$this->filters).')';
}
/**
* Allows to check if some filters are added to multiple filter
*
* @return bool
* @access public
*/
function hasFilters()
{
return $this->filters ? true : false;
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/utility/filters.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.8
\ No newline at end of property
+1.8.2.1
\ No newline at end of property
Index: branches/RC/core/kernel/utility/socket.php
===================================================================
--- branches/RC/core/kernel/utility/socket.php (revision 10097)
+++ branches/RC/core/kernel/utility/socket.php (revision 10098)
@@ -1,361 +1,361 @@
<?php
/**
* Generalized Socket class.
*
*/
class kSocket extends kBase {
-
+
/**
* Socket file pointer.
* @var resource $fp
*/
var $fp = null;
-
+
/**
* Whether the socket is blocking. Defaults to true.
* @var boolean $blocking
*/
var $blocking = true;
-
+
/**
* Whether the socket is persistent. Defaults to false.
* @var boolean $persistent
*/
var $persistent = false;
-
+
/**
* The IP address to connect to.
* @var string $addr
*/
var $addr = '';
-
+
/**
* The port number to connect to.
* @var integer $port
*/
var $port = 0;
-
+
/**
* Number of seconds to wait on socket connections before assuming
* there's no more data. Defaults to no timeout.
* @var integer $timeout
*/
var $timeout = false;
-
+
/**
* Number of bytes to read at a time in readLine() and
* readAll(). Defaults to 2048.
* @var integer $lineLength
*/
var $lineLength = 2048;
-
+
/**
* Connect to the specified port. If called when the socket is
* already connected, it disconnects and connects again.
*
* @param string $addr IP address or host name.
* @param integer $port TCP port number.
* @param boolean $persistent (optional) Whether the connection is
* persistent (kept open between requests
* by the web server).
* @param integer $timeout (optional) How long to wait for data.
*
* @access public
*
* @return boolean | PEAR_Error True on success or a PEAR_Error on failure.
*/
function connect($addr, $port = 0, $persistent = null, $timeout = null)
{
if (is_resource($this->fp)) {
@fclose($this->fp);
$this->fp = null;
}
-
+
// convert hostname to ip address
if (!$addr) {
return $this->raiseError('host address cannot be empty');
} elseif (strspn($addr, '.0123456789') == strlen($addr) || strstr($addr, '/') !== false) {
$this->addr = $addr;
} else {
$this->addr = @gethostbyname($addr);
}
-
+
$this->port = $port % 65536;
-
+
if ($persistent !== null) {
$this->persistent = $persistent;
}
-
+
if ($timeout !== null) {
$this->timeout = $timeout;
}
-
+
$openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
$errno = 0;
$errstr = '';
-
+
if ($this->timeout) {
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $this->timeout);
} else {
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr);
}
-
+
if (!$fp) {
return $this->raiseError($errstr, Array($errno));
}
-
+
$this->fp = $fp;
-
+
return $this->setBlocking($this->blocking);
}
-
+
/**
* Disconnects from the peer, closes the socket.
*
* @access public
* @return mixed true on success or an error object otherwise
*/
function disconnect()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
-
+
@fclose($this->fp);
$this->fp = null;
return true;
}
-
+
/**
* Find out if the socket is in blocking mode.
*
* @access public
* @return boolean The current blocking mode.
*/
function isBlocking()
{
return $this->blocking;
}
-
+
/**
* Sets whether the socket connection should be blocking or
* not. A read call to a non-blocking socket will return immediately
* if there is no data available, whereas it will block until there
* is data for blocking sockets.
*
* @param boolean $mode True for blocking sockets, false for nonblocking.
* @access public
* @return mixed true on success or an error object otherwise
*/
function setBlocking($mode)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
-
+
$this->blocking = $mode;
socket_set_blocking($this->fp, $this->blocking);
return true;
}
-
+
/**
* Sets the timeout value on socket descriptor,
* expressed in the sum of seconds and microseconds
*
* @param integer $seconds Seconds.
* @param integer $microseconds Microseconds.
* @access public
* @return mixed true on success or an error object otherwise
*/
function setTimeout($seconds, $microseconds)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
-
+
return socket_set_timeout($this->fp, $seconds, $microseconds);
}
-
+
/**
* Returns information about an existing socket resource.
* Currently returns four entries in the result array:
*
* <p>
* timed_out (bool) - The socket timed out waiting for data<br>
* blocked (bool) - The socket was blocked<br>
* eof (bool) - Indicates EOF event<br>
* unread_bytes (int) - Number of bytes left in the socket buffer<br>
* </p>
*
* @access public
* @return mixed Array containing information about existing socket resource or an error object otherwise
*/
function getStatus()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
-
+
return socket_get_status($this->fp);
}
-
+
/**
* Get a specified line of data
*
* @access public
* @return $size bytes of data from the socket, or a PEAR_Error if
* not connected.
*/
function gets($size)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
-
+
return @fgets($this->fp, $size);
}
-
+
/**
* Read a specified amount of data. This is guaranteed to return,
* and has the added benefit of getting everything in one fread()
* chunk; if you know the size of the data you're getting
* beforehand, this is definitely the way to go.
*
* @param integer $size The number of bytes to read from the socket.
* @access public
* @return $size bytes of data from the socket, or a PEAR_Error if
* not connected.
*/
function read($size)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
-
+
return @fread($this->fp, $size);
}
-
+
/**
* Write a specified amount of data.
*
* @param string $data Data to write.
* @param integer $blocksize Amount of data to write at once.
* NULL means all at once.
*
* @access public
* @return mixed true on success or an error object otherwise
*/
function write($data, $blocksize = null)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
-
+
if (is_null($blocksize) && !OS_WINDOWS) {
return fwrite($this->fp, $data);
} else {
if (is_null($blocksize)) {
$blocksize = 1024;
}
-
+
$pos = 0;
$size = strlen($data);
while ($pos < $size) {
$written = @fwrite($this->fp, substr($data, $pos, $blocksize));
if ($written === false) {
return false;
}
$pos += $written;
}
-
+
return $pos;
}
}
-
+
/**
* Write a line of data to the socket, followed by a trailing "\r\n".
*
* @access public
* @return mixed fputs result, or an error
*/
function writeLine($data)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
-
+
return fwrite($this->fp, $data . "\r\n");
}
-
+
/**
* Tests for end-of-file on a socket descriptor.
*
* @access public
* @return bool
*/
function eof()
{
return (is_resource($this->fp) && feof($this->fp));
}
-
+
/**
* Read until either the end of the socket or a newline, whichever
* comes first. Strips the trailing newline from the returned data.
*
* @access public
* @return All available data up to a newline, without that
* newline, or until the end of the socket, or a PEAR_Error if
* not connected.
*/
function readLine()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
-
+
$line = '';
$timeout = time() + $this->timeout;
while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
$line .= @fgets($this->fp, $this->lineLength);
if (substr($line, -1) == "\n") {
return rtrim($line, "\r\n");
}
}
return $line;
}
-
+
/**
* Read until the socket closes, or until there is no more data in
* the inner PHP buffer. If the inner buffer is empty, in blocking
* mode we wait for at least 1 byte of data. Therefore, in
* blocking mode, if there is no data at all to be read, this
* function will never exit (unless the socket is closed on the
* remote end).
*
* @access public
*
* @return string All data until the socket closes, or a PEAR_Error if
* not connected.
*/
function readAll()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
-
+
$data = '';
while (!feof($this->fp)) {
$data .= @fread($this->fp, $this->lineLength);
}
return $data;
}
-
+
function raiseError($text, $params = Array())
{
trigger_error(vsprintf($text, $params), E_USER_WARNING);
return false;
}
}
-
+
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/utility/socket.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.2.2.1
\ No newline at end of property
Index: branches/RC/core/kernel/event_handler.php
===================================================================
--- branches/RC/core/kernel/event_handler.php (revision 10097)
+++ branches/RC/core/kernel/event_handler.php (revision 10098)
@@ -1,347 +1,347 @@
<?php
/**
* Note:
* 1. When adressing variables from submit containing
* Prefix_Special as part of their name use
* $event->getPrefixSpecial(true) instead of
* $event->Prefix_Special as usual. This is due PHP
* is converting "." symbols in variable names during
* submit info "_". $event->getPrefixSpecial optional
* 1st parameter returns correct corrent Prefix_Special
* for variables beeing submitted such way (e.g. variable
* name that will be converted by PHP: "users.read_only_id"
* will be submitted as "users_read_only_id".
*
* 2. When using $this->Application-LinkVar on variables submitted
* from form which contain $Prefix_Special then note 1st item. Example:
* LinkVar($event->getPrefixSpecial(true).'_varname',$event->Prefix_Special.'_varname')
*
*/
/**
* Default event handler. Mostly abstract class
*
*/
class kEventHandler extends kBase {
/**
* In case if event should be handled with mehod,
* which name differs from event name, then it
* should be specified here.
* key - event name, value - event method
*
* @var Array
* @access protected
*/
var $eventMethods = Array();
/**
* Defines mapping vs event names and permission names
*
* @var Array
*/
var $permMapping = Array();
/**
* Define alternative event processing method names
*
* @see $eventMethods
* @access protected
*/
function mapEvents()
{
}
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
}
function getPrefixSpecial()
{
trigger_error('Usage of getPrefixSpecial() this method is forbidden in kEventHandler class children. Use $event->getPrefixSpecial(true); instead', E_USER_ERROR);
}
/**
* Set's prefix and special
*
* @param string $prefix
* @param string $special
* @access public
*/
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$this->mapEvents();
$this->mapPermissions();
}
/**
* Process Event
*
* @param kEvent $event
* @access public
*/
function processEvent(&$event)
{
$event_name=$event->Name;
if( isset($this->eventMethods[$event_name]) ) $event_name=$this->eventMethods[$event_name];
if( method_exists($this,$event_name) )
{
$this->$event_name($event);
}
else
{
trigger_error('event <b>'.$event->Name.'</b> not implemented in class <b>'.get_class($this).'</b>', E_USER_ERROR);
}
}
/**
* Sample dummy event
*
* @param kEvent $event
* @access protected
*/
function OnBuild(&$event)
{
/*echo 'building: <br>';
print_pre($event);*/
}
/**
* Returns to previous template in opener stack
*
* @param kEvent $event
*/
function OnGoBack(&$event)
{
$url = $this->Application->RecallVar('export_finish_url');
if ($url) {
$this->Application->Redirect('external:'.$url);
}
$event->SetRedirectParam('opener', 'u');
}
/**
* Apply some special processing to
* object beeing recalled before using
* it in other events that call prepareObject
*
* @param Object $object
* @param kEvent $event
* @access protected
*/
function prepareObject(&$object, &$event)
{
// processing here
}
/**
* Creates new event as child of
* event passed as $event param
*
* @param kEvent $event
* @access protected
*/
function &inheritEvent(&$event, $name=null)
{
$child_event = new kEvent();
$child_event->MasterEvent =& $event;
$child_event->Prefix=$event->Prefix;
$child_event->Special=$event->Special;
$child_event->Prefix_Special=$event->Prefix_Special;
$child_event->Name = $name;
return $child_event;
}
/**
* Created url part for this module
*
* @param kEvent $event
*/
function BuildEnv(&$event)
{
$prefix_special = $event->getPrefixSpecial();
$url_params = $event->getEventParam('url_params');
$pass_events = $event->getEventParam('pass_events');
$query_vars = $this->Application->getUnitOption($event->Prefix, 'QueryString');
$event_key = array_search('event', $query_vars);
if ($event_key) {
// pass through event of this prefix
unset($query_vars[$event_key]);
}
if (!getArrayValue($url_params, $prefix_special.'_event')) {
// if empty event, then remove it from url
unset( $url_params[$prefix_special.'_event'] );
}
//if pass events is off and event is not implicity passed
if ( !$pass_events && !isset($url_params[$prefix_special.'_event']) )
{
unset($url_params[$prefix_special.'_event']); // remove event from url if requested
//otherwise it will use value from get_var
}
if(!$query_vars) return true;
$processed_params = Array();
foreach($query_vars as $index => $var_name)
{
//if value passed in params use it, otherwise use current from application
$var_name = $prefix_special.'_'.$var_name;
$processed_params[$var_name] = isset( $url_params[$var_name] ) ? $url_params[$var_name] : $this->Application->GetVar($var_name);
if ( isset($url_params[$var_name]) ) unset( $url_params[$var_name] );
}
$ret = '';
/*if($processed_params[$prefix_special.'_Page'] > 1 && !$processed_params[$prefix_special.'_id'])
{
$ret .= $processed_params[$prefix_special.'_Page'].'/';
}*/
if (!$processed_params[$prefix_special.'_id']) {
if ($processed_params[$prefix_special.'_Page'] == 1) {
// when printing "items" from category, there is 1st page -> nothing from "item prefix" in url
// and auto-guess pass_category will not be added to url
$url_params['pass_category'] = 1;
}
else {
$ret .= $processed_params[$prefix_special.'_Page'].'/';
}
}
-
+
if ($processed_params[$prefix_special.'_id']) {
// this allows to fill 3 cache records with one query (see this method for details)
$category_id = isset($url_params['m_cat_id']) ? $url_params['m_cat_id'] : $this->Application->GetVar('m_cat_id');
$category_filename = $this->Application->getFilename('c', $category_id);
// if template is also item template of category, then remove template
$template = getArrayValue($url_params, 't');
$item_template = $this->Application->getCache('item_templates', $category_id);
if ($template == $item_template || strtolower($template) == '__default__') {
unset($url_params['t']);
}
// get item's filename
$filename = $this->Application->getFilename($event->Prefix, $processed_params[$prefix_special.'_id'], $category_id );
if($filename !== false) $ret .= $filename.'/';
}
if( getArrayValue($processed_params, $prefix_special.'_Reviews_Page') > 1)
{
if($processed_params[$prefix_special.'_id']) $ret = rtrim($ret, '/');
$ret .= '_'.$processed_params[$prefix_special.'_Reviews_Page'].'/';
}
$event->setEventParam('url_params', $url_params);
- $event->setEventParam('env_string', strtolower($ret) );
+ $event->setEventParam('env_string', mb_strtolower($ret) );
}
/**
* Process mod_rewrite url part left after previous parser
*
* @param kEvent $event
*/
function ParseEnv(&$event)
{
// <module_page>/<item_filename>_<reviews_page>
$url_parts = $event->getEventParam('url_parts');
$defaults = Array('id' => 0, 'Page' => 1, 'Reviews_Page' => 1);
foreach ($defaults as $var_name => $var_value)
{
$this->Application->SetVar($event->getPrefixSpecial().'_'.$var_name, $var_value);
}
if (!$url_parts) {
// $event->status = erFAIL;
return false;
}
$ret = '';
$url_part = array_shift($url_parts);
// match module page
if( is_numeric($url_part) )
{
$this->Application->SetVar( $event->getPrefixSpecial().'_Page', $url_part);
$url_part = $url_parts ? array_shift($url_parts) : '';
}
if (!$url_part) {
$event->setEventParam('url_parts', $url_parts);
// $event->status = erFAIL;
return true;
}
// match module reviews page
if( preg_match('/(.*)_([\d]+)$/', $url_part, $rets) )
{
$url_part = $rets[1];
$this->Application->SetVar( $event->getPrefixSpecial().'_Reviews_Page', $rets[2]);
}
// match item's filename
$db =& $this->Application->GetADODBConnection();
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
$table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$sql = 'SELECT item_table.'.$id_field.'
FROM '.$table.' item_table
LEFT JOIN '.TABLE_PREFIX.'CategoryItems cat_items ON item_table.ResourceId = cat_items.ItemResourceId
WHERE (item_table.Filename = '.$db->qstr($url_part).') AND (cat_items.CategoryId = '.$this->Application->GetVar('m_cat_id').')';
$item_id = $db->GetOne($sql);
if($item_id !== false)
{
$this->Application->SetVar($event->getPrefixSpecial().'_id', $item_id);
}
elseif ($url_part !== 'index') // otherwise category/index.html is parsed as /index.tpl
{
array_unshift($url_parts, $url_part);
$event->status = erFAIL;
}
$event->setEventParam('url_parts', $url_parts);
}
/**
* Checks permissions of user
*
* @param kEvent $event
*/
function CheckPermission(&$event)
{
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
return $perm_helper->CheckEventPermission($event, $this->permMapping);
}
/**
* Occurs, when config was parsed, allows to change config data dynamically
*
* @param kEvent $event
*/
function OnAfterConfigRead(&$event)
{
// readonly, for hooking only!
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.35
\ No newline at end of property
+1.35.2.1
\ No newline at end of property
Index: branches/RC/core/kernel/db/db_tag_processor.php
===================================================================
--- branches/RC/core/kernel/db/db_tag_processor.php (revision 10097)
+++ branches/RC/core/kernel/db/db_tag_processor.php (revision 10098)
@@ -1,2105 +1,2105 @@
<?php
class kDBTagProcessor extends TagProcessor {
/**
* Description
*
* @var kDBConnection
* @access public
*/
var $Conn;
function kDBTagProcessor()
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
}
/**
* Returns true if "new" button was pressed in toolbar
*
* @param Array $params
* @return bool
*/
function IsNewMode($params)
{
$object =& $this->getObject($params);
return $object->GetID() <= 0;
}
/**
* Returns view menu name for current prefix
*
* @param Array $params
* @return string
*/
function GetItemName($params)
{
$item_name = $this->Application->getUnitOption($this->Prefix, 'ViewMenuPhrase');
return $this->Application->Phrase($item_name);
}
function ViewMenu($params)
{
$block_params = $params;
unset($block_params['block']);
$block_params['name'] = $params['block'];
$list =& $this->GetList($params);
$block_params['PrefixSpecial'] = $list->getPrefixSpecial();
return $this->Application->ParseBlock($block_params);
}
function SearchKeyword($params)
{
$list =& $this->GetList($params);
return $this->Application->RecallVar($list->getPrefixSpecial().'_search_keyword');
}
/**
* Draw filter menu content (for ViewMenu) based on filters defined in config
*
* @param Array $params
* @return string
*/
function DrawFilterMenu($params)
{
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $params['spearator_block'];
$separator = $this->Application->ParseBlock($block_params);
$filter_menu = $this->Application->getUnitOption($this->Prefix,'FilterMenu');
if(!$filter_menu)
{
trigger_error('<span class="debug_error">no filters defined</span> for prefix <b>'.$this->Prefix.'</b>, but <b>DrawFilterMenu</b> tag used', E_USER_WARNING);
return '';
}
// Params: label, filter_action, filter_status
$block_params['name'] = $params['item_block'];
$view_filter = $this->Application->RecallVar($this->getPrefixSpecial().'_view_filter');
if($view_filter === false)
{
$event_params = Array('prefix'=>$this->Prefix,'special'=>$this->Special,'name'=>'OnRemoveFilters');
$this->Application->HandleEvent( new kEvent($event_params) );
$view_filter = $this->Application->RecallVar($this->getPrefixSpecial().'_view_filter');
}
$view_filter = unserialize($view_filter);
$filters = Array();
$prefix_special = $this->getPrefixSpecial();
foreach ($filter_menu['Filters'] as $filter_key => $filter_params) {
$group_params = isset($filter_params['group_id']) ? $filter_menu['Groups'][ $filter_params['group_id'] ] : Array();
if (!isset($group_params['element_type'])) {
$group_params['element_type'] = 'checkbox';
}
if (!$filter_params) {
$filters[] = $separator;
continue;
}
$block_params['label'] = addslashes( $this->Application->Phrase($filter_params['label']) );
if (getArrayValue($view_filter,$filter_key)) {
$submit = 0;
if (isset($params['old_style'])) {
$status = $group_params['element_type'] == 'checkbox' ? 1 : 2;
}
else {
$status = $group_params['element_type'] == 'checkbox' ? '[\'img/check_on.gif\']' : '[\'img/menu_dot.gif\']';
}
}
else {
$submit = 1;
$status = 'null';
}
$block_params['filter_action'] = 'set_filter("'.$prefix_special.'","'.$filter_key.'","'.$submit.'",'.$params['ajax'].');';
$block_params['filter_status'] = $status; // 1 - checkbox, 2 - radio, 0 - no image
$filters[] = $this->Application->ParseBlock($block_params);
}
return implode('', $filters);
}
function IterateGridFields($params)
{
$mode = $params['mode'];
$def_block = isset($params['block']) ? $params['block'] : '';
$force_block = isset($params['force_block']) ? $params['force_block'] : false;
$grids = $this->Application->getUnitOption($this->Prefix,'Grids');
$grid_config = $grids[$params['grid']]['Fields'];
$picker_helper =& $this->Application->RecallObject('ColumnPickerHelper');
/* @var $picker_helper kColumnPickerHelper */
$picker_helper->ApplyPicker($this->getPrefixSpecial(), $grid_config, $params['grid']);
if ($mode == 'fields') {
return "'".join("','", array_keys($grid_config))."'";
}
$std_params['pass_params'] = 'true';
$std_params['PrefixSpecial'] = $this->getPrefixSpecial();
$object =& $this->GetList($params);
$o = '';
$i = 0;
foreach ($grid_config as $field => $options) {
$i++;
$block_params = Array();
$block_params['name'] = $force_block ? $force_block : (isset($options[$mode.'_block']) ? $options[$mode.'_block'] : $def_block);
$block_params['field'] = $field;
$block_params['sort_field'] = isset($options['sort_field']) ? $options['sort_field'] : $field;
$block_params['filter_field'] = isset($options['filter_field']) ? $options['filter_field'] : $field;
$w = $picker_helper->GetWidth($field);
if ($w) $options['width'] = $w;
/*if (isset($options['filter_width'])) {
$block_params['filter_width'] = $options['filter_width'];
}
elseif (isset($options['width'])) {
if (isset($options['filter_block']) && preg_match('/range/', $options['filter_block'])) {
if ($options['width'] < 60) {
$options['width'] = 60;
$block_params['filter_width'] = 20;
}
else {
$block_params['filter_width'] = $options['width'] - 40;
}
}
else {
$block_params['filter_width'] = max($options['width']-10, 20);
}
}*/
/*if (isset($block_params['filter_width'])) $block_params['filter_width'] .= 'px';
if (isset($options['filter_block']) && preg_match('/range/', $options['filter_block'])) {
$block_params['filter_width'] = '20px';
}
else {
$block_params['filter_width'] = '97%';
// $block_params['filter_width'] = max($options['width']-10, 20);
}*/
$field_options = $object->GetFieldOptions($field);
if (array_key_exists('use_phrases', $field_options)) {
$block_params['use_phrases'] = $field_options['use_phrases'];
}
$block_params['is_last'] = ($i == count($grid_config));
$block_params = array_merge($std_params, $options, $block_params);
$o.= $this->Application->ParseBlock($block_params, 1);
}
return $o;
}
function PickerCRC($params)
{
/* @var $picker_helper kColumnPickerHelper */
$picker_helper =& $this->Application->RecallObject('ColumnPickerHelper');
$picker_helper->SetGridName($params['grid']);
$data = $picker_helper->LoadColumns($this->getPrefixSpecial());
return $data['crc'];
}
function FreezerPosition($params)
{
/* @var $picker_helper kColumnPickerHelper */
$picker_helper =& $this->Application->RecallObject('ColumnPickerHelper');
$picker_helper->SetGridName($params['grid']);
$data = $picker_helper->LoadColumns($this->getPrefixSpecial());
$freezer_pos = array_search('__FREEZER__', $data['order']);
return $freezer_pos === false || in_array('__FREEZER__', $data['hidden_fields']) ? 1 : ++$freezer_pos;
}
function GridFieldsCount($params)
{
$grids = $this->Application->getUnitOption($this->Prefix, 'Grids');
$grid_config = $grids[$params['grid']]['Fields'];
return count($grid_config);
}
/**
* Prints list content using block specified
*
* @param Array $params
* @return string
* @access public
*/
function PrintList($params)
{
$params['no_table'] = 1;
return $this->PrintList2($params);
}
function InitList($params)
{
$list_name = isset($params['list_name']) ? $params['list_name'] : '';
$names_mapping = $this->Application->GetVar('NamesToSpecialMapping');
if( !getArrayValue($names_mapping, $this->Prefix, $list_name) )
{
$list =& $this->GetList($params);
}
}
function BuildListSpecial($params)
{
return $this->Special;
}
/**
* Returns key, that identifies each list on template (used internally, not tag)
*
* @param Array $params
* @return string
*/
function getUniqueListKey($params)
{
$types = $this->SelectParam($params, 'types');
$except = $this->SelectParam($params, 'except');
$list_name = $this->SelectParam($params, 'list_name');
if (!$list_name) {
$list_name = $this->Application->Parser->GetParam('list_name');
}
return $types.$except.$list_name;
}
/**
* Enter description here...
*
* @param Array $params
* @return kDBList
*/
function &GetList($params)
{
$list_name = $this->SelectParam($params, 'list_name,name');
if (!$list_name) {
$list_name = $this->Application->Parser->GetParam('list_name');
}
$requery = isset($params['requery']) && $params['requery'];
if ($list_name && !$requery){
$names_mapping = $this->Application->GetVar('NamesToSpecialMapping');
$special = is_array($names_mapping) && isset($names_mapping[$this->Prefix]) && isset($names_mapping[$this->Prefix][$list_name]) ? $names_mapping[$this->Prefix][$list_name] : false;
// $special = getArrayValue($names_mapping, $this->Prefix, $list_name);
if(!$special)
{
$special = $this->BuildListSpecial($params);
}
}
else
{
$special = $this->BuildListSpecial($params);
}
$prefix_special = rtrim($this->Prefix.'.'.$special, '.');
$params['skip_counting'] = true;
$list =& $this->Application->recallObject( $prefix_special, $this->Prefix.'_List', $params);
/* @var $list kDBList */
if ($requery) {
$this->Application->HandleEvent($an_event, $prefix_special.':OnListBuild', $params);
}
if (array_key_exists('offset', $params)) {
$list->Offset += $params['offset']; // apply custom offset
}
$list->Query($requery);
if (array_key_exists('offset', $params)) {
$list->Offset -= $params['offset']; // remove custom offset
}
$this->Special = $special;
if ($list_name) {
$names_mapping[$this->Prefix][$list_name] = $special;
$this->Application->SetVar('NamesToSpecialMapping', $names_mapping);
}
return $list;
}
function ListMarker($params)
{
$list =& $this->GetList($params);
$ret = $list->getPrefixSpecial();
if( getArrayValue($params, 'as_preg') ) $ret = preg_quote($ret, '/');
return $ret;
}
/**
* Prepares name for field with event in it (used only on front-end)
*
* @param Array $params
* @return string
*/
function SubmitName($params)
{
$list =& $this->GetList($params);
$prefix_special = $list->getPrefixSpecial();
return 'events['.$prefix_special.']['.$params['event'].']';
}
/**
* Prints list content using block specified
*
* @param Array $params
* @return string
* @access public
*/
function PrintList2($params)
{
$per_page = $this->SelectParam($params, 'per_page,max_items');
if ($per_page !== false) $params['per_page'] = $per_page;
$list =& $this->GetList($params);
$o = '';
$direction = (isset($params['direction']) && $params['direction']=="H")?"H":"V";
$columns = (isset($params['columns'])) ? $params['columns'] : 1;
$id_field = (isset($params['id_field'])) ? $params['id_field'] : $this->Application->getUnitOption($this->Prefix, 'IDField');
if ($columns>1 && $direction=="V") {
$list->Records = $this->LinearToVertical($list->Records, $columns, $list->GetPerPage());
$list->SelectedCount=count($list->Records);
ksort($list->Records); // this is issued twice, maybe need to be removed
}
$list->GoFirst();
$block_params=$this->prepareTagParams($params);
$block_params['name']=$this->SelectParam($params, 'render_as,block');
$block_params['pass_params']='true';
$block_params['column_width'] = 100 / $columns;
$block_start_row_params = $this->prepareTagParams($params);
$block_start_row_params['name'] = $this->SelectParam($params, 'row_start_render_as,block_row_start,row_start_block');
$block_end_row_params=$this->prepareTagParams($params);
$block_end_row_params['name'] = $this->SelectParam($params, 'row_end_render_as,block_row_end,row_end_block');
$block_empty_cell_params = $this->prepareTagParams($params);
$block_empty_cell_params['name'] = $this->SelectParam($params, 'empty_cell_render_as,block_empty_cell,empty_cell_block');
$i=0;
$backup_id=$this->Application->GetVar($this->Prefix."_id");
$displayed = array();
$column_number = 1;
$cache_mod_rw = $this->Application->getUnitOption($this->Prefix, 'CacheModRewrite') && $this->Application->RewriteURLs();
while (!$list->EOL())
{
$this->Application->SetVar( $this->getPrefixSpecial().'_id', $list->GetDBField($id_field) ); // for edit/delete links using GET
$this->Application->SetVar( $this->Prefix.'_id', $list->GetDBField($id_field) );
$block_params['is_last'] = ($i == $list->SelectedCount - 1);
$block_params['not_last'] = !$block_params['is_last']; // for front-end
if ($cache_mod_rw) {
$this->Application->setCache('filenames', $this->Prefix.'_'.$list->GetDBField($id_field), $list->GetDBField('Filename'));
$this->Application->setCache('filenames', 'c_'.$list->GetDBField('CategoryId'), $list->GetDBField('CategoryFilename'));
}
if ($i % $columns == 0) {
// record in this iteration is first in row, then open row
$column_number = 1;
$o.= $block_start_row_params['name'] ?
$this->Application->ParseBlock($block_start_row_params, 1) :
(!isset($params['no_table']) ? '<tr>' : '');
}
else {
$column_number++;
}
$block_params['first_col'] = $column_number == 1 ? 1 : 0;
$block_params['last_col'] = $column_number == $columns ? 1 : 0;
$block_params['column_number'] = $column_number;
$this->PrepareListElementParams($list, $block_params); // new, no need to rewrite PrintList
$o.= $this->Application->ParseBlock($block_params, 1);
array_push($displayed, $list->GetDBField($id_field));
if (($i+1) % $columns == 0) {
// record in next iteration is first in row too, then close this row
$o.= $block_end_row_params['name'] ?
$this->Application->ParseBlock($block_end_row_params, 1) :
(!isset($params['no_table']) ? '</tr>' : '');
}
$list->GoNext();
$i++;
}
// append empty cells in place of missing cells in last row
while ($i % $columns != 0) {
// until next cell will be in new row append empty cells
$o .= $block_empty_cell_params['name'] ? $this->Application->ParseBlock($block_empty_cell_params, 1) : '<td>&nbsp;</td>';
if (($i+1) % $columns == 0) {
// record in next iteration is first in row too, then close this row
$o .= $block_end_row_params['name'] ? $this->Application->ParseBlock($block_end_row_params, 1) : '</tr>';
}
$i++;
}
$cur_displayed = $this->Application->GetVar($this->Prefix.'_displayed_ids');
if (!$cur_displayed) {
$cur_displayed = Array();
}
else {
$cur_displayed = explode(',', $cur_displayed);
}
$displayed = array_unique(array_merge($displayed, $cur_displayed));
$this->Application->SetVar($this->Prefix.'_displayed_ids', implode(',',$displayed));
$this->Application->SetVar( $this->Prefix.'_id', $backup_id);
$this->Application->SetVar( $this->getPrefixSpecial().'_id', '');
if (isset($params['more_link_render_as'])) {
$block_params = $params;
$params['render_as'] = $params['more_link_render_as'];
$o .= $this->MoreLink($params);
}
return $o;
}
/**
* Allows to modify block params & current list record before PrintList parses record
*
* @param kDBList $object
* @param Array $block_params
*/
function PrepareListElementParams(&$object, &$block_params)
{
// $fields_hash =& $object->Records[$this->CurrentIndex];
//
// $object->Records[$this->CurrentIndex] =& $fields_hash;
}
function MoreLink($params)
{
$per_page = $this->SelectParam($params, 'per_page,max_items');
if ($per_page !== false) $params['per_page'] = $per_page;
$list =& $this->GetList($params);
if ($list->PerPage < $list->RecordsCount) {
$block_params = array();
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
return $this->Application->ParseBlock($block_params, 1);
}
}
function NotLastItem($params)
{
$object =& $this->getList($params); // maybe we should use $this->GetList($params) instead
return ($object->CurrentIndex < min($object->PerPage == -1 ? $object->RecordsCount : $object->PerPage, $object->RecordsCount) - 1);
}
function PageLink($params)
{
$t = isset($params['template']) ? $params['template'] : '';
unset($params['template']);
if (!$t) $t = $this->Application->GetVar('t');
if (isset($params['page'])) {
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $params['page']);
unset($params['page']);
}
if (!isset($params['pass'])) {
$params['pass'] = 'm,'.$this->getPrefixSpecial();
}
return $this->Application->HREF($t, '', $params);
}
function ColumnWidth($params)
{
$columns = $this->Application->Parser->GetParam('columns');
return round(100/$columns).'%';
}
/**
* Append prefix and special to tag
* params (get them from tagname) like
* they were really passed as params
*
* @param Array $tag_params
* @return Array
* @access protected
*/
function prepareTagParams($tag_params = Array())
{
/*if (isset($tag_params['list_name'])) {
$list =& $this->GetList($tag_params);
$this->Init($list->Prefix, $list->Special);
}*/
$ret = $tag_params;
$ret['Prefix'] = $this->Prefix;
$ret['Special'] = $this->Special;
$ret['PrefixSpecial'] = $this->getPrefixSpecial();
return $ret;
}
function GetISO($currency)
{
if ($currency == 'selected') {
$iso = $this->Application->RecallVar('curr_iso');
}
elseif ($currency == 'primary' || $currency == '') {
$iso = $this->Application->GetPrimaryCurrency();
}
else { //explicit currency
$iso = $currency;
}
return $iso;
}
function ConvertCurrency($value, $iso)
{
$converter =& $this->Application->recallObject('kCurrencyRates');
// convery primary currency to selected (if they are the same, converter will just return)
$value = $converter->Convert($value, 'PRIMARY', $iso);
return $value;
}
function AddCurrencySymbol($value, $iso)
{
$currency =& $this->Application->recallObject('curr.-'.$iso, null, Array('skip_autoload' => true));
if( !$currency->isLoaded() ) $currency->Load($iso, 'ISO');
$symbol = $currency->GetDBField('Symbol');
if (!$symbol) $symbol = $currency->GetDBField('ISO').'&nbsp;';
if ($currency->GetDBField('SymbolPosition') == 0) {
$value = $symbol.$value;
}
if ($currency->GetDBField('SymbolPosition') == 1) {
$value = $value.$symbol;
}
return $value;
}
/**
* Get's requested field value
*
* @param Array $params
* @return string
* @access public
*/
function Field($params)
{
$field = $this->SelectParam($params, 'name,field');
if( !$this->Application->IsAdmin() ) $params['no_special'] = 'no_special';
$object =& $this->getObject($params);
if ( $this->HasParam($params, 'db') )
{
$value = $object->GetDBField($field);
}
else
{
if( $this->HasParam($params, 'currency') )
{
$iso = $this->GetISO($params['currency']);
$original = $object->GetDBField($field);
$value = $this->ConvertCurrency($original, $iso);
$object->SetDBField($field, $value);
$object->Fields[$field]['converted'] = true;
}
$format = getArrayValue($params, 'format');
if (!$format || $format == '$format') {
$format = null;
}
else {
// maybe duplicate code, test if code in kDateFormatter::SetMixedFormat works like code below (note by Alex)
if (preg_match("/_regional_(.*)/", $format, $regs)) {
$lang =& $this->Application->recallObject('lang.current');
$format = $lang->GetDBField($regs[1]);
}
}
$value = $object->GetField($field, $format);
if( $this->SelectParam($params, 'negative') )
{
if(strpos($value, '-') === 0)
{
$value = substr($value, 1);
}
else
{
$value = '-'.$value;
}
}
if( $this->HasParam($params, 'currency') )
{
$value = $this->AddCurrencySymbol($value, $iso);
$params['no_special'] = 1;
}
}
if( !$this->HasParam($params, 'no_special') ) $value = htmlspecialchars($value);
if( getArrayValue($params,'checked' ) ) $value = ($value == ( isset($params['value']) ? $params['value'] : 1)) ? 'checked' : '';
if( isset($params['plus_or_as_label']) ) {
$value = substr($value, 0,1) == '+' ? substr($value, 1) : $this->Application->Phrase($value);
}
elseif( isset($params['as_label']) && $params['as_label'] ) $value = $this->Application->Phrase($value);
$first_chars = $this->SelectParam($params,'first_chars,cut_first');
if($first_chars)
{
- $needs_cut = strlen($value) > $first_chars;
- $value = extension_loaded('mbstring') ? mb_substr($value,0,$first_chars) : substr($value,0,$first_chars);
- if($needs_cut) $value .= ' ...';
+ $needs_cut = mb_strlen($value) > $first_chars;
+ $value = mb_substr($value, 0, $first_chars);
+ if ($needs_cut) $value .= ' ...';
}
if( getArrayValue($params,'nl2br' ) ) $value = nl2br($value);
if ($value != '') $this->Application->Parser->DataExists = true;
if( $this->HasParam($params, 'currency') )
{
//restoring value in original currency, for other Field tags to work properly
$object->SetDBField($field, $original);
}
return $value;
}
function SetField($params)
{
// <inp2:SetField field="Value" src=p:cust_{$custom_name}"/>
$object =& $this->getObject($params);
$dst_field = $this->SelectParam($params, 'name,field');
list($prefix_special, $src_field) = explode(':', $params['src']);
$src_object =& $this->Application->recallObject($prefix_special);
$object->SetDBField($dst_field, $src_object->GetDBField($src_field));
}
/**
* Checks if parameter is passed
* Note: works like Tag and line simple method too
*
* @param Array $params
* @param string $param_name
* @return bool
*/
function HasParam($params, $param_name = null)
{
if( !isset($param_name) )
{
$param_name = $this->SelectParam($params, 'name');
$params = $this->Application->Parser->Params;
}
$value = isset($params[$param_name]) ? $params[$param_name] : false;
return $value && ($value != '$'.$param_name);
}
function PhraseField($params)
{
$field_label = $this->Field($params);
$translation = $this->Application->Phrase( $field_label );
return $translation;
}
function Error($params)
{
$field = $this->SelectParam($params, 'name,field');
$object =& $this->getObject($params);
$msg = $object->GetErrorMsg($field, false);
return $msg;
}
function HasError($params)
{
if ($params['field'] == 'any')
{
$object =& $this->getObject($params);
$skip_fields = getArrayValue($params, 'except');
$skip_fields = $skip_fields ? explode(',', $skip_fields) : Array();
return $object->HasErrors($skip_fields);
}
else
{
$fields = $this->SelectParam($params, 'field,fields');
$fields = explode(',', $fields);
$res = false;
foreach($fields as $field)
{
$params['field'] = $field;
$res = $res || ($this->Error($params) != '');
}
return $res;
}
}
function ErrorWarning($params)
{
if (!isset($params['field'])) {
$params['field'] = 'any';
}
if ($this->HasError($params)) {
$params['prefix'] = $this->getPrefixSpecial();
return $this->Application->ParseBlock($params);
}
}
function IsRequired($params)
{
$field = $params['field'];
$object =& $this->getObject($params);;
$formatter_class = getArrayValue($object->Fields, $field, 'formatter');
if ($formatter_class == 'kMultiLanguage')
{
$formatter =& $this->Application->recallObject($formatter_class);
$field = $formatter->LangFieldName($field);
}
$options = $object->GetFieldOptions($field);
return getArrayValue($options,'required');
}
function FieldOption($params)
{
$object =& $this->getObject($params);;
$options = $object->GetFieldOptions($params['field']);
$ret = isset($options[$params['option']]) ? $options[$params['option']] : '';
if (isset($params['as_label']) && $params['as_label']) $ret = $this->Application->ReplaceLanguageTags($ret);
return $ret;
}
function PredefinedOptions($params)
{
$object =& $this->getObject($params);
$field = $params['field'];
$value = array_key_exists('value', $params) ? $params['value'] : $object->GetDBField($field);
$field_options = $object->GetFieldOptions($field);
if (!array_key_exists('options', $field_options) || !is_array($field_options['options'])) {
trigger_error('Options not defined for <strong>'.$object->Prefix.'</strong> field <strong>'.$field.'</strong>', E_USER_WARNING);
return '';
}
$options = $field_options['options'];
if ($this->HasParam($params, 'has_empty')) {
$empty_value = array_key_exists('empty_value', $params) ? $params['empty_value'] : '';
$options = array_merge_recursive2(Array ($empty_value => ''), $options); // don't use other array merge function, because they will reset keys !!!
}
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
$block_params['pass_params'] = 'true';
if (method_exists($object, 'EOL') && count($object->Records) == 0) {
// for drawing grid column filter
$block_params['field_name'] = '';
}
else {
$block_params['field_name'] = $this->InputName($params); // depricated (produces warning when used as grid filter), but used in Front-End (submission create), admin (submission view)
}
$selected_param_name = getArrayValue($params, 'selected_param');
if (!$selected_param_name) {
$selected_param_name = $params['selected'];
}
$selected = $params['selected'];
$o = '';
if ($this->HasParam($params, 'no_empty') && !getArrayValue($options, '')) {
// removes empty option, when present (needed?)
array_shift($options);
}
if (strpos($value, '|') !== false) {
// multiple checkboxes OR multiselect
$value = explode('|', substr($value, 1, -1) );
foreach ($options as $key => $val) {
$block_params['key'] = $key;
$block_params['option'] = $val;
$block_params[$selected_param_name] = ( in_array($key, $value) ? ' '.$selected : '');
$o .= $this->Application->ParseBlock($block_params, 1);
}
}
else {
// single selection radio OR checkboxes OR dropdown
foreach ($options as $key => $val) {
$block_params['key'] = $key;
$block_params['option'] = $val;
$block_params[$selected_param_name] = (strlen($key) == strlen($value) && ($key == $value) ? ' '.$selected : '');
$o .= $this->Application->ParseBlock($block_params, 1);
}
}
return $o;
}
function PredefinedSearchOptions($params)
{
$object =& $this->getObject($params);
/* @var $object kDBList */
$params['value'] = $this->SearchField($params);
$view_name = $this->Application->RecallVar($this->getPrefixSpecial().'_current_view');
$custom_filter = $this->Application->RecallPersistentVar($this->getPrefixSpecial().'_custom_filter.'.$view_name, ALLOW_DEFAULT_SETTINGS);
return $this->PredefinedOptions($params);
}
function Format($params)
{
$field = $this->SelectParam($params, 'name,field');
$object =& $this->getObject($params);
$options = $object->GetFieldOptions($field);
$format = $options[ $this->SelectParam($params, 'input_format') ? 'input_format' : 'format' ];
$formatter_class = getArrayValue($options,'formatter');
if ($formatter_class) {
$formatter =& $this->Application->recallObject($formatter_class);
$human_format = getArrayValue($params,'human');
$edit_size = getArrayValue($params,'edit_size');
$sample = getArrayValue($params,'sample');
if($sample)
{
return $formatter->GetSample($field, $options, $object);
}
elseif($human_format || $edit_size)
{
$format = $formatter->HumanFormat($format);
return $edit_size ? strlen($format) : $format;
}
}
return $format;
}
/**
* Returns grid padination information
* Can return links to pages
*
* @param Array $params
* @return mixed
*/
function PageInfo($params)
{
$object =& $this->GetList($params);
/* @var $object kDBList */
$type = $params['type'];
unset($params['type']); // remove parameters used only by current tag
$ret = '';
switch ($type) {
case 'current':
$ret = $object->Page;
break;
case 'total':
$ret = $object->GetTotalPages();
break;
case 'prev':
$ret = $object->Page > 1 ? $object->Page - 1 : false;
break;
case 'next':
$ret = $object->Page < $object->GetTotalPages() ? $object->Page + 1 : false;
break;
}
if ($ret && isset($params['as_link']) && $params['as_link']) {
unset($params['as_link']); // remove parameters used only by current tag
$params['page'] = $ret;
$current_page = $object->Page; // backup current page
$ret = $this->PageLink($params);
$this->Application->SetVar($object->getPrefixSpecial().'_Page', $current_page); // restore page
}
return $ret;
}
/**
* Print grid pagination using
* block names specified
*
* @param Array $params
* @return string
* @access public
*/
function PrintPages($params)
{
$list =& $this->GetList($params);
$prefix_special = $list->getPrefixSpecial();
$total_pages = $list->GetTotalPages();
if ($total_pages > 1) $this->Application->Parser->DataExists = true;
if($total_pages == 0) $total_pages = 1; // display 1st page as selected in case if we have no pages at all
$o = '';
// what are these 2 lines for?
$this->Application->SetVar($prefix_special.'_event','');
$this->Application->SetVar($prefix_special.'_id','');
$current_page = $list->Page; // $this->Application->RecallVar($prefix_special.'_Page');
$block_params = $this->prepareTagParams($params);
$split = ( isset($params['split'] ) ? $params['split'] : 10 );
$split_start = $current_page - ceil($split/2);
if ($split_start < 1){
$split_start = 1;
}
$split_end = $split_start + $split-1;
if ($split_end > $total_pages) {
$split_end = $total_pages;
$split_start = max($split_end - $split + 1, 1);
}
if ($current_page > 1){
$prev_block_params = $this->prepareTagParams();
if ($total_pages > $split){
$prev_block_params['page'] = max($current_page-$split, 1);
$prev_block_params['name'] = $this->SelectParam($params, 'prev_page_split_render_as,prev_page_split_block');
if ($prev_block_params['name']){
$o .= $this->Application->ParseBlock($prev_block_params, 1);
}
}
$prev_block_params['name'] = 'page';
$prev_block_params['page'] = $current_page-1;
$prev_block_params['name'] = $this->SelectParam($params, 'prev_page_render_as,block_prev_page,prev_page_block');
if ($prev_block_params['name']) {
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $current_page-1);
$o .= $this->Application->ParseBlock($prev_block_params, 1);
}
}
else {
if ( $no_prev_page_block = $this->SelectParam($params, 'no_prev_page_render_as,block_no_prev_page') ) {
$block_params['name'] = $no_prev_page_block;
$o .= $this->Application->ParseBlock($block_params, 1);
}
}
$separator_params['name'] = $this->SelectParam($params, 'separator_render_as,block_separator');
for ($i = $split_start; $i <= $split_end; $i++)
{
if ($i == $current_page) {
$block = $this->SelectParam($params, 'current_render_as,active_render_as,block_current,active_block');
}
else {
$block = $this->SelectParam($params, 'link_render_as,inactive_render_as,block_link,inactive_block');
}
$block_params['name'] = $block;
$block_params['page'] = $i;
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $i);
$o .= $this->Application->ParseBlock($block_params, 1);
if ($this->SelectParam($params, 'separator_render_as,block_separator')
&& $i < $split_end)
{
$o .= $this->Application->ParseBlock($separator_params, 1);
}
}
if ($current_page < $total_pages){
$next_block_params = $this->prepareTagParams();
$next_block_params['page']=$current_page+1;
$next_block_params['name'] = $this->SelectParam($params, 'next_page_render_as,block_next_page,next_page_block');
if ($next_block_params['name']){
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $current_page+1);
$o .= $this->Application->ParseBlock($next_block_params, 1);
}
if ($total_pages > $split){
$next_block_params['page']=min($current_page+$split, $total_pages);
$next_block_params['name'] = $this->SelectParam($params, 'next_page_split_render_as,next_page_split_block');
if ($next_block_params['name']){
$o .= $this->Application->ParseBlock($next_block_params, 1);
}
}
}
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $current_page);
return $o;
}
/**
* Print grid pagination using
* block names specified
*
* @param Array $params
* @return string
* @access public
*/
function PaginationBar($params)
{
return $this->PrintPages($params);
}
/**
* Returns field name (processed by kMultiLanguage formatter
* if required) and item's id from it's IDField or field required
*
* @param Array $params
* @return Array (id,field)
* @access private
*/
function prepareInputName($params)
{
$field = $this->SelectParam($params, 'name,field');
$object =& $this->getObject($params);
$formatter_class = getArrayValue($object->Fields, $field, 'formatter');
if ($formatter_class == 'kMultiLanguage')
{
$formatter =& $this->Application->recallObject($formatter_class);
/* @var $formatter kMultiLanguage */
$force_primary = isset($object->Fields[$field]['force_primary']) && $object->Fields[$field]['force_primary'];
$field = $formatter->LangFieldName($field, $force_primary);
}
$id_field = getArrayValue($params, 'IdField');
$id = $id_field ? $object->GetDBField($id_field) : $object->GetID();
return Array($id, $field);
}
/**
* Returns input field name to
* be placed on form (for correct
* event processing)
*
* @param Array $params
* @return string
* @access public
*/
function InputName($params)
{
list($id, $field) = $this->prepareInputName($params);
$ret = $this->getPrefixSpecial().'['.$id.']['.$field.']';
if( getArrayValue($params, 'as_preg') ) $ret = preg_quote($ret, '/');
return $ret;
}
/**
* Allows to override various field options through hidden fields with specific names in submit.
* This tag generates this special names
*
* @param Array $params
* @return string
* @author Alex
*/
function FieldModifier($params)
{
list($id, $field) = $this->prepareInputName($params);
$ret = 'field_modifiers['.$this->getPrefixSpecial().']['.$field.']['.$params['type'].']';
if( getArrayValue($params, 'as_preg') ) $ret = preg_quote($ret, '/');
if (isset($params['value'])) {
$object =& $this->getObject($params);
$field_modifiers[$field][$params['type']] = $params['value'];
$object->ApplyFieldModifiers($field_modifiers);
}
return $ret;
}
/**
* Returns index where 1st changable sorting field begins
*
* @return int
* @access private
*/
function getUserSortIndex()
{
$list_sortings = $this->Application->getUnitOption($this->Prefix, 'ListSortings');
$sorting_prefix = getArrayValue($list_sortings, $this->Special) ? $this->Special : '';
$user_sorting_start = 0;
if ( $forced_sorting = getArrayValue($list_sortings, $sorting_prefix, 'ForcedSorting') ) {
$user_sorting_start = count($forced_sorting);
}
return $user_sorting_start;
}
/**
* Returns order direction for given field
*
*
*
* @param Array $params
* @return string
* @access public
*/
function Order($params)
{
$field = $params['field'];
$user_sorting_start = $this->getUserSortIndex();
$list =& $this->GetList($params);
if ($list->GetOrderField($user_sorting_start) == $field)
{
return strtolower($list->GetOrderDirection($user_sorting_start));
}
elseif($list->GetOrderField($user_sorting_start+1) == $field)
{
return '2_'.strtolower($list->GetOrderDirection($user_sorting_start+1));
}
else
{
return 'no';
}
}
/**
* Get's information of sorting field at "pos" position,
* like sorting field name (type="field") or sorting direction (type="direction")
*
* @param Array $params
* @return mixed
*/
function OrderInfo($params)
{
$user_sorting_start = $this->getUserSortIndex() + --$params['pos'];
$list =& $this->GetList($params);
// $object =& $this->Application->recallObject( $this->getPrefixSpecial() );
if($params['type'] == 'field') return $list->GetOrderField($user_sorting_start);
if($params['type'] == 'direction') return $list->GetOrderDirection($user_sorting_start);
}
/**
* Checks if sorting field/direction matches passed field/direction parameter
*
* @param Array $params
* @return bool
*/
function IsOrder($params)
{
$params['type'] = isset($params['field']) ? 'field' : 'direction';
$value = $this->OrderInfo($params);
if( isset($params['field']) ) return $params['field'] == $value;
if( isset($params['direction']) ) return $params['direction'] == $value;
}
/**
* Returns list perpage
*
* @param Array $params
* @return int
*/
function PerPage($params)
{
$object =& $this->getObject($params);
return $object->PerPage;
}
/**
* Checks if list perpage matches value specified
*
* @param Array $params
* @return bool
*/
function PerPageEquals($params)
{
$object =& $this->getObject($params);
return $object->PerPage == $params['value'];
}
function SaveEvent($params)
{
// SaveEvent is set during OnItemBuild, but we may need it before any other tag calls OnItemBuild
$object =& $this->getObject($params);
return $this->Application->GetVar($this->getPrefixSpecial().'_SaveEvent');
}
function NextId($params)
{
$object =& $this->getObject($params);
$wid = $this->Application->GetTopmostWid($this->Prefix);
$session_name = rtrim($this->getPrefixSpecial().'_selected_ids_'.$wid, '_');
$ids = explode(',', $this->Application->RecallVar($session_name));
$cur_id = $object->GetID();
$i = array_search($cur_id, $ids);
if ($i !== false) {
return $i < count($ids) - 1 ? $ids[$i + 1] : '';
}
return '';
}
function PrevId($params)
{
$object =& $this->getObject($params);
$wid = $this->Application->GetTopmostWid($this->Prefix);
$session_name = rtrim($this->getPrefixSpecial().'_selected_ids_'.$wid, '_');
$ids = explode(',', $this->Application->RecallVar($session_name));
$cur_id = $object->GetID();
$i = array_search($cur_id, $ids);
if ($i !== false) {
return $i > 0 ? $ids[$i - 1] : '';
}
return '';
}
function IsSingle($params)
{
return ($this->NextId($params) === '' && $this->PrevId($params) === '');
}
function IsLast($params)
{
return ($this->NextId($params) === '');
}
function IsFirst($params)
{
return ($this->PrevId($params) === '');
}
/**
* Checks if field value is equal to proposed one
*
* @param Array $params
* @return bool
*/
function FieldEquals($params)
{
$object =& $this->getObject($params);
$ret = $object->GetDBField($this->SelectParam($params, 'name,field')) == $params['value'];
// if( getArrayValue($params,'inverse') ) $ret = !$ret;
return $ret;
}
function ItemIcon($params)
{
$object =& $this->getObject($params);
$grids = $this->Application->getUnitOption($this->Prefix,'Grids');
$icons =& $grids[ $params['grid'] ]['Icons'];
$key = '';
$status_fields = $this->Application->getUnitOption($this->Prefix,'StatusField');
if(!$status_fields) return $icons['default'];
foreach($status_fields as $status_field)
{
$key .= $object->GetDBField($status_field).'_';
}
$key = rtrim($key,'_');
$value = ($key !== false) ? $key : 'default';
return isset($icons[$value]) ? $icons[$value] : $icons['default'];
}
/**
* Generates bluebar title + initializes prefixes used on page
*
* @param Array $params
* @return string
*/
function SectionTitle($params)
{
$preset_name = replaceModuleSection($params['title_preset']);
$title_presets = $this->Application->getUnitOption($this->Prefix,'TitlePresets');
$title_info = getArrayValue($title_presets, $preset_name);
if ($title_info === false) {
$title = str_replace('#preset_name#', $preset_name, $params['title']);
if ($this->Application->ConfigValue('UseSmallHeader') && isset($params['group_title']) && $params['group_title']) {
$title .= ' - '.$params['group_title'];
}
return $title;
}
if (getArrayValue($title_presets,'default')) {
// use default labels + custom labels specified in preset used
$title_info = array_merge_recursive2($title_presets['default'], $title_info);
}
$title = $title_info['format'];
// 1. get objects in use for title construction
$objects = Array();
$object_status = Array();
$status_labels = Array();
$prefixes = getArrayValue($title_info,'prefixes');
$all_tag_params = getArrayValue($title_info,'tag_params');
if ($prefixes) {
// extract tag_perams passed directly to SectionTitle tag for specific prefix
foreach ($params as $tp_name => $tp_value) {
if (preg_match('/(.*)\[(.*)\]/', $tp_name, $regs)) {
$all_tag_params[ $regs[1] ][ $regs[2] ] = $tp_value;
unset($params[$tp_name]);
}
}
$tag_params = Array();
foreach ($prefixes as $prefix_special) {
$prefix_data = $this->Application->processPrefix($prefix_special);
$prefix_data['prefix_special'] = rtrim($prefix_data['prefix_special'],'.');
if ($all_tag_params) {
$tag_params = getArrayValue($all_tag_params, $prefix_data['prefix_special']);
if (!$tag_params) $tag_params = Array();
}
$tag_params = array_merge_recursive2($params, $tag_params);
$objects[ $prefix_data['prefix_special'] ] =& $this->Application->recallObject($prefix_data['prefix_special'], $prefix_data['prefix'], $tag_params);
$object_status[ $prefix_data['prefix_special'] ] = $objects[ $prefix_data['prefix_special'] ]->IsNewItem() ? 'new' : 'edit';
// a. set object's status field (adding item/editing item) for each object in title
if (getArrayValue($title_info[ $object_status[ $prefix_data['prefix_special'] ].'_status_labels' ],$prefix_data['prefix_special'])) {
$status_labels[ $prefix_data['prefix_special'] ] = $title_info[ $object_status[ $prefix_data['prefix_special'] ].'_status_labels' ][ $prefix_data['prefix_special'] ];
$title = str_replace('#'.$prefix_data['prefix_special'].'_status#', $status_labels[ $prefix_data['prefix_special'] ], $title);
}
// b. setting object's titlefield value (in titlebar ONLY) to default in case if object beeing created with no titlefield filled in
if ($object_status[ $prefix_data['prefix_special'] ] == 'new') {
$new_value = $this->getInfo( $objects[ $prefix_data['prefix_special'] ], 'titlefield' );
if(!$new_value && getArrayValue($title_info['new_titlefield'],$prefix_data['prefix_special']) ) $new_value = $this->Application->Phrase($title_info['new_titlefield'][ $prefix_data['prefix_special'] ]);
$title = str_replace('#'.$prefix_data['prefix_special'].'_titlefield#', $new_value, $title);
}
}
}
// 2. replace phrases if any found in format string
$title = $this->Application->ReplaceLanguageTags($title,false);
// 3. find and replace any replacement vars
preg_match_all('/#(.*_.*)#/Uis',$title,$rets);
if ($rets[1]) {
$replacement_vars = array_keys( array_flip($rets[1]) );
foreach ($replacement_vars as $replacement_var) {
$var_info = explode('_',$replacement_var,2);
$object =& $objects[ $var_info[0] ];
$new_value = $this->getInfo($object,$var_info[1]);
$title = str_replace('#'.$replacement_var.'#', $new_value, $title);
}
}
// replace trailing spaces inside title preset + '' occurences into single space
$title = preg_replace('/[ ]*\'\'[ ]*/', ' ', $title);
if ($this->Application->ConfigValue('UseSmallHeader') && isset($params['group_title']) && $params['group_title']) {
$title .= ' - '.$params['group_title'];
}
$cut_first = getArrayValue($params, 'cut_first');
- if ($cut_first && strlen($title) > $cut_first) {
+ if ($cut_first && mb_strlen($title) > $cut_first) {
if (!preg_match('/<a href="(.*)">(.*)<\/a>/',$title)) {
- $title = substr($title, 0, $cut_first).' ...';
+ $title = mb_substr($title, 0, $cut_first).' ...';
}
}
return $title;
}
function getInfo(&$object, $info_type)
{
switch ($info_type)
{
case 'titlefield':
$field = $this->Application->getUnitOption($object->Prefix,'TitleField');
return $field !== false ? $object->GetField($field) : 'TitleField Missing';
break;
case 'recordcount':
$of_phrase = $this->Application->Phrase('la_of');
return $object->NoFilterCount != $object->RecordsCount ? $object->RecordsCount.' '.$of_phrase.' '.$object->NoFilterCount : $object->RecordsCount;
break;
default:
return $object->GetField($info_type);
break;
}
}
function GridInfo($params)
{
$object =& $this->GetList($params);
/* @var $object kDBList */
switch ($params['type']) {
case 'filtered':
return $object->GetRecordsCount();
case 'total':
return $object->GetNoFilterCount();
case 'from':
return $object->RecordsCount ? $object->Offset+1 : 0; //0-based
case 'to':
return min($object->Offset + $object->PerPage, $object->RecordsCount);
case 'total_pages':
return $object->GetTotalPages();
case 'needs_pagination':
return ($object->RecordsCount > $object->PerPage) || ($object->Page > 1);
}
}
/**
* Parses block depending on its element type.
* For radio and select elements values are taken from 'value_list_field' in key1=value1,key2=value2
* format. key=value can be substituted by <SQL>SELECT f1 AS OptionName, f2 AS OptionValue... FROM <PREFIX>TableName </SQL>
* where prefix is TABLE_PREFIX
*
* @param Array $params
* @return string
*/
function ConfigFormElement($params)
{
$object =& $this->getObject($params);
$field = $params['field'];
$helper =& $this->Application->recallObject('InpCustomFieldsHelper');
$element_type = $object->GetDBField($params['element_type_field']);
if($element_type == 'label') $element_type = 'text';
$params['name'] = $params['blocks_prefix'].$element_type;
switch ($element_type) {
case 'select':
case 'multiselect':
case 'radio':
$field_options = $object->GetFieldOptions($field, 'options');
if ($object->GetDBField('DirectOptions')) {
// used for custom fields
$field_options['options'] = $object->GetDBField('DirectOptions');
}
else {
// used for configuration
$field_options['options'] = $helper->GetValuesHash( $object->GetDBField($params['value_list_field']) );
}
$object->SetFieldOptions($field, $field_options);
break;
case 'text':
case 'textarea':
$params['field_params'] = $helper->ParseConfigSQL($object->GetDBField($params['value_list_field']));
break;
case 'password':
case 'checkbox':
default:
break;
}
return $this->Application->ParseBlock($params, 1);
}
/**
* Get's requested custom field value
*
* @param Array $params
* @return string
* @access public
*/
function CustomField($params)
{
$params['name'] = 'cust_'.$this->SelectParam($params, 'name,field');
return $this->Field($params);
}
function CustomFieldLabel($params)
{
$object =& $this->getObject($params);
$field = $this->SelectParam($params, 'name,field');
$sql = 'SELECT FieldLabel
FROM '.$this->Application->getUnitOption('cf', 'TableName').'
WHERE FieldName = '.$this->Conn->qstr($field);
return $this->Application->Phrase($this->Conn->GetOne($sql));
}
/**
* transposes 1-dimensional array elements for vertical alignment according to given columns and per_page parameters
*
* @param array $arr
* @param int $columns
* @param int $per_page
* @return array
*/
function LinearToVertical(&$arr, $columns, $per_page)
{
$rows = $columns;
// in case if after applying per_page limit record count less then
// can fill requrested column count, then fill as much as we can
$cols = min(ceil($per_page / $columns), ceil(count($arr) / $columns));
$imatrix = array();
for ($row = 0; $row < $rows; $row++) {
for ($col = 0; $col < $cols; $col++) {
$source_index = $row * $cols + $col;
if (!isset($arr[$source_index])) {
// in case if source array element count is less then element count in one row
continue;
}
$imatrix[$col * $rows + $row] = $arr[$source_index];
}
}
ksort($imatrix);
return array_values($imatrix);
}
/**
* If data was modfied & is in TempTables mode, then parse block with name passed;
* remove modification mark if not in TempTables mode
*
* @param Array $params
* @return string
* @access public
* @author Alexey
*/
function SaveWarning($params)
{
$main_prefix = getArrayValue($params, 'main_prefix');
if ($main_prefix && $main_prefix != '$main_prefix') {
$top_prefix = $main_prefix;
}
else {
$top_prefix = $this->Application->GetTopmostPrefix($this->Prefix);
}
$temp_tables = substr($this->Application->GetVar($top_prefix.'_mode'), 0, 1) == 't';
$modified = $this->Application->RecallVar($top_prefix.'_modified');
if ($temp_tables && $modified) {
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $this->SelectParam($params, 'render_as,name');
$block_params['edit_mode'] = $temp_tables ? 1 : 0;
return $this->Application->ParseBlock($block_params);
}
$this->Application->RemoveVar($top_prefix.'_modified');
return '';
}
/**
* Returns list record count queries (on all pages)
*
* @param Array $params
* @return int
*/
function TotalRecords($params)
{
$list =& $this->GetList($params);
if (!$list->Counted) $list->CountRecs();
return $list->RecordsCount;
}
/**
* Range filter field name
*
* @param Array $params
* @return string
*/
function SearchInputName($params)
{
$field = $this->SelectParam($params, 'field,name');
$ret = 'custom_filters['.$this->getPrefixSpecial().']['.$params['grid'].']['.$field.']['.$params['filter_type'].']';
if (isset($params['type'])) {
$ret .= '['.$params['type'].']';
}
return $ret;
}
/**
* Return range filter field value
*
* @param Array $params
* @return string
*/
function SearchField($params) // RangeValue
{
$field = $this->SelectParam($params, 'field,name');
$view_name = $this->Application->RecallVar($this->getPrefixSpecial().'_current_view');
$custom_filter = $this->Application->RecallPersistentVar($this->getPrefixSpecial().'_custom_filter.'.$view_name, ALLOW_DEFAULT_SETTINGS);
$custom_filter = $custom_filter ? unserialize($custom_filter) : Array();
if (isset($custom_filter[ $params['grid'] ][$field])) {
$ret = $custom_filter[ $params['grid'] ][$field][ $params['filter_type'] ]['submit_value'];
if (isset($params['type'])) {
$ret = $ret[ $params['type'] ];
}
if( !$this->HasParam($params, 'no_special') ) $ret = htmlspecialchars($ret);
return $ret;
}
return '';
}
function SearchFormat($params)
{
$field = $params['field'];
$object =& $this->GetList($params);
$options = $object->GetFieldOptions($field);
$format = $options[ $this->SelectParam($params, 'input_format') ? 'input_format' : 'format' ];
$formatter_class = getArrayValue($options,'formatter');
if($formatter_class)
{
$formatter =& $this->Application->recallObject($formatter_class);
$human_format = getArrayValue($params,'human');
$edit_size = getArrayValue($params,'edit_size');
$sample = getArrayValue($params,'sample');
if($sample)
{
return $formatter->GetSample($field, $options, $object);
}
elseif($human_format || $edit_size)
{
$format = $formatter->HumanFormat($format);
return $edit_size ? strlen($format) : $format;
}
}
return $format;
}
/**
* Returns error of range field
*
* @param unknown_type $params
* @return unknown
*/
function SearchError($params)
{
$field = $this->SelectParam($params, 'field,name');
$error_var_name = $this->getPrefixSpecial().'_'.$field.'_error';
$pseudo = $this->Application->RecallVar($error_var_name);
if ($pseudo) {
$this->Application->RemoveVar($error_var_name);
}
$object =& $this->Application->recallObject($this->Prefix.'.'.$this->Special.'-item', null, Array('skip_autoload' => true));
/* @var $object kDBItem */
$object->SetError($field, $pseudo);
return $object->GetErrorMsg($field, false);
}
/**
* Returns templates path for module, which is gathered from prefix module
*
* @param Array $params
* @return string
* @author Alex
*/
function ModulePath($params)
{
$force_module = getArrayValue($params, 'module');
if ($force_module) {
if ($force_module == '#session#') {
$force_module = preg_replace('/([^:]*):.*/', '\1', $this->Application->RecallVar('module'));
if (!$force_module) $force_module = 'core';
}
else {
- $force_module = strtolower($force_module);
+ $force_module = mb_strtolower($force_module);
}
if ($force_module == 'core') {
$module_folder = 'core';
}
else {
$module_folder = trim( $this->Application->findModule('Name', $force_module, 'Path'), '/');
}
}
else {
$module_folder = $this->Application->getUnitOption($this->Prefix, 'ModuleFolder');
}
return '../../'.$module_folder.'/admin_templates/';
}
/**
* Returns object used in tag processor
*
* @access public
* @return kDBBase
*/
function &getObject($params = Array())
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
if (isset($params['requery']) && $params['requery']) {
$this->Application->HandleEvent($q_event, $this->getPrefixSpecial().':LoadItem');
}
return $object;
}
/**
* Checks if object propery value matches value passed
*
* @param Array $params
* @return bool
*/
function PropertyEquals($params)
{
$object =& $this->getObject($params);
$property_name = $this->SelectParam($params, 'name,var,property');
return $object->$property_name == $params['value'];
}
/**
* Group list records by header, saves internal order in group
*
* @param Array $records
* @param string $heading_field
*/
function groupRecords(&$records, $heading_field)
{
$sorted = Array();
$i = 0; $record_count = count($records);
while ($i < $record_count) {
$sorted[ $records[$i][$heading_field] ][] = $records[$i];
$i++;
}
$records = Array();
foreach ($sorted as $heading => $heading_records) {
$records = array_merge_recursive($records, $heading_records);
}
}
function DisplayOriginal($params)
{
return false;
}
function MultipleEditing($params)
{
$wid = $this->Application->GetTopmostWid($this->Prefix);
$session_name = rtrim($this->getPrefixSpecial().'_selected_ids_'.$wid, '_');
$selected_ids = explode(',', $this->Application->RecallVar($session_name));
$ret = '';
if ($selected_ids) {
$selected_ids = explode(',', $selected_ids);
$object =& $this->getObject( array_merge_recursive2($params, Array('skip_autoload' => true)) );
$params['name'] = $params['render_as'];
foreach ($selected_ids as $id) {
$object->Load($id);
$ret .= $this->Application->ParseBlock($params);
}
}
return $ret;
}
function ExportStatus($params)
{
$export_object =& $this->Application->recallObject('CatItemExportHelper');
$event = new kEvent($this->getPrefixSpecial().':OnDummy');
$action_method = 'perform'.ucfirst($this->Special);
$field_values = $export_object->$action_method($event);
// finish code is done from JS now
if ($field_values['start_from'] >= $field_values['total_records'])
{
if ($this->Special == 'import') {
$this->Application->StoreVar('PermCache_UpdateRequired', 1);
$this->Application->Redirect('in-portal/categories/cache_updater', Array('m_opener' => 'r', 'pass' => 'm', 'continue' => 1, 'no_amp' => 1));
}
elseif ($this->Special == 'export') {
$finish_t = $this->Application->RecallVar('export_finish_t');
$this->Application->Redirect($finish_t, Array('pass' => 'all'));
$this->Application->RemoveVar('export_finish_t');
}
}
$export_options = $export_object->loadOptions($event);
return $export_options['start_from'] * 100 / $export_options['total_records'];
}
/**
* Returns path where exported category items should be saved
*
* @param Array $params
*/
function ExportPath($params)
{
$ret = EXPORT_PATH.'/';
if( getArrayValue($params, 'as_url') )
{
$ret = str_replace( FULL_PATH.'/', $this->Application->BaseURL(), $ret);
}
$export_options = unserialize($this->Application->RecallVar($this->getPrefixSpecial().'_options'));
$ret .= $export_options['ExportFilename'].'.'.($export_options['ExportFormat'] == 1 ? 'csv' : 'xml');
return $ret;
}
function FieldTotal($params)
{
$list =& $this->GetList($params);
return $list->GetFormattedTotal($this->SelectParam($params, 'field,name'), $params['function']);
}
function FCKEditor($params) {
$params['no_special'] = 1;
$value = $this->Field($params);
$name = $this->InputName($params);
- $theme_path = $this->Application->BaseURL().substr($this->Application->GetFrontThemePath(), 1);
+ $theme_path = $this->Application->BaseURL().mb_substr($this->Application->GetFrontThemePath(), 1);
$bgcolor = isset($params['bgcolor']) ? $params['bgcolor'] : $this->Application->GetVar('bgcolor');
if (!$bgcolor) $bgcolor = '#ffffff';
include_once(FULL_PATH.'/core/cmseditor/fckeditor.php');
$oFCKeditor = new FCKeditor($name);
$oFCKeditor->BasePath = BASE_PATH.'/core/cmseditor/';
$oFCKeditor->Width = $params['width'] ;
$oFCKeditor->Height = $params['height'] ;
$oFCKeditor->ToolbarSet = 'Advanced' ;
$oFCKeditor->Value = $value ;
$oFCKeditor->Config = Array(
//'UserFilesPath' => $pathtoroot.'kernel/user_files',
'ProjectPath' => BASE_PATH.'/',
'CustomConfigurationsPath' => $this->Application->BaseURL().'core/admin_templates/js/inp_fckconfig.js',
'StylesXmlPath' => $theme_path.'/inc/styles.xml',
'EditorAreaCSS' => $theme_path.'/inc/style.css',
'DefaultClass' => 'Default Text',
// 'Debug' => 1,
'Admin' => 1,
'K4' => 1,
'newBgColor' => $bgcolor,
);
return $oFCKeditor->CreateHtml();
}
function IsNewItem($params)
{
$object =& $this->getObject($params);
return $object->IsNewItem();
}
/**
* Creates link to an item including only it's id
*
* @param Array $params
* @return string
*/
function ItemLink($params)
{
$object =& $this->getObject($params);
if (!isset($params['pass'])) {
$params['pass'] = 'm';
}
$params[$object->getPrefixSpecial().'_id'] = $object->GetID();
$m =& $this->Application->recallObject('m_TagProcessor');
return $m->t($params);
}
function PresetFormFields($params)
{
$prefix = $this->getPrefixSpecial();
if (!$this->Application->GetVar($prefix.'_event')) {
$this->Application->HandleEvent(new kEvent($prefix.':OnNew'));
}
}
function PrintSerializedFields($params)
{
$object =& $this->getObject();
$field = $this->SelectParam($params, 'field');
$data = unserialize($object->GetDBField($field));
$o = '';
$std_params['name'] = $params['render_as'];
$std_params['field'] = $params['field'];
$std_params['pass_params'] = true;
foreach ($data as $key => $row) {
$block_params = array_merge($std_params, $row, array('key'=>$key));
$o .= $this->Application->ParseBlock($block_params);
}
return $o;
}
/**
* Checks if current prefix is main item
*
* @param Array $params
* @return bool
*/
function IsTopmostPrefix($params)
{
return $this->Prefix == $this->Application->GetTopmostPrefix($this->Prefix);
}
function PermSection($params)
{
$section = $this->SelectParam($params, 'section,name');
$perm_sections = $this->Application->getUnitOption($this->Prefix, 'PermSection');
return isset($perm_sections[$section]) ? $perm_sections[$section] : '';
}
function PerPageSelected($params)
{
$list =& $this->GetList($params);
return $list->PerPage == $params['per_page'] ? $params['selected'] : '';
}
/**
* Returns prefix + generated sepcial + any word
*
* @param Array $params
* @return string
*/
function VarName($params)
{
$list =& $this->GetList($params);
return $list->getPrefixSpecial().'_'.$params['type'];
}
/**
* Returns edit tabs by specified preset name or false in case of error
*
* @param string $preset_name
* @return mixed
*/
function getEditTabs($preset_name)
{
$presets = $this->Application->getUnitOption($this->Prefix, 'EditTabPresets');
if (!$presets || !isset($presets[$preset_name]) || count($presets[$preset_name]) == 0) {
return false;
}
return $presets[$preset_name];
}
/**
* Detects if specified preset has tabs in it
*
* @param Array $params
* @return bool
*/
function HasEditTabs($params)
{
return $this->getEditTabs($params['preset_name']) ? true : false;
}
/**
* Sorts edit tabs based on their priority
*
* @param Array $tab_a
* @param Array $tab_b
* @return int
*/
function sortEditTabs($tab_a, $tab_b)
{
if ($tab_a['priority'] == $tab_b['priority']) {
return 0;
}
return $tab_a['priority'] < $tab_b['priority'] ? -1 : 1;
}
/**
* Prints edit tabs based on preset name specified
*
* @param Array $params
* @return string
*/
function PrintEditTabs($params)
{
$edit_tabs = $this->getEditTabs($params['preset_name']);
if (!$edit_tabs) {
return ;
}
usort($edit_tabs, Array (&$this, 'sortEditTabs'));
$ret = '';
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $params['render_as'];
foreach ($edit_tabs as $tab_info) {
$block_params['title'] = $tab_info['title'];
$block_params['template'] = $tab_info['t'];
$ret .= $this->Application->ParseBlock($block_params);
}
return $ret;
}
/**
* Performs image resize to required dimensions and returns resulting url (cached resized image)
*
* @param Array $params
* @return string
*/
function ImageSrc($params)
{
$max_width = isset($params['MaxWidth']) ? $params['MaxWidth'] : false;
$max_height = isset($params['MaxHeight']) ? $params['MaxHeight'] : false;
$logo_filename = isset($params['LogoFilename']) ? $params['LogoFilename'] : false;
$logo_h_margin = isset($params['LogoHMargin']) ? $params['LogoHMargin'] : false;
$logo_v_margin = isset($params['LogoVMargin']) ? $params['LogoVMargin'] : false;
$object =& $this->getObject($params);
$field = $this->SelectParam($params, 'name,field');
return $object->GetField($field, 'resize:'.$max_width.'x'.$max_height.';wm:'.$logo_filename.'|'.$logo_h_margin.'|'.$logo_v_margin);
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/db/db_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.97.2.18
\ No newline at end of property
+1.97.2.19
\ No newline at end of property
Index: branches/RC/core/kernel/db/dbitem.php
===================================================================
--- branches/RC/core/kernel/db/dbitem.php (revision 10097)
+++ branches/RC/core/kernel/db/dbitem.php (revision 10098)
@@ -1,1060 +1,1060 @@
<?php
/**
* DBItem
*
* Desciption
* @package kernel4
*/
class kDBItem extends kDBBase {
/**
* Description
*
* @var array Associative array of current item' field values
* @access public
*/
var $FieldValues;
/**
* Unformatted field values, before parse
*
* @var Array
* @access private
*/
var $DirtyFieldValues = Array();
/**
* Holds item values after loading (not affected by submit)
*
* @var Array
* @access private
*/
var $OriginalFieldValues = Array ();
var $FieldErrors;
var $ErrorMsgs = Array();
/**
* If set to true, Update will skip Validation before running
*
* @var array Associative array of current item' field values
* @access public
*/
var $IgnoreValidation = false;
var $Loaded = false;
/**
* Holds item' primary key value
*
* @var int Value of primary key field for current item
* @access public
*/
var $ID;
function kDBItem()
{
parent::kDBBase();
$this->ErrorMsgs['required'] = '!la_err_required!'; //'Field is required';
$this->ErrorMsgs['unique'] = '!la_err_unique!'; //'Field value must be unique';
$this->ErrorMsgs['value_out_of_range'] = '!la_err_value_out_of_range!'; //'Field is out of range, possible values from %s to %s';
$this->ErrorMsgs['length_out_of_range'] = '!la_err_length_out_of_range!'; //'Field is out of range';
$this->ErrorMsgs['bad_type'] = '!la_err_bad_type!'; //'Incorrect data format, please use %s';
$this->ErrorMsgs['invalid_format'] = '!la_err_invalid_format!'; //'Incorrect data format, please use %s';
$this->ErrorMsgs['bad_date_format'] = '!la_err_bad_date_format!'; //'Incorrect date format, please use (%s) ex. (%s)';
$this->ErrorMsgs['primary_lang_required'] = '!la_err_primary_lang_required!';
}
function SetDirtyField($field_name, $field_value)
{
$this->DirtyFieldValues[$field_name] = $field_value;
}
function GetDirtyField($field_name)
{
return $this->DirtyFieldValues[$field_name];
}
function GetOriginalField($field_name)
{
return $this->OriginalFieldValues[$field_name];
}
/**
* Sets original field value (useful for custom virtual fields)
*
* @param string $field_name
*/
function SetOriginalField($field_name, $field_value)
{
$this->OriginalFieldValues[$field_name] = $field_value;
}
/**
* Set's default values for all fields
*
* @param bool $populate_ml_fields create all ml fields from db in config or not
*
* @access public
*/
function SetDefaultValues($populate_ml_fields = false)
{
parent::SetDefaultValues($populate_ml_fields);
if ($populate_ml_fields) {
$this->PopulateMultiLangFields();
}
foreach ($this->Fields as $field => $params) {
if ( isset($params['default']) ) {
$this->SetDBField($field, $params['default']);
}
else {
$this->SetDBField($field, NULL);
}
}
}
/**
* Sets current item field value
* (applies formatting)
*
* @access public
* @param string $name Name of the field
* @param mixed $value Value to set the field to
* @return void
*/
function SetField($name,$value)
{
$options = $this->GetFieldOptions($name);
$parsed = $value;
if ($value == '') {
$parsed = NULL;
}
// kFormatter is always used, to make sure, that numeric value is converted to normal representation
// according to regional format, even when formatter is not set (try seting format to 1.234,56 to understand why)
$formatter =& $this->Application->recallObject(isset($options['formatter']) ? $options['formatter'] : 'kFormatter');
$parsed = $formatter->Parse($value, $name, $this);
$this->SetDBField($name,$parsed);
}
/**
* Sets current item field value
* (doesn't apply formatting)
*
* @access public
* @param string $name Name of the field
* @param mixed $value Value to set the field to
* @return void
*/
function SetDBField($name,$value)
{
$this->FieldValues[$name] = $value;
/*if (isset($this->Fields[$name]['formatter'])) {
$formatter =& $this->Application->recallObject($this->Fields[$name]['formatter']);
$formatter->UpdateSubFields($name, $value, $this->Fields[$name], $this);
}*/
}
/**
* Set's field error, if pseudo passed not found then create it with message text supplied.
* Don't owerrite existing pseudo translation.
*
* @param string $field
* @param string $pseudo
* @param string $error_label
*/
function SetError($field, $pseudo, $error_label = null, $error_params = null)
{
$error_field = isset($this->Fields[$field]['error_field']) ? $this->Fields[$field]['error_field'] : $field;
if (isset($this->FieldErrors[$error_field]['pseudo'])) {
// don't set more then one error on field
return ;
}
$this->FieldErrors[$error_field]['pseudo'] = $pseudo;
if (isset($error_params)) {
// additional params, that helps to determine error sources
$this->FieldErrors[$error_field]['params'] = $error_params;
}
if (isset($error_label) && !isset($this->ErrorMsgs[$pseudo])) {
// label for error (only when not already set)
$this->ErrorMsgs[$pseudo] = (substr($error_label, 0, 1) == '+') ? substr($error_label, 1) : '!'.$error_label.'!';
}
}
/**
* Return current item' field value by field name
* (doesn't apply formatter)
*
* @access public
* @param string $name field name to return
* @return mixed
*/
function GetDBField($name)
{
return $this->FieldValues[$name];
}
function HasField($name)
{
return isset($this->FieldValues[$name]);
}
function GetFieldValues()
{
return $this->FieldValues;
}
/**
* Sets item' fields corresponding to elements in passed $hash values.
*
* The function sets current item fields to values passed in $hash, by matching $hash keys with field names
* of current item. If current item' fields are unknown {@link kDBItem::PrepareFields()} is called before acutally setting the fields
*
* @access public
* @param Array $hash
* @param Array $set_fields Optional param, field names in target object to set, other fields will be skipped
* @return void
*/
function SetFieldsFromHash($hash, $set_fields=null)
{
// used in formatter which work with multiple fields together
foreach($hash as $field_name => $field_value)
{
if( eregi("^[0-9]+$", $field_name) || !array_key_exists($field_name,$this->Fields) ) continue;
if ( is_array($set_fields) && !in_array($field_name, $set_fields) ) continue;
$this->SetDirtyField($field_name, $field_value);
}
// formats all fields using associated formatters
foreach ($hash as $field_name => $field_value)
{
if( eregi("^[0-9]+$", $field_name) || !array_key_exists($field_name,$this->Fields) ) continue;
if ( is_array($set_fields) && !in_array($field_name, $set_fields) ) continue;
$this->SetField($field_name,$field_value);
}
}
function SetDBFieldsFromHash($hash, $set_fields=null)
{
foreach ($hash as $field_name => $field_value)
{
if( eregi("^[0-9]+$", $field_name) || !array_key_exists($field_name,$this->Fields) ) continue;
if ( is_array($set_fields) && !in_array($field_name, $set_fields) ) continue;
$this->SetDBField($field_name, $field_value);
}
}
/**
* Returns part of SQL WHERE clause identifing the record, ex. id = 25
*
* @access public
* @param string $method Child class may want to know who called GetKeyClause, Load(), Update(), Delete() send its names as method
* @param Array $keys_hash alternative, then item id, keys hash to load item by
* @return void
* @see kDBItem::Load()
* @see kDBItem::Update()
* @see kDBItem::Delete()
*/
function GetKeyClause($method=null, $keys_hash = null)
{
if( !isset($keys_hash) ) $keys_hash = Array($this->IDField => $this->ID);
$ret = '';
foreach($keys_hash as $field => $value)
{
if (!preg_match('/\./', $field)) {
$ret .= '(`'.$this->TableName.'`.'.$field.' = '.$this->Conn->qstr($value).') AND ';
}
else {
$ret .= '('.$field.' = '.$this->Conn->qstr($value).') AND ';
}
}
return preg_replace('/(.*) AND $/', '\\1', $ret);
}
/**
* Loads item from the database by given id
*
* @access public
* @param mixed $id item id of keys->values hash to load item by
* @param string $id_field_name Optional parameter to load item by given Id field
* @return bool True if item has been loaded, false otherwise
*/
function Load($id, $id_field_name = null)
{
if ( isset($id_field_name) ) $this->SetIDField( $id_field_name );
$keys_sql = '';
if( is_array($id) )
{
$keys_sql = $this->GetKeyClause('load', $id);
}
else
{
$this->setID($id);
$keys_sql = $this->GetKeyClause('load');
}
if ( isset($id_field_name) ) $this->setIDField( $this->Application->getUnitOption($this->Prefix, 'IDField') );
if( ($id === false) || !$keys_sql ) return $this->Clear();
if( !$this->raiseEvent('OnBeforeItemLoad', $id) ) return false;
$q = $this->GetSelectSQL().' WHERE '.$keys_sql;
$field_values = $this->Conn->GetRow($q);
if($field_values)
{
$this->FieldValues = array_merge_recursive2($this->FieldValues, $field_values);
$this->OriginalFieldValues = $this->FieldValues;
}
else {
return $this->Clear();
}
if( is_array($id) || isset($id_field_name) ) $this->setID( $this->FieldValues[$this->IDField] );
$this->UpdateFormattersSubFields(); // used for updating separate virtual date/time fields from DB timestamp (for example)
$this->raiseEvent('OnAfterItemLoad', $this->GetID() );
$this->Loaded = true;
return true;
}
/**
* Builds select sql, SELECT ... FROM parts only
*
* @access public
* @return string
*/
function GetSelectSQL()
{
$sql = $this->addCalculatedFields($this->SelectClause);
return parent::GetSelectSQL($sql);
}
function UpdateFormattersMasterFields()
{
foreach ($this->Fields as $field => $options) {
if (isset($options['formatter'])) {
$formatter =& $this->Application->recallObject($options['formatter']);
$formatter->UpdateMasterFields($field, $this->GetDBField($field), $options, $this);
}
}
}
function SkipField($field_name, $force_id=false)
{
$skip = false;
$skip = $skip || ( isset($this->VirtualFields[$field_name]) ); //skipping 'virtual' field
$skip = $skip || ( !getArrayValue($this->FieldValues, $field_name) && getArrayValue($this->Fields[$field_name], 'skip_empty') ); //skipping marked field with 'skip_empty'
// $skip = $skip || ($field_name == $this->IDField && !$force_id); //skipping Primary Key
// $table_name = preg_replace("/^(.*)\./", "$1", $field_name);
// $skip = $skip || ($table_name && ($table_name != $this->TableName)); //skipping field from other tables
$skip = $skip || ( !isset($this->Fields[$field_name]) ); //skipping field not in Fields (nor virtual, nor real)
return $skip;
}
/**
* Updates previously loaded record with current item' values
*
* @access public
* @param int Primery Key Id to update
* @return bool
*/
function Update($id=null, $system_update=false)
{
if( isset($id) ) $this->setID($id);
if( !$this->raiseEvent('OnBeforeItemUpdate') ) return false;
if( !isset($this->ID) ) return false;
// Validate before updating
if( !$this->IgnoreValidation && !$this->Validate() ) return false;
if( !$this->raiseEvent('OnAfterItemValidate') ) return false;
//Nothing to update
if(!$this->FieldValues) return true;
$sql = sprintf('UPDATE %s SET ',$this->TableName);
foreach ($this->FieldValues as $field_name => $field_value)
{
if ($this->SkipField($field_name)) continue;
$real_field_name = eregi_replace("^.*\.", '',$field_name); //removing table names from field names
//Adding part of SET clause for current field, escaping data with ADODB' qstr
if (is_null( $this->FieldValues[$field_name] )) {
if (isset($this->Fields[$field_name]['not_null']) && $this->Fields[$field_name]['not_null']) {
$sql .= '`'.$real_field_name.'` = '.$this->Conn->qstr($this->Fields[$field_name]['default']).', ';
}
else {
$sql .= '`'.$real_field_name.'` = NULL, ';
}
}
else {
$sql.= sprintf('`%s`=%s, ', $real_field_name, $this->Conn->qstr($this->FieldValues[$field_name], 0));
}
}
$sql = ereg_replace(", $", '', $sql); //Removing last comma and space
$sql.= sprintf(' WHERE %s', $this->GetKeyClause('update')); //Adding WHERE clause with Primary Key
if( $this->Conn->ChangeQuery($sql) === false ) return false;
$affected = $this->Conn->getAffectedRows();
if (!$system_update && $affected == 1){
$this->setModifiedFlag();
}
$this->saveCustomFields();
$this->raiseEvent('OnAfterItemUpdate');
$this->Loaded = true;
if ($this->mode != 't') {
$this->Application->resetCounters($this->TableName);
}
return true;
}
function ValidateField($field)
{
$options = $this->Fields[$field];
/*if (isset($options['formatter'])) {
$formatter =& $this->Application->recallObject($options['formatter']);
$formatter->UpdateMasterFields($field, $this->GetDBField($field), $options, $this);
}*/
$error_field = isset($options['error_field']) ? $options['error_field'] : $field;
$res = !isset($this->FieldErrors[$error_field]['pseudo']) || !$this->FieldErrors[$error_field]['pseudo'];
$res = $res && $this->ValidateType($field, $options);
$res = $res && $this->ValidateRange($field, $options);
$res = $res && $this->ValidateUnique($field, $options);
$res = $res && $this->ValidateRequired($field, $options);
$res = $res && $this->CustomValidation($field, $options);
return $res;
}
/**
* Validate all item fields based on
* constraints set in each field options
* in config
*
* @return bool
* @access private
*/
function Validate()
{
$this->UpdateFormattersMasterFields(); //order is critical - should be called BEFORE checking errors
$global_res = true;
foreach ($this->Fields as $field => $params) {
$res = $this->ValidateField($field);
$global_res = $global_res && $res;
}
if (!$global_res && $this->Application->isDebugMode()) {
$error_msg = ' Validation failed in prefix <strong>'.$this->Prefix.'</strong>,
FieldErrors follow (look at items with <strong>"pseudo"</strong> key set)<br />
You may ignore this notice if submitted data really has a validation error';
trigger_error(trim($error_msg), E_USER_NOTICE);
$this->Application->Debugger->dumpVars($this->FieldErrors);
}
return $global_res;
}
/**
* Check field value by user-defined alghoritm
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
*/
function CustomValidation($field, $params)
{
return true;
}
/**
* Check if item has errors
*
* @param Array $skip_fields fields to skip during error checking
* @return bool
*/
function HasErrors($skip_fields)
{
$global_res = false;
foreach ($this->Fields as $field => $field_params) {
// If Formatter has set some error messages during values parsing
if ( !( in_array($field, $skip_fields) ) &&
isset($this->FieldErrors[$field]['pseudo']) && $this->FieldErrors[$field] != '') {
$global_res = true;
}
}
return $global_res;
}
/**
* Check if value in field matches field type specified in config
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
*/
function ValidateType($field, $params)
{
$res = true;
$val = $this->FieldValues[$field];
if ( $val != '' &&
isset($params['type']) &&
preg_match("#int|integer|double|float|real|numeric|string#", $params['type'])
) {
if ($params['type'] == 'numeric') {
trigger_error('Invalid field type <strong>'.$params['type'].'</strong> (in ValidateType method), please use <strong>float</strong> instead', E_USER_NOTICE);
$params['type'] = 'float';
}
$res = is_numeric($val);
if ($params['type']=='string' || $res) {
$f = 'is_'.$params['type'];
settype($val, $params['type']);
$res = $f($val) && ($val == $this->FieldValues[$field]);
}
if (!$res) {
$this->SetError($field, 'bad_type', null, $params['type']);
}
}
return $res;
}
/**
* Check if value is set for required field
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateRequired($field, $params)
{
$res = true;
if (isset($params['required']) && $params['required']) {
$check_value = $this->FieldValues[$field];
if ($this->Application->ConfigValue('TrimRequiredFields')) {
$check_value = trim($check_value);
}
$res = ((string)$check_value != '');
}
$options = $this->GetFieldOptions($field);
if (!$res && getArrayValue($options, 'formatter') != 'kUploadFormatter') {
$this->SetError($field, 'required');
}
return $res;
}
/**
* Validates that current record has unique field combination among other table records
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateUnique($field, $params)
{
$res = true;
$unique_fields = getArrayValue($params,'unique');
if($unique_fields !== false)
{
$where = Array();
array_push($unique_fields,$field);
foreach($unique_fields as $unique_field)
{
// if field is not empty or if it is required - we add where condition
if ($this->GetDBField($unique_field) != '' || (isset($this->Fields[$unique_field]['required']) && $this->Fields[$unique_field]['required'])) {
$where[] = '`'.$unique_field.'` = '.$this->Conn->qstr( $this->GetDBField($unique_field) );
}
}
// This can ONLY happen if all unique fields are empty and not required.
// In such case we return true, because if unique field is not required there may be numerous empty values
if (!$where) return true;
$sql = 'SELECT COUNT(*) FROM %s WHERE ('.implode(') AND (',$where).') AND ('.$this->IDField.' <> '.(int)$this->ID.')';
$res_temp = $this->Conn->GetOne( str_replace('%s', $this->TableName, $sql) );
$current_table_only = getArrayValue($params, 'current_table_only'); // check unique record only in current table
$res_live = $current_table_only ? 0 : $this->Conn->GetOne( str_replace('%s', $this->Application->GetLiveName($this->TableName), $sql) );
$res = ($res_temp == 0) && ($res_live == 0);
if (!$res) {
$this->SetError($field, 'unique');
}
}
return $res;
}
/**
* Check if field value is in range specified in config
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateRange($field, $params)
{
$res = true;
$val = $this->FieldValues[$field];
if ( isset($params['type']) && preg_match("#int|integer|double|float|real#", $params['type']) && strlen($val) > 0 ) {
if ( isset($params['max_value_inc'])) {
$res = $res && $val <= $params['max_value_inc'];
$max_val = $params['max_value_inc'].' (inclusive)';
}
if ( isset($params['min_value_inc'])) {
$res = $res && $val >= $params['min_value_inc'];
$min_val = $params['min_value_inc'].' (inclusive)';
}
if ( isset($params['max_value_exc'])) {
$res = $res && $val < $params['max_value_exc'];
$max_val = $params['max_value_exc'].' (exclusive)';
}
if ( isset($params['min_value_exc'])) {
$res = $res && $val > $params['min_value_exc'];
$min_val = $params['min_value_exc'].' (exclusive)';
}
}
if (!$res) {
if ( !isset($min_val) ) $min_val = '-&infin;';
if ( !isset($max_val) ) $max_val = '&infin;';
$this->SetError($field, 'value_out_of_range', null, Array ($min_val, $max_val));
return $res;
}
if ( isset($params['max_len'])) {
- $res = $res && strlen($val) <= $params['max_len'];
+ $res = $res && mb_strlen($val) <= $params['max_len'];
}
if ( isset($params['min_len'])) {
- $res = $res && strlen($val) >= $params['min_len'];
+ $res = $res && mb_strlen($val) >= $params['min_len'];
}
if (!$res) {
$error_params = Array (getArrayValue($params, 'min_len'), getArrayValue($params, 'max_len'));
$this->SetError($field, 'length_out_of_range', null, $error_params);
return $res;
}
return $res;
}
/**
* Return error message for field
*
* @param string $field
* @return string
* @access public
*/
function GetErrorMsg($field, $force_escape = null)
{
if( !isset($this->FieldErrors[$field]) ) return '';
$err = getArrayValue($this->FieldErrors[$field], 'pseudo');
if (!$err) return '';
// if special error msg defined in config
if( isset($this->Fields[$field]['error_msgs'][$err]) )
{
$msg = $this->Fields[$field]['error_msgs'][$err];
}
else //fall back to defaults
{
if( !isset($this->ErrorMsgs[$err]) ) {
trigger_error('No user message is defined for pseudo error <b>'.$err.'</b><br>', E_USER_WARNING);
return $err; //return the pseudo itself
}
$msg = $this->ErrorMsgs[$err];
}
$msg = $this->Application->ReplaceLanguageTags($msg, $force_escape);
if ( isset($this->FieldErrors[$field]['params']) )
{
return vsprintf($msg, $this->FieldErrors[$field]['params']);
}
return $msg;
}
/**
* Creates a record in the database table with current item' values
*
* @param mixed $force_id Set to TRUE to force creating of item's own ID or to value to force creating of passed id. Do not pass 1 for true, pass exactly TRUE!
* @access public
* @return bool
*/
function Create($force_id=false, $system_create=false)
{
if( !$this->raiseEvent('OnBeforeItemCreate') ) return false;
// Validating fields before attempting to create record
if( !$this->IgnoreValidation && !$this->Validate() ) return false;
if( !$this->raiseEvent('OnAfterItemValidate') ) return false;
if (is_int($force_id)) {
$this->FieldValues[$this->IDField] = $force_id;
}
elseif (!$force_id || !is_bool($force_id)) {
$this->FieldValues[$this->IDField] = $this->generateID();
}
$fields_sql = '';
$values_sql = '';
foreach ($this->FieldValues as $field_name => $field_value) {
if ($this->SkipField($field_name, $force_id)) continue;
//Adding field' value to Values block of Insert statement, escaping it with qstr
if (is_null( $this->FieldValues[$field_name] )) {
if (isset($this->Fields[$field_name]['not_null']) && $this->Fields[$field_name]['not_null']) {
$values_sql .= $this->Conn->qstr($this->Fields[$field_name]['default'], 0);
}
else {
$values_sql .= 'NULL';
}
}
else {
if ($field_name == $this->IDField && $this->FieldValues[$field_name] == 0) {
$values_sql .= 'DEFAULT';
}
else {
$values_sql .= $this->Conn->qstr($this->FieldValues[$field_name], 0);
}
}
$fields_sql .= '`'.$field_name.'`, '; //Adding field name to fields block of Insert statement
$values_sql .= ', ';
}
//Cutting last commas and spaces
$fields_sql = ereg_replace(", $", '', $fields_sql);
$values_sql = ereg_replace(", $", '', $values_sql);
$sql = sprintf('INSERT INTO %s (%s) VALUES (%s)', $this->TableName, $fields_sql, $values_sql); //Formatting query
//Executing the query and checking the result
if ($this->Conn->ChangeQuery($sql) === false) return false;
$insert_id = $this->Conn->getInsertID();
if ($insert_id == 0) {
// insert into temp table (id is not auto-increment field)
$insert_id = $this->FieldValues[$this->IDField];
}
$this->setID($insert_id);
if (!$system_create){
$this->setModifiedFlag();
}
$this->saveCustomFields();
if ($this->mode != 't') {
$this->Application->resetCounters($this->TableName);
}
$this->raiseEvent('OnAfterItemCreate');
$this->Loaded = true;
return true;
}
/**
* Deletes the record from databse
*
* @access public
* @return bool
*/
function Delete($id = null)
{
if( isset($id) ) $this->setID($id);
if( !$this->raiseEvent('OnBeforeItemDelete') ) return false;
$q = 'DELETE FROM '.$this->TableName.' WHERE '.$this->GetKeyClause('Delete');
$ret = $this->Conn->ChangeQuery($q);
$this->setModifiedFlag();
if ($this->Conn->getAffectedRows() > 0) {
// something was actually deleted
$this->raiseEvent('OnAfterItemDelete');
}
if ($this->mode != 't') {
$this->Application->resetCounters($this->TableName);
}
return $ret;
}
function PopulateMultiLangFields()
{
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$lang_count = $ml_helper->getLanguageCount();
foreach ($this->Fields as $field => $options)
{
if (isset($options['formatter']) && $options['formatter'] == 'kMultiLanguage' && isset($options['master_field'])) {
if (preg_match('/^l([0-9]+)_(.*)/', $field, $regs)) {
$l = $regs[1];
$name = $regs[2];
unset($options['required']); // all non-primary language field set to non-required
for ($i=1; $i<=$lang_count; $i++) {
if ($i == $l || !$ml_helper->LanguageFound($i)) continue;
$this->Fields['l'.$i.'_'.$name] = $options;
}
}
}
}
}
/**
* Sets new name for item in case if it is beeing copied
* in same table
*
* @param array $master Table data from TempHandler
* @param int $foreign_key ForeignKey value to filter name check query by
* @param string $title_field FieldName to alter, by default - TitleField of the prefix
* @param string $format sprintf-style format of renaming pattern, by default Copy %1$s of %2$s which makes it Copy [Number] of Original Name
* @access private
*/
function NameCopy($master=null, $foreign_key=null, $title_field=null, $format='Copy %1$s of %2$s')
{
if (!isset($title_field)) {
$title_field = $this->Application->getUnitOption($this->Prefix, 'TitleField');
if (!$title_field || isset($this->CalculatedFields[$title_field]) ) return;
}
$new_name = $this->GetDBField($title_field);
$original_checked = false;
do {
if ( preg_match('/'.sprintf($format, '([0-9]*) *', '(.*)').'/', $new_name, $regs) ) {
$new_name = sprintf($format, ($regs[1]+1), $regs[2]);
}
elseif ($original_checked) {
$new_name = sprintf($format, '', $new_name);
}
// if we are cloning in temp table this will look for names in temp table,
// since object' TableName contains correct TableName (for temp also!)
// if we are cloning live - look in live
$query = 'SELECT '.$title_field.' FROM '.$this->TableName.'
WHERE '.$title_field.' = '.$this->Conn->qstr($new_name);
$foreign_key_field = getArrayValue($master, 'ForeignKey');
$foreign_key_field = is_array($foreign_key_field) ? $foreign_key_field[ $master['ParentPrefix'] ] : $foreign_key_field;
if ($foreign_key_field && isset($foreign_key)) {
$query .= ' AND '.$foreign_key_field.' = '.$foreign_key;
}
$res = $this->Conn->GetOne($query);
/*// if not found in live table, check in temp table if applicable
if ($res === false && $object->Special == 'temp') {
$query = 'SELECT '.$name_field.' FROM '.$this->GetTempName($master['TableName']).'
WHERE '.$name_field.' = '.$this->Conn->qstr($new_name);
$res = $this->Conn->GetOne($query);
}*/
$original_checked = true;
} while ($res !== false);
$this->SetDBField($title_field, $new_name);
}
function raiseEvent($name, $id = null, $additional_params = Array())
{
if( !isset($id) ) $id = $this->GetID();
$event = new kEvent( Array('name'=>$name,'prefix'=>$this->Prefix,'special'=>$this->Special) );
$event->setEventParam('id', $id);
if ($additional_params) {
foreach ($additional_params as $ap_name => $ap_value) {
$event->setEventParam($ap_name, $ap_value);
}
}
$this->Application->HandleEvent($event);
return $event->status == erSUCCESS ? true : false;
}
/**
* Set's new ID for item
*
* @param int $new_id
* @access public
*/
function setID($new_id)
{
$this->ID = $new_id;
$this->SetDBField($this->IDField, $new_id);
}
/**
* Generate and set new temporary id
*
* @access private
*/
function setTempID()
{
$new_id = (int)$this->Conn->GetOne('SELECT MIN('.$this->IDField.') FROM '.$this->TableName);
if($new_id > 0) $new_id = 0;
--$new_id;
$this->Conn->Query('UPDATE '.$this->TableName.' SET `'.$this->IDField.'` = '.$new_id.' WHERE `'.$this->IDField.'` = '.$this->GetID());
$this->SetID($new_id);
}
/**
* Set's modification flag for main prefix of current prefix to true
*
* @access private
* @author Alexey
*/
function setModifiedFlag()
{
$main_prefix = $this->Application->GetTopmostPrefix($this->Prefix);
$this->Application->StoreVar($main_prefix.'_modified', '1');
}
/**
* Returns ID of currently processed record
*
* @return int
* @access public
*/
function GetID()
{
return $this->ID;
}
/**
* Generates ID for new items before inserting into database
*
* @return int
* @access private
*/
function generateID()
{
return 0;
}
/**
* Returns true if item was loaded successfully by Load method
*
* @return bool
*/
function isLoaded()
{
return $this->Loaded;
}
/**
* Checks if field is required
*
* @param string $field
* @return bool
*/
function isRequired($field)
{
return getArrayValue( $this->Fields[$field], 'required' );
}
/**
* Sets new required flag to field
*
* @param string $field
* @param bool $is_required
*/
function setRequired($field, $is_required = true)
{
$this->Fields[$field]['required'] = $is_required;
}
function Clear($new_id = null)
{
$this->setID($new_id);
$this->Loaded = false;
$this->FieldValues = Array();
$this->OriginalFieldValues = Array ();
$this->SetDefaultValues();
$this->FieldErrors = Array();
return $this->Loaded;
}
function Query($force = false)
{
if( $this->Application->isDebugMode() )
{
$this->Application->Debugger->appendTrace();
}
trigger_error('<b>Query</b> method is called in class <b>'.get_class($this).'</b> for prefix <b>'.$this->getPrefixSpecial().'</b>', E_USER_ERROR);
}
function saveCustomFields()
{
if (!$this->customFields) {
return true;
}
$cdata_key = rtrim($this->Prefix.'-cdata.'.$this->Special, '.');
$cdata =& $this->Application->recallObject($cdata_key, null, Array('skip_autoload' => true, 'populate_ml_fields' => true));
$resource_id = $this->GetDBField('ResourceId');
$cdata->Load($resource_id, 'ResourceId');
$cdata->SetDBField('ResourceId', $resource_id);
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
/* @var $ml_formatter kMultiLanguage */
foreach ($this->customFields as $custom_id => $custom_name) {
$force_primary = isset($cdata->Fields['cust_'.$custom_id]['force_primary']) && $cdata->Fields['cust_'.$custom_id]['force_primary'];
$cdata->SetDBField($ml_formatter->LangFieldName('cust_'.$custom_id, $force_primary), $this->GetDBField('cust_'.$custom_name));
}
if ($cdata->isLoaded()) {
$ret = $cdata->Update();
}
else {
$ret = $cdata->Create();
if ($cdata->mode == 't') $cdata->setTempID();
}
return $ret;
}
/**
* Returns specified field value from all selected rows.
* Don't affect current record index
*
* @param string $field
* @return Array
*/
function GetCol($field)
{
return Array (0 => $this->GetDBField($field));
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/db/dbitem.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.44.2.7
\ No newline at end of property
+1.44.2.8
\ No newline at end of property
Index: branches/RC/core/kernel/languages/phrases_cache.php
===================================================================
--- branches/RC/core/kernel/languages/phrases_cache.php (revision 10097)
+++ branches/RC/core/kernel/languages/phrases_cache.php (revision 10098)
@@ -1,249 +1,249 @@
<?php
class PhrasesCache extends kBase {
/**
* Connection to database
*
* @var kDBConnection
* @access public
*/
var $Conn;
var $Phrases = Array();
var $Ids = Array();
var $OriginalIds = Array(); //for comparing cache
var $LanguageId = null;
var $fromTag = false;
function PhrasesCache()
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
}
function Init($prefix, $special = '')
{
if (constOn('IS_INSTALL')) {
$this->LanguageId = 1;
}
else {
if ($this->Application->IsAdmin()) {
$id_field = $this->Application->getUnitOption('lang', 'IDField');
$table_name = $this->Application->getUnitOption('lang', 'TableName');
$sql = 'SELECT '.$id_field.'
FROM '.$table_name.'
WHERE AdminInterfaceLang = 1';
$this->LanguageId = $this->Conn->GetOne($sql);
}
else {
$this->LanguageId = $this->Application->GetVar('m_lang');
}
}
if (isset($this->Application->Caches['PhraseList'])) {
$this->LoadPhrases( $this->Application->Caches['PhraseList'] );
}
}
function GetCachedIds()
{
$query = sprintf("SELECT PhraseList, ConfigVariables FROM %s WHERE Template = %s",
TABLE_PREFIX.'PhraseCache',
$this->Conn->Qstr(md5($this->Application->GetVar('t').$this->Application->GetVar('m_theme').$this->Application->GetVar('m_lang'))));
$res = $this->Conn->GetRow($query);
if ($res && $res['ConfigVariables']) {
$this->Application->OriginalConfigCacheIds = explode(',', $res['ConfigVariables']);
$this->Application->ConfigCacheIds = $this->Application->OriginalConfigCacheIds;
}
return ($res === false) ? Array() : explode(',', $res['PhraseList']);
}
function LoadPhrases($ids)
{
if ( !is_array($ids) || !implode('', $ids) ) return;
$query = sprintf("SELECT Translation,UPPER(Phrase) AS Phrase FROM %s WHERE LanguageId = %s AND PhraseId IN (%s)",
TABLE_PREFIX.'Phrase',
$this->LanguageId,
join(',', $ids));
$this->Phrases = $this->Conn->GetCol($query,'Phrase');
/*foreach($phrases as $phrase => $tanslation)
{
- $this->AddCachedPhrase(strtoupper($phrase), $tanslation);
+ $this->AddCachedPhrase(mb_strtoupper($phrase), $tanslation);
}*/
$this->Ids = $ids;
$this->OriginalIds = $ids;
}
function AddCachedPhrase($label, $value)
{
- $label = strtoupper($label);
+ $label = mb_strtoupper($label);
$this->Phrases[$label] = $value;
}
function NeedsCacheUpdate()
{
return is_array($this->Ids) && count($this->Ids) > 0 && $this->Ids != $this->OriginalIds;
}
/**
* Copy from Application->UpdateCache method
*
* @deprecated
*/
function UpdateCache()
{
$update = false;
//something changed
$update = $update || (is_array($this->Ids) && count($this->Ids) > 0 && $this->Ids != $this->OriginalIds);
$update = $update || (count($this->Application->ConfigCacheIds) && $this->Application->ConfigCacheIds != $this->Application->OriginalConfigCacheIds);
if ($update) {
$query = sprintf("REPLACE %s (PhraseList, CacheDate, Template, ConfigVariables)
VALUES (%s, %s, %s, %s)",
TABLE_PREFIX.'PhraseCache',
$this->Conn->Qstr(join(',', $this->Ids)),
adodb_mktime(),
$this->Conn->Qstr(md5($this->Application->GetVar('t').$this->Application->GetVar('m_theme').$this->Application->GetVar('m_lang'))),
$this->Conn->qstr(implode(',', array_unique($this->Application->ConfigCacheIds))));
$this->Conn->Query($query);
}
}
function GetPhrase($label)
{
if (ereg("^!.+!$", $label) > 0)
{
$label = substr($label, 1, -1); //cut exclamation marks
}
if( strlen($label) == 0 ) return '';
$original_label = $label;
- $label = strtoupper($label);
+ $label = mb_strtoupper($label);
if(isset($this->Phrases[$label])) {
$translated_label = $this->Phrases[$label];
// debug mode is checked directly to improve performance
if (defined('DEBUG_MODE') && DEBUG_MODE && constOn('DBG_PHRASES_HIGHLIGHT')) {
if (!$this->Application->isDebugMode()) return $translated_label;
if ($this->Application->IsAdmin()) {
$sql = 'SELECT Module
FROM '.TABLE_PREFIX.'Phrase
WHERE (LanguageId = '.$this->LanguageId.') AND (Phrase = '.$this->Conn->qstr($label).')';
$this->Application->Debugger->appendHTML('Phrase: <b>'.$label.'</b>; Module: <b>'.$this->Conn->GetOne($sql).'</b>');
// $translated_label = $translated_label.' [m: '.$this->Conn->GetOne($sql).'; l: '.$label.']';
}
else {
// highlight text created via translated phrase (used to detect if text on screen is phrase or not)
$translated_label = '<span style="border: 1px solid #999999; background-color: #cccccc; color: #999999; ">'.$translated_label.'</span></a> <span style="color: red; background-color:#ffffcc">'.$original_label.'</span>';
}
}
return $translated_label;
}
$this->LoadPhraseByLabel($label, $original_label);
return $this->GetPhrase($label);
}
function LoadPhraseByLabel($label, $original_label)
{
$query = sprintf("SELECT PhraseId, Translation FROM %s WHERE LanguageId = %s AND UPPER(Phrase) = UPPER(%s)",
TABLE_PREFIX.'Phrase',
$this->LanguageId,
$this->Conn->qstr($label));
$res = $this->Conn->GetRow($query);
if ($res === false || count($res) == 0)
{
$translation = '!'.$label.'!';
if($this->Application->isDebugMode() && constOn('DBG_PHRASES')) {
list($edit_tpl, $index_file) = $this->Application->IsAdmin() ? Array('regional/phrases_edit', 'index.php') : Array('phrases_edit', 'index.php');
if ($this->Application->IsAdmin() && $this->Application->ConfigValue('UsePopups')) {
// link to popup when using popups (only in admin)
$edit_url = 'javascript:translate_phrase(\''.addslashes($original_label).'\', \''.$edit_tpl.'\');';
}
else {
// direct link, when not using popups OR on frontend
$edit_url = $this->Application->HREF($edit_tpl,'',Array('m_opener'=>'d','phrases_label'=>$original_label,'phrases_event'=>'OnNew', 'pass'=>'all,phrases'), $index_file );
}
$translation = '<a href="'.$edit_url.'">!'.$label.'!</a>';
if($this->fromTag) $translation = $this->escapeTagReserved($translation);
}
$this->AddCachedPhrase($label, $translation); //add it as already cached, as long as we dont need to cache not found phrase
return false;
}
$this->Phrases[$label] = $res['Translation'];
array_push($this->Ids, $res['PhraseId']);
$this->Ids = array_unique($this->Ids); //just to make sure
return true;
}
/**
* Sort params by name and then by length
*
* @param string $a
* @param string $b
* @return int
* @access private
*/
function CmpParams($a, $b)
{
- $a_len = strlen($a);
- $b_len = strlen($b);
+ $a_len = mb_strlen($a);
+ $b_len = mb_strlen($b);
if ($a_len == $b_len) return 0;
return $a_len > $b_len ? -1 : 1;
}
/**
* Replace language tags in exclamation marks found in text
*
* @param string $text
* @param bool $force_escape force escaping, not escaping of resulting string
* @return string
* @access public
*/
function ReplaceLanguageTags($text,$forse_escaping=null)
{
$this->fromTag = true;
if( isset($forse_escaping) ) $this->fromTag = $forse_escaping;
preg_match_all("(!(la|lu)[^!]+!)", $text, $res, PREG_PATTERN_ORDER);
$language_tags = $res[0];
uasort($language_tags, Array(&$this, 'CmpParams') );
$values = Array();
$i = 0;
foreach ($language_tags as $label) {
array_push($values, $this->GetPhrase($label) );
//array_push($values, $this->Application->Phrase($label) );
$language_tags[$i] = '/' . $language_tags[$i] . '/';
$i++;
}
$this->fromTag = false;
return preg_replace($language_tags, $values, $text);
}
/**
* Escape chars in phrase translation, that could harm parser to process tag
*
* @param string $text
* @return string
* @access private
*/
function escapeTagReserved($text)
{
$reserved = Array('"',"'"); // =
$replacement = Array('\"',"\'"); // \=
return str_replace($reserved,$replacement,$text);
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/languages/phrases_cache.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.19.2.1
\ No newline at end of property
+1.19.2.2
\ No newline at end of property
Index: branches/RC/core/kernel/startup.php
===================================================================
--- branches/RC/core/kernel/startup.php (revision 10097)
+++ branches/RC/core/kernel/startup.php (revision 10098)
@@ -1,148 +1,149 @@
<?php
define('KERNEL_PATH', FULL_PATH.'/core/kernel');
if (file_exists(FULL_PATH.'/kernel/kernel4/application.php')) {
die('Please remove '.FULL_PATH.'/kernel/kernel4 directiry - it has been moved to '.KERNEL_PATH.'<br/>Don\'t forget to clean Cache table afterwards');
}
if (!function_exists('getmicrotime')) {
function getmicrotime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
}
$globals_start = getmicrotime();
include_once(KERNEL_PATH.'/globals.php'); // non OOP functions used through kernel, e.g. print_pre
+ include_once(KERNEL_PATH.'/utility/multibyte.php'); // emulating multi-byte php extension
$globals_end = getmicrotime();
define('INPORTAL_ENV', 1);
$vars = parse_portal_ini(FULL_PATH.'/config.php');
$admin_directory = isset($vars['AdminDirectory']) ? $vars['AdminDirectory'] : '/admin';
safeDefine('ADMIN_DIRECTORY', $admin_directory);
# New path detection method: begin
if (defined('REL_PATH')) {
// location of index.php relatively to site base folder
$relative_path = preg_replace('/^[\/]{0,1}admin(.*)/', $admin_directory.'\\1', REL_PATH);
}
else {
// default index.php relative location is administrative console folder
define('REL_PATH', $admin_directory);
$relative_path = REL_PATH;
}
$ps = rtrim(preg_replace('/'.preg_quote(rtrim($relative_path, '/'), '/').'$/', '', str_replace('\\', '/', dirname($_SERVER['PHP_SELF']))), '/');
safeDefine('BASE_PATH', $ps); // in case in-portal has defined it before
# New path detection method: end
safeDefine('INPORTAL_TAGS', true);
safeDefine('SERVER_NAME', $_SERVER['HTTP_HOST']);
$https_mark = getArrayValue($_SERVER, 'HTTPS');
safeDefine('PROTOCOL', ($https_mark == 'on') || ($https_mark == '1') ? 'https://' : 'http://');
safeDefine('APPLICATION_CLASS', isset($vars['ApplicationClass']) ? $vars['ApplicationClass'] : 'kApplication');
safeDefine('APPLICATION_PATH', isset($vars['ApplicationPath']) ? $vars['ApplicationPath'] : '/core/kernel/application.php');
if (isset($vars['WriteablePath'])) {
define('WRITEABLE', FULL_PATH.$vars['WriteablePath']);
define('WRITEBALE_BASE', $vars['WriteablePath']);
}
if ($vars === false || count($vars) == 0) {
global $rootURL;
echo 'In-Portal is probably not installed, or configuration file is missing.<br>';
echo 'Please use the installation script to fix the problem.<br><br>';
$install_script = file_exists(FULL_PATH.'/proj-base/install.php') ? 'core' : 'admin';
echo '<a href="'.PROTOCOL.SERVER_NAME.rtrim(BASE_PATH, '/').'/'.$install_script.'/install.php">Go to installation script</a><br><br>';
flush();
exit;
}
define('SQL_TYPE', $vars['DBType']);
define('SQL_SERVER', $vars['DBHost']);
define('SQL_USER', $vars['DBUser']);
define('SQL_PASS', $vars['DBUserPassword']);
define('SQL_DB', $vars['DBName']);
if (isset($vars['DBCollation']) && isset($vars['DBCharset'])) {
define('SQL_COLLATION', $vars['DBCollation']);
define('SQL_CHARSET', $vars['DBCharset']);
}
define('TABLE_PREFIX', $vars['TablePrefix']);
define('DOMAIN', getArrayValue($vars, 'Domain'));
ini_set('memory_limit', '50M');
define('MODULES_PATH', FULL_PATH);
define('EXPORT_PATH', defined('WRITEABLE') ? WRITEABLE.'/export' : FULL_PATH.ADMIN_DIRECTORY.'/export');
define('GW_CLASS_PATH', MODULES_PATH.'/in-commerce/units/gateways/gw_classes'); // Payment Gateway Classes Path
define('SYNC_CLASS_PATH', FULL_PATH.'/sync'); // path for 3rd party user syncronization scripts
safeDefine('ENV_VAR_NAME','env');
safeDefine('IMAGES_PATH', '/kernel/images/');
safeDefine('IMAGES_PENDING_PATH', IMAGES_PATH.'pending/');
safeDefine('CUSTOM_UPLOAD_PATH', '/templates/images/custom/');
safeDefine('MAX_UPLOAD_SIZE', min(ini_get('upload_max_filesize'), ini_get('post_max_size'))*1024*1024);
if( ini_get('safe_mode') ) define('SAFE_MODE', 1);
safeDefine('EXPERIMENTAL_PRE_PARSE', 1);
safeDefine('SILENT_LOG', 0);
if( file_exists(FULL_PATH.'/debug.php') )
{
include_once(FULL_PATH.'/debug.php');
if(isset($dbg_options['DEBUG_MODE']) && $dbg_options['DEBUG_MODE']) {
$debugger_start = getmicrotime();
include_once(KERNEL_PATH.'/utility/debugger.php');
$debugger_end = getmicrotime();
if (isset($debugger) && constOn('DBG_PROFILE_INCLUDES')) {
$debugger->profileStart('inc_globals', KERNEL_PATH.'/globals.php', $globals_start);
$debugger->profileFinish('inc_globals', KERNEL_PATH.'/globals.php', $globals_end);
$debugger->profilerAddTotal('includes', 'inc_globals');
$debugger->profileStart('inc_debugger', KERNEL_PATH.'/utility/debugger.php', $debugger_start);
$debugger->profileFinish('inc_debugger', KERNEL_PATH.'/utility/debugger.php', $debugger_end);
$debugger->profilerAddTotal('includes', 'inc_debugger');
}
}
}
$includes = Array(
KERNEL_PATH.'/application.php',
FULL_PATH.APPLICATION_PATH,
KERNEL_PATH.'/db/db_connection.php',
KERNEL_PATH."/kbase.php",
KERNEL_PATH.'/utility/event.php',
KERNEL_PATH."/utility/factory.php",
KERNEL_PATH."/languages/phrases_cache.php",
KERNEL_PATH."/db/dblist.php",
KERNEL_PATH."/db/dbitem.php",
KERNEL_PATH."/event_handler.php",
KERNEL_PATH.'/db/db_event_handler.php',
);
foreach ($includes as $a_file) {
k4_include_once($a_file);
}
if (defined('DEBUG_MODE') && DEBUG_MODE && isset($debugger)) {
$debugger->AttachToApplication();
}
if( !function_exists('adodb_mktime') ) include_once(KERNEL_PATH.'/utility/adodb-time.inc.php');
// include_once(KERNEL_PATH."/utility/temp_handler.php"); // needed because of static calls from kBase
// up to here
// global constants
define ('KG_TO_POUND', 2.20462262);
define ('POUND_TO_KG', 0.45359237);
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/startup.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.55.2.2
\ No newline at end of property
+1.55.2.3
\ No newline at end of property
Index: branches/RC/core/kernel/application.php
===================================================================
--- branches/RC/core/kernel/application.php (revision 10097)
+++ branches/RC/core/kernel/application.php (revision 10098)
@@ -1,2572 +1,2573 @@
<?php
/**
* Basic class for Kernel3-based Application
*
* This class is a Facade for any other class which needs to deal with Kernel3 framework.<br>
* The class incapsulates the main run-cycle of the script, provide access to all other objects in the framework.<br>
* <br>
* The class is a singleton, which means that there could be only one instance of KernelApplication in the script.<br>
* This could be guranteed by NOT calling the class constuctor directly, but rather calling KernelApplication::Instance() method,
* which returns an instance of the application. The method gurantees that it will return exactly the same instance for any call.<br>
* See singleton pattern by GOF.
* @package kernel4
*/
class kApplication {
/**
* Is true, when Init method was called already, prevents double initialization
*
* @var bool
*/
var $InitDone = false;
/**
* Holds internal TemplateParser object
* @access private
* @var TemplateParser
*/
var $Parser;
/**
* New Parser (Experimental)
*
* @var NParser
*/
var $NParser;
/**
* Holds parser output buffer
* @access private
* @var string
*/
var $HTML;
/**
* Prevents request from beeing proceeded twice in case if application init is called mere then one time
*
* @var bool
* @todo This is not good anyway (by Alex)
*/
var $RequestProcessed = false;
/**
* The main Factory used to create
* almost any class of kernel and
* modules
*
* @access private
* @var kFactory
*/
var $Factory;
/**
* All ConfigurationValues table content (hash) here
*
* @var Array
* @access private
*/
var $ConfigHash = Array();
/**
* Ids of config variables used in current run (for caching)
*
* @var Array
* @access private
*/
var $ConfigCacheIds = array();
/**
* Template names, that will be used instead of regular templates
*
* @var Array
*/
var $ReplacementTemplates = Array ();
/**
* Reference to debugger
*
* @var Debugger
*/
var $Debugger = null;
/**
* Holds all phrases used
* in code and template
*
* @var PhrasesCache
*/
var $Phrases;
/**
* Modules table content, key - module name
*
* @var Array
*/
var $ModuleInfo = Array();
/**
* Holds DBConnection
*
* @var kDBConnection
*/
var $Conn = null;
/**
* Maintains list of user-defined error handlers
*
* @var Array
*/
var $errorHandlers = Array();
// performance needs:
/**
* Holds a refererence to httpquery
*
* @var kHttpQuery
*/
var $HttpQuery = null;
/**
* Holds a reference to UnitConfigReader
*
* @var kUnitConfigReader
*/
var $UnitConfigReader = null;
/**
* Holds a reference to Session
*
* @var Session
*/
var $Session = null;
/**
* Holds a ref to kEventManager
*
* @var kEventManager
*/
var $EventManager = null;
/**
* Ref to itself, needed because everybody used to write $this->Application, even inside kApplication
*
* @var kApplication
*/
var $Application = null;
/**
* Ref for TemplatesChache
*
* @var TemplatesCache
*/
var $TemplatesCache = null;
var $CompilationCache = array(); //used when compiling templates
var $CachedProcessors = array(); //used when running compiled templates
var $LambdaElements = 1; // for autonumbering unnamed RenderElements [any better place for this prop? KT]
/**
* Holds current NParser tag while parsing, can be used in error messages to display template file and line
*
* @var unknown_type
*/
var $CurrentNTag = null;
/**
* Returns kApplication instance anywhere in the script.
*
* This method should be used to get single kApplication object instance anywhere in the
* Kernel-based application. The method is guranteed to return the SAME instance of kApplication.
* Anywhere in the script you could write:
* <code>
* $application =& kApplication::Instance();
* </code>
* or in an object:
* <code>
* $this->Application =& kApplication::Instance();
* </code>
* to get the instance of kApplication. Note that we call the Instance method as STATIC - directly from the class.
* To use descendand of standard kApplication class in your project you would need to define APPLICATION_CLASS constant
* BEFORE calling kApplication::Instance() for the first time. If APPLICATION_CLASS is not defined the method would
* create and return default KernelApplication instance.
* @static
* @access public
* @return kApplication
*/
function &Instance()
{
static $instance = false;
if(!$instance)
{
safeDefine('APPLICATION_CLASS', 'kApplication');
$class = APPLICATION_CLASS;
$instance = new $class();
$instance->Application =& $instance;
}
return $instance;
}
/**
* Initializes the Application
*
* @access public
* @see kHTTPQuery
* @see Session
* @see TemplatesCache
* @return bool Was Init actually made now or before
*/
function Init()
{
if($this->InitDone) return false;
if (!constOn('SKIP_OUT_COMPRESSION')) {
ob_start(); // collect any output from method (other then tags) into buffer
}
if(defined('DEBUG_MODE') && $this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Init:');
}
if (!$this->isDebugMode() && !constOn('DBG_ZEND_PRESENT')) {
error_reporting(0);
ini_set('display_errors', 0);
}
if (!constOn('DBG_ZEND_PRESENT')) {
$error_handler = set_error_handler( Array(&$this,'handleError') );
if ($error_handler) $this->errorHandlers[] = $error_handler;
}
$this->Conn = new kDBConnection(SQL_TYPE, Array(&$this, 'handleSQLError') );
$this->Conn->debugMode = $this->isDebugMode();
$this->Conn->Connect(SQL_SERVER, SQL_USER, SQL_PASS, SQL_DB);
$this->Factory = new kFactory();
$this->registerDefaultClasses();
$this->Phrases = new PhrasesCache();
$this->EventManager =& $this->Factory->makeClass('EventManager');
$this->Factory->Storage['EventManager'] =& $this->EventManager;
$this->RegisterDefaultBuildEvents();
$this->SetDefaultConstants();
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
$this->UnitConfigReader->scanModules(MODULES_PATH);
$this->registerModuleConstants();
$rewrite_on = $this->ConfigValue('UseModRewrite');
// admin=1 - when front is browsed using admin session
$admin_on = getArrayValue($_REQUEST, 'admin') || $this->IsAdmin();
define('MOD_REWRITE', $rewrite_on && !$admin_on ? 1 : 0);
$this->HttpQuery =& $this->recallObject('HTTPQuery');
$this->Session =& $this->recallObject('Session');
$this->HttpQuery->AfterInit();
$this->LoadCache();
$this->InitConfig();
$this->Phrases->Init('phrases');
$this->UnitConfigReader->AfterConfigRead();
/*// Module items are recalled during url parsing & PhrasesCache is needed already there,
// because it's used in their build events. That's why phrases cache initialization is
// called from kHTTPQuery in case when mod_rewrite is used
if (!$this->RewriteURLs()) {
$this->Phrases = new PhrasesCache();
}*/
if(!$this->RecallVar('UserGroups')) {
$session =& $this->recallObject('Session');
$user_groups = trim($session->GetField('GroupList'), ',');
if (!$user_groups) $user_groups = $this->ConfigValue('User_GuestGroup');
$this->StoreVar('UserGroups', $user_groups);
}
if ($this->GetVar('m_cat_id') === false) $this->SetVar('m_cat_id', 0);
if( !$this->RecallVar('curr_iso') ) $this->StoreVar('curr_iso', $this->GetPrimaryCurrency() );
$this->SetVar('visits_id', $this->RecallVar('visit_id') );
$language =& $this->recallObject( 'lang.current', null, Array('live_table' => true) );
if (preg_match('/utf-8/', $language->GetDBField('Charset'))) {
setlocale(LC_ALL, 'en_US.UTF-8');
+ mb_internal_encoding('UTF-8');
}
$this->ValidateLogin();
if($this->isDebugMode()) {
$this->Debugger->profileFinish('kernel4_startup');
}
$this->InitDone = true;
$this->HandleEvent( new kEvent('adm:OnStartup') );
return true;
}
/**
* Returns module information. Searches module by requested field
*
* @param string $field
* @param mixed $value
* @param string field value to returns, if not specified, then return all fields
* @param string field to return
* @return Array
*/
function findModule($field, $value, $return_field = null)
{
$found = false;
foreach ($this->ModuleInfo as $module_name => $module_info) {
if (strtolower($module_info[$field]) == strtolower($value)) {
$found = true;
break;
}
}
if ($found) {
return isset($return_field) ? $module_info[$return_field] : $module_info;
}
return false;
}
function refreshModuleInfo()
{
if (defined('IS_INSTALL') && IS_INSTALL && !$this->TableFound('Modules')) {
$this->registerModuleConstants();
return false;
}
$modules_helper =& $this->recallObject('ModulesHelper');
$this->ModuleInfo = $this->Conn->Query('SELECT * FROM '.TABLE_PREFIX.'Modules WHERE Loaded = 1 ORDER BY LoadOrder', 'Name');
$sql = 'SELECT *
FROM '.TABLE_PREFIX.'Modules
WHERE '.$modules_helper->getWhereClause().'
ORDER BY LoadOrder';
$this->ModuleInfo = $this->Conn->Query($sql, 'Name');
$this->registerModuleConstants();
}
/**
* Checks if passed language id if valid and sets it to primary otherwise
*
*/
function VerifyLanguageId()
{
$language_id = $this->GetVar('m_lang');
if (!$language_id) {
$language_id = 'default';
}
$this->SetVar('lang.current_id', $language_id );
$this->SetVar('m_lang', $language_id );
$lang_mode = $this->GetVar('lang_mode');
$this->SetVar('lang_mode', '');
$lang =& $this->recallObject('lang.current');
if ( !$lang->IsLoaded() || (!$this->Application->IsAdmin() && !$lang->GetDBField('Enabled')) ) {
if (!defined('IS_INSTALL')) $this->ApplicationDie('Unknown or disabled language');
}
$this->SetVar('lang_mode',$lang_mode);
}
/**
* Checks if passed theme id if valid and sets it to primary otherwise
*
*/
function VerifyThemeId()
{
if ($this->Application->IsAdmin()) {
safeDefine('THEMES_PATH', '/core/admin_templates');
return;
}
$path = $this->GetFrontThemePath();
if ($path === false) {
$this->ApplicationDie('No Primary Theme Selected or Current Theme is Unknown or Disabled');
}
safeDefine('THEMES_PATH', $path);
/*
$theme_id = $this->GetVar('m_theme');
if (!$theme_id) {
$theme_id = $this->GetDefaultThemeId();
if (!$theme_id) {
if (!defined('IS_INSTALL')) $this->ApplicationDie('No Primary Theme Selected');
}
}
$this->SetVar('m_theme', $theme_id);
$this->SetVar('theme.current_id', $theme_id ); // KOSTJA: this is to fool theme' getPassedId
$theme =& $this->recallObject('theme.current');
if (!$theme->IsLoaded() || !$theme->GetDBField('Enabled')) {
if (!defined('IS_INSTALL')) $this->ApplicationDie('Unknown or disabled theme');
}
safeDefine('THEMES_PATH', '/themes/'.$theme->GetDBField('Name'));
*/
}
function GetFrontThemePath($force=0)
{
static $path=null;
if (!$force && isset($path)) return $path;
$theme_id = $this->GetVar('m_theme');
if (!$theme_id) {
$theme_id = $this->GetDefaultThemeId(1); //1 to force front-end mode!
if (!$theme_id) {
return false;
}
}
$this->SetVar('m_theme', $theme_id);
$this->SetVar('theme.current_id', $theme_id ); // KOSTJA: this is to fool theme' getPassedId
$theme =& $this->recallObject('theme.current');
if (!$theme->IsLoaded() || !$theme->GetDBField('Enabled')) {
return false;
}
$path = '/themes/'.$theme->GetDBField('Name');
return $path;
}
function GetDefaultLanguageId()
{
static $language_id = 0;
if ($language_id > 0) return $language_id;
$table = $this->getUnitOption('lang','TableName');
$id_field = $this->getUnitOption('lang','IDField');
$sql = 'SELECT '.$id_field.'
FROM '.$table.'
WHERE (PrimaryLang = 1) AND (Enabled = 1)';
$language_id = $this->Conn->GetOne($sql);
if (!$language_id && defined('IS_INSTALL') && IS_INSTALL) {
$language_id = 1;
}
return $language_id;
}
function GetDefaultThemeId($force_front=0)
{
static $theme_id = 0;
if($theme_id > 0) return $theme_id;
if (constOn('DBG_FORCE_THEME')) {
$theme_id = DBG_FORCE_THEME;
}
elseif (!$force_front && $this->IsAdmin()) {
$theme_id = 999;
}
else {
$table = $this->getUnitOption('theme','TableName');
$id_field = $this->getUnitOption('theme','IDField');
$sql = 'SELECT '.$id_field.'
FROM '.$table.'
WHERE (PrimaryTheme = 1) AND (Enabled = 1)';
$theme_id = $this->Conn->GetOne($sql);
}
return $theme_id;
}
function GetPrimaryCurrency()
{
if ($this->isModuleEnabled('In-Commerce')) {
$table = $this->getUnitOption('curr', 'TableName');
return $this->Conn->GetOne('SELECT ISO FROM '.$table.' WHERE IsPrimary = 1');
}
else {
return 'USD';
}
}
/**
* Registers default classes such as ItemController, GridController and LoginController
*
* Called automatically while initializing Application
* @access private
* @return void
*/
function RegisterDefaultClasses()
{
$this->registerClass('kTempTablesHandler', KERNEL_PATH.'/utility/temp_handler.php');
$this->registerClass('kEventManager', KERNEL_PATH.'/event_manager.php', 'EventManager');
$this->registerClass('kUnitConfigReader', KERNEL_PATH.'/utility/unit_config_reader.php');
$this->registerClass('kArray', KERNEL_PATH.'/utility/params.php');
$this->registerClass('Params', KERNEL_PATH.'/utility/params.php');
$this->registerClass('kHelper', KERNEL_PATH.'/kbase.php');
$this->registerClass('kCache', KERNEL_PATH.'/utility/cache.php', 'Cache', Array('Params'));
$this->registerClass('kHTTPQuery', KERNEL_PATH.'/utility/http_query.php', 'HTTPQuery', Array('Params') );
$this->registerClass('Session', KERNEL_PATH.'/session/session.php');
$this->registerClass('SessionStorage', KERNEL_PATH.'/session/session.php');
$this->registerClass('Params', KERNEL_PATH.'/utility/params.php', 'kActions');
$this->registerClass('kMultipleFilter', KERNEL_PATH.'/utility/filters.php');
$this->registerClass('kDBList', KERNEL_PATH.'/db/dblist.php');
$this->registerClass('kDBItem', KERNEL_PATH.'/db/dbitem.php');
$this->registerClass('kDBEventHandler', KERNEL_PATH.'/db/db_event_handler.php');
$this->registerClass('kTagProcessor', KERNEL_PATH.'/processors/tag_processor.php');
$this->registerClass('kMainTagProcessor', KERNEL_PATH.'/processors/main_processor.php','m_TagProcessor', 'kTagProcessor');
$this->registerClass('kDBTagProcessor', KERNEL_PATH.'/db/db_tag_processor.php', null, 'kTagProcessor');
$this->registerClass('TemplatesCache', KERNEL_PATH.'/parser/template.php',null, 'kDBTagProcessor');
$this->registerClass('Template', KERNEL_PATH.'/parser/template.php');
$this->registerClass('TemplateParser', KERNEL_PATH.'/parser/template_parser.php',null, 'kDBTagProcessor');
if (defined('NPARSER') && 'NPARSER') {
$this->registerClass('NParser', KERNEL_PATH.'/nparser/nparser.php');
}
$this->registerClass('kEmailSendingHelper', KERNEL_PATH.'/utility/email_send.php', 'EmailSender', Array('kHelper'));
$this->registerClass('kSocket', KERNEL_PATH.'/utility/socket.php', 'Socket');
if (file_exists(MODULES_PATH.'/in-commerce/units/currencies/currency_rates.php')) {
$this->registerClass('kCurrencyRates', MODULES_PATH.'/in-commerce/units/currencies/currency_rates.php');
}
$this->registerClass('FCKeditor', FULL_PATH.'/admin/editor/cmseditor/fckeditor.php'); // need this?
/* Moved from MyApplication */
$this->registerClass('Inp1Parser',KERNEL_PATH.'/../units/general/inp1_parser.php','Inp1Parser');
$this->registerClass('InpSession',KERNEL_PATH.'/../units/general/inp_ses_storage.php','Session');
$this->registerClass('InpSessionStorage',KERNEL_PATH.'/../units/general/inp_ses_storage.php','SessionStorage');
$this->registerClass('kCatDBItem',KERNEL_PATH.'/../units/general/cat_dbitem.php');
$this->registerClass('kCatDBItemExportHelper',KERNEL_PATH.'/../units/general/cat_dbitem_export.php', 'CatItemExportHelper');
$this->registerClass('kCatDBList',KERNEL_PATH.'/../units/general/cat_dblist.php');
$this->registerClass('kCatDBEventHandler',KERNEL_PATH.'/../units/general/cat_event_handler.php');
$this->registerClass('kCatDBTagProcessor',KERNEL_PATH.'/../units/general/cat_tag_processor.php');
// Do not move to config - this helper is used before configs are read
$this->registerClass('kModulesHelper', KERNEL_PATH.'/../units/general/helpers/modules.php', 'ModulesHelper');
/* End moved */
}
function RegisterDefaultBuildEvents()
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->registerBuildEvent('kTempTablesHandler', 'OnTempHandlerBuild');
}
/**
* Returns item's filename that corresponds id passed. If possible, then get it from cache
*
* @param string $prefix
* @param int $id
* @return string
*/
function getFilename($prefix, $id, $category_id=null)
{
$filename = $this->getCache('filenames', $prefix.'_'.$id);
if ($filename === false) {
$table = $this->getUnitOption($prefix, 'TableName');
$id_field = $this->getUnitOption($prefix, 'IDField');
if ($prefix == 'c') {
if(!$id) {
$this->setCache('filenames', $prefix.'_'.$id, '');
return '';
}
// this allows to save 2 sql queries for each category
$sql = 'SELECT NamedParentPath, CachedCategoryTemplate
FROM '.$table.'
WHERE '.$id_field.' = '.$this->Conn->qstr($id);
$category_data = $this->Conn->GetRow($sql);
$filename = $category_data['NamedParentPath'];
$this->setCache('category_templates', $id, $category_data['CachedCategoryTemplate']);
// $this->setCache('item_templates', $id, $category_data['CachedItemTemplate']);
}
else {
$resource_id = $this->Conn->GetOne('SELECT ResourceId FROM '.$table.' WHERE '.$id_field.' = '.$this->Conn->qstr($id));
if (is_null($category_id)) $category_id = $this->GetVar('m_cat_id');
$sql = 'SELECT Filename FROM '.TABLE_PREFIX.'CategoryItems WHERE ItemResourceId = '.$resource_id.' AND CategoryId = '.$category_id;
$filename = $this->Conn->GetOne($sql);
/*if (!$filename) {
$sql = 'SELECT Filename FROM '.TABLE_PREFIX.'CategoryItems WHERE ItemResourceId = '.$resource_id.' AND PrimaryCat = 1';
$filename = $this->Conn->GetOne($sql);
}*/
/*$sql = 'SELECT Filename
FROM '.$table.'
WHERE '.$id_field.' = '.$this->Conn->qstr($id);
$filename = $this->Conn->GetOne($sql);*/
}
$this->setCache('filenames', $prefix.'_'.$id, $filename);
}
return $filename;
}
/**
* Adds new value to cache $cache_name and identified by key $key
*
* @param string $cache_name cache name
* @param int $key key name to add to cache
* @param mixed $value value of chached record
*/
function setCache($cache_name, $key, $value)
{
$cache =& $this->recallObject('Cache');
$cache->setCache($cache_name, $key, $value);
}
/**
* Returns cached $key value from cache named $cache_name
*
* @param string $cache_name cache name
* @param int $key key name from cache
* @return mixed
*/
function getCache($cache_name, $key)
{
$cache =& $this->recallObject('Cache');
return $cache->getCache($cache_name, $key);
}
/**
* Defines default constants if it's not defined before - in config.php
*
* @access private
*/
function SetDefaultConstants() // it's defined in startup.php - can be removed??
{
safeDefine('SERVER_NAME', $_SERVER['HTTP_HOST']);
}
/**
* Registers each module specific constants if any found
*
*/
function registerModuleConstants()
{
if (file_exists(KERNEL_PATH.'/constants.php')) {
k4_include_once(KERNEL_PATH.'/constants.php');
}
if (!$this->ModuleInfo) return false;
foreach($this->ModuleInfo as $module_name => $module_info)
{
$module_path = '/'.$module_info['Path'];
$contants_file = FULL_PATH.$module_path.'constants.php';
if( file_exists($contants_file) ) k4_include_once($contants_file);
}
return true;
}
function ProcessRequest()
{
$event_manager =& $this->recallObject('EventManager');
/* @var $event_manager kEventManager */
if($this->isDebugMode() && constOn('DBG_SHOW_HTTPQUERY')) {
$this->Debugger->appendHTML('HTTPQuery:');
$this->Debugger->dumpVars($this->HttpQuery->_Params);
}
$event_manager->ProcessRequest();
$event_manager->RunRegularEvents(reBEFORE);
$this->RequestProcessed = true;
}
/**
* Actually runs the parser against current template and stores parsing result
*
* This method gets t variable passed to the script, loads the template given in t variable and
* parses it. The result is store in {@link $this->HTML} property.
* @access public
* @return void
*/
function Run()
{
if($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Run:');
}
if ($this->IsAdmin()) {
// for permission checking in events & templates
$this->LinkVar('module'); // for common configuration templates
$this->LinkVar('section'); // for common configuration templates
if ($this->GetVar('m_opener') == 'p') {
$this->LinkVar('main_prefix'); // window prefix, that opened selector
$this->LinkVar('dst_field'); // field to set value choosed in selector
// $this->LinkVar('return_template'); // template to go, when something was coosen from popup (from finalizePopup)
// $this->LinkVar('return_m'); // main env part to restore after popup will be closed (from finalizePopup)
}
if ($this->GetVar('ajax') == 'yes' && !$this->GetVar('debug_ajax')) {
// hide debug output from ajax requests automatically
define('DBG_SKIP_REPORTING', 1);
}
}
if (!$this->RequestProcessed) $this->ProcessRequest();
$this->InitParser();
$t = $this->GetVar('t');
if ($this->isModuleEnabled('In-Edit')) {
$cms_handler =& $this->recallObject('cms_EventHandler');
if (!$this->TemplatesCache->TemplateExists($t) && !$this->IsAdmin()) {
$t = $cms_handler->GetDesignTemplate();
}
/*else {
$cms_handler->SetCatByTemplate();
}*/
}
if ($this->isModuleEnabled('Proj-CMS')) {
$cms_handler =& $this->recallObject('st_EventHandler');
if (!$this->TemplatesCache->TemplateExists($t) && !$this->IsAdmin()) {
$t = $cms_handler->GetDesignTemplate();
}
}
if($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Parsing:');
}
if (defined('NPARSER') && 'NPARSER') {
$this->HTML = $this->NParser->Run( $t );
}
else {
$this->HTML = $this->Parser->ParseTemplate( $t );
}
if ($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application after Parsing:');
}
}
function InitParser()
{
if (defined('NPARSER') && 'NPARSER') {
if( !is_object($this->NParser) ) {
$this->NParser =& $this->recallObject('NParser');
$this->TemplatesCache =& $this->recallObject('TemplatesCache');
// can be removed in future
// $this->Parser =& $this->recallObject('TemplateParser');
$this->Parser =& $this->NParser;
}
}
else {
if( !is_object($this->Parser) ) {
$this->Parser =& $this->recallObject('TemplateParser');
$this->TemplatesCache =& $this->recallObject('TemplatesCache');
}
}
}
/**
* Send the parser results to browser
*
* Actually send everything stored in {@link $this->HTML}, to the browser by echoing it.
* @access public
* @return void
*/
function Done()
{
$this->HandleEvent( new kEvent('adm:OnBeforeShutdown') );
if ($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Done:');
}
if ($this->GetVar('admin')) {
$reg = '/('.preg_quote(BASE_PATH, '/').'.*\.html)(#.*){0,1}(")/sU';
$this->HTML = preg_replace($reg, "$1?admin=1$2$3", $this->HTML);
}
//eval("?".">".$this->HTML);
if ($this->isDebugMode()) {
$this->EventManager->RunRegularEvents(reAFTER);
$this->Session->SaveData();
$this->HTML = ob_get_clean() . $this->HTML . $this->Debugger->printReport(true);
}
else {
$this->HTML = ob_get_clean().$this->HTML;
}
if ($this->UseOutputCompression()) {
header('Content-Encoding: gzip');
$compression_level = $this->ConfigValue('OutputCompressionLevel');
if ($compression_level < 0 || $compression_level > 9) $compression_level = 7;
echo gzencode($this->HTML, $compression_level);
}
else {
echo $this->HTML;
}
$this->UpdateCache();
flush();
if ($this->isDebugMode() && constOn('DBG_CACHE')) {
$cache =& $this->recallObject('Cache');
$cache->printStatistics();
}
$this->EventManager->RunRegularEvents(reAFTER);
$this->Session->SaveData();
}
/**
* Checks if output compression options is available
*
* @return string
*/
function UseOutputCompression()
{
if (constOn('IS_INSTALL') || constOn('DBG_ZEND_PRESENT') || constOn('SKIP_OUT_COMPRESSION')) return false;
return $this->ConfigValue('UseOutputCompression') && function_exists('gzencode') && strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
}
// Facade
/**
* Returns current session id (SID)
* @access public
* @return longint
*/
function GetSID()
{
$session =& $this->recallObject('Session');
return $session->GetID();
}
function DestroySession()
{
$session =& $this->recallObject('Session');
$session->Destroy();
}
/**
* Returns variable passed to the script as GET/POST/COOKIE
*
* @access public
* @param string $name Name of variable to retrieve
* @param int $default default value returned in case if varible not present
* @return mixed
*/
function GetVar($name, $default = false)
{
// $http_query =& $this->recallObject('HTTPQuery');
return isset($this->HttpQuery->_Params[$name]) ? $this->HttpQuery->_Params[$name] : $default;
}
/**
* Returns ALL variables passed to the script as GET/POST/COOKIE
*
* @access public
* @return array
*/
function GetVars()
{
return $this->HttpQuery->GetParams();
}
/**
* Set the variable 'as it was passed to the script through GET/POST/COOKIE'
*
* This could be useful to set the variable when you know that
* other objects would relay on variable passed from GET/POST/COOKIE
* or you could use SetVar() / GetVar() pairs to pass the values between different objects.<br>
*
* This method is formerly known as $this->Session->SetProperty.
* @param string $var Variable name to set
* @param mixed $val Variable value
* @access public
* @return void
*/
function SetVar($var,$val)
{
// $http_query =& $this->recallObject('HTTPQuery');
return $this->HttpQuery->Set($var, $val);
}
/**
* Deletes kHTTPQuery variable
*
* @param string $var
* @todo think about method name
*/
function DeleteVar($var)
{
return $this->HttpQuery->Remove($var);
}
/**
* Deletes Session variable
*
* @param string $var
*/
function RemoveVar($var)
{
return $this->Session->RemoveVar($var);
}
function RemovePersistentVar($var)
{
return $this->Session->RemovePersistentVar($var);
}
/**
* Restores Session variable to it's db version
*
* @param string $var
*/
function RestoreVar($var)
{
return $this->Session->RestoreVar($var);
}
/**
* Returns session variable value
*
* Return value of $var variable stored in Session. An optional default value could be passed as second parameter.
*
* @see SimpleSession
* @access public
* @param string $var Variable name
* @param mixed $default Default value to return if no $var variable found in session
* @return mixed
*/
function RecallVar($var,$default=false)
{
return $this->Session->RecallVar($var,$default);
}
function RecallPersistentVar($var, $default = false)
{
return $this->Session->RecallPersistentVar($var, $default);
}
/**
* Stores variable $val in session under name $var
*
* Use this method to store variable in session. Later this variable could be recalled.
* @see RecallVar
* @access public
* @param string $var Variable name
* @param mixed $val Variable value
*/
function StoreVar($var, $val)
{
$session =& $this->recallObject('Session');
$this->Session->StoreVar($var, $val);
}
function StorePersistentVar($var, $val)
{
$this->Session->StorePersistentVar($var, $val);
}
function StoreVarDefault($var, $val)
{
$session =& $this->recallObject('Session');
$this->Session->StoreVarDefault($var, $val);
}
/**
* Links HTTP Query variable with session variable
*
* If variable $var is passed in HTTP Query it is stored in session for later use. If it's not passed it's recalled from session.
* This method could be used for making sure that GetVar will return query or session value for given
* variable, when query variable should overwrite session (and be stored there for later use).<br>
* This could be used for passing item's ID into popup with multiple tab -
* in popup script you just need to call LinkVar('id', 'current_id') before first use of GetVar('id').
* After that you can be sure that GetVar('id') will return passed id or id passed earlier and stored in session
* @access public
* @param string $var HTTP Query (GPC) variable name
* @param mixed $ses_var Session variable name
* @param mixed $default Default variable value
*/
function LinkVar($var, $ses_var = null, $default = '')
{
if (!isset($ses_var)) $ses_var = $var;
if ($this->GetVar($var) !== false) {
$this->StoreVar($ses_var, $this->GetVar($var));
}
else {
$this->SetVar($var, $this->RecallVar($ses_var, $default));
}
}
/**
* Returns variable from HTTP Query, or from session if not passed in HTTP Query
*
* The same as LinkVar, but also returns the variable value taken from HTTP Query if passed, or from session if not passed.
* Returns the default value if variable does not exist in session and was not passed in HTTP Query
*
* @see LinkVar
* @access public
* @param string $var HTTP Query (GPC) variable name
* @param mixed $ses_var Session variable name
* @param mixed $default Default variable value
* @return mixed
*/
function GetLinkedVar($var, $ses_var = null, $default = '')
{
$this->LinkVar($var, $ses_var, $default);
return $this->GetVar($var);
}
function AddBlock($name, $tpl)
{
$this->cache[$name] = $tpl;
}
/* Seems to be not used anywhere... /Kostja
function SetTemplateBody($title,$body)
{
$templates_cache =& $this->recallObject('TemplatesCache');
$templates_cache->SetTemplateBody($title,$body);
}*/
function ProcessTag($tag_data)
{
$a_tag = new Tag($tag_data,$this->Parser);
return $a_tag->DoProcessTag();
}
function ProcessParsedTag($prefix, $tag, $params)
{
if (defined('NPARSER') && NPARSER) {
$p = $this->Parser->GetProcessor($prefix);
return $p->ProcessParsedTag($tag, $params, $prefix);
}
$a_tag = new Tag('',$this->Parser);
$a_tag->Tag = $tag;
$tmp=$this->Application->processPrefix($prefix);
$a_tag->Processor = $tmp['prefix'];
$a_tag->Special = $tmp['special'];
$a_tag->NamedParams = $params;
return $a_tag->DoProcessTag();
}
/**
* Return ADODB Connection object
*
* Returns ADODB Connection object already connected to the project database, configurable in config.php
* @access public
* @return kDBConnection
*/
function &GetADODBConnection()
{
return $this->Conn;
}
function ParseBlock($params,$pass_params=0,$as_template=false)
{
if (substr($params['name'], 0, 5) == 'html:') return substr($params['name'], 6);
return $this->Parser->ParseBlock($params, $pass_params, $as_template);
}
/**
* Returns index file, that could be passed as parameter to method, as parameter to tag and as constant or not passed at all
*
* @param string $prefix
* @param string $index_file
* @param Array $params
* @return string
*/
function getIndexFile($prefix, $index_file, &$params)
{
if (isset($params['index_file'])) {
$index_file = $params['index_file'];
unset($params['index_file']);
return $index_file;
}
if (isset($index_file)) {
return $index_file;
}
if (defined('INDEX_FILE')) {
return INDEX_FILE;
}
$cut_prefix = trim(BASE_PATH, '/').'/'.trim($prefix, '/');
return trim(preg_replace('/'.preg_quote($cut_prefix, '/').'(.*)/', '\\1', $_SERVER['PHP_SELF']), '/');
}
/**
* Return href for template
*
* @access public
* @param string $t Template path
* @var string $prefix index.php prefix - could be blank, 'admin'
*/
function HREF($t, $prefix='', $params=null, $index_file=null)
{
if(!$t) $t = $this->GetVar('t'); // moved from kMainTagProcessor->T()
if ($this->isModuleEnabled('Proj-CMS')) {
$t = preg_replace('/^Content\//', '', $t);
}
/*if ($this->GetVar('skip_last_template')) {
$params['opener'] = 'p';
$this->SetVar('m_opener', 'p');
}
if ($t == 'incs/close_popup') {
// because this template closes the popup and we don't need popup mark here anymore
$params['m_opener'] = 's';
}*/
if( substr($t, -4) == '.tpl' ) $t = substr($t, 0, strlen($t) - 4 );
if ( $this->IsAdmin() && $prefix == '') $prefix = ADMIN_DIRECTORY;
if ( $this->IsAdmin() && $prefix == '_FRONT_END_') $prefix = '';
$index_file = $this->getIndexFile($prefix, $index_file, $params);
if (isset($params['_auto_prefix_'])) {
unset($params['_auto_prefix_']); // this is parser-related param, do not need to pass it here
}
$ssl = isset($params['__SSL__']) ? $params['__SSL__'] : null;
if ($ssl !== null) {
$session =& $this->recallObject('Session');
$cookie_url = trim($session->CookieDomain.$session->CookiePath, '/.');
if ($ssl) {
$target_url = $this->ConfigValue('SSL_URL');
}
else {
$target_url = 'http://'.DOMAIN.$this->ConfigValue('Site_Path');
}
if (!preg_match('#'.preg_quote($cookie_url).'#', $target_url)) {
$session->SetMode(smGET_ONLY);
}
}
if (isset($params['opener']) && $params['opener'] == 'u') {
$wid = $this->Application->GetVar('m_wid');
$stack_name = rtrim('opener_stack_'.$wid, '_');
$opener_stack = $this->RecallVar($stack_name);
if ($opener_stack && $opener_stack != serialize(Array())) {
$opener_stack = unserialize($opener_stack);
list($index_file, $env) = explode('|', $opener_stack[count($opener_stack) - 1]);
$ret = $this->BaseURL($prefix, $ssl).$index_file.'?'.ENV_VAR_NAME.'='.$env;
if ( getArrayValue($params,'escape') ) $ret = addslashes($ret);
if (isset($params['m_opener']) && $params['m_opener'] == 'u') {
array_pop($opener_stack);
if (!$opener_stack) {
$this->RemoveVar($stack_name);
// remove popups last templates, because popup is closing now
$this->RemoveVar('last_template_'.$wid);
$this->RemoveVar('last_template_popup_'.$wid);
// don't save popups last templates again :)
$this->SetVar('skip_last_template', 1);
}
else {
$this->StoreVar($stack_name, serialize($opener_stack));
}
}
return $ret;
}
else {
//define('DBG_REDIRECT', 1);
$t = $this->GetVar('t');
}
}
$pass = isset($params['pass']) ? $params['pass'] : '';
$pass_events = isset($params['pass_events']) ? $params['pass_events'] : false; // pass events with url
$map_link = '';
if( isset($params['anchor']) )
{
$map_link = '#'.$params['anchor'];
unset($params['anchor']);
}
if ( isset($params['no_amp']) )
{
$params['__URLENCODE__'] = $params['no_amp'];
unset($params['no_amp']);
}
$no_rewrite = false;
if( isset($params['__NO_REWRITE__']) )
{
$no_rewrite = true;
unset($params['__NO_REWRITE__']);
}
$force_rewrite = false;
if( isset($params['__MOD_REWRITE__']) )
{
$force_rewrite = true;
unset($params['__MOD_REWRITE__']);
}
$force_no_sid = false;
if( isset($params['__NO_SID__']) )
{
$force_no_sid = true;
unset($params['__NO_SID__']);
}
// append pass through variables to each link to be build
// $params = array_merge_recursive2($this->getPassThroughVariables($params), $params);
$params = array_merge($this->getPassThroughVariables($params), $params);
if ($force_rewrite || ($this->RewriteURLs($ssl) && !$no_rewrite))
{
$session =& $this->recallObject('Session');
if( $session->NeedQueryString() && !$force_no_sid ) $params['sid'] = $this->GetSID();
$url = $this->BuildEnv_NEW($t, $params, $pass, $pass_events);
$ret = $this->BaseURL($prefix, $ssl).$url.$map_link;
}
else
{
unset($params['pass_category']); // we don't need to pass it when mod_rewrite is off
$env = $this->BuildEnv($t, $params, $pass, $pass_events);
$ret = $this->BaseURL($prefix, $ssl).$index_file.'?'.$env.$map_link;
}
return $ret;
}
/**
* Returns variables with values that should be passed throught with this link + variable list
*
* @param Array $params
* @return Array
*/
function getPassThroughVariables(&$params)
{
static $cached_pass_through = null;
if (isset($params['no_pass_through']) && $params['no_pass_through']) {
unset($params['no_pass_through']);
return Array();
}
// because pass through is not changed during script run, then we can cache it
if (is_null($cached_pass_through)) {
$cached_pass_through = Array();
$pass_through = $this->Application->GetVar('pass_through');
if ($pass_through) {
// names of variables to pass to each link
$cached_pass_through['pass_through'] = $pass_through;
$pass_through = explode(',', $pass_through);
foreach ($pass_through as $pass_through_var) {
$cached_pass_through[$pass_through_var] = $this->Application->GetVar($pass_through_var);
}
}
}
return $cached_pass_through;
}
/**
* Returns sorted array of passed prefixes (to build url from)
*
* @param string $pass
* @return Array
*/
function getPassInfo($pass = 'all')
{
if (!$pass) $pass = 'all';
$pass = trim(
preg_replace(
'/(?<=,|\\A)all(?=,|\\z)/',
trim($this->GetVar('passed'), ','),
trim($pass, ',')
),
',');
if (!$pass) {
return Array();
}
$pass_info = array_unique( explode(',', $pass) ); // array( prefix[.special], prefix[.special] ...
sort($pass_info, SORT_STRING); // to be prefix1,prefix1.special1,prefix1.special2,prefix3.specialX
// ensure that "m" prefix is at the beginning
$main_index = array_search('m', $pass_info);
if ($main_index !== false) {
unset($pass_info[$main_index]);
array_unshift($pass_info, 'm');
}
return $pass_info;
}
function BuildEnv_NEW($t, $params, $pass='all', $pass_events = false)
{
// $session =& $this->recallObject('Session');
$force_admin = getArrayValue($params,'admin') || $this->GetVar('admin');
// if($force_admin) $sid = $this->GetSID();
$ret = '';
$env = '';
$encode = false;
if (isset($params['__URLENCODE__']))
{
$encode = $params['__URLENCODE__'];
unset($params['__URLENCODE__']);
}
if (isset($params['__SSL__'])) {
unset($params['__SSL__']);
}
$m_only = true;
$pass_info = $this->getPassInfo($pass);
if ($pass_info) {
if ($pass_info[0] == 'm') array_shift($pass_info);
$params['t'] = $t;
foreach($pass_info as $pass_index => $pass_element)
{
list($prefix) = explode('.', $pass_element);
$require_rewrite = $this->findModule('Var', $prefix) && $this->getUnitOption($prefix, 'CatalogItem');
if ($require_rewrite) {
// if next prefix is same as current, but with special => exclude current prefix from url
$next_prefix = getArrayValue($pass_info, $pass_index + 1);
if ($next_prefix) {
$next_prefix = substr($next_prefix, 0, strlen($prefix) + 1);
if ($prefix.'.' == $next_prefix) continue;
}
$a = $this->BuildModuleEnv_NEW($pass_element, $params, $pass_events);
if ($a) {
$ret .= '/'.$a;
$m_only = false;
}
}
else
{
$env .= ':'.$this->BuildModuleEnv($pass_element, $params, $pass_events);
}
}
if (!$m_only) $params['pass_category'] = 1;
$ret = $this->BuildModuleEnv_NEW('m', $params, $pass_events).$ret;
$cat_processed = isset($params['category_processed']) && $params['category_processed'];
if ($cat_processed) {
unset($params['category_processed']);
}
if (!$m_only || !$cat_processed || !defined('EXP_DIR_URLS')) {
$ret = trim($ret, '/').'.html';
}
else {
$ret .= '/';
}
// $ret = trim($ret, '/').'/';
if($env) $params[ENV_VAR_NAME] = ltrim($env, ':');
}
unset($params['pass'], $params['opener'], $params['m_event']);
if ($force_admin) $params['admin'] = 1;
if( getArrayValue($params,'escape') )
{
$ret = addslashes($ret);
unset($params['escape']);
}
$ret = str_replace('%2F', '/', urlencode($ret));
$params_str = '';
$join_string = $encode ? '&' : '&amp;';
foreach ($params as $param => $value)
{
$params_str .= $join_string.$param.'='.$value;
}
$ret .= preg_replace('/^'.$join_string.'(.*)/', '?\\1', $params_str);
if ($encode) {
$ret = str_replace('\\', '%5C', $ret);
}
return $ret;
}
function BuildModuleEnv_NEW($prefix_special, &$params, $pass_events = false)
{
$event_params = Array('pass_events' => $pass_events, 'url_params' => $params);
$event = new kEvent($prefix_special.':BuildEnv', $event_params);
$this->HandleEvent($event);
$params = $event->getEventParam('url_params'); // save back unprocessed parameters
$ret = '';
if ($event->getEventParam('env_string')) {
$ret = trim( $event->getEventParam('env_string'), '/');
}
return $ret;
}
/**
* Builds env part that corresponds prefix passed
*
* @param string $prefix_special item's prefix & [special]
* @param Array $params url params
* @param bool $pass_events
*/
function BuildModuleEnv($prefix_special, &$params, $pass_events = false)
{
list($prefix) = explode('.', $prefix_special);
$query_vars = $this->getUnitOption($prefix, 'QueryString');
//if pass events is off and event is not implicity passed
if( !$pass_events && !isset($params[$prefix_special.'_event']) ) {
$params[$prefix_special.'_event'] = ''; // remove event from url if requested
//otherwise it will use value from get_var
}
if(!$query_vars) return '';
$tmp_string = Array(0 => $prefix_special);
foreach($query_vars as $index => $var_name)
{
//if value passed in params use it, otherwise use current from application
$var_name = $prefix_special.'_'.$var_name;
$tmp_string[$index] = isset( $params[$var_name] ) ? $params[$var_name] : $this->GetVar($var_name);
if ( isset($params[$var_name]) ) unset( $params[$var_name] );
}
$escaped = array();
foreach ($tmp_string as $tmp_val) {
$escaped[] = str_replace(Array('-',':'), Array('\-','\:'), $tmp_val);
}
$ret = implode('-', $escaped);
if ($this->getUnitOption($prefix, 'PortalStyleEnv') == true)
{
$ret = preg_replace('/^([a-zA-Z]+)-([0-9]+)-(.*)/','\\1\\2-\\3', $ret);
}
return $ret;
}
function BuildEnv($t, $params, $pass='all', $pass_events = false, $env_var = true)
{
$session =& $this->recallObject('Session');
$ssl = isset($params['__SSL__']) ? $params['__SSL__'] : 0;
$sid = $session->NeedQueryString() && !$this->RewriteURLs($ssl) ? $this->GetSID() : '';
// if (getArrayValue($params,'admin') == 1) $sid = $this->GetSID();
$ret = '';
if ($env_var) {
$ret = ENV_VAR_NAME.'=';
}
$ret .= $sid.(constOn('INPORTAL_ENV') ? '-' : ':');
$encode = false;
if (isset($params['__URLENCODE__'])) {
$encode = $params['__URLENCODE__'];
unset($params['__URLENCODE__']);
}
if (isset($params['__SSL__'])) {
unset($params['__SSL__']);
}
$env_string = '';
$category_id = isset($params['m_cat_id']) ? $params['m_cat_id'] : $this->GetVar('m_cat_id');
$item_id = 0;
$pass_info = $this->getPassInfo($pass);
if ($pass_info) {
if ($pass_info[0] == 'm') array_shift($pass_info);
foreach ($pass_info as $pass_element) {
list($prefix) = explode('.', $pass_element);
$require_rewrite = $this->findModule('Var', $prefix);
if ($require_rewrite) {
$item_id = isset($params[$pass_element.'_id']) ? $params[$pass_element.'_id'] : $this->GetVar($pass_element.'_id');
}
$env_string .= ':'.$this->BuildModuleEnv($pass_element, $params, $pass_events);
}
}
if (strtolower($t) == '__default__') {
// to put category & item templates into cache
$filename = $this->getFilename('c', $category_id);
if ($item_id) {
$mod_rw_helper =& $this->Application->recallObject('ModRewriteHelper');
$t = $mod_rw_helper->GetItemTemplate($category_id, $pass_element); // $pass_element should be the last processed element
// $t = $this->getCache('item_templates', $category_id);
}
elseif ($category_id) {
$t = $this->getCache('category_templates', $category_id);
}
else {
$t = 'index';
}
}
$ret .= $t.':'.$this->BuildModuleEnv('m', $params, $pass_events).$env_string;
unset($params['pass'], $params['opener'], $params['m_event']);
if ($this->GetVar('admin') && !isset($params['admin'])) {
$params['admin'] = 1;
}
if( isset($params['escape']) && $params['escape'] )
{
$ret = addslashes($ret);
unset($params['escape']);
}
$join_string = $encode ? '&' : '&amp;';
$params_str = '';
foreach ($params as $param => $value)
{
$params_str .= $join_string.$param.'='.$value;
}
$ret .= $params_str;
if ($encode) {
$ret = str_replace('\\', '%5C', $ret);
}
return $ret;
}
function BaseURL($prefix='', $ssl=null)
{
if ($ssl === null) {
return PROTOCOL.SERVER_NAME.(defined('PORT')?':'.PORT : '').rtrim(BASE_PATH, '/').$prefix.'/';
}
else {
if ($ssl) {
return rtrim( $this->ConfigValue('SSL_URL'), '/').$prefix.'/';
}
else {
return 'http://'.DOMAIN.(defined('PORT')?':'.PORT : '').rtrim( $this->ConfigValue('Site_Path'), '/').$prefix.'/';
}
}
}
function Redirect($t='', $params=null, $prefix='', $index_file=null)
{
$js_redirect = getArrayValue($params, 'js_redirect');
if (preg_match("/external:(.*)/", $t, $rets)) {
$location = $rets[1];
}
else {
if ($t == '' || $t === true) $t = $this->GetVar('t');
// pass prefixes and special from previous url
if( isset($params['js_redirect']) ) unset($params['js_redirect']);
if (!isset($params['pass'])) $params['pass'] = 'all';
if ($this->GetVar('ajax') == 'yes' && $t == $this->GetVar('t')) {
// redirects to the same template as current
$params['ajax'] = 'yes';
}
$params['__URLENCODE__'] = 1;
$location = $this->HREF($t, $prefix, $params, $index_file);
//echo " location : $location <br>";
}
$a_location = $location;
$location = "Location: $location";
if ($this->isDebugMode() && constOn('DBG_REDIRECT')) {
$this->Debugger->appendTrace();
echo "<b>Debug output above!!!</b> Proceed to redirect: <a href=\"$a_location\">$a_location</a><br>";
}
else {
if ($js_redirect) {
$this->SetVar('t', 'redirect');
$this->SetVar('redirect_to_js', addslashes($a_location) );
$this->SetVar('redirect_to', $a_location);
return true;
}
else {
if ($this->GetVar('ajax') == 'yes' && $t != $this->GetVar('t')) {
// redirection to other then current template during ajax request
echo '#redirect#'.$a_location;
}
elseif (headers_sent() != '') {
// some output occured -> redirect using javascript
echo '<script type="text/javascript">window.location.href = \''.$a_location.'\';</script>';
}
else {
// no output before -> redirect using HTTP header
// header('HTTP/1.1 302 Found');
header("$location");
}
}
}
ob_end_flush();
// session expiration is called from session initialization,
// that's why $this->Session may be not defined here
$session =& $this->Application->recallObject('Session');
/* @var $session Session */
$this->HandleEvent( new kEvent('adm:OnBeforeShutdown') );
$session->SaveData();
exit;
}
function Phrase($label)
{
return $this->Phrases->GetPhrase($label);
}
/**
* Replace language tags in exclamation marks found in text
*
* @param string $text
* @param bool $force_escape force escaping, not escaping of resulting string
* @return string
* @access public
*/
function ReplaceLanguageTags($text, $force_escape=null)
{
// !!!!!!!!
// if( !is_object($this->Phrases) ) $this->Debugger->appendTrace();
return $this->Phrases->ReplaceLanguageTags($text,$force_escape);
}
/**
* Checks if user is logged in, and creates
* user object if so. User object can be recalled
* later using "u.current" prefix_special. Also you may
* get user id by getting "u.current_id" variable.
*
* @access private
*/
function ValidateLogin()
{
$session =& $this->recallObject('Session');
$user_id = $session->GetField('PortalUserId');
if (!$user_id && $user_id != -1) $user_id = -2;
$this->SetVar('u.current_id', $user_id);
if (!$this->IsAdmin()) {
// needed for "profile edit", "registration" forms ON FRONT ONLY
$this->SetVar('u_id', $user_id);
}
$this->StoreVar('user_id', $user_id);
if ($this->GetVar('expired') == 1) {
// this parameter is set only from admin
$user =& $this->recallObject('u.current');
$user->SetError('ValidateLogin', 'session_expired', 'la_text_sess_expired');
}
if (($user_id != -2) && constOn('DBG_REQUREST_LOG') ) {
$http_query =& $this->recallObject('HTTPQuery');
$http_query->writeRequestLog(DBG_REQUREST_LOG);
}
if ($user_id != -2) {
// normal users + root
$this->LoadPersistentVars();
}
}
/**
* Loads current user persistent session data
*
*/
function LoadPersistentVars()
{
$this->Session->LoadPersistentVars();
}
function LoadCache() {
$cache_key = $this->GetVar('t').$this->GetVar('m_theme').$this->GetVar('m_lang').$this->IsAdmin();
$query = sprintf("SELECT PhraseList, ConfigVariables FROM %s WHERE Template = %s",
TABLE_PREFIX.'PhraseCache',
$this->Conn->Qstr(md5($cache_key)));
$res = $this->Conn->GetRow($query);
if ($res) {
$this->Caches['PhraseList'] = $res['PhraseList'] ? explode(',', $res['PhraseList']) : array();
$config_ids = $res['ConfigVariables'] ? explode(',', $res['ConfigVariables']) : array();
if (isset($this->Caches['ConfigVariables'])) {
$config_ids = array_diff($config_ids, $this->Caches['ConfigVariables']);
}
}
else {
$config_ids = array();
}
$this->Caches['ConfigVariables'] = $config_ids;
$this->ConfigCacheIds = $config_ids;
}
function UpdateCache()
{
$update = false;
//something changed
$update = $update || $this->Phrases->NeedsCacheUpdate();
$update = $update || (count($this->ConfigCacheIds) && $this->ConfigCacheIds != $this->Caches['ConfigVariables']);
if ($update) {
$cache_key = $this->GetVar('t').$this->GetVar('m_theme').$this->GetVar('m_lang').$this->IsAdmin();
$query = sprintf("REPLACE %s (PhraseList, CacheDate, Template, ConfigVariables)
VALUES (%s, %s, %s, %s)",
TABLE_PREFIX.'PhraseCache',
$this->Conn->Qstr(join(',', $this->Phrases->Ids)),
adodb_mktime(),
$this->Conn->Qstr(md5($cache_key)),
$this->Conn->qstr(implode(',', array_unique($this->ConfigCacheIds))));
$this->Conn->Query($query);
}
}
function InitConfig()
{
if (isset($this->Caches['ConfigVariables']) && count($this->Caches['ConfigVariables']) > 0) {
$this->ConfigHash = array_merge($this->ConfigHash, $this->Conn->GetCol(
'SELECT VariableValue, VariableName FROM '.TABLE_PREFIX.'ConfigurationValues
WHERE VariableId IN ('.implode(',', $this->Caches['ConfigVariables']).')', 'VariableName'));
}
}
/**
* Returns configuration option value by name
*
* @param string $name
* @return string
*/
function ConfigValue($name)
{
$res = isset($this->ConfigHash[$name]) ? $this->ConfigHash[$name] : false;
if ($res !== false) return $res;
if (defined('IS_INSTALL') && IS_INSTALL && !$this->TableFound('ConfigurationValues')) {
return false;
}
$res = $this->Conn->GetRow('SELECT VariableId, VariableValue FROM '.TABLE_PREFIX.'ConfigurationValues WHERE VariableName = '.$this->Conn->qstr($name));
if ($res) {
$this->ConfigHash[$name] = $res['VariableValue'];
$this->ConfigCacheIds[] = $res['VariableId'];
return $res['VariableValue'];
}
return false;
}
function UpdateConfigCache()
{
if ($this->ConfigCacheIds) {
}
}
/**
* Allows to process any type of event
*
* @param kEvent $event
* @access public
* @author Alex
*/
function HandleEvent(&$event, $params=null, $specificParams=null)
{
if ( isset($params) ) {
$event = new kEvent( $params, $specificParams );
}
if (!isset($this->EventManager)) {
$this->EventManager =& $this->recallObject('EventManager');
}
$this->EventManager->HandleEvent($event);
}
/**
* Registers new class in the factory
*
* @param string $real_class Real name of class as in class declaration
* @param string $file Filename in what $real_class is declared
* @param string $pseudo_class Name under this class object will be accessed using getObject method
* @param Array $dependecies List of classes required for this class functioning
* @access public
* @author Alex
*/
function registerClass($real_class, $file, $pseudo_class = null, $dependecies = Array() )
{
$this->Factory->registerClass($real_class, $file, $pseudo_class, $dependecies);
}
/**
* Add $class_name to required classes list for $depended_class class.
* All required class files are included before $depended_class file is included
*
* @param string $depended_class
* @param string $class_name
* @author Alex
*/
function registerDependency($depended_class, $class_name)
{
$this->Factory->registerDependency($depended_class, $class_name);
}
/**
* Registers Hook from subprefix event to master prefix event
*
* @param string $hookto_prefix
* @param string $hookto_special
* @param string $hookto_event
* @param string $mode
* @param string $do_prefix
* @param string $do_special
* @param string $do_event
* @param string $conditional
* @access public
* @todo take care of a lot parameters passed
* @author Kostja
*/
function registerHook($hookto_prefix, $hookto_special, $hookto_event, $mode, $do_prefix, $do_special, $do_event, $conditional)
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->registerHook($hookto_prefix, $hookto_special, $hookto_event, $mode, $do_prefix, $do_special, $do_event, $conditional);
}
/**
* Allows one TagProcessor tag act as other TagProcessor tag
*
* @param Array $tag_info
* @author Kostja
*/
function registerAggregateTag($tag_info)
{
$aggregator =& $this->recallObject('TagsAggregator', 'kArray');
$aggregator->SetArrayValue($tag_info['AggregateTo'], $tag_info['AggregatedTagName'], Array($tag_info['LocalPrefix'], $tag_info['LocalTagName'], getArrayValue($tag_info, 'LocalSpecial')));
}
/**
* Returns object using params specified,
* creates it if is required
*
* @param string $name
* @param string $pseudo_class
* @param Array $event_params
* @return Object
* @author Alex
*/
function &recallObject($name,$pseudo_class=null,$event_params=Array())
{
$result =& $this->Factory->getObject($name, $pseudo_class, $event_params);
return $result;
}
/**
* Returns object using Variable number of params,
* all params starting with 4th are passed to object consturctor
*
* @param string $name
* @param string $pseudo_class
* @param Array $event_params
* @return Object
* @author Alex
*/
function &recallObjectP($name,$pseudo_class=null,$event_params=Array())
{
$func_args = func_get_args();
$result =& ref_call_user_func_array( Array(&$this->Factory, 'getObjectP'), $func_args );
return $result;
}
/**
* Returns tag processor for prefix specified
*
* @param string $prefix
* @return kDBTagProcessor
*/
function &recallTagProcessor($prefix)
{
$this->InitParser(); // because kDBTagProcesor is in TemplateParser dependencies
$result =& $this->recallObject($prefix.'_TagProcessor');
return $result;
}
/**
* Checks if object with prefix passes was already created in factory
*
* @param string $name object presudo_class, prefix
* @return bool
* @author Kostja
*/
function hasObject($name)
{
return isset($this->Factory->Storage[$name]);
}
/**
* Removes object from storage by given name
*
* @param string $name Object's name in the Storage
* @author Kostja
*/
function removeObject($name)
{
$this->Factory->DestroyObject($name);
}
/**
* Get's real class name for pseudo class,
* includes class file and creates class
* instance
*
* @param string $pseudo_class
* @return Object
* @access public
* @author Alex
*/
function &makeClass($pseudo_class)
{
$func_args = func_get_args();
$result =& ref_call_user_func_array( Array(&$this->Factory, 'makeClass'), $func_args);
return $result;
}
/**
* Checks if application is in debug mode
*
* @param bool $check_debugger check if kApplication debugger is initialized too, not only for defined DEBUG_MODE constant
* @return bool
* @author Alex
* @access public
*/
function isDebugMode($check_debugger = true)
{
$debug_mode = defined('DEBUG_MODE') && DEBUG_MODE;
if ($check_debugger) {
$debug_mode = $debug_mode && is_object($this->Debugger);
}
return $debug_mode;
}
/**
* Checks if it is admin
*
* @return bool
* @author Alex
*/
function IsAdmin()
{
return constOn('ADMIN');
}
/**
* Apply url rewriting used by mod_rewrite or not
*
* @param bool $ssl Force ssl link to be build
* @return bool
*/
function RewriteURLs($ssl = false)
{
// case #1,#4:
// we want to create https link from http mode
// we want to create https link from https mode
// conditions: ($ssl || PROTOCOL == 'https://') && $this->ConfigValue('UseModRewriteWithSSL')
// case #2,#3:
// we want to create http link from https mode
// we want to create http link from http mode
// conditions: !$ssl && (PROTOCOL == 'https://' || PROTOCOL == 'http://')
$allow_rewriting =
(!$ssl && (PROTOCOL == 'https://' || PROTOCOL == 'http://')) // always allow mod_rewrite for http
|| // or allow rewriting for redirect TO httpS or when already in httpS
(($ssl || PROTOCOL == 'https://') && $this->ConfigValue('UseModRewriteWithSSL')); // but only if it's allowed in config!
return constOn('MOD_REWRITE') && $allow_rewriting;
}
/**
* Reads unit (specified by $prefix)
* option specified by $option
*
* @param string $prefix
* @param string $option
* @param mixed $default
* @return string
* @access public
* @author Alex
*/
function getUnitOption($prefix, $option, $default = false)
{
/*if (!isset($this->UnitConfigReader)) {
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
}*/
return $this->UnitConfigReader->getUnitOption($prefix, $option, $default);
}
/**
* Set's new unit option value
*
* @param string $prefix
* @param string $name
* @param string $value
* @author Alex
* @access public
*/
function setUnitOption($prefix, $option, $value)
{
// $unit_config_reader =& $this->recallObject('kUnitConfigReader');
return $this->UnitConfigReader->setUnitOption($prefix,$option,$value);
}
/**
* Read all unit with $prefix options
*
* @param string $prefix
* @return Array
* @access public
* @author Alex
*/
function getUnitOptions($prefix)
{
// $unit_config_reader =& $this->recallObject('kUnitConfigReader');
return $this->UnitConfigReader->getUnitOptions($prefix);
}
/**
* Returns true if config exists and is allowed for reading
*
* @param string $prefix
* @return bool
*/
function prefixRegistred($prefix)
{
/*if (!isset($this->UnitConfigReader)) {
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
}*/
return $this->UnitConfigReader->prefixRegistred($prefix);
}
/**
* Splits any mixing of prefix and
* special into correct ones
*
* @param string $prefix_special
* @return Array
* @access public
* @author Alex
*/
function processPrefix($prefix_special)
{
return $this->Factory->processPrefix($prefix_special);
}
/**
* Set's new event for $prefix_special
* passed
*
* @param string $prefix_special
* @param string $event_name
* @access public
*/
function setEvent($prefix_special,$event_name)
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->setEvent($prefix_special,$event_name);
}
/**
* SQL Error Handler
*
* @param int $code
* @param string $msg
* @param string $sql
* @return bool
* @access private
* @author Alex
*/
function handleSQLError($code, $msg, $sql)
{
if ( isset($this->Debugger) )
{
$errorLevel = constOn('DBG_SQL_FAILURE') && !defined('IS_INSTALL') ? E_USER_ERROR : E_USER_WARNING;
$this->Debugger->appendTrace();
$error_msg = '<span class="debug_error">'.$msg.' ('.$code.')</span><br><a href="javascript:$Debugger.SetClipboard(\''.htmlspecialchars($sql).'\');"><b>SQL</b></a>: '.$this->Debugger->formatSQL($sql);
$long_id = $this->Debugger->mapLongError($error_msg);
- trigger_error( substr($msg.' ('.$code.') ['.$sql.']',0,1000).' #'.$long_id, $errorLevel);
+ trigger_error( mb_substr($msg.' ('.$code.') ['.$sql.']',0,1000).' #'.$long_id, $errorLevel);
return true;
}
else
{
//$errorLevel = constOn('IS_INSTALL') ? E_USER_WARNING : E_USER_ERROR;
$errorLevel = E_USER_WARNING;
trigger_error('<b>SQL Error</b> in sql: '.$sql.', code <b>'.$code.'</b> ('.$msg.')', $errorLevel);
/*echo '<b>xProcessing SQL</b>: '.$sql.'<br>';
echo '<b>Error ('.$code.'):</b> '.$msg.'<br>';*/
return $errorLevel == E_USER_ERROR ? false : true;
}
}
/**
* Default error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param Array $errcontext
*/
function handleError($errno, $errstr, $errfile = '', $errline = '', $errcontext = '')
{
if( constOn('SILENT_LOG') )
{
$fp = fopen(FULL_PATH.'/silent_log.txt','a');
$time = adodb_date('d/m/Y H:i:s');
fwrite($fp, '['.$time.'] #'.$errno.': '.strip_tags($errstr).' in ['.$errfile.'] on line '.$errline."\n");
fclose($fp);
}
if( !$this->errorHandlers ) {
if ($errno == E_USER_ERROR) {
header('HTTP/1.0 500 Script Fatal Error');
echo ('<div style="background-color: #FEFFBF; margin: auto; padding: 10px; border: 2px solid red; text-align: center">
<strong>Fatal Error: </strong>
'."$errstr in $errfile on line $errline".'
</div>');
exit;
}
return true;
}
$res = false;
$i = 0; // while (not foreach) because it is array of references in some cases
$eh_count = count($this->errorHandlers);
while($i < $eh_count)
{
if( is_array($this->errorHandlers[$i]) )
{
$object =& $this->errorHandlers[$i][0];
$method = $this->errorHandlers[$i][1];
$res = $object->$method($errno, $errstr, $errfile, $errline, $errcontext);
}
else
{
$function = $this->errorHandlers[$i];
$function($errno, $errstr, $errfile, $errline, $errcontext);
}
$i++;
}
return $res;
}
/**
* Returns & blocks next ResourceId available in system
*
* @return int
* @access public
* @author Alex
*/
function NextResourceId()
{
$table_name = TABLE_PREFIX.'IdGenerator';
$this->Conn->Query('LOCK TABLES '.$table_name.' WRITE');
$this->Conn->Query('UPDATE '.$table_name.' SET lastid = lastid + 1');
$id = $this->Conn->GetOne('SELECT lastid FROM '.$table_name);
if($id === false)
{
$this->Conn->Query('INSERT INTO '.$table_name.' (lastid) VALUES (2)');
$id = 2;
}
$this->Conn->Query('UNLOCK TABLES');
return $id - 1;
}
/**
* Returns genealogical main prefix for subtable prefix passes
* OR prefix, that has been found in REQUEST and some how is parent of passed subtable prefix
*
* @param string $current_prefix
* @param string $real_top if set to true will return real topmost prefix, regardless of its id is passed or not
* @return string
* @access public
* @author Kostja / Alex
*/
function GetTopmostPrefix($current_prefix, $real_top=false)
{
// 1. get genealogical tree of $current_prefix
$prefixes = Array ($current_prefix);
while ( $parent_prefix = $this->getUnitOption($current_prefix, 'ParentPrefix') ) {
$current_prefix = $parent_prefix;
array_unshift($prefixes, $current_prefix);
}
if ($real_top) return $current_prefix;
// 2. find what if parent is passed
$passed = explode(',', $this->GetVar('all_passed'));
foreach ($prefixes as $a_prefix) {
if (in_array($a_prefix, $passed)) {
return $a_prefix;
}
}
return $current_prefix;
}
/**
* Triggers email event of type Admin
*
* @param string $email_event_name
* @param int $to_user_id
* @param array $send_params associative array of direct send params, possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEventAdmin($email_event_name, $to_user_id = -1, $send_params = false)
{
$event =& $this->EmailEvent($email_event_name, 1, $to_user_id, $send_params);
return $event;
}
/**
* Triggers email event of type User
*
* @param string $email_event_name
* @param int $to_user_id
* @param array $send_params associative array of direct send params, possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEventUser($email_event_name, $to_user_id = -1, $send_params = false)
{
$event =& $this->EmailEvent($email_event_name, 0, $to_user_id, $send_params);
return $event;
}
/**
* Triggers general email event
*
* @param string $email_event_name
* @param int $email_event_type ( 0 for User, 1 for Admin)
* @param int $to_user_id
* @param array $send_params associative array of direct send params,
* possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEvent($email_event_name, $email_event_type, $to_user_id = -1, $send_params = false)
{
$params = array(
'EmailEventName' => $email_event_name,
'EmailEventToUserId' => $to_user_id,
'EmailEventType' => $email_event_type,
);
if ($send_params) {
$params['DirectSendParams'] = $send_params;
}
$event_str = isset($send_params['use_special']) ? 'emailevents.'.$send_params['use_special'].':OnEmailEvent' : 'emailevents:OnEmailEvent';
$this->HandleEvent($event, $event_str, $params);
return $event;
}
/**
* Allows to check if user in this session is logged in or not
*
* @return bool
*/
function LoggedIn()
{
// no session during expiration process
return is_null($this->Session) ? false : $this->Session->LoggedIn();
}
/**
* Check current user permissions based on it's group permissions in specified category
*
* @param string $name permission name
* @param int $cat_id category id, current used if not specified
* @param int $type permission type {1 - system, 0 - per category}
* @return int
*/
function CheckPermission($name, $type = 1, $cat_id = null)
{
$perm_helper =& $this->recallObject('PermissionsHelper');
return $perm_helper->CheckPermission($name, $type, $cat_id);
}
/**
* Set's any field of current visit
*
* @param string $field
* @param mixed $value
*/
function setVisitField($field, $value)
{
$visit =& $this->recallObject('visits');
$visit->SetDBField($field, $value);
$visit->Update();
}
/**
* Allows to check if in-portal is installed
*
* @return bool
*/
function isInstalled()
{
return $this->InitDone && (count($this->ModuleInfo) > 0);
}
/**
* Allows to determine if module is installed & enabled
*
* @param string $module_name
* @return bool
*/
function isModuleEnabled($module_name)
{
return $this->findModule('Name', $module_name) !== false;
}
function reportError($class, $method)
{
$this->Debugger->appendTrace();
trigger_error('depricated method <b>'.$class.'->'.$method.'(...)</b>', E_USER_ERROR);
}
/**
* Returns Window ID of passed prefix main prefix (in edit mode)
*
* @param string $prefix
* @return mixed
*/
function GetTopmostWid($prefix)
{
$top_prefix = $this->GetTopmostPrefix($prefix);
$mode = $this->GetVar($top_prefix.'_mode');
return $mode != '' ? substr($mode, 1) : '';
}
/**
* Get temp table name
*
* @param string $table
* @param mixed $wid
* @return string
*/
function GetTempName($table, $wid = '')
{
if (preg_match('/prefix:(.*)/', $wid, $regs)) {
$wid = $this->GetTopmostWid($regs[1]);
}
return TABLE_PREFIX.'ses_'.$this->GetSID().($wid ? '_'.$wid : '').'_edit_'.$table;
}
function GetTempTablePrefix($wid = '')
{
if (preg_match('/prefix:(.*)/', $wid, $regs)) {
$wid = $this->GetTopmostWid($regs[1]);
}
return TABLE_PREFIX.'ses_'.$this->GetSID().($wid ? '_'.$wid : '').'_edit_';
}
function IsTempTable($table)
{
return preg_match('/'.TABLE_PREFIX.'ses_'.$this->GetSID().'(_[\d]+){0,1}_edit_(.*)/',$table);
}
/**
* Return live table name based on temp table name
*
* @param string $temp_table
* @return string
*/
function GetLiveName($temp_table)
{
if( preg_match('/'.TABLE_PREFIX.'ses_'.$this->GetSID().'(_[\d]+){0,1}_edit_(.*)/',$temp_table, $rets) )
{
// cut wid from table end if any
return $rets[2];
}
else
{
return $temp_table;
}
}
function CheckProcessors($processors)
{
foreach ($processors as $a_processor)
{
if (!isset($this->CachedProcessors[$a_processor])) {
$this->CachedProcessors[$a_processor] =& $this->recallObject($a_processor.'_TagProcessor');
}
}
}
function TimeZoneAdjustment($time_zone = null)
{
if ($time_zone == 'GMT') {
return (-1) * adodb_date('Z');
}
$target_zone = isset($time_zone) ? $time_zone : $this->ConfigValue('Config_Site_Time');
return 3600 * ($target_zone - $this->ConfigValue('Config_Server_Time'));
}
function ApplicationDie($message = '')
{
$message = ob_get_clean().$message;
if ($this->isDebugMode()) {
$message .= $this->Debugger->printReport(true);
}
echo $this->UseOutputCompression() ? gzencode($message, DBG_COMPRESSION_LEVEL) : $message;
exit;
}
/* moved from MyApplication */
function getUserGroups($user_id)
{
switch($user_id)
{
case -1:
$user_groups = $this->ConfigValue('User_LoggedInGroup');
break;
case -2:
$user_groups = $this->ConfigValue('User_LoggedInGroup');
$user_groups .= ','.$this->ConfigValue('User_GuestGroup');
break;
default:
$sql = 'SELECT GroupId FROM '.TABLE_PREFIX.'UserGroup WHERE PortalUserId = '.$user_id;
$res = $this->Conn->GetCol($sql);
$user_groups = Array( $this->ConfigValue('User_LoggedInGroup') );
if(is_array($res))
{
$user_groups = array_merge($user_groups, $res);
}
$user_groups = implode(',', $user_groups);
}
return $user_groups;
}
/**
* Allows to detect if page is browsed by spider (293 agents supported)
*
* @return bool
*/
function IsSpider()
{
static $is_spider = null;
if (!isset($is_spider)) {
$user_agent = trim($_SERVER['HTTP_USER_AGENT']);
$robots = file(FULL_PATH.'/core/robots_list.txt');
foreach ($robots as $robot_info) {
$robot_info = explode("\t", $robot_info, 3);
if ($user_agent == trim($robot_info[2])) {
$is_spider = true;
break;
}
}
}
return $is_spider;
}
/**
* Allows to detect table's presense in database
*
* @param string $table_name
* @return bool
*/
function TableFound($table_name)
{
return $this->Conn->TableFound($table_name);
}
/**
* Returns counter value
*
* @param string $name counter name
* @param Array $params counter parameters
* @param string $query_name specify query name directly (don't generate from parmeters)
* @param bool $multiple_results
* @return mixed
*/
function getCounter($name, $params = Array (), $query_name = null, $multiple_results = false)
{
$count_helper =& $this->Application->recallObject('CountHelper');
/* @var $count_helper kCountHelper */
return $count_helper->getCounter($name, $params, $query_name, $multiple_results);
}
/**
* Resets counter, whitch are affected by one of specified tables
*
* @param string $tables comma separated tables list used in counting sqls
*/
function resetCounters($tables)
{
if (constOn('IS_INSTALL')) {
return ;
}
$count_helper =& $this->Application->recallObject('CountHelper');
/* @var $count_helper kCountHelper */
return $count_helper->resetCounters($tables);
}
/**
* Sends XML header + optionally displays xml heading
*
* @param string $xml_version
* @return string
* @author Alex
*/
function XMLHeader($xml_version = false)
{
$lang =& $this->recallObject('lang.current');
header('Content-type: text/xml; charset='.$lang->GetDBField('Charset'));
return $xml_version ? '<?xml version="'.$xml_version.'" encoding="'.$lang->GetDBField('Charset').'"?>' : '';
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/application.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.186.2.6
\ No newline at end of property
+1.186.2.7
\ No newline at end of property
Index: branches/RC/core/kernel/globals.php
===================================================================
--- branches/RC/core/kernel/globals.php (revision 10097)
+++ branches/RC/core/kernel/globals.php (revision 10098)
@@ -1,633 +1,633 @@
<?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] = isset($paArray1[$sKey2]) ? array_merge_recursive2($paArray1[$sKey2], $sValue2) : $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;
}
/**
* Same as print_r, budet designed for viewing in web page
*
* @param Array $data
* @param string $label
*/
function print_pre($data, $label='', $on_screen = false)
{
$is_debug = false;
if (class_exists('kApplication') && !$on_screen) {
$application =& kApplication::Instance();
$is_debug = $application->isDebugMode();
}
if ($is_debug) {
if ($label) $application->Debugger->appendHTML('<b>'.$label.'</b>');
$application->Debugger->dumpVars($data);
}
else
{
if ($label) echo '<b>', $label, '</b><br>';
echo '<pre>', print_r($data, true), '</pre>';
}
}
/**
* Returns array value if key exists
*
* @param Array $array searchable array
* @param int $key array key
* @return string
* @access public
*/
//
function getArrayValue(&$array, $key)
{
// global $debugger;
// if (is_object($debugger)) $debugger->ProfilePoint('getArrayValue', 1);
$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;
}
/**
* 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));
+ $section = mb_substr($line,1,(mb_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)
{
global $debugger;
if ( defined('DEBUG_MODE') && DEBUG_MODE && isset($debugger) && constOn('DBG_PROFILE_INCLUDES') )
{
if ( in_array($file, get_required_files()) ) return;
global $debugger;
/* $debugger->IncludeLevel++;
$before_mem = memory_get_usage();
*/
$debugger->ProfileStart('inc_'.crc32($file), $file);
include_once($file);
$debugger->ProfileFinish('inc_'.crc32($file));
$debugger->profilerAddTotal('includes', 'inc_'.crc32($file));
/* $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});
+ $p=$p+mb_strlen(${'c'.$strpart});
}
$previous=$strpart;
}
// generating the password from the structure defined in $pass_structure
- for ($g=0;$g<strlen($pass_structure);$g++)
+ for ($g=0;$g<mb_strlen($pass_structure);$g++)
{
mt_srand((double)microtime()*1000000);
- $sel=substr($pass_structure,$g,1);
+ $sel=mb_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, $headers=null, $request_type = 'POST', $curl_options=null)
{
if( is_array($post) )
{
$params_str = '';
foreach($post as $key => $value) $params_str .= $key.'='.urlencode($value).'&';
$post = $params_str;
}
$ch = curl_init($url);
$dbg = false;
if (defined('DEBUG_MODE') && DEBUG_MODE && constOn('DBG_CURL')) {
$dbg = true;
safeDefine('DBG_CURL_LOGFILE', '/curl.log');
$log = fopen(FULL_PATH.DBG_CURL_LOGFILE, 'a');
curl_setopt($ch, CURLOPT_FILE, $log);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_STDERR, $log);
//curl_setopt($ch, CURLOPT_WRITEHEADER, $log);
}
if (!is_null($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
// if we have post data, then POST else use GET method instead
if ($request_type == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
elseif ($request_type == 'GET' && isset($post) && strlen($post) > 0) {
curl_setopt($ch, CURLOPT_URL, preg_match('/\?/', $url) ? $url.'&'.$post : $url.'?'.$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);
curl_setopt($ch, CURLOPT_TIMEOUT, 90);
if (is_array($curl_options)) {
foreach ($curl_options as $option => $value) {
curl_setopt($ch, $option, $value);
}
}
$ret = curl_exec($ch);
$GLOBALS['curl_errorno'] = curl_errno($ch);
$GLOBALS['curl_error'] = curl_error($ch);
curl_close($ch);
if ($dbg) {
fwrite($log, "\n".$ret);
fclose($log);
}
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;
}
/**
* 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, 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, 5);
}
/**
* Formats file/memory size in nice way
*
* @param int $bytes
* @return string
* @access public
*/
function formatSize($bytes)
{
if ($bytes >= 1099511627776) {
$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "TB";
} elseif ($bytes >= 1073741824) {
$return = round($bytes / 1024 / 1024 / 1024, 2);
$suffix = "GB";
} elseif ($bytes >= 1048576) {
$return = round($bytes / 1024 / 1024, 2);
$suffix = "MB";
} elseif ($bytes >= 1024) {
$return = round($bytes / 1024, 2);
$suffix = "KB";
} else {
$return = $bytes;
$suffix = "Byte";
}
$return .= ' '.$suffix;
return $return;
}
/**
* Enter description here...
*
* @param resource $filePointer the file resource to write to
* @param Array $data the data to write out
* @param string $delimiter the field separator
* @param string $enclosure symbol to enclose field data to
* @param string $recordSeparator symbols to separate records with
*/
function fputcsv2($filePointer, $data, $delimiter = ',', $enclosure = '"', $recordSeparator = "\r\n")
{
foreach($data as $field_index => $field_value) {
// replaces an enclosure with two enclosures
$data[$field_index] = str_replace($enclosure, $enclosure.$enclosure, $field_value);
}
$line = $enclosure.implode($enclosure.$delimiter.$enclosure, $data).$enclosure.$recordSeparator;
$line = preg_replace('/'.preg_quote($enclosure).'([0-9\.]+)'.preg_quote($enclosure).'/', '$1', $line);
fwrite($filePointer, $line);
}
/**
* Enter description here...
*
* @param resource $filePointer the file resource to write to
* @param Array $data the data to write out
* @param string $delimiter the field separator
* @param string $enclosure symbol to enclose field data to
* @param string $recordSeparator symbols to separate records with
*/
function getcsvline($data, $delimiter = ',', $enclosure = '"', $recordSeparator = "\r\n")
{
foreach($data as $field_index => $field_value) {
// replaces an enclosure with two enclosures
$data[$field_index] = str_replace($enclosure, $enclosure.$enclosure, $field_value);
}
$line = $enclosure.implode($enclosure.$delimiter.$enclosure, $data).$enclosure.$recordSeparator;
$line = preg_replace('/'.preg_quote($enclosure).'([0-9\.]+)'.preg_quote($enclosure).'/', '$1', $line);
return $line;
}
/**
* Allows to replace #section# within any string with current section
*
* @param string $string
* @return string
*/
function replaceModuleSection($string)
{
$application =& kApplication::Instance();
$module_section = $application->RecallVar('section');
if ($module_section) {
// substitute section instead of #section# parameter in title preset name
$module_section = explode(':', $module_section);
$section = preg_replace('/(configuration|configure)_(.*)/i', '\\2', $module_section[count($module_section) == 2 ? 1 : 0]);
- $string = str_replace('#section#', strtolower($section), $string);
+ $string = str_replace('#section#', mb_strtolower($section), $string);
}
return $string;
}
/**
* Checks, that user IP address is within allowed range
*
* @param string $ip_list semi-column (by default) separated ip address list
* @param string $separator ip address separator (default ";")
*
* @return bool
*/
function ipMatch($ip_list, $separator = ';')
{
$ip_match = false;
$ip_addresses = $ip_list ? explode($separator, $ip_list) : Array ();
foreach ($ip_addresses as $ip_address) {
if (netMatch($ip_address, $_SERVER['REMOTE_ADDR'])) {
$ip_match = true;
break;
}
}
return $ip_match;
}
function netMatch($network, $ip) {
$network = trim($network);
$ip = trim($ip);
if ($network == $ip) {
// comparing 2 ip addresses directly
return true;
}
$d = strpos($network, '-');
if ($d === false) {
// sigle subnet specified
$ip_arr = explode('/', $network);
if (!preg_match("@\d*\.\d*\.\d*\.\d*@", $ip_arr[0], $matches)) {
$ip_arr[0] .= '.0'; // Alternate form 194.1.4/24
}
$network_long = ip2long($ip_arr[0]);
$x = ip2long($ip_arr[1]);
$mask = long2ip($x) == $ip_arr[1] ? $x : (0xffffffff << (32 - $ip_arr[1]));
$ip_long = ip2long($ip);
return ($ip_long & $mask) == ($network_long & $mask);
}
else {
// ip address range specified
$from = ip2long(trim(substr($network, 0, $d)));
$to = ip2long(trim(substr($network, $d + 1)));
$ip = ip2long($ip);
return ($ip >= $from && $ip <= $to);
}
}
function request_headers()
{
if(function_exists("apache_request_headers")) // If apache_request_headers() exists...
{
if($headers = apache_request_headers()) // And works...
{
return $headers; // Use it
}
}
$headers = array();
foreach(array_keys($_SERVER) as $skey)
{
if(substr($skey, 0, 5) == "HTTP_")
{
$headername = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($skey, 0, 5)))));
$headers[$headername] = $_SERVER[$skey];
}
}
return $headers;
}
if (!function_exists('easter_date')) {
// calculates easter date, when calendar extension not installed in php
// see also: http://php.prod.intechnic.lv/manual/en/function.easter-date.php
function easter_date ($Year) {
/*
G is the Golden Number-1
H is 23-Epact (modulo 30)
I is the number of days from 21 March to the Paschal full moon
J is the weekday for the Paschal full moon (0=Sunday,
1=Monday, etc.)
L is the number of days from 21 March to the Sunday on or before
the Paschal full moon (a number between -6 and 28)
*/
$G = $Year % 19;
$C = (int)($Year / 100);
$H = (int)($C - ($C / 4) - ((8*$C+13) / 25) + 19*$G + 15) % 30;
$I = (int)$H - (int)($H / 28)*(1 - (int)($H / 28)*(int)(29 / ($H + 1))*((int)(21 - $G) / 11));
$J = ($Year + (int)($Year/4) + $I + 2 - $C + (int)($C/4)) % 7;
$L = $I - $J;
$m = 3 + (int)(($L + 40) / 44);
$d = $L + 28 - 31 * ((int)($m / 4));
$y = $Year;
$E = mktime(0,0,0, $m, $d, $y);
return $E;
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/globals.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.37.2.2
\ No newline at end of property
+1.37.2.3
\ No newline at end of property
Index: branches/RC/core/kernel/nparser/compiler.php
===================================================================
--- branches/RC/core/kernel/nparser/compiler.php (revision 10097)
+++ branches/RC/core/kernel/nparser/compiler.php (revision 10098)
@@ -1,90 +1,90 @@
<?php
class NParserCompiler extends kHelper {
var $Errors = array();
var $Templates = array();
function CompileTemplatesStep()
{
$templates = $this->Application->RecallVar('templates_to_compile');
if (!$templates) {
// build $templates
$templates = $this->FindTemplates();
}
else {
$templates = unserialize($templates);
}
$total = count($templates);
$current = $this->Application->RecallVar('current_template_to_compile');
if (!$current) $current = 0;
if ($errors = $this->Application->RecallVar('compile_errors')) {
$this->Errors = unserialize($errors);
}
$save_handler = $this->Application->errorHandlers[0];
$this->Application->errorHandlers[0] = array(&$this, 'SaveError');
safeDefine('DBG_NPARSER_FORCE_COMPILE',1);
$i = $current;
$this->Application->InitParser();
while ($i < $total && $i < ($current + 20)) {
$a_template = $templates[$i];
$this->Application->Parser->CheckTemplate($a_template['module'].'/'.$a_template['path']);
$i++;
}
$this->Application->errorHandlers[0] = $save_handler;
$this->Application->StoreVar('current_template_to_compile', $i);
$this->Application->StoreVar('templates_to_compile', serialize($templates));
$this->Application->StoreVar('compile_errors', serialize($this->Errors));
$res = floor(($current / $total) * 100);
if ($res == 100 || $current >= $total) {
$this->Application->RemoveVar('templates_to_compile');
$this->Application->RemoveVar('current_template_to_compile');
$this->Application->Redirect($this->Application->GetVar('finish_template'));
}
echo $res;
}
function SaveError($errno, $errstr, $errfile, $errline, $errcontext)
{
$this->Errors[] = array('msg'=>$errstr, 'file'=>$errfile, 'line'=>$errline);
return true;
}
function FindTemplates()
{
$this->Templates = array();
foreach ($this->Application->ModuleInfo as $module=>$options) {
$this->FindTemplateFiles('/'.$options['Path'].'admin_templates', $options);
}
return $this->Templates;
}
function FindTemplateFiles($folderPath, $options)
{
// if FULL_PATH = "/" ensure, that all "/" in $folderPath are not deleted
$reg_exp = '/^'.preg_quote(FULL_PATH, '/').'/';
$folderPath = preg_replace($reg_exp, '', $folderPath, 1); // this make sense, since $folderPath may NOT contain FULL_PATH
$fh = opendir(FULL_PATH.$folderPath);
while (($sub_folder = readdir($fh))) {
$full_path = FULL_PATH.$folderPath.'/'.$sub_folder;
$base_name = basename($full_path);
if (is_dir($full_path) && $base_name != '.' && $base_name != '..') {
$this->FindTemplateFiles($full_path, $options);
}
else {
$info = pathinfo($full_path);
if (isset($info['extension']) && $info['extension'] == 'tpl') {
- $this->Templates[] = array('module' => strtolower($options['Name']), 'path' => str_replace(FULL_PATH.'/'.$options['Path'].'admin_templates/', '', preg_replace('/\.tpl$/', '', $full_path)));
+ $this->Templates[] = array('module' => mb_strtolower($options['Name']), 'path' => str_replace(FULL_PATH.'/'.$options['Path'].'admin_templates/', '', preg_replace('/\.tpl$/', '', $full_path)));
}
}
}
}
}
\ No newline at end of file
Property changes on: branches/RC/core/kernel/nparser/compiler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1.2.2
\ No newline at end of property
+1.1.2.3
\ No newline at end of property
Index: branches/RC/core/kernel/parser/template.php
===================================================================
--- branches/RC/core/kernel/parser/template.php (revision 10097)
+++ branches/RC/core/kernel/parser/template.php (revision 10098)
@@ -1,267 +1,267 @@
<?php
class Template {
var $Body = '';
var $BasePath = '';
var $Filename = '';
function Template($base_path=null, $filename=null, $silent=0)
{
if ($this->SetBasePath($base_path)) {
if (isset($filename)) {
$this->Filename = $filename;
$this->LoadTemplate($silent);
}
}
}
function SetBasePath($base_path=null)
{
if (isset($base_path)) {
$base_path = eregi_replace("/$", '', $base_path); //Cutting possible last slash
$this->BasePath = $base_path;
return true;
}
return false;
}
function GetFullPath()
{
return $this->BasePath.'/'.ltrim($this->Filename, '/').'.tpl';
}
/**
* Enter description here...
*
* @param int $silent template not found {0 - fatal error, 1 - warning, 2 - nothing}
* @return bool
*/
function LoadTemplate($silent = 0)
{
$filename = $this->GetFullPath();
if (file_exists($filename)) {
if (filesize ($filename) == 0) {
trigger_error("Template file size is 0: <b>$filename</b>", ($silent ? E_USER_NOTICE : E_USER_ERROR) );
}
// stripping out special comments
$this->SetBody(preg_replace('/<!--##.*##-->/sU', '', file_get_contents($filename)));
/*$handle = fopen ($filename, "r");
$contents = fread ($handle, filesize ($filename));
$this->SetBody($contents);
fclose ($handle);*/
return true;
}
else {
if (($silent != 2) && !$silent) {
$application =& kApplication::Instance();
if ($application->isDebugMode()) {
$application->Debugger->appendTrace();
}
trigger_error('File or block not found: <b>'.$filename.'</b> at '.$application->Parser->TemplateName, E_USER_ERROR);
}
return false;
}
}
function SetBody($body)
{
$this->Body = $body;
}
function GetBody()
{
return $this->Body;
}
}
class TemplatesCache extends kBase {
var $Templates = Array();
var $BasePath;
var $FileNames = Array();
function TemplatesCache()
{
parent::kBase();
$this->BasePath = FULL_PATH.THEMES_PATH;
$conn =& $this->Application->GetADODBConnection();
}
/**
* Based on template name gets it's location on disk and owner module
*
* @param string $filename
* @return Array 0 - path on disk, 1 - template name
*/
function GetTemplatePaths($filename)
{
if ($this->Application->IsAdmin() && isset($this->Application->ReplacementTemplates[$filename])) {
$filename = $this->Application->ReplacementTemplates[$filename];
}
// allows to use non-replaced version of replaced template
$filename = preg_replace('/^original:(.*)/', '\\1', $filename);
if (preg_match('#^[\/]{0,1}([^\/]*)\/(.*)#', $filename, $regs)) {
$module_filename = $regs[2];
$first_dir = $regs[1];
}
else {
$first_dir = '';
$module_filename = $filename;
}
// !preg_match for backward compatability with full-path plugins
if ($this->Application->IsAdmin() && $first_dir == 'plugins' && !preg_match('/admin_templates/', $module_filename)) {
if (preg_match('#^[\/]{0,1}([^\/]*)\/(.*)#', $module_filename, $regs)) {;
- $path = MODULES_PATH.'/'.strtolower($first_dir).'/'.$regs[1].'/admin_templates';
+ $path = MODULES_PATH.'/'.mb_strtolower($first_dir).'/'.$regs[1].'/admin_templates';
$module_filename = $regs[2];
}
else {
$first_dir = '';
$module_filename = $filename;
}
}
elseif ( $this->Application->IsAdmin() && $this->Application->findModule('Name', $first_dir)) {
if ($first_dir == 'in-portal') {
$first_dir = 'kernel';
}
- $path = MODULES_PATH.'/'.strtolower($first_dir).'/admin_templates';
+ $path = MODULES_PATH.'/'.mb_strtolower($first_dir).'/admin_templates';
}
else {
$path = $this->BasePath;
$module_filename = $first_dir.'/'.$module_filename;
}
return Array ($path, $module_filename);
}
function LoadTemplate($filename, $title=NULL, $silent=0)
{
list ($path, $module_filename) = $this->GetTemplatePaths($filename);
$template = new Template($path, $module_filename, $silent);
if (!isset($title)) $title = $filename;
$this->SetTemplate($title, $template);
}
function GetRealFilename($filename)
{
list ($path, $module_filename) = $this->GetTemplatePaths($filename);
return $path.'/'.trim($module_filename, '/');
}
function SetTemplate($title, &$template, $filename=null)
{
if (!isset($filename)) $filename=$title;
$this->Templates[$title] = $template;
$this->FileNames[$title] = $filename;
}
function &GetTemplate($title, $silent=0)
{
if (!isset($this->Templates[$title])) {
$this->LoadTemplate($title, null, $silent);
}
return $this->Templates[$title];
}
function GetTemplateBody($title, $silent=0)
{
$template =& $this->GetTemplate($title, $silent);
if ( !is_object($template) ) {
return '';
}
return $template->GetBody();
}
function GetTemplateFileName($title)
{
return getArrayValue($this->FileNames, $title);
}
function SetTemplateBody($title, $body)
{
$template = new Template();
$template->SetBody($body);
$this->SetTemplate($title, $template);
}
function ParseTemplate($template_name)
{
$Parser = new TemplateParser($this->Application);
return $Parser->Parse( $this->GetTemplateBody($template_name) );
}
function TemplateExists($filename)
{
$real_file = $this->GetRealFilename($filename);
if (!preg_match('/\.tpl$/', $real_file)) {
$real_file .= '.tpl';
}
return file_exists($real_file);
}
function GetPreParsed($template)
{
$real_name = $this->GetRealFilename($template);
$fname = $real_name.'.php';
$fname = str_replace(FULL_PATH, defined('WRITEABLE') ? WRITEABLE.'/cache' : FULL_PATH.'/kernel/cache', $fname);
$tname = $real_name.'.tpl';
if (!file_exists($tname)) {
return false;
}
if (defined('SAFE_MODE') && SAFE_MODE) {
$conn =& $this->Application->GetADODBConnection();
$cached = $conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'Cache WHERE VarName = "'.$fname.'"');
if ($cached !== false && $cached['Cached'] > filemtime($tname)) {
return array('active' => 1, 'fname' => $fname, 'tname' => $tname, 'mode' => 'db', 'content' => $cached['Data']);
}
}
else {
if (file_exists($fname) && file_exists($tname) && filemtime($fname) > filemtime($tname)) {
return array('active' => 1, 'fname' => $fname, 'tname' => $tname, 'mode' => 'file');
}
if (!file_exists($fname)) {
// make sure to create directory if pre-parsed file does not exist
$this->CheckDir(dirname($fname), defined('WRITEABLE') ? WRITEABLE.'/cache' : FULL_PATH.'/kernel/cache');
}
}
return array('active' => 0, 'fname' => $fname, 'tname' => $tname, 'mode'=>'file');
}
/**
* Recursive mkdir
*
* @param string $dir
* @param string $base_path base path to directory where folders should be created in
*/
function CheckDir($dir, $base_path = '')
{
if (file_exists($dir)) {
return;
}
else {
// remove $base_path from beggining because it is already created during install
$dir = preg_replace('/^'.preg_quote($base_path.'/', '/').'/', '', $dir, 1);
$segments = explode('/', $dir);
$cur_path = $base_path;
foreach ($segments as $segment) {
// do not add leading / for windows paths (c:\...)
$cur_path .= preg_match('/^[a-zA-Z]{1}:/', $segment) ? $segment : '/'.$segment;
if (!file_exists($cur_path)) {
mkdir($cur_path);
}
}
}
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/parser/template.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.26.2.1
\ No newline at end of property
+1.26.2.2
\ No newline at end of property
Index: branches/RC/core/units/themes/themes_tag_processor.php
===================================================================
--- branches/RC/core/units/themes/themes_tag_processor.php (revision 10097)
+++ branches/RC/core/units/themes/themes_tag_processor.php (revision 10098)
@@ -1,61 +1,61 @@
<?php
class ThemesTagProcessor extends kDBTagProcessor
{
function StylesheetFile($params)
{
$object =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix, $params );
if (!$object->GetDBField('StyleName')) {
// no stylesheet is associated with current theme
return '';
}
-
+
$css_url = $this->Application->BaseURL('/kernel/stylesheets');
$css_path = rtrim( str_replace( $this->Application->BaseURL(), FULL_PATH.'/', $css_url), '/' );
$last_compiled = $object->GetDBField('LastCompiled');
- $style_name = strtolower( $object->GetDBField('StyleName') );
+ $style_name = mb_strtolower( $object->GetDBField('StyleName') );
if( file_exists($css_path.'/'.$style_name.'-'.$last_compiled.'.css') )
{
$ret = rtrim($css_url, '/').'/'.$style_name.'-'.$last_compiled.'.css';
}
else
{
// search for previously compiled stylesheet
$last_compiled = 0;
if( $dh = opendir($css_path) )
{
while( ($file = readdir($dh)) !== false )
{
if( preg_match('/(.*)-([\d]+).css/', $file, $rets) )
{
if( $rets[1] == $style_name && $rets[2] > $last_compiled ) $last_compiled = $rets[2];
}
}
closedir($dh);
}
if ($last_compiled) {
// found
$ret = $css_url.'/'.$style_name.'-'.$last_compiled.'.css';
}
else {
// not found
return '';
}
}
if (isset($params['file_only'])) return $ret;
return '<link rel="stylesheet" rev="stylesheet" href="'.$ret.'" type="text/css" media="screen" />';
}
-
+
function SelectedTheme($params)
{
$object =& $this->getObject($params);
return $object->GetDBField('ThemeId') == $this->Application->GetVar('m_theme');
- }
+ }
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/themes/themes_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.7.2.1
\ No newline at end of property
+1.7.2.2
\ No newline at end of property
Index: branches/RC/core/units/categories/categories_item.php
===================================================================
--- branches/RC/core/units/categories/categories_item.php (revision 10097)
+++ branches/RC/core/units/categories/categories_item.php (revision 10098)
@@ -1,229 +1,229 @@
<?php
class CategoriesItem extends kDBItem
{
function Create($force_id=false, $system_create=false)
{
$this->checkFilename();
$this->generateFilename();
if (!$this->Validate()) return false;
$this->SetDBField('ResourceId', $this->Application->NextResourceId());
$this->SetDBField('CreatedById', $this->Application->RecallVar('user_id') );
$this->SetDBField('CreatedOn_date', adodb_mktime() );
$this->SetDBField('CreatedOn_time', adodb_mktime() );
$parent_category = $this->GetDBField('ParentId') > 0 ? $this->GetDBField('ParentId') : $this->Application->GetVar('m_cat_id');
$this->SetDBField('ParentId', $parent_category);
$ret = parent::Create($force_id, $system_create);
if ($ret) {
$sql = 'UPDATE %s SET ParentPath = %s WHERE CategoryId = %s';
$parent_path = $this->buildParentPath();
$this->Conn->Query( sprintf($sql, $this->TableName, $this->Conn->qstr($parent_path), $this->GetID() ) );
$this->SetDBField('ParentPath', $parent_path);
}
return $ret;
}
function Update($id=null, $system_update=false)
{
$this->checkFilename();
$this->generateFilename();
$ret = parent::Update($id, $system_update);
return $ret;
}
function buildParentPath()
{
$parent_id = $this->GetDBField('ParentId');
if ($parent_id == 0) {
$parent_path = '|';
}
else {
$cat_table = $this->Application->getUnitOption($this->Prefix, 'TableName');
$sql = 'SELECT ParentPath FROM '.$cat_table.' WHERE CategoryId = %s';
$parent_path = $this->Conn->GetOne( sprintf($sql, $parent_id) );
}
return $parent_path.$this->GetID().'|';
}
/**
* replace not allowed symbols with "_" chars + remove duplicate "_" chars in result
*
* @param string $string
* @return string
*/
function stripDisallowed($string)
{
$not_allowed = Array( ' ', '\\', '/', ':', '*', '?', '"', '<', '>', '|', '`',
'~', '!', '@', '#', '$', '%', '^', '&', '(', ')', '~',
'+', '=', '-', '{', '}', ']', '[', "'", ';', '.', ',');
$string = str_replace($not_allowed, '_', $string);
$string = preg_replace('/(_+)/', '_', $string);
$string = $this->checkAutoFilename($string);
return $string;
}
function checkFilename()
{
// System templates allow any characters in filename, because they may and will contain "/"
if( !$this->GetDBField('AutomaticFilename') && !$this->GetDBField('IsSystem'))
{
$filename = $this->GetDBField('Filename');
$this->SetDBField('Filename', $this->stripDisallowed($filename) );
}
}
function checkAutoFilename($filename)
{
if(!$filename) return $filename;
$item_id = !$this->GetID() ? 0 : $this->GetID();
-
+
if ($item_id) {
- $parent_cat_id = $this->GetDBField("ParentId");
+ $parent_cat_id = $this->GetDBField("ParentId");
$check_in_parent_cat_only = ' AND ParentId = '.$parent_cat_id;
}
// check temp table
$sql_temp = 'SELECT '.$this->IDField.' FROM '.$this->TableName.' WHERE Filename = '.$this->Conn->qstr($filename).$check_in_parent_cat_only;
$found_temp_ids = $this->Conn->GetCol($sql_temp);
// check live table
$sql_live = 'SELECT '.$this->IDField.' FROM '.$this->Application->GetLiveName($this->TableName).' WHERE Filename = '.$this->Conn->qstr($filename).$check_in_parent_cat_only;
$found_live_ids = $this->Conn->GetCol($sql_live);
$found_item_ids = array_unique( array_merge($found_temp_ids, $found_live_ids) );
$has_page = preg_match('/(.*)_([\d]+)([a-z]*)$/', $filename, $rets);
$duplicates_found = (count($found_item_ids) > 1) || ($found_item_ids && $found_item_ids[0] != $item_id);
if ($duplicates_found || $has_page) // other category has same filename as ours OR we have filename, that ends with _number
{
$append = $duplicates_found ? '_a' : '';
if($has_page)
{
$filename = $rets[1].'_'.$rets[2];
$append = $rets[3] ? $rets[3] : '_a';
}
// check live & temp table
$sql_temp = 'SELECT '.$this->IDField.' FROM '.$this->TableName.' WHERE (Filename = %s) AND ('.$this->IDField.' != '.$item_id.')';
$sql_live = 'SELECT '.$this->IDField.' FROM '.$this->Application->GetLiveName($this->TableName).' WHERE (Filename = %s) AND ('.$this->IDField.' != '.$item_id.')';
while ( $this->Conn->GetOne( sprintf($sql_temp, $this->Conn->qstr($filename.$append)) ) > 0 ||
$this->Conn->GetOne( sprintf($sql_live, $this->Conn->qstr($filename.$append)) ) > 0 )
{
- if (substr($append, -1) == 'z') $append .= 'a';
- $append = substr($append, 0, strlen($append) - 1) . chr( ord( substr($append, -1) ) + 1 );
+ if (mb_substr($append, -1) == 'z') $append .= 'a';
+ $append = mb_substr($append, 0, mb_strlen($append) - 1) . chr( ord( mb_substr($append, -1) ) + 1 );
}
return $filename.$append;
}
return $filename;
}
/**
* Generate item's filename based on it's title field value
*
* @return string
*/
function generateFilename()
{
if ( !$this->GetDBField('AutomaticFilename') && $this->GetDBField('Filename') ) return false;
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$name = $this->stripDisallowed( $this->GetDBField( $ml_formatter->LangFieldName('Name', true) ) );
if ( $name != $this->GetDBField('Filename') ) $this->SetDBField('Filename', $name);
}
/**
* Allows to detect if root category being edited
*
* @param Array $params
*/
function IsRoot()
{
return $this->Application->RecallVar('IsRootCategory_'.$this->Application->GetVar('m_wid'));
}
/**
* Sets correct name to Home category while editing it
*
* @return bool
*/
function IsNewItem()
{
if ($this->IsRoot() && $this->Prefix == 'c') {
$title_field = $this->Application->getUnitOption($this->Prefix, 'TitleField');
$category_name = $this->Application->Phrase( $this->Application->ConfigValue('Root_Name') );
$this->SetDBField($title_field, $category_name);
return false;
}
return parent::IsNewItem();
}
/**
* Sets new name for item in case if it is beeing copied
* in same table
*
* @param array $master Table data from TempHandler
* @param int $foreign_key ForeignKey value to filter name check query by
* @access private
*/
function NameCopy($master=null, $foreign_key=null)
{
$title_field = $this->Application->getUnitOption($this->Prefix, 'TitleField');
if (!$title_field || isset($this->CalculatedFields[$title_field]) ) return;
$new_name = $this->GetDBField($title_field);
$cat_id = $this->Application->GetVar('m_cat_id');
$this->SetDBField('ParentId', $cat_id);
$original_checked = false;
do {
if ( preg_match('/Copy ([0-9]*) *of (.*)/', $new_name, $regs) ) {
$new_name = 'Copy '.($regs[1]+1).' of '.$regs[2];
}
elseif ($original_checked) {
$new_name = 'Copy of '.$new_name;
}
// if we are cloning in temp table this will look for names in temp table,
// since object' TableName contains correct TableName (for temp also!)
// if we are cloning live - look in live
$query = 'SELECT '.$title_field.' FROM '.$this->TableName.'
WHERE ParentId = '.$cat_id.' AND '.$title_field.' = '.$this->Conn->qstr($new_name);
$foreign_key_field = getArrayValue($master, 'ForeignKey');
$foreign_key_field = is_array($foreign_key_field) ? $foreign_key_field[ $master['ParentPrefix'] ] : $foreign_key_field;
if ($foreign_key_field && isset($foreign_key)) {
$query .= ' AND '.$foreign_key_field.' = '.$foreign_key;
}
$res = $this->Conn->GetOne($query);
/*// if not found in live table, check in temp table if applicable
if ($res === false && $object->Special == 'temp') {
$query = 'SELECT '.$name_field.' FROM '.$this->GetTempName($master['TableName']).'
WHERE '.$name_field.' = '.$this->Conn->qstr($new_name);
$res = $this->Conn->GetOne($query);
}*/
$original_checked = true;
} while ($res !== false);
$this->SetDBField($title_field, $new_name);
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/categories/categories_item.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.14.2.1
\ No newline at end of property
+1.14.2.2
\ No newline at end of property
Index: branches/RC/core/units/skins/skin_eh.php
===================================================================
--- branches/RC/core/units/skins/skin_eh.php (revision 10097)
+++ branches/RC/core/units/skins/skin_eh.php (revision 10098)
@@ -1,91 +1,91 @@
<?php
class SkinEventHandler extends kDBEventHandler {
/**
* Allows to set selected theme as primary
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$ids = $this->StoreSelectedIDs($event);
if ($ids) {
$id = array_shift($ids);
$this->setPrimary($id);
}
$this->clearSelectedIDs($event);
}
function setPrimary($id)
{
$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');
$sql = 'UPDATE '.$table_name.'
SET IsPrimary = 0';
$this->Conn->Query($sql);
$sql = 'UPDATE '.$table_name.'
SET IsPrimary = 1
WHERE '.$id_field.' = '.$id;
$this->Conn->Query($sql);
}
/**
* [HOOK] Compile stylesheet file based on theme definitions
*
* @param kEvent $event
*/
function OnCompileStylesheet(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->SwitchToLive();
$ids = $event->MasterEvent->getEventParam('ids');
if (!is_array($ids)) $ids = explode(',', $ids);
if(!$ids) return false;
foreach($ids as $id)
{
$object->Load($id);
$this->Compile($object);
}
}
function Compile(&$object)
{
$ret = $object->GetDBField('CSS');
$options = $object->GetDBField('Options');
$options = unserialize($options);
$options['base_url'] = array('Value'=>rtrim($this->Application->BaseURL(), '/'));
foreach ($options as $key => $row) {
$ret = str_replace('@@'.$key.'@@', $row['Value'], $ret);
}
$compile_ts = adodb_mktime();
$css_path = (defined('WRITEABLE') ? WRITEABLE : FULL_PATH.'/kernel').'/user_files/';
- $css_file = $css_path.'admin-'.strtolower($object->GetDBField('Name')).'-'.$compile_ts.'.css';
+ $css_file = $css_path.'admin-'.mb_strtolower($object->GetDBField('Name')).'-'.$compile_ts.'.css';
$fp = fopen($css_file,'w');
if($fp)
{
- $prev_css = $css_path.'admin-'.strtolower($object->GetDBField('Name')).'-'.$object->GetDBField('LastCompiled').'.css';
+ $prev_css = $css_path.'admin-'.mb_strtolower($object->GetDBField('Name')).'-'.$object->GetDBField('LastCompiled').'.css';
if( file_exists($prev_css) ) unlink($prev_css);
fwrite($fp, $ret);
fclose($fp);
$sql = 'UPDATE '.$object->TableName.' SET LastCompiled = '.$compile_ts.' WHERE '.$object->IDField.' = '.$object->GetID();
$this->Conn->Query($sql);
}
}
}
\ No newline at end of file
Property changes on: branches/RC/core/units/skins/skin_eh.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2.4.2
\ No newline at end of property
+1.2.4.3
\ No newline at end of property
Index: branches/RC/core/units/files/file_tp.php
===================================================================
--- branches/RC/core/units/files/file_tp.php (revision 10097)
+++ branches/RC/core/units/files/file_tp.php (revision 10098)
@@ -1,25 +1,25 @@
<?php
class FileTagProcessor extends kDBTagProcessor {
function DownloadFileLink($params)
{
$params[$this->getPrefixSpecial().'_event'] = 'OnDownloadFile';
$params['pass'] = 'm,'.$this->Application->getUnitOption($this->Prefix, 'ParentPrefix').','.$this->getPrefixSpecial();
return $this->ItemLink($params);
}
function FileIcon($params)
{
$object =& $this->getObject($params);
/* @var $object kDBItem */
- $last_dot = strrpos($object->GetDBField('FilePath'), '.');
- $ext = ($last_dot !== false) ? substr($object->GetDBField('FilePath'), $last_dot + 1).'.gif' : '';
+ $last_dot = mb_strrpos($object->GetDBField('FilePath'), '.');
+ $ext = ($last_dot !== false) ? mb_substr($object->GetDBField('FilePath'), $last_dot + 1).'.gif' : '';
return $ext ? $ext : $params['default'];
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/files/file_tp.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1.2.2
\ No newline at end of property
+1.1.2.3
\ No newline at end of property
Index: branches/RC/core/units/images/image_tag_processor.php
===================================================================
--- branches/RC/core/units/images/image_tag_processor.php (revision 10097)
+++ branches/RC/core/units/images/image_tag_processor.php (revision 10098)
@@ -1,331 +1,331 @@
<?php
class ImageTagProcessor extends kDBTagProcessor {
/**
* Prepares all image parameters as list block parameters (for easy usage)
*
* @param kDBList $object
* @param Array $block_params
* @author Alex
*/
function PrepareListElementParams(&$object, &$block_params)
{
$image_url = $this->ImageSrc($block_params);
if (!$image_url) {
return ;
}
$parent_prefix = $this->Application->getUnitOption($object->Prefix, 'ParentPrefix');
$parent_item =& $this->Application->recallObject($parent_prefix);
$block_params['img_path'] = $image_url;
$image_dimensions = $this->ImageSize($block_params);
$block_params['img_size'] = $image_dimensions ? $image_dimensions : ' width="'.$block_params['DefaultWidth'].'"';
$block_params['alt'] = htmlspecialchars($this->getItemTitle($parent_item)); // $object->GetField('AltName') really used ?
$block_params['align'] = array_key_exists('align', $block_params) ? $block_params['align'] : 'left';
}
/**
* Returns value of object's title field
*
* @param kDBItem $object
* @return string
*/
function getItemTitle(&$object)
{
$title_field = $this->Application->getUnitOption($object->Prefix, 'TitleField');
return $object->GetField($title_field);
}
/**
* [AGGREGATED TAGS] works as <inp2:CatalogItemPrefix_Image, ImageSize, ImageSrc ..../>
*
* @param Array $params
* @return string
*/
function ItemImageTag($params)
{
$this->LoadItemImage($params);
return $this->$params['original_tag']($params);
}
function LargeImageExists($params)
{
$object =& $this->getObject($params);
if ($object->GetDBField('SameImages') == null || $object->GetDBField('SameImages') == 1) {
return false;
}
else {
return true;
}
}
function LoadItemImage($params)
{
$parent_item =& $this->Application->recallObject($params['PrefixSpecial']);
/* @var $parent_item kCatDBItem */
$object =& $this->Application->recallObject($this->getPrefixSpecial(), null, Array('skip_autoload' => true));
/* @var $object kDBItem */
$object->Clear();
// if we need primary thumbnail which is preloaded with category item's list
$is_primary = $this->SelectParam($params, 'primary,Primary');
$image_id = $this->Application->GetVar($this->Prefix.'_id');
if (
// is primary, when primary mark set OR name & field not given
($is_primary || !(isset($params['name']) || isset($params['field']))) &&
// primary image is preloaded AND direct id not given
isset($parent_item->Fields['ThumbPath']) && !$image_id
) {
$object->SetDefaultValues();
$object->SetDBField('Url', $parent_item->GetDBField('FullUrl'));
$object->SetDBField('AltName', $this->getItemTitle($parent_item));
$object->SetDBFieldsFromHash($parent_item->GetFieldValues(), Array('SameImages', 'LocalThumb', 'ThumbPath', 'ThumbUrl', 'LocalImage', 'LocalPath'));
$object->Loaded = true;
}
else { // if requested image is not primary thumbnail - load it directly
$id_field = $this->Application->getUnitOption($this->Prefix, 'ForeignKey');
$parent_table_key = $this->Application->getUnitOption($this->Prefix, 'ParentTableKey');
$keys[$id_field] = $parent_item->GetDBField($parent_table_key);
// which image to load?
if ($is_primary) {
// by PrimaryImage mark
$keys['DefaultImg'] = 1;
}
elseif (getArrayValue($params, 'name')) {
// by ImageName
$keys['Name'] = $params['name'];
}
elseif (getArrayValue($params, 'field')) {
// by virtual field name in main object
$field_options = $parent_item->GetFieldOptions($params['field']);
$keys['Name'] = isset($field_options['original_field']) ? $field_options['original_field'] : $params['field'];
}
elseif ($image_id) {
// by ID
$keys['ImageId'] = $image_id;
}
else {
// by PrimaryImage if no other criteria given
$keys['DefaultImg'] = 1;
}
$object->Load($keys);
if (isset($params['field'])) {
$image_src = $parent_item->GetDBField($params['field']);
// when image is uploaded to virtual field in main item, but not saved to db
$object->SetDBField('ThumbPath', $image_src);
if (!$object->isLoaded()) {
// set fields for displaing new image during main item suggestion with errors
$fields_hash = Array (
'Url' => '',
'ThumbUrl' => '',
'LocalPath' => '',
'SameImages' => 1,
'LocalThumb' => 1,
'LocalImage' => 1,
);
$object->SetDBFieldsFromHash($fields_hash);
$object->Loaded = true;
}
}
}
}
function getImageDimension($type, $params)
{
$ret = isset($params['Max'.$type]) ? $params['Max'.$type] : false;
if (!$ret) {
return $ret;
}
$parent_prefix = $this->Application->getUnitOption($this->Prefix, 'ParentPrefix');
if ($ret == 'thumbnail') {
$ret = $this->Application->ConfigValue($parent_prefix.'_ThumbnailImage'.$type);
}
if ($ret == 'fullsize') {
$ret = $this->Application->ConfigValue($parent_prefix.'_FullImage'.$type);
}
return $ret;
}
/**
* Appends "/" to beginning of image path (in case when missing)
*
* @param kDBItem $object
* @todo old in-portal doesn't append first slash, but we do => append first slash for him :)
*/
function makeRelativePaths(&$object)
{
$thumb_path = $object->GetDBField('ThumbPath');
if ($thumb_path && substr($thumb_path, 0, 1) != '/') {
$object->SetDBField('ThumbPath', '/'.$thumb_path);
}
$local_path = $object->GetDBField('LocalPath');
if ($local_path && substr($local_path, 0, 1) != '/') {
$object->SetDBField('LocalPath', '/'.$local_path);
}
}
function ImageSrc($params)
{
$object =& $this->getObject($params);
$this->makeRelativePaths($object);
$base_url = rtrim($this->Application->BaseURL(), '/');
if ($object->GetDBField('SameImages') && $object->GetDBField('ThumbPath')) {
// we can auto-resize image, when source image available & we use same image for thumbnail & full image in admin
$max_width = $this->getImageDimension('Width', $params);
$max_height = $this->getImageDimension('Height', $params);
// user watermarks from format param
if (!$max_width) {
$max_width = $params['format'];
if ($max_width) {
$max_height = null;
}
}
if ($max_width > 0 || $max_height > 0 || $params['format']) {
$image_helper =& $this->Application->recallObject('ImageHelper');
/* @var $image_helper ImageHelper */
$src_image = FULL_PATH.$object->GetDBField('ThumbPath');
return $image_helper->ResizeImage($src_image, $max_width, $max_height);
}
}
$ret = '';
// if we need thumbnail, or full image is same as thumbnail
$show_thumbnail = $this->SelectParam($params, 'thumbnail,Thumbnail') || // old style
(isset($params['MaxWidth']) && $params['MaxWidth'] == 'thumbnail') || // new style
(isset($params['MaxHeight']) && $params['MaxHeight'] == 'thumbnail');
if ($show_thumbnail || $object->GetDBField('SameImages')) {
// return local image or url
$ret = $object->GetDBField('LocalThumb') ? $base_url.$object->GetDBField('ThumbPath') : $object->GetDBField('ThumbUrl');
if ($object->GetDBField('LocalThumb') && !file_exists(FULL_PATH.$object->GetDBField('ThumbPath')) && !constOn('DBG_IMAGE_RECOVERY')) {
// local thumbnail file is missing
$ret = '';
}
}
else { // if we need full which is not the same as thumb
$ret = $object->GetDBField('LocalImage') ? $base_url.$object->GetDBField('LocalPath') : $object->GetDBField('Url');
if ($object->GetDBField('LocalImage') && !file_exists(FULL_PATH.$object->GetDBField('LocalPath'))) {
// local full image file is missing
$ret = '';
}
}
$default_image = $this->SelectParam($params, 'default_image,DefaultImage');
return ($ret && $ret != $base_url) ? $ret : ($default_image ? $base_url.THEMES_PATH.'/'.$default_image : false);
}
function getFullPath($path)
{
if (!$path) {
return $path;
}
// absolute url
if (preg_match('/^(.*):\/\/(.*)$/U', $path)) {
return preg_replace('/^'.preg_quote($this->Application->BaseURL(), '/').'(.*)/', FULL_PATH.'/\\1', $path);
}
// relative url
- return FULL_PATH.'/'.substr(THEMES_PATH, 1).'/'.$path;
+ return FULL_PATH.'/'.mb_substr(THEMES_PATH, 1).'/'.$path;
}
/**
* Makes size clause for img tag, such as
* ' width="80" height="100"' according to max_width
* and max_heght limits.
*
* @param array $params
* @return string
*/
function ImageSize($params)
{
$img_path = $this->getFullPath($params['img_path']);
$image_helper =& $this->Application->recallObject('ImageHelper');
/* @var $image_helper ImageHelper */
$max_width = $this->getImageDimension('Width', $params);
$max_height = $this->getImageDimension('Height', $params);
$image_dimensions = $image_helper->GetImageDimensions($img_path, $max_width, $max_height);
if (!$image_dimensions) {
return false;
}
return ' width="'.$image_dimensions[0].'" height="'.$image_dimensions[1].'"';
}
/**
* Prepares image parameters & parses block with them (for admin)
*
* @param Array $params
* @return string
*/
function Image($params)
{
$image_url = $this->ImageSrc($params);
if (!$image_url) {
return ;
}
$object =& $this->getObject($params);
$params['img_path'] = $image_url;
$image_dimensions = $this->ImageSize($params);
$params['img_size'] = $image_dimensions ? $image_dimensions : ' width="'.$params['DefaultWidth'].'"';
$params['alt'] = htmlspecialchars($object->GetField('AltName')); // really used ?
$params['name'] = $this->SelectParam($params, 'block,render_as');
$params['align'] = array_key_exists('align', $params) ? $params['align'] : 'left';
if (!$object->isLoaded() && !$this->SelectParam($params, 'default_image,DefaultImage')) {
return false;
}
return $this->Application->ParseBlock($params);
}
/**
* Returns url for image in case when image source is url (for admin)
*
* @param Array $params
* @return string
*/
function ImageUrl($params)
{
$object =& $this->getObject($params);
if ($object->GetDBField('SameImages') ? $object->GetDBField('LocalThumb') : $object->GetDBField('LocalImage') ) {
$ret = $this->Application->Phrase(getArrayValue($params,'local_phrase'));
}
else {
$ret = $object->GetDBField('SameImages') ? $object->GetDBField('ThumbUrl') : $object->GetDBField('Url');
}
return $ret;
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/images/image_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.13.2.5
\ No newline at end of property
+1.13.2.6
\ No newline at end of property
Index: branches/RC/core/units/images/image_event_handler.php
===================================================================
--- branches/RC/core/units/images/image_event_handler.php (revision 10097)
+++ branches/RC/core/units/images/image_event_handler.php (revision 10098)
@@ -1,350 +1,350 @@
<?php
class ImageEventHandler extends kDBEventHandler {
function mapEvents()
{
parent::mapEvents(); // ensure auto-adding of approve/decine and so on events
$image_events = Array(
'OnAfterCopyToTemp'=>'ImageAction',
'OnBeforeDeleteFromLive'=>'ImageAction',
'OnBeforeCopyToLive'=>'ImageAction',
'OnBeforeItemDelete'=>'ImageAction',
'OnAfterClone'=>'ImageAction',
);
$this->eventMethods = array_merge($this->eventMethods, $image_events);
}
/**
* Get's special of main item for linking with subitem
*
* @param kEvent $event
* @return string
*/
function getMainSpecial(&$event)
{
if ($event->Special == 'list' && !$this->Application->IsAdmin()) {
// ListImages aggregated tag uses this special
return '';
}
-
+
return parent::getMainSpecial($event);
}
-
+
function customProcessing(&$event, $type)
{
$object =& $event->GetObject();
switch ($type)
{
case 'before' :
if ($object->GetDBField('LocalImage'))
{
$object->SetDBField('Url', '');
}
else
{
$object->SetDBField('LocalPath', '');
}
if ($object->GetDBField('LocalThumb'))
{
$object->SetDBField('ThumbUrl', '');
}
else
{
$object->SetDBField('ThumbPath', '');
}
if ($object->GetDBField('SameImages'))
{
$object->SetDBField('LocalImage', 1);
$object->SetDBField('LocalPath', '');
$object->SetDBField('Url', '');
}
break;
case 'after' :
if ($object->GetDBField('DefaultImg') )
{
$sql = 'UPDATE '.$object->TableName.' SET DefaultImg=0 WHERE ResourceId='.
$object->GetDBField('ResourceId').' AND ImageId<>'.
$object->GetId();
$res = $this->Conn->Query($sql);
}
break;
default:
}
}
function ImageAction(&$event)
{
$id = $event->getEventParam('id');
$object =& $this->Application->recallObject($event->Prefix.'.-item', $event->Prefix);
if (in_array($event->Name, Array('OnBeforeDeleteFromLive','OnAfterClone')) ) {
$object->SwitchToLive();
}
elseif ($event->Name == 'OnBeforeItemDelete') {
// keep current table
}
else {
$object->SwitchToTemp();
}
$object->Load($id);
$fields = Array('LocalPath' => 'LocalImage', 'ThumbPath' => 'LocalThumb');
foreach ($fields as $a_field => $mode_field) {
$file = $object->GetField($a_field);
if (!$file) continue;
$source_file = FULL_PATH.$file;
switch ($event->Name) {
// Copy image files to pending dir and update corresponding fields in temp record
// Checking for existing files and renaming if nessessary - two users may upload same pending files at the same time!
case 'OnAfterCopyToTemp':
$new_file = IMAGES_PENDING_PATH . $this->ValidateFileName(FULL_PATH.IMAGES_PENDING_PATH, basename($file));
$dest_file = FULL_PATH.$new_file;
copy($source_file, $dest_file);
$object->Fields[$a_field]['skip_empty'] = false;
$object->SetDBField($a_field, $new_file);
break;
// Copy image files to live dir (checking if fileexists and renameing if nessessary)
// and update corresponding fields in temp record (which gets copied to live automatically)
case 'OnBeforeCopyToLive':
if ( $object->GetDBField($mode_field) ) { // if image is local
// rename file if it exists in live folder
$new_file = IMAGES_PATH . $this->ValidateFileName(FULL_PATH.IMAGES_PATH, basename($file));
$dest_file = FULL_PATH.$new_file;
rename($source_file, $dest_file);
}
else { // if image is remote url - remove local file (if any), update local file field with empty value
if (file_exists($source_file)) @unlink($source_file);
$new_file = '';
}
$object->Fields[$a_field]['skip_empty'] = false;
$object->SetDBField($a_field, $new_file);
break;
case 'OnBeforeDeleteFromLive': // Delete image files from live folder before copying over from temp
case 'OnBeforeItemDelete': // Delete image files when deleteing Image object
@unlink(FULL_PATH.$file);
break;
case 'OnAfterClone': // Copy files when cloning objects, renaming it on the fly
$path_info = pathinfo($file);
$new_file = $path_info['dirname'].'/'.$this->ValidateFileName(FULL_PATH.$path_info['dirname'], $path_info['basename']);
$dest_file = FULL_PATH . $new_file;
copy($source_file, $dest_file);
$object->Fields[$a_field]['skip_empty'] = false;
$object->SetDBField($a_field, $new_file);
break;
}
}
if ( in_array($event->Name, Array('OnAfterClone', 'OnBeforeCopyToLive', 'OnAfterCopyToTemp')) ) {
$object->Update(null, true);
}
}
function ValidateFileName($path, $name)
{
$parts = pathinfo($name);
$ext = '.'.$parts['extension'];
- $filename = substr($parts['basename'], 0, -strlen($ext));
+ $filename = mb_substr($parts['basename'], 0, -mb_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;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
$object =& $event->getObject();
$object->SetDBField('DefaultImg', 1);
$object->Update();
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnBeforeItemUpdate(&$event)
{
$object =& $event->getObject();
// $parent_info = $object->getLinkedInfo();
$id = $object->GetDBField('ResourceId');
// $id = $parent_info['ParentId'] ? $parent_info['ParentId'] : $this->Application->GetVar('p_id');
$sql = 'SELECT ImageId FROM '.$object->TableName.' WHERE ResourceId='.$id.' AND DefaultImg=1';
if(!$this->Conn->GetOne($sql))
{
$object->SetDBField('DefaultImg', 1);
}
if($object->GetDBField('DefaultImg') && $object->Validate())
{
$sql = 'UPDATE '.$object->TableName.'
SET DefaultImg = 0
WHERE ResourceId = '.$id.' AND ImageId <> '.$object->GetDBField('ImageId');
$this->Conn->Query($sql);
$object->SetDBField('Enabled', 1);
}
}
function OnAfterItemCreate(&$event)
{
$event->CallSubEvent('OnBeforeItemUpdate');
$object =& $event->getObject();
$object->Update();
}
/**
* Deletes all selected items.
* Automatically recurse into sub-items using temp handler, and deletes sub-items
* by calling its Delete method if sub-item has AutoDelete set to true in its config file
*
* @param kEvent $event
*/
function OnMassDelete(&$event)
{
$event->status=erSUCCESS;
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$event->setEventParam('ids', $this->StoreSelectedIDs($event) );
$this->customProcessing($event, 'before');
$ids = $event->getEventParam('ids');
$object =& $event->getObject();
$sql = 'SELECT ImageId FROM '.$object->TableName.' WHERE DefaultImg=1';
$primary = $this->Conn->GetOne($sql);
if( $primary && ($key = array_search($primary, $ids)) )
{
$sql = 'SELECT ImageId FROM '.$object->TableName.' WHERE DefaultImg=0';
$res = $this->Conn->Query($sql);
if($res)
{
unset($ids[$key]);
}
}
if($ids)
{
$temp->DeleteItems($event->Prefix, $event->Special, $ids);
}
$this->clearSelectedIDs($event);
}
/*function OnAfterItemLoad(&$event)
{
$object =& $event->getObject();
if ( $object->GetDBField('ThumbPath') || $object->GetDBField('SameImages') )
{
// return local image or url
$path = $object->GetDBField('LocalThumb') ? PROTOCOL.SERVER_NAME.BASE_PATH.$object->GetDBField('ThumbPath') : $object->GetDBField('ThumbUrl');
if ( $object->GetDBField('LocalThumb') && !file_exists(FULL_PATH.$object->GetDBField('ThumbPath')) ) $path = '';
}
else { // if we need full which is not the same as thumb
$path = $object->GetDBField('LocalImage') ? PROTOCOL.SERVER_NAME.BASE_PATH.$object->GetDBField('LocalPath') : $object->GetDBField('Url');
if ( $object->GetDBField('LocalImage') && !file_exists(FULL_PATH.$object->GetDBField('LocalPath')) ) $path = '';
}
$object->SetDBField('ImageUrl', $path);
}*/
function SetCustomQuery(&$event)
{
parent::SetCustomQuery($event);
$types=$event->getEventParam('types');
$except_types=$event->getEventParam('except');
$object =& $event->getObject();
$type_clauses = Array();
if( !$this->Application->IsAdmin() )
{
$object->addFilter('active', '%1$s.Enabled = 1');
}
if($product_id = $event->getEventParam('product_id'))
{
$object->removeFilter('parent_filter');
$sql = 'SELECT ResourceId FROM '.$this->Application->getUnitOption('p', 'TableName').'
WHERE ProductId = '.$product_id;
$resource_id = (int) $this->Conn->GetOne($sql);
$object->addFilter('product_images', '%1$s.ResourceId = '.$resource_id);
}
$type_clauses['additional']['include'] = '%1$s.DefaultImg != 1';
$type_clauses['additional']['except'] = '%1$s.DefaultImg = 1';
$type_clauses['additional']['having_filter'] = false;
/********************************************/
$includes_or_filter =& $this->Application->makeClass('kMultipleFilter');
$includes_or_filter->setType(FLT_TYPE_OR);
$excepts_and_filter =& $this->Application->makeClass('kMultipleFilter');
$excepts_and_filter->setType(FLT_TYPE_AND);
$includes_or_filter_h =& $this->Application->makeClass('kMultipleFilter');
$includes_or_filter_h->setType(FLT_TYPE_OR);
$excepts_and_filter_h =& $this->Application->makeClass('kMultipleFilter');
$excepts_and_filter_h->setType(FLT_TYPE_AND);
$except_types_array=explode(',', $types);
if ($types){
$types_array=explode(',', $types);
for ($i=0; $i<sizeof($types_array); $i++){
$type=trim($types_array[$i]);
if (isset($type_clauses[$type])){
if ($type_clauses[$type]['having_filter']){
$includes_or_filter_h->removeFilter('filter_'.$type);
$includes_or_filter_h->addFilter('filter_'.$type, $type_clauses[$type]['include']);
}else{
$includes_or_filter->removeFilter('filter_'.$type);
$includes_or_filter->addFilter('filter_'.$type, $type_clauses[$type]['include']);
}
}
}
}
if ($except_types){
$except_types_array=explode(',', $except_types);
for ($i=0; $i<sizeof($except_types_array); $i++){
$type=trim($except_types_array[$i]);
if (isset($type_clauses[$type])){
if ($type_clauses[$type]['having_filter']){
$excepts_and_filter_h->removeFilter('filter_'.$type);
$excepts_and_filter_h->addFilter('filter_'.$type, $type_clauses[$type]['except']);
}else{
$excepts_and_filter->removeFilter('filter_'.$type);
$excepts_and_filter->addFilter('filter_'.$type, $type_clauses[$type]['except']);
}
}
}
}
$object->addFilter('includes_filter', $includes_or_filter);
$object->addFilter('excepts_filter', $excepts_and_filter);
$object->addFilter('includes_filter_h', $includes_or_filter_h, HAVING_FILTER);
$object->addFilter('excepts_filter_h', $excepts_and_filter_h, HAVING_FILTER);
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/images/image_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.4
\ No newline at end of property
+1.4.2.1
\ No newline at end of property
Index: branches/RC/core/units/help/help_event_handler.php
===================================================================
--- branches/RC/core/units/help/help_event_handler.php (revision 10097)
+++ branches/RC/core/units/help/help_event_handler.php (revision 10098)
@@ -1,30 +1,30 @@
<?php
class HelpEventHandler extends kDBEventHandler
{
/**
* Saves help file or created new one
*
* @param kEvent $event
*/
function OnSaveHelp(&$event)
{
$new_content = $this->Application->GetVar('HelpContent');
$module = $this->Application->GetVar('h_module');
$title_preset = $this->Application->GetVar('h_title_preset');
- $sql = 'SELECT Path FROM '.TABLE_PREFIX.'Modules WHERE LOWER(Name)='.$this->Conn->qstr( strtolower($module) );
+ $sql = 'SELECT Path FROM '.TABLE_PREFIX.'Modules WHERE LOWER(Name)='.$this->Conn->qstr( mb_strtolower($module) );
$module_path = $this->Conn->GetOne($sql);
$help_file = FULL_PATH.'/'.$module_path.'module_help/'.$title_preset.'.txt';
$help_data = $this->Application->GetVar('HelpContent');
$fp = fopen($help_file,'w');
fwrite($fp,$help_data);
fclose($fp);
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/help/help_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.2.2.1
\ No newline at end of property
Index: branches/RC/core/units/admin/admin_tag_processor.php
===================================================================
--- branches/RC/core/units/admin/admin_tag_processor.php (revision 10097)
+++ branches/RC/core/units/admin/admin_tag_processor.php (revision 10098)
@@ -1,920 +1,920 @@
<?php
class AdminTagProcessor extends kDBTagProcessor {
function SetConst($params)
{
$name = $this->SelectParam($params, 'name,const');
safeDefine($name, $params['value']);
}
/**
* Allows to execute js script after the page is fully loaded
*
* @param Array $params
* @return string
*/
function AfterScript($params)
{
$after_script = $this->Application->GetVar('after_script');
if ($after_script) {
return '<script type="text/javascript">'.$after_script.'</script>';
}
return '';
}
/**
* Returns section title with #section# keyword replaced with current section
*
* @param Array $params
* @return string
*/
function GetSectionTitle($params)
{
if (array_key_exists('default', $params)) {
return $params['default'];
}
return $this->Application->Phrase( replaceModuleSection($params['phrase']) );
}
/**
* Returns section icon with #section# keyword replaced with current section
*
* @param Array $params
* @return string
*/
function GetSectionIcon($params)
{
return replaceModuleSection($params['icon']);
}
/**
* Allows to detect if current template is one of listed ones
*
* @param Array $params
* @return int
*/
function TemplateMatches($params)
{
$templates = explode(',' ,$params['templates']);
$t = $this->Application->GetVar('t');
return in_array($t, $templates) ? 1 : 0;
}
/**
* Save return script in cases, when old sections are opened from new sections
*
* @param Array $params
*/
function SaveReturnScript($params)
{
// admin/save_redirect.php?do=
$m =& $this->Application->recallObject('m_TagProcessor');
$url = str_replace($this->Application->BaseURL(), '', $m->Link($params) );
$url = explode('?', $url, 2);
$url = 'save_redirect.php?'.$url[1].'&do='.$url[0];
$this->Application->StoreVar('ReturnScript', $url);
}
/**
* Redirects to correct next import step template based on import script data
*
* @param Array $params
*/
function ImportRedirect($params)
{
$import_id = $this->Application->GetVar('import_id');
if ($import_id) {
// redirect forward to step3 (import parameters coosing)
$this->Application->StoreVar('ImportScriptID', $import_id);
$sql = 'SELECT *
FROM '.TABLE_PREFIX.'ImportScripts
WHERE is_id = '.$import_id;
$db =& $this->Application->GetADODBConnection();
$is_params = $db->GetRow($sql);
if ($is_params['is_type'] == 'db') {
$this->Application->Redirect('', null, '', 'import/step3.php');
}
elseif ($is_params['is_type'] == 'csv') {
- $module = strtolower($is_params['is_Module']);
+ $module = mb_strtolower($is_params['is_Module']);
$template = $module.'/import';
$module_info = $this->Application->findModule('Name', $module);
$item_prefix = $module_info['Var'];
$pass_params = Array('m_opener' => 'd', $item_prefix.'.import_id' => 0, $item_prefix.'.import_event' => 'OnNew', 'pass' => 'm,'.$item_prefix.'.import', 'm_cat_id' => $module_info['RootCat']);
$this->Application->Redirect($template, $pass_params);
}
}
else {
// redirect back to step2 (import type choosing)
$this->Application->Redirect('', null, '', 'import/step2.php');
}
}
/**
* Returns version of module by name
*
* @param Array $params
* @return string
*/
function ModuleVersion($params)
{
return $this->Application->findModule('Name', $params['module'], 'Version');
}
/**
* Used in table form section drawing
*
* @param Array $params
* @return string
*/
function DrawTree($params)
{
static $deep_level = 0;
// when processings, then sort children by priority (key of children array)
$ret = '';
$section_name = $params['section_name'];
$params['name'] = $this->SelectParam($params, 'name,render_as,block');
$sections_helper =& $this->Application->recallObject('SectionsHelper');
$section_data =& $sections_helper->getSectionData($section_name);
$params['children_count'] = isset($section_data['children']) ? count($section_data['children']) : 0;
$params['deep_level'] = $deep_level++;
$template = $section_data['url']['t'];
unset($section_data['url']['t']);
$section_data['section_url'] = $this->Application->HREF($template, '', $section_data['url']);
$ret .= $this->Application->ParseBlock( array_merge_recursive2($params, $section_data) );
if (!isset($section_data['children'])) {
return $ret;
}
$debug_mode = $this->Application->isDebugMode();
$super_admin_mode = $this->Application->RecallVar('super_admin');
ksort($section_data['children'], SORT_NUMERIC);
foreach ($section_data['children'] as $section_name) {
$section_data =& $sections_helper->getSectionData($section_name);
if (isset($section_data['show_mode']) && is_numeric($section_data['show_mode'])) {
$show_mode = $section_data['show_mode'];
// if super admin section -> show in super admin mode & debug mode
$show_section = (($show_mode & smSUPER_ADMIN) == smSUPER_ADMIN) && ($super_admin_mode || $debug_mode);
if (!$show_section) {
// if section is in debug mode only && debug mode -> show
$show_section = (($show_mode & smDEBUG) == smDEBUG) && $debug_mode;
}
if (!$show_section) {
continue;
}
}
$params['section_name'] = $section_name;
$ret .= $this->DrawTree($params);
$deep_level--;
}
return $ret;
}
function SectionInfo($params)
{
$section = $params['section'];
if ($section == '#session#') {
$section = $this->Application->RecallVar('section');
}
$sections_helper =& $this->Application->recallObject('SectionsHelper');
/* @var $sections_helper kSectionsHelper */
$section_data =& $sections_helper->getSectionData($section);
if (isset($params['parent']) && $params['parent']) {
do {
$section_data =& $sections_helper->getSectionData($section_data['parent']);
} while (isset($section_data['use_parent_header']) && $section_data['use_parent_header']);
}
$info = $params['info'];
switch ($info) {
case 'module_path':
if (isset($params['module']) && $params['module']) {
$module = $params['module'];
}
elseif (isset($section_data['icon_module'])) {
$module = $section_data['icon_module'];
}
else {
$module = '#session#';
}
$res = $this->ModulePath(array('module' => $module));
break;
case 'perm_section':
$res = $sections_helper->getPermSection($section);
break;
default:
$res = $section_data[$info];
}
if ($info == 'label' || isset($params['as_label'])) {
$res = $this->Application->Phrase($res);
}
return $res;
}
function PrintSection($params)
{
$section_name = $params['section_name'];
if ($section_name == '#session#') {
$section_name = $this->Application->RecallVar('section');
}
$sections_helper =& $this->Application->recallObject('SectionsHelper');
/* @var $sections_helper kSectionsHelper */
if (isset($params['use_first_child']) && $params['use_first_child']) {
$section_name = $sections_helper->getFirstChild($section_name, true);
}
$section_data =& $sections_helper->getSectionData($section_name);
$params['name'] = $this->SelectParam($params, 'name,render_as,block');
$params['section_name'] = $section_name;
$template = $section_data['url']['t'];
unset($section_data['url']['t']);
$section_data['section_url'] = $this->Application->HREF($template, '', $section_data['url']);
$ret = $this->Application->ParseBlock( array_merge_recursive2($params, $section_data) );
return $ret;
}
/**
* Used in XML drawing for tree
*
* @param Array $params
* @return string
*/
function PrintSections($params)
{
// when processings, then sort children by priority (key of children array)
$ret = '';
$section_name = $params['section_name'];
if ($section_name == '#session#') {
$section_name = $this->Application->RecallVar('section');
}
$sections_helper =& $this->Application->recallObject('SectionsHelper');
/* @var $sections_helper kSectionsHelper */
$section_data =& $sections_helper->getSectionData($section_name);
$params['name'] = $this->SelectParam($params, 'name,render_as,block');
if (!isset($section_data['children'])) {
return '';
}
$debug_mode = $this->Application->isDebugMode();
$super_admin_mode = $this->Application->RecallVar('super_admin');
ksort($section_data['children'], SORT_NUMERIC);
foreach ($section_data['children'] as $section_name) {
$params['section_name'] = $section_name;
$section_data =& $sections_helper->getSectionData($section_name);
if (isset($section_data['show_mode']) && is_numeric($section_data['show_mode'])) {
$show_mode = $section_data['show_mode'];
// if super admin section -> show in super admin mode & debug mode
$show_section = (($show_mode & smSUPER_ADMIN) == smSUPER_ADMIN) && ($super_admin_mode || $debug_mode);
if (!$show_section) {
// if section is in debug mode only && debug mode -> show
$show_section = (($show_mode & smDEBUG) == smDEBUG) && $debug_mode;
}
if (!$show_section) {
continue;
}
}
if (isset($section_data['tabs_only']) && $section_data['tabs_only']) {
$perm_status = false;
$folder_label = $section_data['label'];
ksort($section_data['children'], SORT_NUMERIC);
foreach ($section_data['children'] as $priority => $section_name) {
// if only tabs in this section & none of them have permission, then skip section too
$section_name = $sections_helper->getPermSection($section_name);
$perm_status = $this->Application->CheckPermission($section_name.'.view', 1);
if ($perm_status) {
break;
}
}
if (!$perm_status) {
// no permission for all tabs -> don't display tree node either
continue;
}
$params['section_name'] = $section_name;
$section_data =& $sections_helper->getSectionData($section_name);
$section_data['label'] = $folder_label; // use folder label in tree
$section_data['is_tab'] = 1;
}
else {
$section_name = $sections_helper->getPermSection($section_name);
if (!$this->Application->CheckPermission($section_name.'.view', 1)) continue;
}
$params['children_count'] = isset($section_data['children']) ? count($section_data['children']) : 0;
$template = $section_data['url']['t'];
unset($section_data['url']['t']);
$section_data['section_url'] = $this->Application->HREF($template, '', $section_data['url']);
$late_load = getArrayValue($section_data, 'late_load');
if ($late_load) {
$t = $late_load['t'];
unset($late_load['t']);
$section_data['late_load'] = $this->Application->HREF($t, '', $late_load);
$params['children_count'] = 99;
}
else {
$section_data['late_load'] = '';
}
$ret .= $this->Application->ParseBlock( array_merge_recursive2($params, $section_data) );
$params['section_name'] = $section_name;
}
return preg_replace("/\r\n|\n/", '', $ret);
}
function ListSectionPermissions($params)
{
$section_name = isset($params['section_name']) ? $params['section_name'] : $this->Application->GetVar('section_name');
$sections_helper =& $this->Application->recallObject('SectionsHelper');
$section_data =& $sections_helper->getSectionData($section_name);
$block_params = array_merge_recursive2($section_data, Array('name' => $params['render_as'], 'section_name' => $section_name));
$ret = '';
foreach ($section_data['permissions'] as $perm_name) {
if (preg_match('/^advanced:(.*)/', $perm_name) != $params['type']) continue;
$block_params['perm_name'] = $perm_name;
$ret .= $this->Application->ParseBlock($block_params);
}
return $ret;
}
function ModuleInclude($params)
{
foreach ($params as $param_name => $param_value) {
$params[$param_name] = replaceModuleSection($param_value);
}
$m =& $this->Application->recallObject('m_TagProcessor');
return $m->ModuleInclude($params);
}
function TodayDate($params)
{
return date($params['format']);
}
function TreeEditWarrning($params)
{
$ret = $this->Application->Phrase($params['label']);
$ret = str_replace(Array('&lt;', '&gt;', 'br/', 'br /', "\n", "\r"), Array('<', '>', 'br', 'br', '', ''), $ret);
if (getArrayValue($params, 'escape')) {
$ret = addslashes($ret);
}
$ret = str_replace('<br>', '\n', $ret);
return $ret;
}
/**
* Draws section tabs using block name passed
*
* @param Array $params
*/
function ListTabs($params)
{
$sections_helper =& $this->Application->recallObject('SectionsHelper');
$section_data =& $sections_helper->getSectionData($params['section_name']);
$ret = '';
$block_params = Array('name' => $params['render_as']);
ksort($section_data['children'], SORT_NUMERIC);
foreach ($section_data['children'] as $priority => $section_name) {
if (!$this->Application->CheckPermission($section_name.'.view', 1)) continue;
$tab_data =& $sections_helper->getSectionData($section_name);
$block_params['t'] = $tab_data['url']['t'];
$block_params['title'] = $tab_data['label'];
$block_params['main_prefix'] = $section_data['SectionPrefix'];
$ret .= $this->Application->ParseBlock($block_params);
}
return $ret;
}
/**
* Returns list of module item tabs that have view permission in current category
*
* @param Array $params
*/
function ListCatalogTabs($params)
{
$ret = '';
$special = isset($params['special']) ? $params['special'] : '';
$replace_main = isset($params['replace_m']) && $params['replace_m'];
$skip_prefixes = isset($params['skip_prefixes']) ? explode(',', $params['skip_prefixes']) : Array();
$block_params = Array('name' => $params['render_as']);
foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
$prefix = $module_info['Var'];
if (in_array($prefix, $skip_prefixes) || !$this->Application->prefixRegistred($prefix) || !$this->Application->getUnitOption($prefix, 'CatalogItem')) continue;
if ($prefix == 'm' && $replace_main) $prefix = 'c';
$label = $this->Application->getUnitOption($prefix, $params['title_property']);
$block_params['title'] = $label;
$block_params['prefix'] = $prefix;
$ret .= $this->Application->ParseBlock($block_params);
}
return $ret;
}
function FCKEditor($params)
{
if (file_exists(FULL_PATH.'/core/cmseditor/fckeditor.php')) {
$editor_path = 'core/cmseditor/';
}
else {
$editor_path = 'admin/editor/cmseditor/';
}
include_once(FULL_PATH.'/'.$editor_path.'/fckeditor.php');
$oFCKeditor = new FCKeditor($params['name']);
$oFCKeditor->BasePath = BASE_PATH.'/'.$editor_path;
$oFCKeditor->Width = $params['width'] ;
$oFCKeditor->Height = $params['height'] ;
$oFCKeditor->ToolbarSet = 'Advanced' ;
$oFCKeditor->Value = '' ;
if ($this->Application->isModuleEnabled('In-Portal')) {
$config_path = $this->Application->BaseURL().'kernel/admin_templates/incs/inp_fckconfig.js';
}
else {
$config_path = $this->Application->BaseURL().'core/admin_templates/js/inp_fckconfig.js';
}
$oFCKeditor->Config = Array(
// 'UserFilesPath' => FULL_PATH.'/kernel/user_files',
'ProjectPath' => BASE_PATH.'/',
'CustomConfigurationsPath' => $config_path,
// 'EditorAreaCSS' => $this->Application->BaseURL().'/themes/inportal_site/inc/inportal.css', //GetThemeCSS(),
//'StylesXmlPath' => '../../inp_styles.xml',
// 'Debug' => 1,
'Admin' => 1,
'K4' => 1,
);
return $oFCKeditor->CreateHtml();
}
/**
* Allows to construct link for opening any type of catalog item selector
*
* @param Array $params
* @return string
*/
function SelectorLink($params)
{
$mode = 'catalog';
if (isset($params['mode'])) { // {catalog, advanced_view}
$mode = $params['mode'];
unset($params['mode']);
}
$params['t'] = 'in-portal/item_selector/item_selector_'.$mode;
$default_params = Array('no_amp' => 1, 'pass' => 'all,'.$params['prefix']);
unset($params['prefix']);
$pass_through = Array();
if (isset($params['tabs_dependant'])) { // {yes, no}
$pass_through['td'] = $params['tabs_dependant'];
unset($params['tabs_dependant']);
}
if (isset($params['selection_mode'])) { // {single, multi}
$pass_through['tm'] = $params['selection_mode'];
unset($params['selection_mode']);
}
if (isset($params['tab_prefixes'])) { // {all, none, <comma separated prefix list}
$pass_through['tp'] = $params['tab_prefixes'];
unset($params['tab_prefixes']);
}
if ($pass_through) {
// add pass_through to selector url if any
$params['pass_through'] = implode(',', array_keys($pass_through));
$params = array_merge_recursive2($params, $pass_through);
}
// user can override default parameters (except pass_through of course)
$params = array_merge_recursive2($default_params, $params);
$main_processor =& $this->Application->recallObject('m_TagProcessor');
return $main_processor->T($params);
}
function TimeFrame($params)
{
$w = adodb_date('w');
$m = adodb_date('m');
$y = adodb_date('Y');
//FirstDayOfWeek is 0 for Sunday and 1 for Monday
$fdow = $this->Application->ConfigValue('FirstDayOfWeek');
if ($fdow && $w == 0) $w = 7;
$today_start = adodb_mktime(0,0,0,adodb_date('m'),adodb_date('d'),$y);
$first_day_of_this_week = $today_start - ($w - $fdow)*86400;
$first_day_of_this_month = adodb_mktime(0,0,0,$m,1,$y);
$this_quater = ceil($m/3);
$this_quater_start = adodb_mktime(0,0,0,$this_quater*3-2,1,$y);
switch ($params['type']) {
case 'last_week_start':
$timestamp = $first_day_of_this_week - 86400*7;
break;
case 'last_week_end':
$timestamp = $first_day_of_this_week - 1;
break;
case 'last_month_start':
$timestamp = $m == 1 ? adodb_mktime(0,0,0,12,1,$y-1) : adodb_mktime(0,0,0,$m-1,1,$y);
break;
case 'last_month_end':
$timestamp = $first_day_of_this_month = adodb_mktime(0,0,0,$m,1,$y) - 1;
break;
case 'last_quater_start':
$timestamp = $this_quater == 1 ? adodb_mktime(0,0,0,10,1,$y-1) : adodb_mktime(0,0,0,($this_quater-1)*3-2,1,$y);
break;
case 'last_quater_end':
$timestamp = $this_quater_start - 1;
break;
case 'last_6_months_start':
$timestamp = $m <= 6 ? adodb_mktime(0,0,0,$m+6,1,$y-1) : adodb_mktime(0,0,0,$m-6,1,$y);
break;
case 'last_year_start':
$timestamp = adodb_mktime(0,0,0,1,1,$y-1);
break;
case 'last_year_end':
$timestamp = adodb_mktime(23,59,59,12,31,$y-1);
break;
}
if (isset($params['format'])) {
$format = $params['format'];
if(preg_match("/_regional_(.*)/", $format, $regs))
{
$lang =& $this->Application->recallObject('lang.current');
$format = $lang->GetDBField($regs[1]);
}
return adodb_date($format, $timestamp);
}
return $timestamp;
}
function CheckPermCache($params)
{
if ($this->Conn->GetOne('SELECT Data FROM '.TABLE_PREFIX.'Cache WHERE VarName = \'ForcePermCacheUpdate\'')) {
$this->Application->Redirect($params['cache_update_t'], array('continue' => 1));
}
}
/**
* Checks if current protocol is SSL
*
* @param Array $params
* @return int
*/
function IsSSL($params)
{
return (PROTOCOL == 'https://')? 1 : 0;
}
function PrintColumns($params)
{
$picker_helper =& $this->Application->RecallObject('ColumnPickerHelper');
$picker_helper->SetGridName($this->Application->GetLinkedVar('grid_name'));
/* @var $picker_helper kColumnPickerHelper */
$main_prefix = $this->Application->RecallVar('main_prefix');
$cols = $picker_helper->LoadColumns($main_prefix);
$this->Application->Phrases->AddCachedPhrase('__FREEZER__', '-------------');
$o = '';
if (isset($params['hidden']) && $params['hidden']) {
foreach ($cols['hidden_fields'] as $col) {
$title = $this->Application->Phrase($cols['titles'][$col]);
$o .= "<option value='$col'>".$title;
}
}
else {
foreach ($cols['order'] as $col) {
if (in_array($col, $cols['hidden_fields'])) continue;
$title = $this->Application->Phrase($cols['titles'][$col]);
$o .= "<option value='$col'>".$title;
}
}
return $o;
}
/**
* Allows to set popup size (key - current template name)
*
* @param Array $params
*/
function SetPopupSize($params)
{
$width = $params['width'];
$height = $params['height'];
if ($this->Application->GetVar('ajax') == 'yes') {
// during AJAX request just output size
die($width.'x'.$height);
}
if (!$this->UsePopups($params)) {
return ;
}
$t = $this->Application->GetVar('t');
$sql = 'SELECT *
FROM '.TABLE_PREFIX.'PopupSizes
WHERE TemplateName = '.$this->Conn->qstr($t);
$popup_info = $this->Conn->GetRow($sql);
if (!$popup_info) {
// create new popup size record
$fields_hash = Array (
'TemplateName' => $t,
'PopupWidth' => $width,
'PopupHeight' => $height,
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'PopupSizes');
}
elseif ($popup_info['PopupWidth'] != $width || $popup_info['PopupHeight'] != $height) {
// popup found and size in tag differs from one in db -> update in db
$fields_hash = Array (
'PopupWidth' => $width,
'PopupHeight' => $height,
);
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX.'PopupSizes', 'PopupId = '.$popup_info['PopupId']);
}
}
/**
* Returns popup size (by template), if not cached, then parse template to get value
*
* @param Array $params
* @return string
*/
function GetPopupSize($params)
{
$t = $this->Application->GetVar('template_name');
$sql = 'SELECT *
FROM '.TABLE_PREFIX.'PopupSizes
WHERE TemplateName = '.$this->Conn->qstr($t);
$popup_info = $this->Conn->GetRow($sql);
if (!$popup_info) {
$this->Application->InitParser();
$this->Application->ParseBlock(array('name' => $t)); // dies when SetPopupSize tag found & in ajax requrest
return '750x400'; // tag SetPopupSize not found in template -> use default size
}
return $popup_info['PopupWidth'].'x'.$popup_info['PopupHeight'];
}
function UsePopups($params)
{
return (int)$this->Application->ConfigValue('UsePopups');
}
function UseToolbarLabels($params)
{
return (int)$this->Application->ConfigValue('UseToolbarLabels');
}
/**
* Checks if debug mode enabled (optionally) and specified constant is on
*
* @param Array $params
* @return bool
*/
function ConstOn($params)
{
$constant_name = $this->SelectParam($params, 'name,const');
$debug_mode = isset($params['debug_mode']) && $params['debug_mode'] ? $this->Application->isDebugMode() : true;
return $debug_mode && constOn($constant_name);
}
/**
* Builds link to last template in main frame of admin
*
* @param Array $params
* @return string
*/
function MainFrameLink($params)
{
$persistent = isset($params['persistent']) && $params['persistent'];
if ($persistent) {
// check last_template in persistent session
$last_template = $this->Application->RecallPersistentVar('last_template_popup');
}
else {
// check last_template in session
$last_template = $this->Application->RecallVar('last_template_popup'); // because of m_opener=s there
}
if (!$last_template) {
$params['persistent'] = 1;
return $persistent ? false : $this->MainFrameLink($params);
}
list($index_file, $env) = explode('|', $last_template);
$vars = $this->Application->HttpQuery->processQueryString($env, 'pass');
$recursion_templates = Array ('login', 'index', 'no_permission');
if (isset($vars['admin']) && $vars['admin'] == 1) {
// index template doesn't begin recursion on front-end (in admin frame)
$vars['m_theme'] = '';
if (isset($params['m_opener']) && $params['m_opener'] == 'r') {
// front-end link for highlighting purposes
$vars['t'] = 'index';
$vars['m_cat_id'] = $this->Application->findModule('Name', 'Proj-CMS', 'RootCat');
}
unset($recursion_templates[ array_search('index', $recursion_templates)]);
}
if (in_array($vars['t'], $recursion_templates)) {
// prevents redirect recursion OR old in-portal pages
$params['persistent'] = 1;
return $persistent ? false : $this->MainFrameLink($params);
}
$vars = array_merge_recursive2($vars, $params);
$t = $vars['t'];
unset($vars['t'], $vars['persistent']);
return $this->Application->HREF($t, '', $vars, $index_file);
}
/**
* Returns menu frame width or 200 in case, when invalid width specified in config
*
* @param Array $params
* @return string
*/
function MenuFrameWidth($params)
{
$width = (int)$this->Application->ConfigValue('MenuFrameWidth');
return $width > 0 ? $width : 200;
}
function AdminSkin($params)
{
static $style;
if (!isset($style)) {
$style = $this->Conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'Skins WHERE IsPrimary = 1');
}
$css_path = (defined('WRITEABLE') ? WRITEABLE : FULL_PATH.'/kernel').'/user_files';
$css_url = $this->Application->BaseURL(defined('WRITEBALE_BASE') ? WRITEBALE_BASE : '/kernel').'user_files/';
if (isset($params['type']) && $params['type'] == 'logo') {
return $style['Logo'] ? $css_url.$style['Logo'] : '';
}
$last_compiled = $style['LastCompiled'];
- $style_name = strtolower( $style['Name'] );
+ $style_name = mb_strtolower( $style['Name'] );
if( file_exists($css_path.'/'.'admin-'.$style_name.'-'.$last_compiled.'.css') )
{
$ret = $css_url.'admin-'.$style_name.'-'.$last_compiled.'.css';
}
else
{
// search for previously compiled stylesheet
$last_compiled = 0;
if( $dh = opendir($css_path) )
{
while( ($file = readdir($dh)) !== false )
{
if( preg_match('/admin-(.*)-([\d]+).css/', $file, $rets) )
{
if( $rets[1] == $style_name && $rets[2] > $last_compiled ) $last_compiled = $rets[2];
}
}
closedir($dh);
}
if ($last_compiled) {
// found
$ret = $css_url.'admin-'.$style_name.'-'.$last_compiled.'.css';
}
else {
// not found (try to compile on the fly)
$object =& $this->Application->recallObject('skin.-item', null, Array ('skip_autoload' => true));
/* @var $object kDBItem */
$skin_eh =& $this->Application->recallObject('skin_EventHandler');
/* @var $skin_eh SkinEventHandler */
$object->Load(1, 'IsPrimary');
$skin_eh->Compile($object);
$ret = $css_url.'admin-'.$style_name.'-'.adodb_mktime().'.css';
}
}
if (isset($params['file_only'])) return $ret;
return '<link rel="stylesheet" rev="stylesheet" href="'.$ret.'" type="text/css" media="screen" />';
}
function PrintCompileErrors($params)
{
$errors = unserialize($this->Application->RecallVar('compile_errors'));
$o = '<table class="edit-form" style="width: 100%;" border="1"><tr><td><b>File</b></td><td><b>Line</b></td><td><b>Message</b></td></tr>';
$class = 'table-color1';
foreach ($errors as $an_error) {
$f = str_replace(FULL_PATH, '', $an_error['file']);
$o .= "<tr class=\'$class\'><td>{$f}</td><td>{$an_error['line']}</td><td>{$an_error['msg']}</td></tr>";
$class = $class == 'table-color1' ? 'table-color2' : 'table-color1';
}
$o .= '</table>';
$this->Application->RemoveVar('compile_errors');
return $o;
}
function ExportData($params)
{
$export_helper =& $this->Application->recallObject('CSVHelper');
/* @var $export_helper kCSVHelper */
$result = $export_helper->ExportData( $this->SelectParam($params, 'var,name,field') );
return ($result === false) ? '' : $result;
}
function ImportData($params)
{
$import_helper =& $this->Application->recallObject('CSVHelper');
/* @var $import_helper kCSVHelper */
$result = $import_helper->ImportData( $this->SelectParam($params, 'var,name,field') );
return ($result === false) ? '' : $result;
}
function PrintCSVNotImportedLines($params)
{
$import_helper =& $this->Application->recallObject('CSVHelper');
/* @var $import_helper kCSVHelper */
return $import_helper->GetNotImportedLines();
}
/**
* Returns input field name to
* be placed on form (for correct
* event processing)
*
* @param Array $params
* @return string
* @access public
*/
function InputName($params)
{
list($id, $field) = $this->prepareInputName($params);
$ret = $this->getPrefixSpecial().'[0]['.$field.']'; // 0 always, as has no idfield
if( getArrayValue($params, 'as_preg') ) $ret = preg_quote($ret, '/');
return $ret;
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/admin/admin_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.43.2.9
\ No newline at end of property
+1.43.2.10
\ No newline at end of property
Index: branches/RC/core/units/languages/languages_event_handler.php
===================================================================
--- branches/RC/core/units/languages/languages_event_handler.php (revision 10097)
+++ branches/RC/core/units/languages/languages_event_handler.php (revision 10098)
@@ -1,479 +1,479 @@
<?php
class LanguagesEventHandler extends kDBEventHandler
{
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnChangeLanguage' => Array('self' => true),
'OnSetPrimary' => Array('self' => 'advanced:set_primary|add|edit'),
'OnImportLanguage' => Array('self' => 'advanced:import'),
'OnImportProgress' => Array('self' => 'advanced:import'),
'OnExportLanguage' => Array('self' => 'advanced:export'),
'OnExportProgress' => Array('self' => 'advanced:export'),
-
+
'OnItemBuild' => Array('self' => true),
);
-
+
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* [HOOK] Updates table structure on new language adding/removing language
*
* @param kEvent $event
*/
function OnReflectMultiLingualFields(&$event)
{
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
-
+
$this->Application->UnitConfigReader->ReReadConfigs();
foreach ($this->Application->UnitConfigReader->configData as $prefix => $config_data) {
$ml_helper->createFields($prefix);
}
}
/**
* Allows to set selected language as primary
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$this->StoreSelectedIDs($event);
$ids = $this->getSelectedIDs($event);
if ($ids) {
$id = array_shift($ids);
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object LanguagesItem */
$object->Load($id);
$object->setPrimary();
}
}
/**
* [HOOK] Reset primary status of other languages if we are saving primary language
*
* @param kEvent $event
*/
function OnUpdatePrimary(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object LanguagesItem */
$object->SwitchToLive();
// set primary for each languages, that have this checkbox checked
$ids = explode(',', $event->MasterEvent->getEventParam('ids'));
foreach ($ids as $id) {
$object->Load($id);
if ($object->GetDBField('PrimaryLang')) {
$object->setPrimary(true, false);
}
if ($object->GetDBField('AdminInterfaceLang')) {
$object->setPrimary(true, true);
}
}
// if no primary language left, then set primary last language (not to load again) from edited list
$sql = 'SELECT '.$object->IDField.'
FROM '.$object->TableName.'
WHERE PrimaryLang = 1';
$primary_language = $this->Conn->GetOne($sql);
if (!$primary_language) {
$object->setPrimary(false, false); // set primary language
}
$sql = 'SELECT '.$object->IDField.'
FROM '.$object->TableName.'
WHERE AdminInterfaceLang = 1';
$primary_language = $this->Conn->GetOne($sql);
if (!$primary_language) {
$object->setPrimary(false, true); // set admin interface language
}
}
/**
* Occurse before updating item
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemUpdate(&$event)
{
$object =& $event->getObject();
$status_field = array_shift( $this->Application->getUnitOption($event->Prefix, 'StatusField') );
if ($object->GetDBField('PrimaryLang') == 1 && $object->GetDBField($status_field) == 0) {
$object->SetDBField($status_field, 1);
}
}
/**
* Shows only enabled languages on front
*
* @param kEvent $event
*/
function SetCustomQuery(&$event)
{
if($event->Special == 'enabled')
{
$object =& $event->getObject();
$object->addFilter('enabled_filter', '%1$s.Enabled = 1');
}
}
/**
* Copy labels from another language
*
* @param kEvent $event
*/
function OnCopyLabels(&$event)
{
$object =& $event->getObject();
$from_lang_id = $object->GetDBField('CopyFromLanguage');
if( ($event->MasterEvent->status == erSUCCESS) && $object->GetDBField('CopyLabels') == 1 && ($from_lang_id > 0) )
{
$lang_id = $object->GetID();
// 1. phrases import
$phrases_live = $this->Application->getUnitOption('phrases','TableName');
$phrases_temp = $this->Application->GetTempName($phrases_live, 'prefix:phrases');
$sql = 'INSERT INTO '.$phrases_temp.'
SELECT Phrase, Translation, PhraseType, 0-PhraseId, '.$lang_id.', '.adodb_mktime().', "", Module
FROM '.$phrases_live.'
WHERE LanguageId='.$from_lang_id;
$this->Conn->Query($sql);
// 2. events import
$em_table_live = $this->Application->getUnitOption('emailmessages','TableName');
$em_table_temp = $this->Application->GetTempName($em_table_live, 'prefix:emailmessages');
$sql = 'SELECT * FROM '.$em_table_live.' WHERE LanguageId = '.$from_lang_id;
$email_messages = $this->Conn->Query($sql);
if($email_messages)
{
$id = $this->Conn->GetOne('SELECT MIN(EmailMessageId) FROM '.$em_table_live);
if($id > 0) $id = 0;
$id--;
$sqls = Array();
foreach($email_messages as $email_message)
{
$sqls[] = $id.','.$this->Conn->qstr($email_message['Template']).','.$this->Conn->qstr($email_message['MessageType']).','.$lang_id.','.$email_message['EventId'];
$id--;
}
$sql = 'INSERT INTO '.$em_table_temp.'(EmailMessageId,Template,MessageType,LanguageId,EventId) VALUES ('.implode('),(',$sqls).')';
$this->Conn->Query($sql);
}
$object->SetDBField('CopyLabels', 0);
}
}
/**
* Prepare temp tables for creating new item
* but does not create it. Actual create is
* done in OnPreSaveCreated
*
* @param kEvent $event
*/
function OnPreCreate(&$event)
{
parent::OnPreCreate($event);
$object =& $event->getObject();
$object->SetDBField('CopyLabels', 1);
$live_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$primary_lang_id = $this->Conn->GetOne('SELECT '.$object->IDField.' FROM '.$live_table.' WHERE PrimaryLang = 1');
$object->SetDBField('CopyFromLanguage', $primary_lang_id);
}
function OnChangeLanguage(&$event)
{
$this->Application->SetVar('m_lang', $this->Application->GetVar('language'));
//$this->Application->LinkVar('language', 'm_lang');
}
/**
* Parse language XML file into temp tables and redirect to progress bar screen
*
* @param kEvent $event
*/
function OnImportLanguage(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$items_info = $this->Application->GetVar('phrases_import');
if($items_info)
{
list($id,$field_values) = each($items_info);
$object =& $this->Application->recallObject('phrases.import', 'phrases', Array('skip_autoload' => true) );
$object->SetFieldsFromHash($field_values);
$filename = getArrayValue($field_values, 'LangFile', 'tmp_name');
if( filesize($filename) )
{
$modules = getArrayValue($field_values,'Module');
$lang_xml =& $this->Application->recallObject('LangXML');
/* @var $lang_xml LangXML_Parser */
$lang_xml->Parse($filename, $field_values['PhraseType'], $modules, $field_values['ImportOverwrite']);
$event->redirect = true;
$event->SetRedirectParams( Array('lang_event' => 'OnImportProgress', 'pass' => 'all,lang', 'mode'=>$field_values['ImportOverwrite']) );
}
else
{
$object =& $this->Application->recallObject('phrases.import');
$object->SetError('LangFile', 'la_empty_file', 'la_EmptyFile');
$event->redirect = false;
}
}
}
/**
* Copies imported from xml file from temp table to live table
*
* @param kEvent $event
*/
function OnImportProgress(&$event)
{
define('IMPORT_BY', 300); // import this much records per step
$template_name = 'regional/languages_import_step2';
$import_mode = (int)$this->Application->GetVar('mode'); // 1 - overwrite existing phrases, 0 - don't overwrite existing phrases
$import_source = (int)$this->Application->GetVar('source');
$import_steps = Array(0 => 'lang', 1 => 'phrases', 2 => 'emailmessages', 3 => 'finish');
$key_fields = Array(0 => 'PackName', 1 => 'Phrase', 2 => 'EventId'); // by what field should we search record match
$import_titles = Array(0 => 'la_ImportingLanguages', 1 => 'la_ImportingPhrases', 2 => 'la_ImportingEmailEvents', 3 => 'la_Done');
// --- BEFORE ---
$import_prefix = $import_steps[$import_source];
$import_start = (int)$this->Application->GetVar('start');
$id_field = $this->Application->getUnitOption($import_prefix,'IDField');
$dst_table = $this->Application->getUnitOption($import_prefix,'TableName');
$src_table = $this->Application->GetTempName($dst_table);
$import_total = $this->Application->GetVar('total');
if(!$import_total) $import_total = $this->Conn->GetOne('SELECT COUNT(*) FROM '.$src_table);
// --- AFTER ---
if($import_start == $import_total)
{
$import_source++;
$import_prefix = $import_steps[$import_source];
if($import_prefix == 'finish')
{
$event->SetRedirectParam('opener','u');
return true;
}
$import_start = 0;
$id_field = $this->Application->getUnitOption($import_prefix,'IDField');
$dst_table = $this->Application->getUnitOption($import_prefix,'TableName');
$src_table = $this->Application->GetTempName($dst_table);
$import_total = $this->Conn->GetOne('SELECT COUNT(*) FROM '.$src_table);
}
if($import_total > 0)
{
$done_percent = ($import_start * 100) / $import_total;
}
else
{
$done_percent = 100;
}
$block_params = Array( 'name' => $template_name,
'title' => $import_titles[$import_source],
'percent_done' => $done_percent,
'percent_left' => 100 - $done_percent);
$this->Application->InitParser();
$this->Application->setUnitOption('phrases','AutoLoad',false);
echo $this->Application->ParseBlock($block_params);
//break out of buffering
$buffer_content = Array();
while (ob_get_level()) {
$buffer_content[] = ob_get_clean();
}
$ret = implode('', array_reverse($buffer_content));
echo $ret;
flush();
$sql = 'SELECT * FROM %s LIMIT %s,%s';
$rows = $this->Conn->Query( sprintf($sql,$src_table,$import_start,IMPORT_BY) );
$values_sql = '';
// if found and mode = 1 (overwrite)
$search_sql = 'SELECT '.$id_field.' FROM '.$dst_table.' WHERE '.$key_fields[$import_source].' = %s AND LanguageId = %s';
$update_sql = 'UPDATE '.$dst_table.' SET %s WHERE '.$id_field.' = %s';
foreach($rows as $row)
{
$tmp_sql = sprintf($search_sql, $this->Conn->qstr($row[ $key_fields[$import_source] ]), $row['LanguageId'] );
$tmp_id = $this->Conn->GetOne($tmp_sql);
if($tmp_id > 0 && $import_mode == 1)
{
// update
$update_fields = '';
foreach($row as $field_name => $field_value)
{
if($field_name == $id_field) continue;
$update_fields .= '`'.$field_name.'` = '.$this->Conn->qstr($field_value).',';
}
$update_fields = preg_replace('/(.*),$/', '\\1', $update_fields);
$this->Conn->Query( sprintf($update_sql, $update_fields, $tmp_id) );
}
elseif(!$tmp_id)
{
$values_sql .= '(';
foreach($row as $field_value)
{
$values_sql .= $this->Conn->qstr($field_value).',';
}
$values_sql = preg_replace('/(.*),$/', '\\1', $values_sql).'),';
}
}
if($values_sql)
{
$fields_sql = '';
$fields = array_keys( $this->Application->getUnitOption($import_prefix,'Fields') );
foreach($fields as $field_name)
{
$fields_sql .= '`'.$field_name.'`,';
}
$fields_sql = preg_replace('/(.*),$/', '\\1', $fields_sql);
$values_sql = preg_replace('/(.*),$/', '\\1', $values_sql);
$sql = sprintf('INSERT INTO %s (%s) VALUES %s', $dst_table, $fields_sql, $values_sql);
$this->Conn->Query($sql);
}
$event->setRedirectParams( Array('lang_event' => 'OnImportProgress', 'pass' => 'all,lang', 'start' => $import_start += count($rows), 'total' => $import_total, 'source' => $import_source, 'mode' => $import_mode) );
}
/**
* Stores ids of selected languages and redirects to export language step 1
*
* @param kEvent $event
*/
function OnExportLanguage(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$this->Application->setUnitOption('phrases','AutoLoad',false);
$this->StoreSelectedIDs($event);
$this->Application->StoreVar('export_language_ids', implode(',', $this->getSelectedIDs($event)) );
$event->setRedirectParams( Array('m_opener'=>'d','phrases.export_event'=>'OnNew','pass'=>'all,phrases.export') );
$event->redirect = 'regional/languages_export';
}
/**
* Saves selected languages to xml file passed
*
* @param kEvent $event
*/
function OnExportProgress(&$event)
{
$items_info = $this->Application->GetVar('phrases_export');
if($items_info)
{
list($id,$field_values) = each($items_info);
$object =& $this->Application->recallObject('phrases.export', 'phrases', Array('skip_autoload' => true) );
$object->SetFieldsFromHash($field_values);
$lang_ids = explode(',', $this->Application->RecallVar('export_language_ids') );
if( !getArrayValue($field_values,'LangFile') )
{
$object->SetError('LangFile', 'required');
$event->redirect = false;
return false;
}
if( !is_writable(EXPORT_PATH) )
{
$object->SetError('LangFile', 'write_error', 'la_ExportFolderNotWritable');
$event->redirect = false;
return false;
}
if( substr($field_values['LangFile'], -5) != '.lang' ) $field_values['LangFile'] .= '.lang';
$filename = EXPORT_PATH.'/'.$field_values['LangFile'];
$lang_xml =& $this->Application->recallObject('LangXML');
if ($object->GetDBField('DoNotEncode')) {
$lang_xml->SetEncoding('plain');
}
$lang_xml->Create($filename, $field_values['PhraseType'], $lang_ids, $field_values['Module']);
}
$event->redirect = 'regional/languages_export_step2';
$event->SetRedirectParam('export_file', $field_values['LangFile']);
}
/**
* Returns to previous template in opener stack
*
* @param kEvent $event
*/
function OnGoBack(&$event)
{
$event->redirect_params['opener'] = 'u';
}
function OnScheduleTopFrameReload(&$event)
{
$this->Application->StoreVar('RefreshTopFrame',1);
}
/**
* Do now allow deleting current language
*
* @param kEvent $event
*/
function OnBeforeItemDelete(&$event)
{
$del_id = $event->getEventParam('id');
$object =& $event->getObject(array('skip_autload' => true));
$object->Load($del_id);
if ($object->GetDBField('PrimaryLang') || $object->GetDBField('AdminInterfaceLang') || $del_id == $this->Application->GetVar('m_lang')) {
$event->status = erFAIL;
}
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/languages/languages_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.33.2.1
\ No newline at end of property
+1.33.2.2
\ No newline at end of property
Index: branches/RC/core/units/stylesheets/stylesheets_item.php
===================================================================
--- branches/RC/core/units/stylesheets/stylesheets_item.php (revision 10097)
+++ branches/RC/core/units/stylesheets/stylesheets_item.php (revision 10098)
@@ -1,43 +1,43 @@
<?php
class StylesheetsItem extends kDBItem
{
function Compile()
{
$selector_item =& $this->Application->recallObject('selectors.item', 'selectors', Array('live_table'=>true, 'skip_autoload' => true) );
$parent_field = $this->Application->getUnitOption($selector_item->Prefix, 'ForeignKey');
$sql_template = 'SELECT '.$selector_item->IDField.' FROM '.$selector_item->TableName.' WHERE '.$parent_field.' = %s ORDER BY SelectorName ASC';
$selectors_ids = $this->Conn->GetCol( sprintf($sql_template, $this->GetID() ) );
$ret = '/* This file is generated automatically. Don\'t edit it manually ! */'."\n\n";
foreach($selectors_ids as $selector_id)
{
$selector_item->Load($selector_id);
$ret .= $selector_item->CompileStyle()."\n";
}
$ret .= $this->GetDBField('AdvancedCSS');
$compile_ts = adodb_mktime();
$css_path = FULL_PATH.'/kernel/stylesheets/';
- $css_file = $css_path.strtolower($this->GetDBField('Name')).'-'.$compile_ts.'.css';
+ $css_file = $css_path.mb_strtolower($this->GetDBField('Name')).'-'.$compile_ts.'.css';
$fp = fopen($css_file,'w');
if($fp)
{
- $prev_css = $css_path.strtolower($this->GetDBField('Name')).'-'.$this->GetDBField('LastCompiled').'.css';
+ $prev_css = $css_path.mb_strtolower($this->GetDBField('Name')).'-'.$this->GetDBField('LastCompiled').'.css';
if( file_exists($prev_css) ) unlink($prev_css);
fwrite($fp, $ret);
fclose($fp);
$sql = 'UPDATE '.$this->TableName.' SET LastCompiled = '.$compile_ts.' WHERE '.$this->IDField.' = '.$this->GetID();
$this->Conn->Query($sql);
}
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/stylesheets/stylesheets_item.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.6
\ No newline at end of property
+1.6.2.1
\ No newline at end of property
Index: branches/RC/core/units/general/helpers/csv_helper.php
===================================================================
--- branches/RC/core/units/general/helpers/csv_helper.php (revision 10097)
+++ branches/RC/core/units/general/helpers/csv_helper.php (revision 10098)
@@ -1,362 +1,362 @@
<?php
safeDefine('EXPORT_STEP', 100); // export by 100 items
safeDefine('IMPORT_STEP', 10);
class kCSVHelper extends kHelper {
var $PrefixSpecial;
var $grid;
var $delimiter_mapping = Array(0 => "\t", 1 => ',', 2 => ';', 3 => ' ', 4 => ':');
var $enclosure_mapping = Array(0 => '"', 1 => "'");
var $separator_mapping = Array(0 => "\n", 1 => "\r\n");
function ExportStep()
{
$export_data = $this->Application->RecallVar('export_data');
$export_rand = $this->Application->RecallVar('export_rand');
$get_rand = $this->Application->GetVar('export_rand');
if($export_data && $export_rand == $get_rand) {
$export_data = unserialize($export_data);
$first_step = false;
}
else {
// first step
$export_data = Array();
$export_data['prefix'] = $this->PrefixSpecial;
$export_data['grid'] = $this->grid;
$export_data['file_name'] = EXPORT_PATH.'/'.$this->ValidateFileName(EXPORT_PATH, 'export_'.$export_data['prefix'].'.csv');
$export_data['step'] = EXPORT_STEP;
$export_data['delimiter'] = $this->delimiter_mapping[(int)$this->Application->ConfigValue('CSVExportDelimiter')];
$export_data['enclosure'] = $this->enclosure_mapping[(int)$this->Application->ConfigValue('CSVExportEnclosure')];
$export_data['record_separator'] = $this->separator_mapping[(int)$this->Application->ConfigValue('CSVExportSeparator')];
$export_data['page'] = 1;
$lang_object =& $this->Application->recallObject('lang.current');
/* @var $lang_object LanguagesItem */
$export_data['source_encoding'] = strtoupper( $lang_object->GetDBField('Charset') );
$export_data['encoding'] = $this->Application->ConfigValue('CSVExportEncoding') ? false : 'UTF-16LE';
$this->Application->StoreVar('export_rand', $get_rand);
$first_step = true;
}
$file = fopen($export_data['file_name'], $first_step ? 'w' : 'a');
$prefix_elems = split('\.|_', $export_data['prefix']);
$grids = $this->Application->getUnitOption($prefix_elems[0], 'Grids');
$grid_config = $grids[ $export_data['grid'] ]['Fields'];
$list_params = Array('per_page' => $export_data['step'], 'grid' => $export_data['grid']);
$list =& $this->Application->recallObject(rtrim(implode('.', $prefix_elems), '.'), $prefix_elems[0].'_List', $list_params);
/* @var $list kDBList */
$list->SetPage($export_data['page']);
$list->Query();
$list->GoFirst();
$picker_helper =& $this->Application->RecallObject('ColumnPickerHelper');
/* @var $picker_helper kColumnPickerHelper */
$picker_helper->ApplyPicker(rtrim(implode('.', $prefix_elems), '.'), $grid_config, $export_data['grid']);
if($first_step) {
// if UTF-16, write Unicode marker
if($export_data['encoding'] == 'UTF-16LE') {
fwrite($file, chr(0xFF).chr(0xFE));
}
// inserting header line
$headers = Array();
foreach($grid_config as $field_name => $field_data) {
$header = $this->Application->Phrase( $field_data['title'] );
array_push($headers, $header);
}
$csv_line = getcsvline($headers, $export_data['delimiter'], $export_data['enclosure'], $export_data['record_separator']);
if($export_data['encoding']) {
$csv_line = mb_convert_encoding($csv_line, $export_data['encoding'], $export_data['source_encoding']);
}
fwrite($file, $csv_line);
}
while(!$list->EOL())
{
$data = Array();
foreach($grid_config as $field_name => $field_data) {
if(isset($field_data['export_field'])) {
$field_name = $field_data['export_field'];
}
$value = $list->GetField($field_name, isset($field_data['format']) ? $field_data['format'] : null);
$value = str_replace("\r\n", "\n", $value);
$value = str_replace("\r", "\n", $value);
array_push($data, $value);
}
if($export_data['encoding'] == 'UTF-16LE') {
fwrite($file, chr(0xFF).chr(0xFE));
}
$csv_line = getcsvline($data, $export_data['delimiter'], $export_data['enclosure'], $export_data['record_separator']);
if($export_data['encoding']) {
$csv_line = mb_convert_encoding($csv_line, $export_data['encoding'], $export_data['source_encoding']);
}
fwrite($file, $csv_line);
$list->GoNext();
}
$records_processed = $export_data['page'] * $export_data['step'];
$percent_complete = min(round($records_processed / $list->RecordsCount * 100), 100);
fclose($file);
if ($records_processed >= $list->RecordsCount) {
$this->Application->StoreVar('export_data', serialize($export_data));
$this->Application->Redirect($this->Application->GetVar('finish_template'));
}
echo $percent_complete;
$export_data['page']++;
$this->Application->StoreVar('export_data', serialize($export_data));
}
function ValidateFileName($path, $name)
{
$parts = pathinfo($name);
$ext = '.'.$parts['extension'];
- $filename = substr($parts['basename'], 0, -strlen($ext));
+ $filename = mb_substr($parts['basename'], 0, -mb_strlen($ext));
$new_name = $filename.$ext;
while ( file_exists($path.'/'.$new_name) )
{
if ( preg_match('/('.preg_quote($filename, '/').'_)([0-9]*)('.preg_quote($ext, '/').')/', $new_name, $regs) ) {
$new_name = $regs[1].($regs[2]+1).$regs[3];
}
else {
$new_name = $filename.'_1'.$ext;
}
}
return $new_name;
}
function ExportData($name)
{
$export_data = unserialize($this->Application->RecallVar('export_data'));
return isset($export_data[$name]) ? $export_data[$name] : false;
}
-
+
function GetCSV()
{
safeDefine('DBG_SKIP_REPORTING', 1);
$export_data = unserialize($this->Application->RecallVar('export_data'));
header('Content-type: text/csv');
$filename = rtrim(basename($export_data['file_name']), '.csv').'.csv';
header('Content-Disposition: attachment; filename="'.$filename.'"');
readfile($export_data['file_name']);
die();
}
function ImportStart($filename)
{
if(!file_exists($filename) || !is_file($filename)) return 'cant_open_file';
$import_data = Array();
$lang_object =& $this->Application->recallObject('lang.current');
/* @var $lang_object LanguagesItem */
$import_data['source_encoding'] = strtoupper( $lang_object->GetDBField('Charset') );
$import_data['encoding'] = $this->Application->ConfigValue('CSVExportEncoding') ? false : 'UTF-16LE';
$import_data['errors'] = '';
// convert file in case of UTF-16LE
if($import_data['source_encoding'] != $import_data['encoding']) {
copy($filename, $filename.'.orginal');
$file_content = file_get_contents($filename);
$file = fopen($filename, 'w');
fwrite($file, mb_convert_encoding(str_replace(chr(0xFF).chr(0xFE), '', $file_content), $import_data['source_encoding'], $import_data['encoding']));
fclose($file);
}
$import_data['prefix'] = $this->PrefixSpecial;
$import_data['grid'] = $this->grid;
$import_data['file'] = $filename;
$import_data['total_lines'] = count(file($filename));
if(!$import_data['total_lines']) $import_data['total_lines'] = 1;
unset($file_content);
$import_data['lines_processed'] = 0;
$import_data['delimiter'] = $this->delimiter_mapping[(int)$this->Application->ConfigValue('CSVExportDelimiter')];
$import_data['enclosure'] = $this->enclosure_mapping[(int)$this->Application->ConfigValue('CSVExportEnclosure')];
$import_data['step'] = IMPORT_STEP;
$import_data['not_imported_lines'] = '';
$import_data['added'] = 0;
$import_data['updated'] = 0;
$file = fopen($filename, 'r');
// getting first line for headers
$headers = fgetcsv($file, 8192, $import_data['delimiter'], $import_data['enclosure']);
fclose($file);
$prefix_elems = split('\.|_', $import_data['prefix']);
$grids = $this->Application->getUnitOption($prefix_elems[0], 'Grids');
$grid_config = $grids[ $import_data['grid'] ]['Fields'];
$field_list = Array();
foreach($grid_config as $field_name => $field_data) {
if(isset($field_data['export_field'])) {
$field_name = $field_data['export_field'];
}
$field_label = $this->Application->Phrase( $field_data['title'] );
$field_pos = array_search($field_label, $headers);
if($field_pos !== false) {
$field_list[$field_pos] = $field_name;
}
}
if(!count($field_list)) return 'no_matching_columns';
$import_data['field_list'] = $field_list;
// getting key list
$field_positions = Array();
$config_key_list = $this->Application->getUnitOption($prefix_elems[0], 'ImportKeys');
if(!$config_key_list) $config_key_list = Array();
array_unshift($config_key_list, Array($this->Application->getUnitOption($prefix_elems[0], 'IDField')));
$key_list = Array();
foreach($config_key_list as $arr_key => $import_key) {
$key_list[$arr_key] = is_array($import_key) ? $import_key : Array($import_key);
foreach($key_list[$arr_key] as $key_field) {
$field_positions[$key_field] = array_search($key_field, $import_data['field_list']);
if($field_positions[$key_field] === false) {
// no such key field combination in imported file
unset($key_list[$arr_key]);
break;
}
}
}
$import_data['key_list'] = $key_list;
$import_data['field_positions'] = $field_positions;
$this->Application->StoreVar('import_data', serialize($import_data));
return true;
}
function ImportStep()
{
$import_data = unserialize($this->Application->RecallVar('import_data'));
$prefix_elems = split('\.|_', $import_data['prefix']);
$object =& $this->Application->recallObject($prefix_elems[0].'.-csvimport', $prefix_elems[0], Array('skip_autoload' => true, 'populate_ml_fields' => true));
/* @var $object kDBItem */
$file = fopen($import_data['file'], 'r');
$eof = false;
// skipping lines that has been already imported
for($i = 0; $i < $import_data['lines_processed'] + 1; $i++) {
if(feof($file)) break;
fgets($file, 8192);
}
$import_event = new kEvent($prefix_elems[0].'.-csvimport:OnBeforeCSVLineImport');
for($i = 0; $i < $import_data['step']; $i++) {
if(feof($file)) break;
$data = fgetcsv($file, 8192, $import_data['delimiter'], $import_data['enclosure']);
if(!$data) continue;
$object->Clear();
$action = 'Create';
// 1. trying to load object by keys
foreach($import_data['key_list'] as $key) {
$fail = false;
$key_array = Array();
foreach($key as $key_field) {
if(!isset($data[ $import_data['field_positions'][$key_field] ])) {
$fail = true;
break;
}
$key_array[$key_field] = $data[ $import_data['field_positions'][$key_field] ];
}
if($fail) continue;
if($object->Load($key_array)) {
$action = 'Update';
break;
}
}
// 2. set object fields
foreach($import_data['field_list'] as $position => $field_name) {
if(isset($data[$position])) {
$object->SetField($field_name, $data[$position]);
}
}
// 3. validate item and run event
$status = $object->Validate();
$import_event->status = $status ? erSUCCESS : erFAIL;
$this->Application->HandleEvent($import_event);
if($import_event->status == erSUCCESS && $object->$action()) {
$import_data[ ($action == 'Create') ? 'added' : 'updated' ]++;
}
else {
$msg = '';
foreach ($object->FieldErrors as $field => $info) {
if (!$info['pseudo']) continue;
$msg .= "$field: {$info['pseudo']} ";
}
$import_data['errors'] .= ($i + $import_data['lines_processed'] + 1).": $msg\n";
$import_data['not_imported_lines'] .= ','.($i + $import_data['lines_processed'] + 1);
}
}
$import_data['lines_processed'] += $import_data['step'];
$import_data['not_imported_lines'] = ltrim($import_data['not_imported_lines'], ',');
$this->Application->StoreVar('import_data', serialize($import_data));
$feof = feof($file);
fclose($file);
if($feof) {
$this->Application->Redirect($this->Application->GetVar('finish_template'));
}
else {
$percent_complete = floor($import_data['lines_processed'] / $import_data['total_lines'] * 100);
if($percent_complete > 99) $percent_complete = 99;
echo $percent_complete;
}
}
function ImportData($name)
{
$import_data = unserialize($this->Application->RecallVar('import_data'));
return isset($import_data[$name]) ? $import_data[$name] : false;
}
function GetNotImportedLines()
{
$import_data = unserialize($this->Application->RecallVar('import_data'));
if(!$import_data['not_imported_lines']) return false;
$line_numbers = explode(',', $import_data['not_imported_lines']);
$line_numbers[] = 0; // include header row in output
$file = fopen($import_data['file'], 'r');
$eof = false;
$result = '';
for($i = 0; $i <= max($line_numbers); $i++) {
if(feof($file)) break;
$line = fgets($file, 8192);
if(in_array($i, $line_numbers)) {
$result .= $i.':'.$line;
}
}
return $result."\n\n".$import_data['errors'];
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/general/helpers/csv_helper.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1.4.1
\ No newline at end of property
+1.1.4.2
\ No newline at end of property
Index: branches/RC/core/units/general/helpers/filenames_helper.php
===================================================================
--- branches/RC/core/units/general/helpers/filenames_helper.php (revision 10097)
+++ branches/RC/core/units/general/helpers/filenames_helper.php (revision 10098)
@@ -1,90 +1,90 @@
<?php
class kFilenamesHelper extends kHelper {
/**
* replace not allowed symbols with "_" chars + remove duplicate "_" chars in result
*
* @param string $string
* @return string
*/
function stripDisallowed($table, $id_field, $item_id, $filename)
{
$not_allowed = Array( ' ', '\\', '/', ':', '*', '?', '"', '<', '>', '|', '`',
'~', '!', '@', '#', '$', '%', '^', '&', '(', ')', '~',
'+', '=', '-', '{', '}', ']', '[', "'", ';', '.', ',', "\r", "\n");
$filename = str_replace($not_allowed, '_', $filename);
$filename = preg_replace('/(_+)/', '_', $filename);
$filename = $this->checkAutoFilename($table, $id_field, $item_id, $filename);
return $filename;
}
function checkAutoFilename($table, $id_field, $item_id, $filename)
{
if(!$filename) return $filename;
$item_id = !$item_id ? 0 : $item_id;
if ($table == TABLE_PREFIX.'CategoryItems') {
$item_categories_cur = $this->Conn->GetCol('SELECT CategoryId FROM '.$table.' WHERE ItemResourceId = '.$item_id);
$item_categories_live = $this->Application->IsTempTable($table) ? $this->Conn->GetCol('SELECT CategoryId FROM '.$this->Application->GetLiveName($table).' WHERE ItemResourceId = '.$item_id) : array();
$item_categories = array_unique(array_merge($item_categories_cur, $item_categories_live));
if (!$item_categories) {
$item_categories = array($this->Application->GetVar('m_cat_id')); // this may happen when creating new item
}
$cat_filter = ' AND CategoryId IN ('.implode(',', $item_categories).')';
}
else {
$cat_filter = '';
}
// check current table (temp or live)
$sql_temp = 'SELECT '.$id_field.' FROM '.$table.' WHERE Filename = '.$this->Conn->qstr($filename).$cat_filter;
$found_temp_ids = $this->Conn->GetCol($sql_temp);
// check live table if current is temp
if ( $this->Application->IsTempTable($table) ) {
$sql_live = 'SELECT '.$id_field.' FROM '.$this->Application->GetLiveName($table).' WHERE Filename = '.$this->Conn->qstr($filename).$cat_filter;
$found_live_ids = $this->Conn->GetCol($sql_live);
}
else {
$found_live_ids = array();
}
$found_item_ids = array_unique( array_merge($found_temp_ids, $found_live_ids) );
$has_page = preg_match('/(.*)_([\d]+)([a-z]*)$/', $filename, $rets);
$duplicates_found = (count($found_item_ids) > 1) || ($found_item_ids && $found_item_ids[0] != $item_id);
if ($duplicates_found || $has_page) // other category has same filename as ours OR we have filename, that ends with _number
{
$append = $duplicates_found ? '_a' : '';
if($has_page)
{
$filename = $rets[1].'_'.$rets[2];
$append = $rets[3] ? $rets[3] : '_a';
}
// check live & temp table
$sql_cur = 'SELECT '.$id_field.' FROM '.$table.' WHERE (Filename = %s) AND ('.$id_field.' != '.$item_id.')'.$cat_filter;
$sql_live = $this->Application->IsTempTable($table) ? 'SELECT '.$id_field.' FROM '.$this->Application->GetLiveName($table).' WHERE (Filename = %s) AND ('.$id_field.' != '.$item_id.')'.$cat_filter : false;
while ( $this->Conn->GetOne( sprintf($sql_cur, $this->Conn->qstr($filename.$append)) ) > 0 ||
( $sql_live
&&
( $this->Conn->GetOne( sprintf($sql_live, $this->Conn->qstr($filename.$append)) ) > 0 )
)
)
{
- if (substr($append, -1) == 'z') $append .= 'a';
- $append = substr($append, 0, strlen($append) - 1) . chr( ord( substr($append, -1) ) + 1 );
+ if (mb_substr($append, -1) == 'z') $append .= 'a';
+ $append = mb_substr($append, 0, mb_strlen($append) - 1) . chr( ord( mb_substr($append, -1) ) + 1 );
}
return $filename.$append;
}
return $filename;
}
}
\ No newline at end of file
Property changes on: branches/RC/core/units/general/helpers/filenames_helper.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3
\ No newline at end of property
+1.3.2.1
\ No newline at end of property
Index: branches/RC/core/units/general/main_event_handler.php
===================================================================
--- branches/RC/core/units/general/main_event_handler.php (revision 10097)
+++ branches/RC/core/units/general/main_event_handler.php (revision 10098)
@@ -1,139 +1,139 @@
<?php
class MainEventHandler extends kEventHandler {
/**
* Description
*
* @var kDBConnection
* @access public
*/
var $Conn;
/**
* Adds ability to address db connection
*
* @return kDBEventHandler
* @access public
*/
function MainEventHandler()
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
}
/**
* Created url part for this module
*
* @param kEvent $event
*/
function BuildEnv(&$event)
{
$prefix_special = $event->getPrefixSpecial();
$url_params = $event->getEventParam('url_params');
$query_vars = $this->Application->getUnitOption($event->Prefix, 'QueryString');
//if pass events is off and event is not implicity passed
if ( !$event->getEventParam('pass_events') && !isset($url_params[$prefix_special.'_event']) )
{
$url_params[$prefix_special.'_event'] = ''; // remove event from url if requested
//otherwise it will use value from get_var
}
if(!$query_vars) return true;
$processed_params = Array();
foreach($query_vars as $index => $var_name)
{
//if value passed in params use it, otherwise use current from application
$var_name = $prefix_special.'_'.$var_name;
$processed_params[$var_name] = isset( $url_params[$var_name] ) ? $url_params[$var_name] : $this->Application->GetVar($var_name);
if ( isset($url_params[$var_name]) ) unset( $url_params[$var_name] );
}
$ret = '';
$default_language_id = $this->Application->GetDefaultLanguageId();
if( $processed_params['m_lang'] && ($processed_params['m_lang'] != $default_language_id) )
{
$language_name = $this->Application->getCache('language_names', $processed_params['m_lang']);
if ($language_name === false) {
$sql = 'SELECT PackName
FROM '.TABLE_PREFIX.'Language
WHERE LanguageId = '.$processed_params['m_lang'];
$language_name = $this->Conn->GetOne($sql);
$this->Application->setCache('language_names', $processed_params['m_lang'], $language_name);
}
$ret .= $language_name.'/';
}
$default_theme_id = $this->Application->GetDefaultThemeId();
if( $processed_params['m_theme'] && ($processed_params['m_theme'] != $default_theme_id) )
{
$theme_name = $this->Application->getCache('theme_names', $processed_params['m_theme']);
if ($theme_name === false) {
$sql = 'SELECT Name
FROM '.TABLE_PREFIX.'Theme
WHERE ThemeId = '.$processed_params['m_theme'];
$theme_name = $this->Conn->GetOne($sql);
$this->Application->setCache('theme_names', $processed_params['m_theme'], $theme_name);
}
$ret .= $theme_name.'/';
}
if ($processed_params['m_cat_id'] > 0 && isset($url_params['pass_category']) && $url_params['pass_category']) {
$category_filename = $this->Application->getFilename('c', $processed_params['m_cat_id']);
$t = isset($url_params['t']) && $url_params['t'] ? $url_params['t'] : false;
// category name doesn't match template name -> Proj-CMS/In-Edit tricks
if (!preg_match('/Content\/'.preg_quote($t, '/').'/i', $category_filename)) {
$ret .= $category_filename.'/';
}
$url_params['category_processed'] = true;
}
else {
// $url_params['no_category'] = 1; // for debugging
}
unset($url_params['pass_category']); // unset it just in case
$force_page_adding = false;
if (getArrayValue($url_params, 'reset'))
{
unset($url_params['reset']);
if ($processed_params['m_cat_id'])
{
$processed_params['m_cat_page'] = 1;
$force_page_adding = true;
}
}
if( $processed_params['m_cat_page'] > 1 || $force_page_adding )
{
$ret = preg_replace('/(.*)\//', '\\1', $ret).'_'.$processed_params['m_cat_page'].'/';
}
$template = getArrayValue($url_params, 't');
$category_template = $processed_params['m_cat_id'] ? $this->Application->getCache('category_templates', $processed_params['m_cat_id']) : '';
if ((strtolower($template) == '__default__') && ($processed_params['m_cat_id'] == 0)) {
// for "Home" category set template to index when not set
$template = 'index';
}
// remove template from url if it is category index cached template
- if ($template == $category_template || strtolower($template) == '__default__') {
+ if ($template == $category_template || mb_strtolower($template) == '__default__') {
$template = '';
}
if ($template) {
$ret .= $template.'/';
}
unset($url_params['t']);
$event->setEventParam('url_params', $url_params);
- $event->setEventParam('env_string', strtolower($ret) );
+ $event->setEventParam('env_string', mb_strtolower($ret) );
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/general/main_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.17
\ No newline at end of property
+1.17.2.1
\ No newline at end of property
Index: branches/RC/core/units/general/cat_event_handler.php
===================================================================
--- branches/RC/core/units/general/cat_event_handler.php (revision 10097)
+++ branches/RC/core/units/general/cat_event_handler.php (revision 10098)
@@ -1,2377 +1,2377 @@
<?php
$application =& kApplication::Instance();
$application->Factory->includeClassFile('kDBEventHandler');
class kCatDBEventHandler extends kDBEventHandler {
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnExport' => Array('self' => 'view|advanced:export'),
'OnExportBegin' => Array('self' => 'view|advanced:export'),
'OnSaveSettings' => Array('self' => 'add|edit|advanced:import'),
'OnBeforeDeleteOriginal' => Array('self' => 'edit|advanced:approve'),
'OnDownloadFile' => Array('self' => 'view'),
'OnCancelAction' => Array('self' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Load item if id is available
*
* @param kEvent $event
*/
function LoadItem(&$event)
{
$object =& $event->getObject();
$id = $this->getPassedID($event);
if ($object->Load($id)) {
$actions =& $this->Application->recallObject('kActions');
$actions->Set($event->Prefix_Special.'_id', $object->GetID() );
$use_pending_editing = $this->Application->getUnitOption($event->Prefix, 'UsePendingEditing');
if ($use_pending_editing && $event->Special != 'original') {
$this->Application->SetVar($event->Prefix.'.original_id', $object->GetDBField('OrgId'));
}
}
else {
$object->setID($id);
}
}
/**
* Checks permissions of user
*
* @param kEvent $event
*/
function CheckPermission(&$event)
{
if (!$this->Application->IsAdmin()) {
if ($event->Name == 'OnSetSortingDirect') {
// allow sorting on front event without view permission
return true;
}
}
if ($event->Name == 'OnExport') {
// save category_id before doing export
$this->Application->LinkVar('m_cat_id');
}
if ($event->Name == 'OnNew' && preg_match('/(.*)\/import$/', $this->Application->GetVar('t'), $rets)) {
// redirect to item import template, where permission (import) category will be chosen)
$root_category = $this->Application->findModule('Path', $rets[1].'/', 'RootCat');
$this->Application->StoreVar('m_cat_id', $root_category);
}
$check_events = Array ('OnEdit', 'OnSave', 'OnMassDelete');
if (in_array($event->Name, $check_events)) {
// check each id from selected individually and only if all are allowed proceed next
if ($event->Name == 'OnSave') {
$selected_ids = implode(',', $this->getSelectedIDs($event, true));
if (!$selected_ids) {
$selected_ids = 0; // when saving newly created item (OnPreCreate -> OnPreSave -> OnSave)
}
}
else {
$selected_ids = implode(',', $this->StoreSelectedIDs($event));
}
$perm_value = true;
if (strlen($selected_ids)) {
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
$items = $perm_helper->GetCategoryItemData($event->Prefix, $selected_ids);
$check_method = ($event->Name == 'OnMassDelete') ? 'DeleteCheckPermission' : 'ModifyCheckPermission';
foreach ($items as $item_id => $item_data) {
if ($perm_helper->$check_method($item_data['CreatedById'], $item_data['CategoryId'], $event->Prefix) == 0) {
// one of items selected has no permission
$perm_value = false;
break;
}
}
if (!$perm_value) {
$event->status = erPERM_FAIL;
}
}
else {
trigger_error('IDs not passed to '.$event->getPrefixSpecial().':CheckPermission', E_USER_WARNING);
}
return $perm_value;
}
return parent::CheckPermission($event);
}
/**
* Add selected items to clipboard with mode = COPY (CLONE)
*
* @param kEvent $event
*/
function OnCopy(&$event)
{
$this->Application->RemoveVar('clipboard');
$clipboard_helper =& $this->Application->recallObject('ClipboardHelper');
$clipboard_helper->setClipboard($event, 'copy', $this->StoreSelectedIDs($event));
}
/**
* Add selected items to clipboard with mode = CUT
*
* @param kEvent $event
*/
function OnCut(&$event)
{
$this->Application->RemoveVar('clipboard');
$clipboard_helper =& $this->Application->recallObject('ClipboardHelper');
$clipboard_helper->setClipboard($event, 'cut', $this->StoreSelectedIDs($event));
}
/**
* Performs category item paste
*
* @param kEvent $event
*/
function OnPaste(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$clipboard_data = $event->getEventParam('clipboard_data');
if (!$clipboard_data['cut'] && !$clipboard_data['copy']) {
return false;
}
if ($clipboard_data['copy']) {
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$this->Application->SetVar('ResetCatBeforeClone', 1);
$temp->CloneItems($event->Prefix, $event->Special, $clipboard_data['copy']);
}
if ($clipboard_data['cut']) {
$object =& $this->Application->recallObject($event->getPrefixSpecial().'.item', $event->Prefix, Array('skip_autoload' => true));
foreach ($clipboard_data['cut'] as $id) {
$object->Load($id);
$object->MoveToCat();
}
}
}
/**
* Deletes all selected items.
* Automatically recurse into sub-items using temp handler, and deletes sub-items
* by calling its Delete method if sub-item has AutoDelete set to true in its config file
*
* @param kEvent $event
*/
function OnMassDelete(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$event->status=erSUCCESS;
$ids = $this->StoreSelectedIDs($event);
$to_delete = array();
if ($recycle_bin = $this->Application->ConfigValue('RecycleBinFolder')) {
$rb =& $this->Application->recallObject('c.recycle', null, array('skip_autoload' => true));
$rb->Load($recycle_bin);
$object =& $this->Application->recallObject($event->Prefix.'.recycleitem', null, Array ('skip_autoload' => true));
foreach ($ids as $id) {
$object->Load($id);
if (preg_match('/^'.preg_quote($rb->GetDBField('ParentPath'),'/').'/', $object->GetDBField('ParentPath'))) {
$to_delete[] = $id;
continue;
}
$object->MoveToCat($recycle_bin);
}
$ids = $to_delete;
}
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$event->setEventParam('ids', $ids);
$this->customProcessing($event, 'before');
$ids = $event->getEventParam('ids');
if($ids)
{
$temp->DeleteItems($event->Prefix, $event->Special, $ids);
}
$this->clearSelectedIDs($event);
}
/**
* Return type clauses for list bulding on front
*
* @param kEvent $event
* @return Array
*/
function getTypeClauses(&$event)
{
$types = $event->getEventParam('types');
$types = $types ? explode(',', $types) : Array ();
$except_types = $event->getEventParam('except');
$except_types = $except_types ? explode(',', $except_types) : Array ();
$type_clauses = Array();
$user_id = $this->Application->RecallVar('user_id');
$owner_field = $this->getOwnerField($event->Prefix);
$type_clauses['my_items']['include'] = '%1$s.'.$owner_field.' = '.$user_id;
$type_clauses['my_items']['except'] = '%1$s.'.$owner_field.' <> '.$user_id;
$type_clauses['my_items']['having_filter'] = false;
$type_clauses['pick']['include'] = '%1$s.EditorsPick = 1 AND '.TABLE_PREFIX.'CategoryItems.PrimaryCat = 1';
$type_clauses['pick']['except'] = '%1$s.EditorsPick! = 1 AND '.TABLE_PREFIX.'CategoryItems.PrimaryCat = 1';
$type_clauses['pick']['having_filter'] = false;
$type_clauses['hot']['include'] = '`IsHot` = 1 AND PrimaryCat = 1';
$type_clauses['hot']['except'] = '`IsHot`! = 1 AND PrimaryCat = 1';
$type_clauses['hot']['having_filter'] = true;
$type_clauses['pop']['include'] = '`IsPop` = 1 AND PrimaryCat = 1';
$type_clauses['pop']['except'] = '`IsPop`! = 1 AND PrimaryCat = 1';
$type_clauses['pop']['having_filter'] = true;
$type_clauses['new']['include'] = '`IsNew` = 1 AND PrimaryCat = 1';
$type_clauses['new']['except'] = '`IsNew`! = 1 AND PrimaryCat = 1';
$type_clauses['new']['having_filter'] = true;
$type_clauses['displayed']['include'] = '';
$displayed = $this->Application->GetVar($event->Prefix.'_displayed_ids');
if ($displayed) {
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
$type_clauses['displayed']['except'] = '%1$s.'.$id_field.' NOT IN ('.$displayed.')';
}
else {
$type_clauses['displayed']['except'] = '';
}
$type_clauses['displayed']['having_filter'] = false;
if (in_array('search', $types) || in_array('search', $except_types)) {
$event_mapping = Array(
'simple' => 'OnSimpleSearch',
'subsearch' => 'OnSubSearch',
'advanced' => 'OnAdvancedSearch');
if($this->Application->GetVar('INPORTAL_ON') && $this->Application->GetVar('Action') == 'm_simple_subsearch')
{
$type = 'subsearch';
}
else
{
$type = $this->Application->GetVar('search_type') ? $this->Application->GetVar('search_type') : 'simple';
}
if($keywords = $event->getEventParam('keyword_string')) // processing keyword_string param of ListProducts tag
{
$this->Application->SetVar('keywords', $keywords);
$type = 'simple';
}
$search_event = $event_mapping[$type];
$this->$search_event($event);
$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$sql = 'SHOW TABLES LIKE "'.$search_table.'"';
if ($this->Conn->Query($sql)) {
$search_res_ids = $this->Conn->GetCol('SELECT ResourceId FROM '.$search_table);
}
if (isset($search_res_ids) && $search_res_ids) {
$type_clauses['search']['include'] = '%1$s.ResourceId IN ('.implode(',', $search_res_ids).') AND PrimaryCat = 1';
$type_clauses['search']['except'] = '%1$s.ResourceId NOT IN ('.implode(',', $search_res_ids).') AND PrimaryCat = 1';
}
else {
$type_clauses['search']['include'] = '0';
$type_clauses['search']['except'] = '1';
}
$type_clauses['search']['having_filter'] = false;
}
if (in_array('related', $types) || in_array('related', $except_types)) {
$related_to = $event->getEventParam('related_to');
if (!$related_to) {
$related_prefix = $event->Prefix;
}
else {
$sql = 'SELECT Prefix
FROM '.TABLE_PREFIX.'ItemTypes
WHERE ItemName = '.$this->Conn->qstr($related_to);
$related_prefix = $this->Conn->GetOne($sql);
}
$rel_table = $this->Application->getUnitOption('rel', 'TableName');
$item_type = $this->Application->getUnitOption($event->Prefix, 'ItemType');
$p_item =& $this->Application->recallObject($related_prefix.'.current', null, Array('skip_autoload' => true));
$p_item->Load( $this->Application->GetVar($related_prefix.'_id') );
$p_resource_id = $p_item->GetDBField('ResourceId');
$sql = 'SELECT SourceId, TargetId FROM '.$rel_table.'
WHERE
(Enabled = 1)
AND (
(Type = 0 AND SourceId = '.$p_resource_id.' AND TargetType = '.$item_type.')
OR
(Type = 1
AND (
(SourceId = '.$p_resource_id.' AND TargetType = '.$item_type.')
OR
(TargetId = '.$p_resource_id.' AND SourceType = '.$item_type.')
)
)
)';
$related_ids_array = $this->Conn->Query($sql);
$related_ids = Array();
foreach ($related_ids_array as $key => $record) {
$related_ids[] = $record[ $record['SourceId'] == $p_resource_id ? 'TargetId' : 'SourceId' ];
}
if (count($related_ids) > 0) {
$type_clauses['related']['include'] = '%1$s.ResourceId IN ('.implode(',', $related_ids).') AND PrimaryCat = 1';
$type_clauses['related']['except'] = '%1$s.ResourceId NOT IN ('.implode(',', $related_ids).') AND PrimaryCat = 1';
}
else {
$type_clauses['related']['include'] = '0';
$type_clauses['related']['except'] = '1';
}
$type_clauses['related']['having_filter'] = false;
}
if (in_array('favorites', $types) || in_array('favorites', $except_types)) {
$sql = 'SELECT ResourceId
FROM '.$this->Application->getUnitOption('fav', 'TableName').'
WHERE PortalUserId = '.$this->Application->RecallVar('user_id');
$favorite_ids = $this->Conn->GetCol($sql);
if ($favorite_ids) {
$type_clauses['favorites']['include'] = '%1$s.ResourceId IN ('.implode(',', $favorite_ids).') AND PrimaryCat = 1';
$type_clauses['favorites']['except'] = '%1$s.ResourceId NOT IN ('.implode(',', $favorite_ids).') AND PrimaryCat = 1';
}
else {
$type_clauses['favorites']['include'] = 0;
$type_clauses['favorites']['except'] = 1;
}
$type_clauses['favorites']['having_filter'] = false;
}
return $type_clauses;
}
/**
* Returns SQL clause, that will help to select only data from specified category & it's children
*
* @param int $category_id
* @return string
*/
function getCategoryLimitClause($category_id)
{
if (!$category_id) {
return false;
}
$sql = 'SELECT TreeLeft, TreeRight
FROM '.TABLE_PREFIX.'Category
WHERE CategoryId = '.$category_id;
$tree_indexes = $this->Conn->GetRow($sql);
return TABLE_PREFIX.'Category.TreeLeft BETWEEN '.$tree_indexes['TreeLeft'].' AND '.$tree_indexes['TreeRight'];
}
/**
* Apply filters to list
*
* @param kEvent $event
*/
function SetCustomQuery(&$event)
{
parent::SetCustomQuery($event);
$object =& $event->getObject();
/* @var $object kDBList */
// add category filter if needed
if ($event->Special != 'showall' && $event->Special != 'user') {
if ($event->getEventParam('parent_cat_id') !== false) {
$parent_cat_id = $event->getEventParam('parent_cat_id');
}
else {
$parent_cat_id = $this->Application->GetVar('c_id');
if (!$parent_cat_id) {
$parent_cat_id = $this->Application->GetVar('m_cat_id');
}
if (!$parent_cat_id) {
$parent_cat_id = 0;
}
}
if ((string) $parent_cat_id != 'any') {
if ($event->getEventParam('recursive')) {
$filter_clause = $this->getCategoryLimitClause($parent_cat_id);
if ($filter_clause !== false) {
$object->addFilter('category_filter', $filter_clause);
}
$object->addFilter('primary_filter', 'PrimaryCat = 1');
}
else {
$object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.CategoryId = '.$parent_cat_id );
}
}
}
else {
$object->addFilter('primary_filter', 'PrimaryCat = 1');
// if using recycle bin don't show items from there
$recycle_bin = $this->Application->ConfigValue('RecycleBinFolder');
if ($recycle_bin) {
$object->addFilter('recyclebin_filter', TABLE_PREFIX.'CategoryItems.CategoryId <> '.$recycle_bin);
}
}
if ($event->Special == 'user') {
$editable_user = $this->Application->GetVar('u_id');
$object->addFilter('owner_filter', '%1$s.'.$this->getOwnerField($event->Prefix).' = '.$editable_user);
}
// add permission filter
if ($this->Application->RecallVar('user_id') == -1) {
// for "root" CATEGORY.VIEW permission is checked for items lists too
$view_perm = 1;
}
else {
// for any real user itemlist view permission is checked instead of CATEGORY.VIEW
$count_helper =& $this->Application->recallObject('CountHelper');
/* @var $count_helper kCountHelper */
list ($view_perm, $view_filter) = $count_helper->GetPermissionClause($event->Prefix, 'perm');
$object->addFilter('perm_filter2', $view_filter);
}
$object->addFilter('perm_filter', 'perm.PermId = '.$view_perm);
$types = $event->getEventParam('types');
$this->applyItemStatusFilter($object, $types);
$except_types = $event->getEventParam('except');
$type_clauses = $this->getTypeClauses($event);
// convert prepared type clauses into list filters
$includes_or_filter =& $this->Application->makeClass('kMultipleFilter');
$includes_or_filter->setType(FLT_TYPE_OR);
$excepts_and_filter =& $this->Application->makeClass('kMultipleFilter');
$excepts_and_filter->setType(FLT_TYPE_AND);
$includes_or_filter_h =& $this->Application->makeClass('kMultipleFilter');
$includes_or_filter_h->setType(FLT_TYPE_OR);
$excepts_and_filter_h =& $this->Application->makeClass('kMultipleFilter');
$excepts_and_filter_h->setType(FLT_TYPE_AND);
if ($types) {
$types_array = explode(',', $types);
for ($i = 0; $i < sizeof($types_array); $i++) {
$type = trim($types_array[$i]);
if (isset($type_clauses[$type])) {
if ($type_clauses[$type]['having_filter']) {
$includes_or_filter_h->removeFilter('filter_'.$type);
$includes_or_filter_h->addFilter('filter_'.$type, $type_clauses[$type]['include']);
}else {
$includes_or_filter->removeFilter('filter_'.$type);
$includes_or_filter->addFilter('filter_'.$type, $type_clauses[$type]['include']);
}
}
}
}
if ($except_types) {
$except_types_array = explode(',', $except_types);
for ($i = 0; $i < sizeof($except_types_array); $i++) {
$type = trim($except_types_array[$i]);
if (isset($type_clauses[$type])) {
if ($type_clauses[$type]['having_filter']) {
$excepts_and_filter_h->removeFilter('filter_'.$type);
$excepts_and_filter_h->addFilter('filter_'.$type, $type_clauses[$type]['except']);
}else {
$excepts_and_filter->removeFilter('filter_'.$type);
$excepts_and_filter->addFilter('filter_'.$type, $type_clauses[$type]['except']);
}
}
}
}
/*if ( !$this->Application->IsAdmin() ) {
$object->addFilter('expire_filter', '%1$s.Expire IS NULL OR %1$s.Expire > UNIX_TIMESTAMP()');
}*/
/*$list_type = $event->getEventParam('ListType');
switch($list_type)
{
case 'favorites':
$fav_table = $this->Application->getUnitOption('fav','TableName');
$user_id =& $this->Application->RecallVar('user_id');
$sql = 'SELECT DISTINCT f.ResourceId
FROM '.$fav_table.' f
LEFT JOIN '.$object->TableName.' p ON p.ResourceId = f.ResourceId
WHERE f.PortalUserId = '.$user_id;
$ids = $this->Conn->GetCol($sql);
if(!$ids) $ids = Array(-1);
$object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.PrimaryCat = 1');
$object->addFilter('favorites_filter', '%1$s.`ResourceId` IN ('.implode(',',$ids).')');
break;
case 'search':
$search_results_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$sql = ' SELECT DISTINCT ResourceId
FROM '.$search_results_table.'
WHERE ItemType=11';
$ids = $this->Conn->GetCol($sql);
if(!$ids) $ids = Array(-1);
$object->addFilter('search_filter', '%1$s.`ResourceId` IN ('.implode(',',$ids).')');
break;
} */
$object->addFilter('includes_filter', $includes_or_filter);
$object->addFilter('excepts_filter', $excepts_and_filter);
$object->addFilter('includes_filter_h', $includes_or_filter_h, HAVING_FILTER);
$object->addFilter('excepts_filter_h', $excepts_and_filter_h, HAVING_FILTER);
}
/**
* Adds filter that filters out items with non-required statuses
*
* @param kDBList $object
* @param string $types
*/
function applyItemStatusFilter(&$object, $types)
{
// Link1 (before modifications) [Status = 1, OrgId = NULL], Link2 (after modifications) [Status = -2, OrgId = Link1_ID]
$pending_editing = $this->Application->getUnitOption($object->Prefix, 'UsePendingEditing');
if ( !$this->Application->IsAdmin() ) {
$types = explode(',', $types);
if (in_array('my_items', $types)) {
$allow_statuses = Array (STATUS_ACTIVE, STATUS_PENDING, STATUS_PENDING_EDITING);
$object->addFilter('status_filter', '%1$s.Status IN ('.implode(',', $allow_statuses).')');
if ($pending_editing) {
$user_id = $this->Application->RecallVar('user_id');
$this->applyPendingEditingFilter($object, $user_id);
}
}
else {
$object->addFilter('status_filter', '%1$s.Status = 1');
if ($pending_editing) {
// if category item uses pending editing abilities, then in no cases show pending copies on front
$object->addFilter('original_filter', '%1$s.OrgId = 0 OR %1$s.OrgId IS NULL');
}
}
}
else {
if ($pending_editing) {
$this->applyPendingEditingFilter($object);
}
}
}
/**
* Adds filter, that removes live items if they have pending editing copies
*
* @param kDBList $object
* @param int $user_id
*/
function applyPendingEditingFilter(&$object, $user_id = null)
{
$sql = 'SELECT OrgId
FROM '.$object->TableName.'
WHERE Status = '.STATUS_PENDING_EDITING.' AND OrgId IS NOT NULL';
if (isset($user_id)) {
$owner_field = $this->getOwnerField($object->Prefix);
$sql .= ' AND '.$owner_field.' = '.$user_id;
}
$pending_ids = $this->Conn->GetCol($sql);
if ($pending_ids) {
$object->addFilter('no_original_filter', '%1$s.'.$object->IDField.' NOT IN ('.implode(',', $pending_ids).')');
}
}
/**
* Adds calculates fields for item statuses
*
* @param kCatDBItem $object
* @param kEvent $event
*/
function prepareObject(&$object, &$event)
{
$this->prepareItemStatuses($event);
$object->addCalculatedField('CachedNavbar', 'l'.$this->Application->GetVar('m_lang').'_CachedNavbar');
if ($event->Special == 'export' || $event->Special == 'import')
{
$export_helper =& $this->Application->recallObject('CatItemExportHelper');
$export_helper->prepareExportColumns($event);
}
}
/**
* Creates calculated fields for all item statuses based on config settings
*
* @param kEvent $event
*/
function prepareItemStatuses(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$property_map = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
if (!$property_map) {
return ;
}
// new items
$object->addCalculatedField('IsNew', ' IF(%1$s.NewItem = 2,
IF(%1$s.CreatedOn >= (UNIX_TIMESTAMP() - '.
$this->Application->ConfigValue($property_map['NewDays']).
'*3600*24), 1, 0),
%1$s.NewItem
)');
// hot items (cache updated every hour)
$sql = 'SELECT Data
FROM '.TABLE_PREFIX.'Cache
WHERE (VarName = "'.$property_map['HotLimit'].'") AND (Cached >'.(adodb_mktime() - 3600).')';
$hot_limit = $this->Conn->GetOne($sql);
if ($hot_limit === false) {
$hot_limit = $this->CalculateHotLimit($event);
}
$object->addCalculatedField('IsHot', ' IF(%1$s.HotItem = 2,
IF(%1$s.'.$property_map['ClickField'].' >= '.$hot_limit.', 1, 0),
%1$s.HotItem
)');
// popular items
$object->addCalculatedField('IsPop', ' IF(%1$s.PopItem = 2,
IF(%1$s.CachedVotesQty >= '.
$this->Application->ConfigValue($property_map['MinPopVotes']).
' AND %1$s.CachedRating >= '.
$this->Application->ConfigValue($property_map['MinPopRating']).
', 1, 0),
%1$s.PopItem)');
}
function CalculateHotLimit(&$event)
{
$property_map = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
if (!$property_map) {
return;
}
$click_field = $property_map['ClickField'];
$last_hot = $this->Application->ConfigValue($property_map['MaxHotNumber']) - 1;
$sql = 'SELECT '.$click_field.' FROM '.$this->Application->getUnitOption($event->Prefix, 'TableName').'
ORDER BY '.$click_field.' DESC
LIMIT '.$last_hot.', 1';
$res = $this->Conn->GetCol($sql);
$hot_limit = (double)array_shift($res);
$this->Conn->Query('REPLACE INTO '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("'.$property_map['HotLimit'].'", "'.$hot_limit.'", '.adodb_mktime().')');
return $hot_limit;
return 0;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnBeforeItemUpdate(&$event)
{
$property_map = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
if (!$property_map) {
return;
}
$click_field = $property_map['ClickField'];
$object =& $event->getObject();
if( $this->Application->IsAdmin() && ($this->Application->GetVar($click_field.'_original') !== false) &&
floor($this->Application->GetVar($click_field.'_original')) != $object->GetDBField($click_field) )
{
$sql = 'SELECT MAX('.$click_field.') FROM '.$this->Application->getUnitOption($event->Prefix, 'TableName').'
WHERE FLOOR('.$click_field.') = '.$object->GetDBField($click_field);
$hits = ( $res = $this->Conn->GetOne($sql) ) ? $res + 0.000001 : $object->GetDBField($click_field);
$object->SetDBField($click_field, $hits);
}
}
/**
* Load price from temp table if product mode is temp table
*
* @param kEvent $event
*/
function OnAfterItemLoad(&$event)
{
$special = substr($event->Special, -6);
$object =& $event->getObject();
/* @var $object kCatDBItem */
if ($special == 'import' || $special == 'export') {
$image_data = $object->getPrimaryImageData();
if ($image_data) {
$thumbnail_image = $image_data[$image_data['LocalThumb'] ? 'ThumbPath' : 'ThumbUrl'];
if ($image_data['SameImages']) {
$full_image = '';
}
else {
$full_image = $image_data[$image_data['LocalImage'] ? 'LocalPath' : 'Url'];
}
$object->SetDBField('ThumbnailImage', $thumbnail_image);
$object->SetDBField('FullImage', $full_image);
$object->SetDBField('ImageAlt', $image_data['AltName']);
}
}
// substituiting pending status value for pending editing
if ($object->HasField('OrgId') && $object->GetDBField('OrgId') > 0 && $object->GetDBField('Status') == -2) {
$options = $object->Fields['Status']['options'];
foreach ($options as $key => $val) {
if ($key == 2) $key = -2;
$new_options[$key] = $val;
}
$object->Fields['Status']['options'] = $new_options;
}
// linking existing images for item with virtual fields
$image_helper =& $this->Application->recallObject('ImageHelper');
/* @var $image_helper ImageHelper */
$image_helper->LoadItemImages($object);
// linking existing files for item with virtual fields
$file_helper =& $this->Application->recallObject('FileHelper');
/* @var $file_helper FileHelper */
$file_helper->LoadItemFiles($object);
// set item's additional categories to virtual field (used in editing)
$item_categories = $this->getItemCategories($object->GetDBField('ResourceId'));
$object->SetDBField('MoreCategories', $item_categories ? '|'.implode('|', $item_categories).'|' : '');
}
function OnAfterItemUpdate(&$event)
{
$this->CalculateHotLimit($event);
if ( substr($event->Special, -6) == 'import') {
$this->setCustomExportColumns($event);
}
if (!$this->Application->IsAdmin()) {
$image_helper =& $this->Application->recallObject('ImageHelper');
/* @var $image_helper ImageHelper */
$object =& $event->getObject();
/* @var $object kDBItem */
// process image upload in virtual fields
$image_helper->SaveItemImages($object);
$file_helper =& $this->Application->recallObject('FileHelper');
/* @var $file_helper FileHelper */
// process file upload in virtual fields
$file_helper->SaveItemFiles($object);
if ($event->Special != '-item') {
// don't touch categories during cloning
$this->processAdditionalCategories($object, 'update');
}
}
}
/**
* sets values for import process
*
* @param kEvent $event
*/
function OnAfterItemCreate(&$event)
{
if ( substr($event->Special, -6) == 'import') {
$this->setCustomExportColumns($event);
}
if (!$this->Application->IsAdmin()) {
$image_helper =& $this->Application->recallObject('ImageHelper');
/* @var $image_helper ImageHelper */
$object =& $event->getObject();
/* @var $object kDBItem */
// process image upload in virtual fields
$image_helper->SaveItemImages($object);
$file_helper =& $this->Application->recallObject('FileHelper');
/* @var $file_helper FileHelper */
// process file upload in virtual fields
$file_helper->SaveItemFiles($object);
if ($event->Special != '-item') {
// don't touch categories during cloning
$this->processAdditionalCategories($object, 'create');
}
}
}
/**
* Make record to search log
*
* @param string $keywords
* @param int $search_type 0 - simple search, 1 - advanced search
*/
function saveToSearchLog($keywords, $search_type = 0)
{
$sql = 'UPDATE '.TABLE_PREFIX.'SearchLog
SET Indices = Indices + 1
WHERE Keyword = '.$this->Conn->qstr($keywords).' AND SearchType = '.$search_type; // 0 - simple search, 1 - advanced search
$this->Conn->Query($sql);
if ($this->Conn->getAffectedRows() == 0) {
$fields_hash = Array('Keyword' => $keywords, 'Indices' => 1, 'SearchType' => $search_type);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'SearchLog');
}
}
/**
* Makes simple search for products
* based on keywords string
*
* @param kEvent $event
* @todo Change all hardcoded Products table & In-Commerce module usage to dynamic usage from item config !!!
*/
function OnSimpleSearch(&$event)
{
if($this->Application->GetVar('INPORTAL_ON') && !($this->Application->GetVar('Action') == 'm_simple_search'))
{
return;
}
$event->redirect = false;
$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$keywords = unhtmlentities( trim($this->Application->GetVar('keywords')) );
$query_object =& $this->Application->recallObject('HTTPQuery');
$sql = 'SHOW TABLES LIKE "'.$search_table.'"';
if(!isset($query_object->Get['keywords']) &&
!isset($query_object->Post['keywords']) &&
$this->Conn->Query($sql))
{
return; // used when navigating by pages or changing sorting in search results
}
if(!$keywords || strlen($keywords) < $this->Application->ConfigValue('Search_MinKeyword_Length'))
{
$this->Conn->Query('DROP TABLE IF EXISTS '.$search_table);
$this->Application->SetVar('keywords_too_short', 1);
return; // if no or too short keyword entered, doing nothing
}
$this->Application->StoreVar('keywords', $keywords);
if (!$this->Application->GetVar('INPORTAL_ON')) {
// don't save search log, because in-portal already saved it
$this->saveToSearchLog($keywords, 0); // 0 - simple search, 1 - advanced search
}
$keywords = strtr($keywords, Array('%' => '\\%', '_' => '\\_'));
$event->setPseudoClass('_List');
$object =& $event->getObject();
$this->Application->SetVar($event->getPrefixSpecial().'_Page', 1);
$lang = $this->Application->GetVar('m_lang');
$items_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$module_name = $this->Application->findModule('Var', $event->Prefix, 'Name');
$sql = ' SELECT * FROM '.$this->Application->getUnitOption('confs', 'TableName').'
WHERE ModuleName="'.$module_name.'"
AND SimpleSearch=1';
$search_config = $this->Conn->Query($sql, 'FieldName');
$field_list = array_keys($search_config);
$join_clauses = Array();
// field processing
$weight_sum = 0;
$alias_counter = 0;
$custom_fields = $this->Application->getUnitOption($event->Prefix, 'CustomFields');
if ($custom_fields) {
$custom_table = $this->Application->getUnitOption($event->Prefix.'-cdata', 'TableName');
$join_clauses[] = ' LEFT JOIN '.$custom_table.' custom_data ON '.$items_table.'.ResourceId = custom_data.ResourceId';
}
// what field in search config becomes what field in sql (key - new field, value - old field (from searchconfig table))
$search_config_map = Array();
foreach ($field_list as $key => $field) {
$options = $object->getFieldOptions($field);
$local_table = TABLE_PREFIX.$search_config[$field]['TableName'];
$weight_sum += $search_config[$field]['Priority']; // counting weight sum; used when making relevance clause
// processing multilingual fields
if (getArrayValue($options, 'formatter') == 'kMultiLanguage') {
$field_list[$key.'_primary'] = 'l'.$this->Application->GetDefaultLanguageId().'_'.$field;
$field_list[$key] = 'l'.$lang.'_'.$field;
if(!isset($search_config[$field]['ForeignField']))
{
$field_list[$key.'_primary'] = $local_table.'.'.$field_list[$key.'_primary'];
$search_config_map[ $field_list[$key.'_primary'] ] = $field;
}
}
// processing fields from other tables
if($foreign_field = $search_config[$field]['ForeignField'])
{
$exploded = explode(':', $foreign_field, 2);
if($exploded[0] == 'CALC')
{
unset($field_list[$key]);
continue; // ignoring having type clauses in simple search
/*$user_groups = $this->Application->RecallVar('UserGroups');
$having_list[$key] = str_replace('{PREFIX}', TABLE_PREFIX, $exploded[1]);
$join_clause = str_replace('{PREFIX}', TABLE_PREFIX, $search_config[$field]['JoinClause']);
$join_clause = str_replace('{USER_GROUPS}', $user_groups, $join_clause);
$join_clause = ' LEFT JOIN '.$join_clause;
$join_clauses[] = $join_clause;*/
}
else
{
$multi_lingual = false;
if ($exploded[0] == 'MULTI')
{
$multi_lingual = true;
$foreign_field = $exploded[1];
}
$exploded = explode('.', $foreign_field); // format: table.field_name
$foreign_table = TABLE_PREFIX.$exploded[0];
$alias_counter++;
$alias = 't'.$alias_counter;
if ($multi_lingual) {
$field_list[$key] = $alias.'.'.'l'.$lang.'_'.$exploded[1];
$field_list[$key.'_primary'] = 'l'.$this->Application->GetDefaultLanguageId().'_'.$field;
$search_config_map[ $field_list[$key] ] = $field;
$search_config_map[ $field_list[$key.'_primary'] ] = $field;
}
else {
$field_list[$key] = $alias.'.'.$exploded[1];
$search_config_map[ $field_list[$key] ] = $field;
}
$join_clause = str_replace('{ForeignTable}', $alias, $search_config[$field]['JoinClause']);
$join_clause = str_replace('{LocalTable}', $items_table, $join_clause);
$join_clauses[] = ' LEFT JOIN '.$foreign_table.' '.$alias.'
ON '.$join_clause;
}
}
else {
// processing fields from local table
if ($search_config[$field]['CustomFieldId']) {
$local_table = 'custom_data';
// search by custom field value on current language
$custom_field_id = array_search($field_list[$key], $custom_fields);
$field_list[$key] = 'l'.$lang.'_cust_'.$custom_field_id;
// search by custom field value on primary language
$field_list[$key.'_primary'] = 'l'.$this->Application->GetDefaultLanguageId().'_cust_'.$custom_field_id;
$search_config_map[ $field_list[$key.'_primary'] ] = $field;
}
$field_list[$key] = $local_table.'.'.$field_list[$key];
$search_config_map[ $field_list[$key] ] = $field;
}
}
// keyword string processing
$search_helper =& $this->Application->recallObject('SearchHelper');
$where_clause = $search_helper->buildWhereClause($keywords, $field_list);
$search_scope = $this->Application->GetVar('search_scope');
if ($search_scope == 'category') {
$category_id = $this->Application->GetVar('m_cat_id');
$category_filter = $this->getCategoryLimitClause($category_id);
if ($category_filter !== false) {
$join_clauses[] = ' LEFT JOIN '.TABLE_PREFIX.'CategoryItems ON '.TABLE_PREFIX.'CategoryItems.ItemResourceId = '.$items_table.'.ResourceId';
$join_clauses[] = ' LEFT JOIN '.TABLE_PREFIX.'Category ON '.TABLE_PREFIX.'Category.CategoryId = '.TABLE_PREFIX.'CategoryItems.CategoryId';
$where_clause = '('.$this->getCategoryLimitClause($category_id).') AND '.$where_clause;
}
}
$where_clause = $where_clause.' AND '.$items_table.'.Status=1';
if($this->Application->GetVar('Action') == 'm_simple_subsearch') // subsearch, In-portal
{
if( $event->getEventParam('ResultIds') )
{
$where_clause .= ' AND '.$items_table.'.ResourceId IN ('.implode(',', $event->specificParams['ResultIds']).')';
}
}
if( $event->MasterEvent && $event->MasterEvent->Name == 'OnListBuild' ) // subsearch, k4
{
if( $event->MasterEvent->getEventParam('ResultIds') )
{
$where_clause .= ' AND '.$items_table.'.ResourceId IN ('.implode(',', $event->MasterEvent->getEventParam('ResultIds')).')';
}
}
// making relevance clause
$positive_words = $search_helper->getPositiveKeywords($keywords);
$this->Application->StoreVar('highlight_keywords', serialize($positive_words));
$revelance_parts = Array();
reset($search_config);
foreach ($field_list as $field) {
$config_elem = $search_config[ $search_config_map[$field] ];
$weight = $config_elem['Priority'];
$revelance_parts[] = 'IF('.$field.' LIKE "%'.implode(' ', $positive_words).'%", '.$weight_sum.', 0)';
foreach ($positive_words as $keyword) {
$revelance_parts[] = 'IF('.$field.' LIKE "%'.$keyword.'%", '.$weight.', 0)';
}
}
$conf_postfix = $this->Application->getUnitOption($event->Prefix, 'SearchConfigPostfix');
$rel_keywords = $this->Application->ConfigValue('SearchRel_Keyword_'.$conf_postfix) / 100;
$rel_pop = $this->Application->ConfigValue('SearchRel_Pop_'.$conf_postfix) / 100;
$rel_rating = $this->Application->ConfigValue('SearchRel_Rating_'.$conf_postfix) / 100;
$relevance_clause = '('.implode(' + ', $revelance_parts).') / '.$weight_sum.' * '.$rel_keywords;
if ($rel_pop && isset($object->Fields['Hits'])) {
$relevance_clause .= ' + (Hits + 1) / (MAX(Hits) + 1) * '.$rel_pop;
}
if ($rel_rating && isset($object->Fields['CachedRating'])) {
$relevance_clause .= ' + (CachedRating + 1) / (MAX(CachedRating) + 1) * '.$rel_rating;
}
// building final search query
if (!$this->Application->GetVar('do_not_drop_search_table') && !$this->Application->GetVar('INPORTAL_ON')) {
$this->Conn->Query('DROP TABLE IF EXISTS '.$search_table); // erase old search table if clean k4 event
$this->Application->SetVar('do_not_drop_search_table', true);
}
$search_table_exists = $this->Conn->Query('SHOW TABLES LIKE "'.$search_table.'"');
if ($search_table_exists) {
$select_intro = 'INSERT INTO '.$search_table.' (Relevance, ItemId, ResourceId, ItemType, EdPick) ';
}
else {
$select_intro = 'CREATE TABLE '.$search_table.' AS ';
}
$edpick_clause = $this->Application->getUnitOption($event->Prefix.'.EditorsPick', 'Fields') ? $items_table.'.EditorsPick' : '0';
$sql = $select_intro.' SELECT '.$relevance_clause.' AS Relevance,
'.$items_table.'.'.$this->Application->getUnitOption($event->Prefix, 'IDField').' AS ItemId,
'.$items_table.'.ResourceId,
'.$this->Application->getUnitOption($event->Prefix, 'ItemType').' AS ItemType,
'.$edpick_clause.' AS EdPick
FROM '.$object->TableName.'
'.implode(' ', $join_clauses).'
WHERE '.$where_clause.'
GROUP BY '.$items_table.'.'.$this->Application->getUnitOption($event->Prefix, 'IDField');
$res = $this->Conn->Query($sql);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSubSearch(&$event)
{
$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$sql = 'SHOW TABLES LIKE "'.$search_table.'"';
if($this->Conn->Query($sql))
{
$sql = 'SELECT DISTINCT ResourceId FROM '.$search_table;
$ids = $this->Conn->GetCol($sql);
}
$event->setEventParam('ResultIds', $ids);
$event->CallSubEvent('OnSimpleSearch');
}
/**
* Enter description here...
*
* @param kEvent $event
* @todo Change all hardcoded Products table & In-Commerce module usage to dynamic usage from item config !!!
*/
function OnAdvancedSearch(&$event)
{
$query_object =& $this->Application->recallObject('HTTPQuery');
if(!isset($query_object->Post['andor']))
{
return; // used when navigating by pages or changing sorting in search results
}
$this->Application->RemoveVar('keywords');
$this->Application->RemoveVar('Search_Keywords');
$module_name = $this->Application->findModule('Var', $event->Prefix, 'Name');
$sql = 'SELECT *
FROM '.$this->Application->getUnitOption('confs', 'TableName').'
WHERE (ModuleName = '.$this->Conn->qstr($module_name).') AND (AdvancedSearch = 1)';
$search_config = $this->Conn->Query($sql);
$lang = $this->Application->GetVar('m_lang');
$object =& $event->getObject();
$object->SetPage(1);
$items_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$search_keywords = $this->Application->GetVar('value'); // will not be changed
$keywords = $this->Application->GetVar('value'); // will be changed down there
$verbs = $this->Application->GetVar('verb');
$glues = $this->Application->GetVar('andor');
$and_conditions = Array();
$or_conditions = Array();
$and_having_conditions = Array();
$or_having_conditions = Array();
$join_clauses = Array();
$highlight_keywords = Array();
$relevance_parts = Array();
$alias_counter = 0;
$custom_fields = $this->Application->getUnitOption($event->Prefix, 'CustomFields');
if ($custom_fields) {
$custom_table = $this->Application->getUnitOption($event->Prefix.'-cdata', 'TableName');
$join_clauses[] = ' LEFT JOIN '.$custom_table.' custom_data ON '.$items_table.'.ResourceId = custom_data.ResourceId';
}
$search_log = '';
$weight_sum = 0;
// processing fields and preparing conditions
foreach ($search_config as $record) {
$field = $record['FieldName'];
$join_clause = '';
$condition_mode = 'WHERE';
// field processing
$options = $object->getFieldOptions($field);
$local_table = TABLE_PREFIX.$record['TableName'];
$weight_sum += $record['Priority']; // counting weight sum; used when making relevance clause
// processing multilingual fields
if (getArrayValue($options, 'formatter') == 'kMultiLanguage') {
$field_name = 'l'.$lang.'_'.$field;
}
else {
$field_name = $field;
}
// processing fields from other tables
if ($foreign_field = $record['ForeignField']) {
$exploded = explode(':', $foreign_field, 2);
if($exploded[0] == 'CALC')
{
$user_groups = $this->Application->RecallVar('UserGroups');
$field_name = str_replace('{PREFIX}', TABLE_PREFIX, $exploded[1]);
$join_clause = str_replace('{PREFIX}', TABLE_PREFIX, $record['JoinClause']);
$join_clause = str_replace('{USER_GROUPS}', $user_groups, $join_clause);
$join_clause = ' LEFT JOIN '.$join_clause;
$condition_mode = 'HAVING';
}
else {
$exploded = explode('.', $foreign_field);
$foreign_table = TABLE_PREFIX.$exploded[0];
if($record['CustomFieldId']) {
$exploded[1] = 'l'.$lang.'_'.$exploded[1];
}
$alias_counter++;
$alias = 't'.$alias_counter;
$field_name = $alias.'.'.$exploded[1];
$join_clause = str_replace('{ForeignTable}', $alias, $record['JoinClause']);
$join_clause = str_replace('{LocalTable}', $items_table, $join_clause);
if($record['CustomFieldId'])
{
$join_clause .= ' AND '.$alias.'.CustomFieldId='.$record['CustomFieldId'];
}
$join_clause = ' LEFT JOIN '.$foreign_table.' '.$alias.'
ON '.$join_clause;
}
}
else
{
// processing fields from local table
if ($record['CustomFieldId']) {
$local_table = 'custom_data';
$field_name = 'l'.$lang.'_cust_'.array_search($field_name, $custom_fields);
}
$field_name = $local_table.'.'.$field_name;
}
$condition = $this->getAdvancedSearchCondition($field_name, $record, $keywords, $verbs, $highlight_keywords);
if ($record['CustomFieldId'] && strlen($condition)) {
// search in primary value of custom field + value in current language
$field_name = $local_table.'.'.'l'.$this->Application->GetDefaultLanguageId().'_cust_'.array_search($field, $custom_fields);
$primary_condition = $this->getAdvancedSearchCondition($field_name, $record, $keywords, $verbs, $highlight_keywords);
$condition = '('.$condition.' OR '.$primary_condition.')';
}
if ($condition) {
if ($join_clause) {
$join_clauses[] = $join_clause;
}
$relevance_parts[] = 'IF('.$condition.', '.$record['Priority'].', 0)';
if ($glues[$field] == 1) { // and
if ($condition_mode == 'WHERE') {
$and_conditions[] = $condition;
}
else {
$and_having_conditions[] = $condition;
}
}
else { // or
if ($condition_mode == 'WHERE') {
$or_conditions[] = $condition;
}
else {
$or_having_conditions[] = $condition;
}
}
// create search log record
$search_log_data = Array('search_config' => $record, 'verb' => getArrayValue($verbs, $field), 'value' => ($record['FieldType'] == 'range') ? $search_keywords[$field.'_from'].'|'.$search_keywords[$field.'_to'] : $search_keywords[$field]);
$search_log[] = $this->Application->Phrase('la_Field').' "'.$this->getHuman('Field', $search_log_data).'" '.$this->getHuman('Verb', $search_log_data).' '.$this->Application->Phrase('la_Value').' '.$this->getHuman('Value', $search_log_data).' '.$this->Application->Phrase($glues[$field] == 1 ? 'lu_And' : 'lu_Or');
}
}
if ($search_log) {
$search_log = implode('<br />', $search_log);
$search_log = preg_replace('/(.*) '.preg_quote($this->Application->Phrase('lu_and'), '/').'|'.preg_quote($this->Application->Phrase('lu_or'), '/').'$/is', '\\1', $search_log);
$this->saveToSearchLog($search_log, 1); // advanced search
}
$this->Application->StoreVar('highlight_keywords', serialize($highlight_keywords));
// making relevance clause
if($relevance_parts)
{
$conf_postfix = $this->Application->getUnitOption($event->Prefix, 'SearchConfigPostfix');
$rel_keywords = $this->Application->ConfigValue('SearchRel_Keyword_'.$conf_postfix) / 100;
$rel_pop = $this->Application->ConfigValue('SearchRel_Pop_'.$conf_postfix) / 100;
$rel_rating = $this->Application->ConfigValue('SearchRel_Rating_'.$conf_postfix) / 100;
$relevance_clause = '('.implode(' + ', $relevance_parts).') / '.$weight_sum.' * '.$rel_keywords;
$relevance_clause .= ' + (Hits + 1) / (MAX(Hits) + 1) * '.$rel_pop;
$relevance_clause .= ' + (CachedRating + 1) / (MAX(CachedRating) + 1) * '.$rel_rating;
}
else
{
$relevance_clause = '0';
}
// building having clause
if($or_having_conditions)
{
$and_having_conditions[] = '('.implode(' OR ', $or_having_conditions).')';
}
$having_clause = implode(' AND ', $and_having_conditions);
$having_clause = $having_clause ? ' HAVING '.$having_clause : '';
// building where clause
if($or_conditions)
{
$and_conditions[] = '('.implode(' OR ', $or_conditions).')';
}
// $and_conditions[] = $items_table.'.Status = 1';
$where_clause = implode(' AND ', $and_conditions);
if(!$where_clause)
{
if($having_clause)
{
$where_clause = '1';
}
else
{
$where_clause = '0';
$this->Application->SetVar('adv_search_error', 1);
}
}
$where_clause .= ' AND '.$items_table.'.Status = 1';
// building final search query
$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$this->Conn->Query('DROP TABLE IF EXISTS '.$search_table);
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
$pick_field = isset($fields['EditorsPick']) ? $items_table.'.EditorsPick' : '0';
$sql = ' CREATE TABLE '.$search_table.'
SELECT '.$relevance_clause.' AS Relevance,
'.$items_table.'.'.$id_field.' AS ItemId,
'.$items_table.'.ResourceId AS ResourceId,
11 AS ItemType,
'.$pick_field.' AS EdPick
FROM '.$items_table.'
'.implode(' ', $join_clauses).'
WHERE '.$where_clause.'
GROUP BY '.$items_table.'.'.$id_field.
$having_clause;
$res = $this->Conn->Query($sql);
}
function getAdvancedSearchCondition($field_name, $record, $keywords, $verbs, &$highlight_keywords)
{
$field = $record['FieldName'];
$condition_patterns = Array (
'any' => '%s LIKE %s',
'contains' => '%s LIKE %s',
'notcontains' => '(NOT (%1$s LIKE %2$s) OR %1$s IS NULL)',
'is' => '%s = %s',
'isnot' => '(%1$s != %2$s OR %1$s IS NULL)'
);
$condition = '';
switch ($record['FieldType']) {
case 'select':
$keywords[$field] = unhtmlentities( $keywords[$field] );
if ($keywords[$field]) {
$condition = sprintf($condition_patterns['is'], $field_name, $this->Conn->qstr( $keywords[$field] ));
}
break;
case 'multiselect':
$keywords[$field] = unhtmlentities( $keywords[$field] );
if ($keywords[$field]) {
$condition = Array ();
$values = explode('|', substr($keywords[$field], 1, -1));
foreach ($values as $selected_value) {
$condition[] = sprintf($condition_patterns['contains'], $field_name, $this->Conn->qstr('%|'.$selected_value.'|%'));
}
$condition = '('.implode(' OR ', $condition).')';
}
break;
case 'text':
$keywords[$field] = unhtmlentities( $keywords[$field] );
- if (strlen($keywords[$field]) >= $this->Application->ConfigValue('Search_MinKeyword_Length')) {
+ if (mb_strlen($keywords[$field]) >= $this->Application->ConfigValue('Search_MinKeyword_Length')) {
$highlight_keywords[] = $keywords[$field];
if (in_array($verbs[$field], Array('any', 'contains', 'notcontains'))) {
$keywords[$field] = '%'.strtr($keywords[$field], Array('%' => '\\%', '_' => '\\_')).'%';
}
$condition = sprintf($condition_patterns[$verbs[$field]], $field_name, $this->Conn->qstr( $keywords[$field] ));
}
break;
case 'boolean':
if ($keywords[$field] != -1) {
$property_mappings = $this->Application->getUnitOption($this->Prefix, 'ItemPropertyMappings');
$items_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
switch ($field) {
case 'HotItem':
$hot_limit_var = getArrayValue($property_mappings, 'HotLimit');
if ($hot_limit_var) {
$sql = 'SELECT Data
FROM '.TABLE_PREFIX.'Cache
WHERE VarName = "'.$hot_limit_var.'"';
$hot_limit = (int)$this->Conn->GetOne($sql);
$condition = 'IF('.$items_table.'.HotItem = 2,
IF('.$items_table.'.Hits >= '.
$hot_limit.
', 1, 0), '.$items_table.'.HotItem) = '.$keywords[$field];
}
break;
case 'PopItem':
$votes2pop_var = getArrayValue($property_mappings, 'VotesToPop');
$rating2pop_var = getArrayValue($property_mappings, 'RatingToPop');
if ($votes2pop_var && $rating2pop_var) {
$condition = 'IF('.$items_table.'.PopItem = 2, IF('.$items_table.'.CachedVotesQty >= '.
$this->Application->ConfigValue($votes2pop_var).
' AND '.$items_table.'.CachedRating >= '.
$this->Application->ConfigValue($rating2pop_var).
', 1, 0), '.$items_table.'.PopItem) = '.$keywords[$field];
}
break;
case 'NewItem':
$new_days_var = getArrayValue($property_mappings, 'NewDays');
if ($new_days_var) {
$condition = 'IF('.$items_table.'.NewItem = 2,
IF('.$items_table.'.CreatedOn >= (UNIX_TIMESTAMP() - '.
$this->Application->ConfigValue($new_days_var).
'*3600*24), 1, 0), '.$items_table.'.NewItem) = '.$keywords[$field];
}
break;
case 'EditorsPick':
$condition = $items_table.'.EditorsPick = '.$keywords[$field];
break;
}
}
break;
case 'range':
$range_conditions = Array();
if ($keywords[$field.'_from'] && !preg_match("/[^0-9]/i", $keywords[$field.'_from'])) {
$range_conditions[] = $field_name.' >= '.$keywords[$field.'_from'];
}
if ($keywords[$field.'_to'] && !preg_match("/[^0-9]/i", $keywords[$field.'_to'])) {
$range_conditions[] = $field_name.' <= '.$keywords[$field.'_to'];
}
if ($range_conditions) {
$condition = implode(' AND ', $range_conditions);
}
break;
case 'date':
if ($keywords[$field]) {
if (in_array($keywords[$field], Array('today', 'yesterday'))) {
$current_time = getdate();
$day_begin = adodb_mktime(0, 0, 0, $current_time['mon'], $current_time['mday'], $current_time['year']);
$time_mapping = Array('today' => $day_begin, 'yesterday' => ($day_begin - 86400));
$min_time = $time_mapping[$keywords[$field]];
}
else {
$time_mapping = Array (
'last_week' => 604800, 'last_month' => 2628000, 'last_3_months' => 7884000,
'last_6_months' => 15768000, 'last_year' => 31536000,
);
$min_time = adodb_mktime() - $time_mapping[$keywords[$field]];
}
$condition = $field_name.' > '.$min_time;
}
break;
}
return $condition;
}
function getHuman($type, $search_data)
{
$type = ucfirst(strtolower($type));
extract($search_data);
switch ($type) {
case 'Field':
return $this->Application->Phrase($search_config['DisplayName']);
break;
case 'Verb':
return $verb ? $this->Application->Phrase('lu_advsearch_'.$verb) : '';
break;
case 'Value':
switch ($search_config['FieldType']) {
case 'date':
$values = Array(0 => 'lu_comm_Any', 'today' => 'lu_comm_Today',
'yesterday' => 'lu_comm_Yesterday', 'last_week' => 'lu_comm_LastWeek',
'last_month' => 'lu_comm_LastMonth', 'last_3_months' => 'lu_comm_Last3Months',
'last_6_months' => 'lu_comm_Last6Months', 'last_year' => 'lu_comm_LastYear');
$ret = $this->Application->Phrase($values[$value]);
break;
case 'range':
$value = explode('|', $value);
return $this->Application->Phrase('lu_comm_From').' "'.$value[0].'" '.$this->Application->Phrase('lu_comm_To').' "'.$value[1].'"';
break;
case 'boolean':
$values = Array(1 => 'lu_comm_Yes', 0 => 'lu_comm_No', -1 => 'lu_comm_Both');
$ret = $this->Application->Phrase($values[$value]);
break;
default:
$ret = $value;
break;
}
return '"'.$ret.'"';
break;
}
}
/**
* Set's correct page for list
* based on data provided with event
*
* @param kEvent $event
* @access private
* @see OnListBuild
*/
function SetPagination(&$event)
{
// get PerPage (forced -> session -> config -> 10)
$per_page = $this->getPerPage($event);
$object =& $event->getObject();
$object->SetPerPage($per_page);
$this->Application->StoreVarDefault($event->getPrefixSpecial().'_Page', 1);
$page = $this->Application->GetVar($event->getPrefixSpecial().'_Page');
if (!$page)
{
$page = $this->Application->GetVar($event->getPrefixSpecial(true).'_Page');
}
if (!$page)
{
if( $this->Application->RewriteURLs() )
{
$page = $this->Application->GetVar($event->Prefix.'_Page');
if (!$page)
{
$page = $this->Application->RecallVar($event->Prefix.'_Page');
}
if($page) $this->Application->StoreVar($event->getPrefixSpecial().'_Page', $page);
}
else
{
$page = $this->Application->RecallVar($event->getPrefixSpecial().'_Page');
}
}
else {
$this->Application->StoreVar($event->getPrefixSpecial().'_Page', $page);
}
if( !$event->getEventParam('skip_counting') )
{
$pages = $object->GetTotalPages();
if($page > $pages)
{
$this->Application->StoreVar($event->getPrefixSpecial().'_Page', 1);
$page = 1;
}
}
/*$cur_per_page = $per_page;
$per_page = $event->getEventParam('per_page');
if ($per_page == 'list_next') {
$cur_page = $page;
$object =& $this->Application->recallObject($event->Prefix);
$object->SetPerPage(1);
$cur_item_index = $object->CurrentIndex;
$page = ($cur_page-1) * $cur_per_page + $cur_item_index + 1;
$object->SetPerPage(1);
}*/
$object->SetPage($page);
}
/* === RELATED TO IMPORT/EXPORT: BEGIN === */
/**
* Shows export dialog
*
* @param kEvent $event
*/
function OnExport(&$event)
{
// use old fasion (in-portal) grid
$selector_name = $this->Application->getUnitOption($event->Prefix, 'CatalogSelectorName');
if ($selector_name) {
$selected_ids = $this->Application->GetVar($selector_name);
}
else {
$selected_ids = $this->StoreSelectedIDs($event);
if (implode(',', $selected_ids) == '') {
// K4 fix when no ids found bad selected ids array is formed
$selected_ids = false;
}
}
$selected_cats_ids = $this->Application->GetVar('export_categories');
$this->Application->StoreVar($event->Prefix.'_export_ids', $selected_ids ? implode(',', $selected_ids) : '' );
$this->Application->StoreVar($event->Prefix.'_export_cats_ids', $selected_cats_ids);
$export_helper =& $this->Application->recallObject('CatItemExportHelper');
$event->redirect = $export_helper->getModuleFolder($event).'/export';
$redirect_params = Array( 'm_opener' => 'd',
$this->Prefix.'.export_event' => 'OnNew',
'pass' => 'all,'.$this->Prefix.'.export');
$event->setRedirectParams($redirect_params);
}
/**
* Performs each export step & displays progress percent
*
* @param kEvent $event
*/
function OnExportProgress(&$event)
{
$export_object =& $this->Application->recallObject('CatItemExportHelper');
/* @var $export_object kCatDBItemExportHelper */
$event = new kEvent($event->getPrefixSpecial().':OnDummy');
$action_method = 'perform'.ucfirst($event->Special);
$field_values = $export_object->$action_method($event);
// finish code is done from JS now
if ($field_values['start_from'] == $field_values['total_records']) {
if ($event->Special == 'import') {
$this->Application->StoreVar('PermCache_UpdateRequired', 1);
$this->Application->Redirect('in-portal/categories/cache_updater', Array('m_opener' => 'r', 'pass' => 'm', 'continue' => 1, 'no_amp' => 1));
}
elseif ($event->Special == 'export') {
$template = $this->Application->getUnitOption($event->Prefix, 'ModuleFolder').'/'.$event->Special.'_finish';
$this->Application->Redirect($template, Array('pass' => 'all'));
}
}
$export_options = $export_object->loadOptions($event);
echo $export_options['start_from'] * 100 / $export_options['total_records'];
$event->status = erSTOP;
}
/**
* Returns specific to each item type columns only
*
* @param kEvent $event
* @return Array
*/
function getCustomExportColumns(&$event)
{
return Array( '__VIRTUAL__ThumbnailImage' => 'ThumbnailImage',
'__VIRTUAL__FullImage' => 'FullImage',
'__VIRTUAL__ImageAlt' => 'ImageAlt');
}
/**
* Sets non standart virtual fields (e.g. to other tables)
*
* @param kEvent $event
*/
function setCustomExportColumns(&$event)
{
$this->restorePrimaryImage($event);
}
/**
* Create/Update primary image record in info found in imported data
*
* @param kEvent $event
*/
function restorePrimaryImage(&$event)
{
$object =& $event->getObject();
$has_image_info = $object->GetDBField('ImageAlt') && ($object->GetDBField('ThumbnailImage') || $object->GetDBField('FullImage'));
if (!$has_image_info) {
return false;
}
$image_data = $object->getPrimaryImageData();
$image =& $this->Application->recallObject('img', null, Array('skip_autoload' => true));
if ($image_data) {
$image->Load($image_data['ImageId']);
}
else {
$image->Clear();
$image->SetDBField('Name', 'main');
$image->SetDBField('DefaultImg', 1);
$image->SetDBField('ResourceId', $object->GetDBField('ResourceId'));
}
$image->SetDBField('AltName', $object->GetDBField('ImageAlt'));
if ($object->GetDBField('ThumbnailImage')) {
$thumbnail_field = $this->isURL( $object->GetDBField('ThumbnailImage') ) ? 'ThumbUrl' : 'ThumbPath';
$image->SetDBField($thumbnail_field, $object->GetDBField('ThumbnailImage') );
$image->SetDBField('LocalThumb', $thumbnail_field == 'ThumbPath' ? 1 : 0);
}
if (!$object->GetDBField('FullImage')) {
$image->SetDBField('SameImages', 1);
}
else {
$image->SetDBField('SameImages', 0);
$full_field = $this->isURL( $object->GetDBField('FullImage') ) ? 'Url' : 'LocalPath';
$image->SetDBField($full_field, $object->GetDBField('FullImage') );
$image->SetDBField('LocalImage', $full_field == 'LocalPath' ? 1 : 0);
}
if ($image->isLoaded()) {
$image->Update();
}
else {
$image->Create();
}
}
function isURL($path)
{
return preg_match('#(http|https)://(.*)#', $path);
}
/**
* Prepares item for import/export operations
*
* @param kEvent $event
*/
function OnNew(&$event)
{
parent::OnNew($event);
if ($event->Special == 'import' || $event->Special == 'export') {
$export_helper =& $this->Application->recallObject('CatItemExportHelper');
$export_helper->setRequiredFields($event);
$this->Application->StoreVar('ImportCategory', 0);
}
}
/**
* Process items selected in item_selector
*
* @param kEvent $event
*/
function OnProcessSelected(&$event)
{
$selected_ids = $this->Application->GetVar('selected_ids');
$dst_field = $this->Application->RecallVar('dst_field');
if ($dst_field == 'ItemCategory') {
// Item Edit -> Categories Tab -> New Categories
$object =& $event->getObject();
$category_ids = explode(',', $selected_ids['c']);
foreach ($category_ids as $category_id) {
$object->assignToCategory($category_id);
}
}
if ($dst_field == 'ImportCategory') {
// Tools -> Import -> Item Import -> Select Import Category
$this->Application->StoreVar('ImportCategory', $selected_ids['c']);
// $this->Application->StoreVar($event->getPrefixSpecial().'_ForceNotValid', 1); // not to loose import/export values on form refresh
$this->Application->SetVar($event->getPrefixSpecial().'_id', 0);
$this->Application->SetVar($event->getPrefixSpecial().'_event', 'OnExportBegin');
$passed = $this->Application->GetVar('passed');
$this->Application->SetVar('passed', $passed.','.$event->getPrefixSpecial());
$event->setEventParam('pass_events', true);
}
$this->finalizePopup($event);
}
/**
* Saves Import/Export settings to session
*
* @param kEvent $event
*/
function OnSaveSettings(&$event)
{
$event->redirect = false;
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if ($items_info) {
list($id, $field_values) = each($items_info);
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->SetFieldsFromHash($field_values);
$field_values['ImportFilename'] = $object->GetDBField('ImportFilename'); //if upload formatter has renamed the file during moving !!!
$field_values['ImportSource'] = 2;
$field_values['ImportLocalFilename'] = $object->GetDBField('ImportFilename');
$items_info[$id] = $field_values;
$this->Application->StoreVar($event->getPrefixSpecial().'_ItemsInfo', serialize($items_info));
}
}
function OnCancelAction(&$event)
{
$event->redirect_params = Array('pass' => 'all,'.$event->GetPrefixSpecial());
$event->redirect = $this->Application->GetVar('cancel_template');
}
/* === RELATED TO IMPORT/EXPORT: END === */
/**
* Stores item's owner login into separate field together with id
*
* @param kEvent $event
* @param string $id_field
* @param string $cached_field
*/
function cacheItemOwner(&$event, $id_field, $cached_field)
{
$object =& $event->getObject();
$user_id = $object->GetDBField($id_field);
$options = $object->GetFieldOptions($id_field);
if (isset($options['options'][$user_id])) {
$object->SetDBField($cached_field, $options['options'][$user_id]);
}
else {
$id_field = $this->Application->getUnitOption('u', 'IDField');
$table_name = $this->Application->getUnitOption('u', 'TableName');
$sql = 'SELECT Login
FROM '.$table_name.'
WHERE '.$id_field.' = '.$user_id;
$object->SetDBField($cached_field, $this->Conn->GetOne($sql));
}
}
/**
* Saves item beeing edited into temp table
*
* @param kEvent $event
*/
function OnPreSave(&$event)
{
parent::OnPreSave($event);
$use_pending_editing = $this->Application->getUnitOption($event->Prefix, 'UsePendingEditing');
if ($event->status == erSUCCESS && $use_pending_editing) {
// decision: clone or not clone
$object =& $event->getObject();
if ($object->GetID() == 0 || $object->GetDBField('OrgId') > 0) {
// new items or cloned items shouldn't be cloned again
return true;
}
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
$owner_field = $this->getOwnerField($event->Prefix);
if ($perm_helper->ModifyCheckPermission($object->GetDBField($owner_field), $object->GetDBField('CategoryId'), $event->Prefix) == 2) {
// 1. clone original item
$temp_handler =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$cloned_ids = $temp_handler->CloneItems($event->Prefix, $event->Special, Array($object->GetID()), null, null, null, true);
$ci_table = $this->Application->GetTempName(TABLE_PREFIX.'CategoryItems');
// 2. delete record from CategoryItems (about cloned item) that was automatically created during call of Create method of kCatDBItem
$sql = 'SELECT ResourceId
FROM '.$object->TableName.'
WHERE '.$object->IDField.' = '.$cloned_ids[0];
$clone_resource_id = $this->Conn->GetOne($sql);
$sql = 'DELETE FROM '.$ci_table.'
WHERE ItemResourceId = '.$clone_resource_id.' AND PrimaryCat = 1';
$this->Conn->Query($sql);
// 3. copy main item categoryitems to cloned item
$sql = ' INSERT INTO '.$ci_table.' (CategoryId, ItemResourceId, PrimaryCat, ItemPrefix, Filename)
SELECT CategoryId, '.$clone_resource_id.' AS ItemResourceId, PrimaryCat, ItemPrefix, Filename
FROM '.$ci_table.'
WHERE ItemResourceId = '.$object->GetDBField('ResourceId');
$this->Conn->Query($sql);
// 4. put cloned id to OrgId field of item being cloned
$sql = 'UPDATE '.$object->TableName.'
SET OrgId = '.$object->GetID().'
WHERE '.$object->IDField.' = '.$cloned_ids[0];
$this->Conn->Query($sql);
// 5. substitute id of item being cloned with clone id
$this->Application->SetVar($event->getPrefixSpecial().'_id', $cloned_ids[0]);
$selected_ids = $this->getSelectedIDs($event, true);
$selected_ids[ array_search($object->GetID(), $selected_ids) ] = $cloned_ids[0];
$this->StoreSelectedIDs($event, $selected_ids);
// 6. delete original item from temp table
$temp_handler->DeleteItems($event->Prefix, $event->Special, Array($object->GetID()));
}
}
}
/**
* Sets default expiration based on module setting
*
* @param kEvent $event
*/
function OnPreCreate(&$event)
{
parent::OnPreCreate($event);
if ($event->status == erSUCCESS) {
$object =& $event->getObject();
$owner_field = $this->getOwnerField($event->Prefix);
$object->SetDBField($owner_field, $this->Application->RecallVar('user_id'));
}
}
/**
* Occures before original item of item in pending editing got deleted (for hooking only)
*
* @param kEvent $event
*/
function OnBeforeDeleteOriginal(&$event)
{
}
/**
* Occures before an item is cloneded
* Id of ORIGINAL item is passed as event' 'id' param
* Do not call object' Update method in this event, just set needed fields!
*
* @param kEvent $event
*/
function OnBeforeClone(&$event)
{
if ($this->Application->GetVar('ResetCatBeforeClone')) {
$object =& $event->getObject();
$object->SetDBField('CategoryId', null);
}
}
/**
* Set status for new category item based on user permission in category
*
* @param kEvent $event
*/
function OnBeforeItemCreate(&$event)
{
if ($this->Application->IsAdmin()) {
return true;
}
$use_pending_editing = $this->Application->getUnitOption($event->Prefix, 'UsePendingEditing');
if ($use_pending_editing) {
$object =& $event->getObject();
/* @var $object kDBItem */
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
$primary_category = $object->GetDBField('CategoryId') > 0 ? $object->GetDBField('CategoryId') : $this->Application->GetVar('m_cat_id');
$item_status = $perm_helper->AddCheckPermission($primary_category, $event->Prefix);
if ($item_status == STATUS_DISABLED) {
$event->status = erFAIL;
return false;
}
else {
$object->SetDBField('Status', $item_status);
}
}
}
/**
* Creates category item & redirects to confirmation template (front-end only)
*
* @param kEvent $event
*/
function OnCreate(&$event)
{
parent::OnCreate($event);
$this->SetFrontRedirectTemplate($event, 'suggest');
}
/**
* Returns item's categories (allows to exclude primary category)
*
* @param int $resource_id
* @param bool $with_primary
* @return Array
*/
function getItemCategories($resource_id, $with_primary = false)
{
$sql = 'SELECT CategoryId
FROM '.TABLE_PREFIX.'CategoryItems
WHERE (ItemResourceId = '.$resource_id.')';
if (!$with_primary) {
$sql .= ' AND (PrimaryCat = 0)';
}
return $this->Conn->GetCol($sql);
}
/**
* Adds new and removes old additional categories from category item
*
* @param kCatDBItem $object
*/
function processAdditionalCategories(&$object, $mode)
{
$process_categories = $object->GetDBField('MoreCategories');
if ($process_categories === '') {
// field was not in submit & have default value (when no categories submitted, then value is null)
return ;
}
if ($mode == 'create') {
// prevents first additional category to become primary
$object->assignPrimaryCategory();
}
$process_categories = $process_categories ? explode('|', substr($process_categories, 1, -1)) : Array ();
$existing_categories = $this->getItemCategories($object->GetDBField('ResourceId'));
$add_categories = array_diff($process_categories, $existing_categories);
foreach ($add_categories as $category_id) {
$object->assignToCategory($category_id);
}
$remove_categories = array_diff($existing_categories, $process_categories);
foreach ($remove_categories as $category_id) {
$object->removeFromCategory($category_id);
}
}
/**
* Creates category item & redirects to confirmation template (front-end only)
*
* @param kEvent $event
*/
function OnUpdate(&$event)
{
$use_pending = $this->Application->getUnitOption($event->Prefix, 'UsePendingEditing');
if ($this->Application->IsAdmin() || !$use_pending) {
parent::OnUpdate($event);
$this->SetFrontRedirectTemplate($event, 'modify');
return ;
}
$object =& $event->getObject(Array('skip_autoload' => true));
/* @var $object kCatDBItem */
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ($items_info) {
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
$temp_handler =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
/* @var $temp_handler kTempTablesHandler */
$owner_field = $this->getOwnerField($event->Prefix);
$file_helper =& $this->Application->recallObject('FileHelper');
/* @var $file_helper FileHelper */
foreach ($items_info as $id => $field_values) {
$object->Load($id);
$edit_perm = $perm_helper->ModifyCheckPermission($object->GetDBField($owner_field), $object->GetDBField('CategoryId'), $event->Prefix);
if ($use_pending && !$object->GetDBField('OrgId') && ($edit_perm == STATUS_PENDING)) {
// pending editing enabled + not pending copy -> get/create pending copy & save changes to it
$original_id = $object->GetID();
$original_resource_id = $object->GetDBField('ResourceId');
$file_helper->PreserveItemFiles($field_values);
$object->Load($original_id, 'OrgId');
if (!$object->isLoaded()) {
// 1. user has no pending copy of live item -> clone live item
$cloned_ids = $temp_handler->CloneItems($event->Prefix, $event->Special, Array($original_id), null, null, null, true);
$object->Load($cloned_ids[0]);
$object->SetFieldsFromHash($field_values);
// 1a. delete record from CategoryItems (about cloned item) that was automatically created during call of Create method of kCatDBItem
$ci_table = $this->Application->getUnitOption('ci', 'TableName');
$sql = 'DELETE FROM '.$ci_table.'
WHERE ItemResourceId = '.$object->GetDBField('ResourceId').' AND PrimaryCat = 1';
$this->Conn->Query($sql);
// 1b. copy main item categoryitems to cloned item
$sql = 'INSERT INTO '.$ci_table.' (CategoryId, ItemResourceId, PrimaryCat, ItemPrefix, Filename)
SELECT CategoryId, '.$object->GetDBField('ResourceId').' AS ItemResourceId, PrimaryCat, ItemPrefix, Filename
FROM '.$ci_table.'
WHERE ItemResourceId = '.$original_resource_id;
$this->Conn->Query($sql);
// 1c. put cloned id to OrgId field of item being cloned
$object->SetDBField('Status', STATUS_PENDING_EDITING);
$object->SetDBField('OrgId', $original_id);
}
else {
// 2. user has pending copy of live item -> just update field values
$object->SetFieldsFromHash($field_values);
}
// update id in request (used for redirect in mod-rewrite mode)
$this->Application->SetVar($event->getPrefixSpecial().'_id', $object->GetID());
}
else {
// 3. already editing pending copy -> just update field values
$object->SetFieldsFromHash($field_values);
}
if ($object->Update()) {
$event->status = erSUCCESS;
}
else {
$event->status = erFAIL;
$event->redirect = false;
break;
}
}
}
$this->SetFrontRedirectTemplate($event, 'modify');
}
/**
* Sets next template to one required for front-end after adding/modifying item
*
* @param kEvent $event
* @param string $template_key - {suggest,modify}
*/
function SetFrontRedirectTemplate(&$event, $template_key)
{
if ($this->Application->IsAdmin() || $event->status != erSUCCESS) {
return ;
}
// prepare redirect template
$object =& $event->getObject();
$is_active = ($object->GetDBField('Status') == STATUS_ACTIVE);
$next_template = $is_active ? 'confirm_template' : 'pending_confirm_template';
$event->redirect = $this->Application->GetVar($template_key.'_'.$next_template);
$event->SetRedirectParam('opener', 's');
// send email events
$perm_prefix = $this->Application->getUnitOption($event->Prefix, 'PermItemPrefix');
switch ($event->Name) {
case 'OnCreate':
$event_suffix = $is_active ? 'ADD' : 'ADD.PENDING';
$owner_field = $this->getOwnerField($event->Prefix);
$this->Application->EmailEventAdmin($perm_prefix.'.'.$event_suffix); // there are no ADD.PENDING event for admin :(
$this->Application->EmailEventUser($perm_prefix.'.'.$event_suffix, $object->GetDBField($owner_field));
break;
case 'OnUpdate':
$event_suffix = $is_active ? 'MODIFY' : 'MODIFY.PENDING';
$this->Application->EmailEventAdmin($perm_prefix.'.'.$event_suffix); // there are no ADD.PENDING event for admin :(
$this->Application->EmailEventUser($perm_prefix.'.'.$event_suffix, $object->GetDBField('ModifiedById'));
break;
}
}
/**
* Apply same processing to each item beeing selected in grid
*
* @param kEvent $event
* @access private
*/
function iterateItems(&$event)
{
if ($event->Name != 'OnMassApprove' && $event->Name != 'OnMassDecline') {
return parent::iterateItems($event);
}
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$object =& $event->getObject( Array('skip_autoload' => true) );
$ids = $this->StoreSelectedIDs($event);
if ($ids) {
foreach ($ids as $id) {
$object->Load($id);
switch ($event->Name) {
case 'OnMassApprove':
$ret = $object->ApproveChanges();
break;
case 'OnMassDecline':
$ret = $object->DeclineChanges();
break;
}
if (!$ret) {
$event->status = erFAIL;
$event->redirect = false;
break;
}
}
}
$this->clearSelectedIDs($event);
}
/**
* Deletes items & preserves clean env
*
* @param kEvent $event
*/
function OnDelete(&$event)
{
parent::OnDelete($event);
if ($event->status == erSUCCESS && !$this->Application->IsAdmin()) {
$event->SetRedirectParam('pass', 'm');
$event->SetRedirectParam('m_cat_id', 0);
}
}
/**
* Checks, that currently loaded item is allowed for viewing (non permission-based)
*
* @param kEvent $event
* @return bool
*/
function checkItemStatus(&$event)
{
$object =& $event->getObject();
if (!$object->isLoaded()) {
return true;
}
$status = $object->GetDBField('Status');
$user_id = $this->Application->RecallVar('user_id');
$owner_field = $this->getOwnerField($event->Prefix);
if (($status == -2 || $status == STATUS_PENDING) && ($object->GetDBField($owner_field) == $user_id)) {
return true;
}
return $status == STATUS_ACTIVE;
}
/**
* Set's correct sorting for list
* based on data provided with event
*
* @param kEvent $event
* @access private
* @see OnListBuild
*/
function SetSorting(&$event)
{
if (!$this->Application->IsAdmin()) {
$event->setEventParam('same_special', true);
}
parent::SetSorting($event);
}
/**
* Returns current per-page setting for list
*
* @param kEvent $event
* @return int
*/
function getPerPage(&$event)
{
if (!$this->Application->IsAdmin()) {
$event->setEventParam('same_special', true);
}
return parent::getPerPage($event);
}
function getOwnerField($prefix)
{
$owner_field = $this->Application->getUnitOption($prefix, 'OwnerField');
if (!$owner_field) {
$owner_field = 'CreatedById';
}
return $owner_field;
}
/**
* Creates virtual image fields for item
*
* @param kEvent $event
*/
function OnAfterConfigRead(&$event)
{
$file_helper =& $this->Application->recallObject('FileHelper');
/* @var $file_helper FileHelper */
$file_helper->createItemFiles($event->Prefix, true); // create image fields
$file_helper->createItemFiles($event->Prefix, false); // create file fields
}
/**
* Returns file contents associated with item
*
* @param kEvent $event
*/
function OnDownloadFile(&$event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
$event->status = erSTOP;
$field = $this->Application->GetVar('field');
if (!preg_match('/^File([\d]+)/', $field)) {
return ;
}
$file_helper =& $this->Application->recallObject('FileHelper');
/* @var $file_helper FileHelper */
$filename = $object->GetField($field, 'full_path');
$file_helper->DownloadFile($filename);
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/general/cat_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.97.2.15
\ No newline at end of property
+1.97.2.16
\ No newline at end of property
Index: branches/RC/core/units/general/country_states.php
===================================================================
--- branches/RC/core/units/general/country_states.php (revision 10097)
+++ branches/RC/core/units/general/country_states.php (revision 10098)
@@ -1,101 +1,101 @@
<?php
- class kCountryStatesHelper extends kHelper
+ class kCountryStatesHelper extends kHelper
{
var $CountriesWithStates = Array('USA', 'CAN');
-
+
function CountryHasStates($country_code)
{
return !$country_code ? false : in_array($country_code,$this->CountriesWithStates);
}
-
+
/**
* Prepares states dropdown based on country selected
*
* @param kEvent $event
* @param string $state_field
* @param string $country_field
*/
function PopulateStates(&$event, $state_field, $country_field)
{
$object =& $event->getObject();
$country_abbr = $object->GetDBField($country_field);
if (!$country_abbr) return;
$country_id = $this->Conn->GetOne('SELECT DestId FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType=1 AND DestAbbr = '.$this->Conn->qstr($country_abbr));
if (!$country_id) return;
$query =
'SELECT p.Translation as DestName, sd.DestAbbr
FROM '.TABLE_PREFIX.'StdDestinations AS sd
LEFT JOIN '.TABLE_PREFIX.'Phrase AS p
ON p.Phrase = sd.DestName
WHERE
DestType=2 AND DestParentId='.$country_id.'
AND
LanguageId = '.$this->Application->GetVar('m_lang').'
ORDER BY Translation';
$states = $this->Conn->GetCol($query, 'DestAbbr');
$object->Fields[$state_field]['options'] = $states;
$object->Fields[$state_field]['options'][''] = '';
}
-
+
/**
* Returns valid state code for state name and country code passed
*
* @param string $state_name
* @param string $country_code
* @return string
*/
function CheckState($state_name, $country_code)
{
if( !$this->CountryHasStates($country_code) ) return $state_name;
-
+
$sql = 'SELECT sdStates.DestAbbr
FROM '.TABLE_PREFIX.'StdDestinations AS sdStates
LEFT JOIN '.TABLE_PREFIX.'Phrase AS p ON p.Phrase = sdStates.DestName
LEFT JOIN '.TABLE_PREFIX.'StdDestinations AS sdCountries ON sdStates.DestParentId = sdCountries.DestId
WHERE (sdStates.DestType = 2) AND
(sdStates.DestParentId = sdCountries.DestId) AND
- (p.LanguageId = %1$s) AND
- (sdCountries.DestAbbr = %2$s) AND
+ (p.LanguageId = %1$s) AND
+ (sdCountries.DestAbbr = %2$s) AND
(
(LOWER(sdStates.DestAbbr) = %3$s) OR (LOWER(sdStates.DestAbbr2) = %3$s) OR (LOWER(sdStates.DestName) = %3$s) OR (LOWER(p.Translation) = %3$s)
)';
-
- $state_name = trim( strtolower($state_name) );
+
+ $state_name = trim( mb_strtolower($state_name) );
$sql = sprintf($sql, $this->Application->GetVar('m_lang'), $this->Conn->qstr($country_code), $this->Conn->qstr($state_name) );
-
+
return $this->Conn->GetOne($sql);
}
-
+
function CheckStateField(&$event, $state_field, $country_field)
{
-
+
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
list($id, $field_values) = each($items_info);
if( isset($field_values[$state_field]) && isset($field_values[$country_field]) )
{
$user_state = getArrayValue($field_values,$state_field);
$valid_state = $this->CheckState($user_state, getArrayValue($field_values,$country_field) );
if($valid_state !== false)
{
$field_values[$state_field] = $valid_state;
$items_info[$id] = $field_values;
$this->Application->SetVar( $event->getPrefixSpecial(true), $items_info);
}
else
{
$object =& $event->getObject();
$object->Fields[$state_field]['options'][$user_state] = $user_state;
$object->SetError($state_field, 'invalid_state', 'la_invalid_state');
}
}
}
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/general/country_states.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.4
\ No newline at end of property
+1.4.48.1
\ No newline at end of property
Index: branches/RC/core/install.php
===================================================================
--- branches/RC/core/install.php (revision 10097)
+++ branches/RC/core/install.php (revision 10098)
@@ -1,1202 +1,1202 @@
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
define('IS_INSTALL', 1);
define('ADMIN', 1);
define('FULL_PATH', realpath(dirname(__FILE__).'/..') );
define('REL_PATH', '/core');
/**
* Upgrade sqls are located using this mask
*
*/
define('UPGRADES_FILE', FULL_PATH.'/%sinstall/upgrades.%s');
/**
* Format of version identificator in upgrade files
*
*/
define('VERSION_MARK', '# ===== v ([\d]+\.[\d]+\.[\d]+) =====');
// print_pre($_POST);
$install_engine = new kInstallator();
$install_engine->Init();
$install_engine->Run();
$install_engine->Done();
class kInstallator {
/**
* Reference to kApplication class object
*
* @var kApplication
*/
var $Application = null;
/**
* Connection to database
*
* @var kDBConnection
*/
var $Conn = null;
/**
* Path to config.php
*
* @var string
*/
var $INIFile = '';
/**
* XML file containing steps information
*
* @var string
*/
var $StepDBFile = '';
/**
* Parsed data from config.php
*
* @var Array
*/
var $systemConfig = Array ();
/**
* Step name, that currently being processed
*
* @var string
*/
var $currentStep = '';
/**
* Steps list (preset) to use for current installation
*
* @var string
*/
var $stepsPreset = '';
/**
* Installtion steps to be done
*
* @var Array
*/
var $steps = Array(
'fresh_install' => Array ('check_paths', 'db_config', 'root_password', 'choose_modules', 'finish'),
'already_installed' => Array ('install_setup'),
'upgrade' => Array ('install_setup', 'upgrade_modules', /* ..., */ 'finish'),
'db_reconfig' => Array ('install_setup',/* ..., */ 'finish'),
'fix_paths' => Array ('install_setup',/* ..., */ 'finish'),
);
/**
* Steps, that doesn't required admin to be logged-in to proceed
*
* @var Array
*/
var $skipLoginSteps = Array ('root_password', 'choose_modules', 'finish', -1);
/**
* Steps, on which kApplication should not be initialized, because of missing correct db table structure
*
* @var Array
*/
var $skipApplicationSteps = Array ('check_paths', 'db_config'/*, 'install_setup'*/); // remove install_setup when application will work separately from install
/**
* Folders that should be writeable to continue installation
*
* @var Array
*/
var $writeableFolders = Array ('/system');
/**
* Contains last error message text
*
* @var string
*/
var $errorMessage = '';
/**
* Base path for includes in templates
*
* @var string
*/
var $baseURL = '';
-
+
/**
* Holds number of last executed query in the SQL
*
* @var unknown_type
*/
var $LastQueryNum = 0;
function Init()
{
$this->INIFile = FULL_PATH.'/config.php';
$this->StepDBFile = FULL_PATH.'/'.REL_PATH.'/install/steps_db.xml';
$base_path = rtrim(preg_replace('/'.preg_quote(rtrim(REL_PATH, '/'), '/').'$/', '', str_replace('\\', '/', dirname($_SERVER['PHP_SELF']))), '/');
$this->baseURL = 'http://'.$_SERVER['HTTP_HOST'].$base_path.'/core/install/';
set_error_handler( Array(&$this, 'ErrorHandler') );
if (file_exists($this->INIFile)) {
// if config.php found, then check his write permission too
$this->writeableFolders[] = '/config.php';
}
else {
$this->writeableFolders[] = '/';
}
$this->systemConfig = $this->ParseConfig(true);
$this->systemConfig['Misc']['WriteablePath'] = '/system'; // for development purposes
$this->systemConfig['Misc']['Domain'] = $_SERVER['HTTP_HOST']; // for redirects from SSL mode
$this->currentStep = $this->GetVar('step');
// can't check login on steps where no application present anyways :)
$this->skipLoginSteps = array_unique(array_merge($this->skipLoginSteps, $this->skipApplicationSteps));
$this->SelectPreset();
if (!$this->currentStep) {
$this->SetFirstStep(); // sets first step of current preset
}
$this->InitStep();
}
function SetFirstStep()
{
reset($this->steps[$this->stepsPreset]);
$this->currentStep = current($this->steps[$this->stepsPreset]);
}
/**
* Selects preset to proceed based on various criteria
*
*/
function SelectPreset()
{
$preset = $this->GetVar('preset');
if (file_exists($this->INIFile) && $this->systemConfig) {
// only at installation first step
$status = $this->CheckDatabase(false);
if ($status && $this->AlreadyInstalled()) {
// if already installed, then all future actions need login to work
$this->skipLoginSteps = Array (-1);
if (!$preset) {
$preset = 'already_installed';
$this->currentStep = '';
}
}
}
if ($preset === false) {
$preset = 'fresh_install'; // default preset
}
$this->stepsPreset = $preset;
}
function GetVar($name)
{
return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
}
/**
* Performs needed intialization of data, that step requires
*
*/
function InitStep()
{
$require_login = !in_array($this->currentStep, $this->skipLoginSteps);
$this->InitApplication($require_login);
if ($require_login) {
// step require login to proceed
if (!$this->Application->LoggedIn()) {
$this->stepsPreset = 'already_installed';
$this->SetFirstStep();
}
}
switch ($this->currentStep) {
case 'check_paths':
foreach ($this->writeableFolders as $folder_path) {
$file_path = FULL_PATH.$folder_path;
if (!is_writable($file_path)) {
$this->errorMessage = 'Install cannot write to specified folder in the root directory of your installation';
break;
}
}
break;
case 'db_config':
$section_name = 'Database';
$fields = Array ('DBType', 'DBHost', 'DBName', 'DBUser', 'DBUserPassword', 'DBCollation', 'TablePrefix');
if (!isset($this->systemConfig[$section_name])) {
$this->systemConfig[$section_name] = Array ();
}
// set fields
foreach ($fields as $field_name) {
$submit_value = $this->GetVar($field_name);
if ($submit_value !== false) {
$this->systemConfig[$section_name][$field_name] = $submit_value;
}
elseif (!isset($this->systemConfig[$section_name][$field_name])) {
$this->systemConfig[$section_name][$field_name] = '';
}
}
break;
case 'choose_modules':
// if no modules found, then proceed to next step
$modules = $this->ScanModules();
if (!$modules) {
$this->currentStep = $this->GetNextStep();
}
break;
case 'upgrade_modules':
// get installed modules from db and compare their versions to upgrade script
$modules = $this->GetUpgradableModules();
if (!$modules) {
$this->currentStep = $this->GetNextStep();
}
break;
case 'install_setup':
$next_preset = $this->Application->GetVar('next_preset');
if ($next_preset !== false && $this->Application->GetVar('login') == 'root') {
// option was choosen, then verify password & login user
$login_event = new kEvent('u.current:OnLogin');
$this->Application->HandleEvent($login_event);
if ($login_event->status == erSUCCESS) {
// login succeeded
if (!isset($this->steps[$next_preset])) {
$this->errorMessage = 'Preset "'.$next_preset.'" not yet implemented';
}
else {
$this->stepsPreset = $next_preset;
}
}
else {
// login failed
$user =& $this->Application->recallObject('u.current');
/* @var $user UsersItem */
$this->errorMessage = $user->GetErrorMsg('ValidateLogin').'. If you don\'t know your username or password, contact Intechnic Support';
}
}
else {
// if preset was not choosen, then raise error
$this->errorMessage = 'Please select action to perform';
}
break;
}
$this->PerformValidation(); // returns validation status (just in case)
}
/**
* Validates data entered by user
*
* @return bool
*/
function PerformValidation()
{
if ($this->GetVar('step') != $this->currentStep) {
// just redirect from previous step, don't validate
return true;
}
$status = true;
switch ($this->currentStep) {
case 'db_config':
// 1. check if required fields are filled
$section_name = 'Database';
$required_fields = Array ('DBType', 'DBHost', 'DBName', 'DBUser', 'DBCollation');
foreach ($required_fields as $required_field) {
if (!$this->systemConfig[$section_name][$required_field]) {
$status = false;
$this->errorMessage = 'Please fill all required fields';
break;
}
}
if (!$status) break;
// 2. check permissions, that use have in this database
$status = $this->CheckDatabase();
break;
case 'root_password':
// check, that password & verify password match
$password = $this->Application->GetVar('root_password');
$password_verify = $this->Application->GetVar('root_password_verify');
if ($password != $password_verify) {
$this->errorMessage = 'Passwords does not match';
}
- elseif (strlen($password) < 4) {
+ elseif (mb_strlen($password) < 4) {
$this->errorMessage = 'Root Password must be at least 4 characters';
}
$status = $this->errorMessage == '';
break;
}
return $status;
}
/**
* Perform installation step actions
*
*/
function Run()
{
if ($this->errorMessage) {
// was error during data validation stage
return ;
}
switch ($this->currentStep) {
case 'db_config':
// store db configuration
$sql = 'SHOW COLLATION
LIKE \''.$this->systemConfig['Database']['DBCollation'].'\'';
$collation_info = $this->Conn->Query($sql);
if ($collation_info) {
$this->systemConfig['Database']['DBCharset'] = $collation_info[0]['Charset'];
// database is already connected, that's why set collation on the fly
$this->Conn->Query('SET NAMES \''.$this->systemConfig['Database']['DBCharset'].'\' COLLATE \''.$this->systemConfig['Database']['DBCollation'].'\'');
}
$this->SaveConfig();
// import base data into database
$this->RunSQL('/core/install/install_schema.sql');
$this->RunSQL('/core/install/install_data.sql');
// set module "Core" version after install (based on upgrade scripts)
$this->SetModuleVersion('Core');
break;
case 'root_password':
// update root password in database
$password = md5( md5($this->Application->GetVar('root_password')) . 'b38');
$this->SetConfigValue('RootPass', $password);
// set Site_Path (for SSL & old in-portal code)
$this->SetConfigValue('Site_Path', BASE_PATH.'/');
// import base language for core (english)
$this->ImportLanguage('/core/install/english');
// set imported language as primary
$lang =& $this->Application->recallObject('lang.-item', null, Array('skip_autoload' => true));
/* @var $lang LanguagesItem */
$lang->Load(1); // fresh install => ID=1
$lang->setPrimary();
break;
case 'choose_modules':
// run module install scripts
$modules = $this->Application->GetVar('modules');
if ($modules) {
foreach ($modules as $module) {
$install_file = MODULES_PATH.'/'.$module.'/install.php';
if (file_exists($install_file)) {
include_once($install_file);
// set module version after install (based on upgrade scripts)
$this->SetModuleVersion($module);
}
}
}
// scan themes
$this->Application->HandleEvent($themes_event, 'adm:OnRebuildThemes');
$this->Conn->Query('UPDATE '.TABLE_PREFIX.'Theme SET Enabled=1, PrimaryTheme =1 LIMIT 1');
// update categories cache
$updater =& $this->Application->recallObject('kPermCacheUpdater');
/* @var $updater kPermCacheUpdater */
$updater->OneStepRun();
break;
case 'upgrade_modules':
// get installed modules from db and compare their versions to upgrade script
$modules = $this->Application->GetVar('modules');
if ($modules) {
$upgrade_data = $this->GetUpgradableModules();
$start_from_module = $this->GetVar('continue_from_module');
$start_from_query = $this->GetVar('continue_from_query');
if (!$start_from_query) $start_from_query = 0;
foreach ($modules as $module_name) {
if ($start_from_module && $module_name != $start_from_module) {
continue;
}
else {
$start_from_module = false; //otherwise it will skip all modules after the one we start with!
}
$module_info = $upgrade_data[$module_name];
$upgrades_file = sprintf(UPGRADES_FILE, $module_info['Path'], 'sql');
$sqls = file_get_contents($upgrades_file);
$version_mark = preg_replace('/(\(.*?\))/', $module_info['FromVersion'], VERSION_MARK);
// get only sqls from next (relative to current) version to end of file
$start_pos = strpos($sqls, $version_mark);
$sqls = substr($sqls, $start_pos);
preg_match_all('/'.VERSION_MARK.'/s', $sqls, $regs);
if (!$start_from_module) {
$this->RunUpgrades($module_info['Path'], $regs[1], 'before');
}
if (!$this->RunSQLText($sqls, null, null, $start_from_query)) {
$this->errorMessage .= '<input type="hidden" name="continue_from_module" value="'.$module_name.'">';
$this->errorMessage .= '<input type="hidden" name="continue_from_query" value="'.$this->LastQueryNum.'">';
$this->errorMessage .= '<br/>Click Continue button below to skip this query and go further<br/>';
$this->Done();
}
$start_from_query = 0; // so that next module start from the beggining
$this->RunUpgrades($module_info['Path'], $regs[1], 'after');
// after upgrade sqls are executed update version
$this->SetModuleVersion($module_name, $module_info['ToVersion']);
}
}
else {
$this->errorMessage = 'Please select module(-s) to upgrade';
}
break;
case 'finish':
// delete cache
$sql = 'DELETE FROM '.TABLE_PREFIX.'Cache
WHERE VarName IN ("config_files","configs_parsed","sections_parsed")';
$this->Conn->Query($sql);
// set installation finished mark
if ($this->Application->ConfigValue('InstallFinished') === false) {
$fields_hash = Array (
'VariableName' => 'InstallFinished',
'VariableValue' => 1,
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'ConfigurationValues');
}
break;
}
if ($this->errorMessage) {
// was error during run stage
return ;
}
$this->currentStep = $this->GetNextStep();
$this->InitStep(); // init next step (that will be shown now)
$this->InitApplication();
if ($this->currentStep == -1) {
// step after last step -> redirect to admin
$this->Application->Redirect('index', null, '', 'index.php');
}
}
/**
* Run upgrade PHP scripts for module with specified path
*
* @param string $module_path
* @param Array $versions
* @param string $mode upgrade mode = {before,after}
*/
function RunUpgrades($module_path, $versions, $mode)
{
static $upgrade_classes = Array ();
$upgrades_file = sprintf(UPGRADES_FILE, $module_path, 'php');
if (!file_exists($upgrades_file) || !$versions) {
return ;
}
if (!isset($upgrade_classes[$module_path])) {
// save class name, because 2nd time
// (in after call $upgrade_class variable will not be present)
include_once $upgrades_file;
$upgrade_classes[$module_path] = $upgrade_class;
}
$upgrade_object = new $upgrade_classes[$module_path]();
if (method_exists($upgrade_object, 'setInstallator')) {
$upgrade_object->setInstallator($this);
}
foreach ($versions as $version) {
$upgrade_method = 'Upgrade_'.str_replace('.', '_', $version);
if (method_exists($upgrade_object, $upgrade_method)) {
$upgrade_object->$upgrade_method($mode);
}
}
}
/**
* Sets module version to passed
*
* @param string $module_name
* @param string $version
*/
function SetModuleVersion($module_name, $version = false)
{
if ($version === false) {
$version = $this->GetMaxModuleVersion($module_name);
}
$table_prefix = $this->systemConfig['Database']['TablePrefix'];
$sql = 'UPDATE '.$table_prefix.'Modules
SET Version = "'.$version.'"
WHERE Name = "'.$module_name.'"';
$this->Conn->Query($sql);
}
/**
* Sets new configuration variable value
*
* @param string $name
* @param mixed $value
*/
function SetConfigValue($name, $value)
{
$sql = 'UPDATE '.TABLE_PREFIX.'ConfigurationValues
SET VariableValue = '.$this->Conn->qstr($value).'
WHERE VariableName = '.$this->Conn->qstr($name);
$this->Conn->Query($sql);
}
/**
* Initialize kApplication
*
* @param bool $force initialize in any case
*/
function InitApplication($force = false)
{
if (($force || !in_array($this->currentStep, $this->skipApplicationSteps)) && !isset($this->Application)) {
// step is allowed for application usage & it was not initialized in previous step
global $start, $debugger, $dbg_options;
include_once(FULL_PATH.'/core/kernel/startup.php');
$this->Application =& kApplication::Instance();
$this->Application->Init();
$this->Conn =& $this->Application->GetADODBConnection();
}
}
/**
* Show next step screen
*
*/
function Done($error_message = null)
{
if (isset($error_message)) {
$this->errorMessage = $error_message;
}
include_once (FULL_PATH.'/'.REL_PATH.'/install/incs/install.tpl');
if (isset($this->Application)) {
$this->Application->Done();
// echo 'SID: ['.$this->Application->GetSID().']<br />';
}
exit;
}
function GetMaxModuleVersion($module_name)
{
- $upgrades_file = sprintf(UPGRADES_FILE, strtolower($module_name).'/', 'sql');
+ $upgrades_file = sprintf(UPGRADES_FILE, mb_strtolower($module_name).'/', 'sql');
if (!file_exists($upgrades_file)) {
// no upgrade file
return '4.0.1';
}
$sqls = file_get_contents($upgrades_file);
$versions_found = preg_match_all('/'.VERSION_MARK.'/s', $sqls, $regs);
if (!$versions_found) {
// upgrades file doesn't contain version definitions
return '4.0.1';
}
return end($regs[1]);
}
function ConnectToDatabase()
{
include_once FULL_PATH.'/core/kernel/db/db_connection.php';
if (!isset($this->systemConfig['Database']['DBType']) ||
!isset($this->systemConfig['Database']['DBUser']) ||
!isset($this->systemConfig['Database']['DBName'])
) {
return false;
}
$this->Conn = new kDBConnection($this->systemConfig['Database']['DBType'], Array(&$this, 'DBErrorHandler'));
$this->Conn->Connect($this->systemConfig['Database']['DBHost'], $this->systemConfig['Database']['DBUser'], $this->systemConfig['Database']['DBUserPassword'], $this->systemConfig['Database']['DBName']);
return $this->Conn->errorCode == 0;
}
/**
* Checks if core is already installed
*
* @return bool
*/
function AlreadyInstalled()
{
$table_prefix = $this->systemConfig['Database']['TablePrefix'];
return $this->TableExists('ConfigurationValues') && $this->Conn->GetOne('SELECT VariableValue FROM '.$table_prefix.'ConfigurationValues WHERE VariableName = \'InstallFinished\'');
}
function CheckDatabase($check_installed = true)
{
// perform various check type to database specified
// 1. user is allowed to connect to database
// 2. user has all types of permissions in database
- if (strlen($this->systemConfig['Database']['TablePrefix']) > 7) {
+ if (mb_strlen($this->systemConfig['Database']['TablePrefix']) > 7) {
$this->errorMessage = 'Table prefix should not be longer than 7 characters';
return false;
}
// connect to database
$status = $this->ConnectToDatabase();
if ($status) {
// if connected, then check if all sql statements work
$sql_tests[] = 'DROP TABLE IF EXISTS test_table';
$sql_tests[] = 'CREATE TABLE test_table(test_col mediumint(6))';
$sql_tests[] = 'LOCK TABLES test_table WRITE';
$sql_tests[] = 'INSERT INTO test_table(test_col) VALUES (5)';
$sql_tests[] = 'UPDATE test_table SET test_col = 12';
$sql_tests[] = 'UNLOCK TABLES';
$sql_tests[] = 'ALTER TABLE test_table ADD COLUMN new_col varchar(10)';
$sql_tests[] = 'SELECT * FROM test_table';
$sql_tests[] = 'DELETE FROM test_table';
$sql_tests[] = 'DROP TABLE IF EXISTS test_table';
foreach ($sql_tests as $sql_test) {
$this->Conn->Query($sql_test);
if ($this->Conn->getErrorCode() != 0) {
$status = false;
break;
}
}
if ($status) {
// if statements work & connection made, then check table existance
if ($check_installed && $this->AlreadyInstalled()) {
$this->errorMessage = 'An In-Portal Database already exists at this location';
return false;
}
}
else {
// user has insufficient permissions in database specified
$db_error = 'Permission Error: ('.$this->Conn->getErrorCode().') '.$this->Conn->getErrorMsg();
return false;
}
}
else {
// was error while connecting
if (!$this->Conn) return false;
$this->errorMessage = 'Connection Error: ('.$this->Conn->getErrorCode().') '.$this->Conn->getErrorMsg();
return false;
}
return true;
}
/**
* Checks if all passed tables exists
*
* @param string $tables comma separated tables list
* @return bool
*/
function TableExists($tables)
{
$prefix = $this->systemConfig['Database']['TablePrefix'];
$all_found = true;
$tables = explode(',', $tables);
foreach ($tables as $table_name) {
$sql = 'SHOW TABLES LIKE "'.$prefix.$table_name.'"';
if (count($this->Conn->Query($sql)) == 0) {
$all_found = false;
break;
}
}
return $all_found;
}
/**
* Runs SQLs from file
*
* @param string $filename
* @param mixed $replace_from
* @param mixed $replace_to
*/
function RunSQL($filename, $replace_from = null, $replace_to = null)
{
if (!file_exists(FULL_PATH.$filename)) {
return ;
}
$sqls = file_get_contents(FULL_PATH.$filename);
if (!$this->RunSQLText($sqls, $replace_from, $replace_to)) {
$this->Done();
}
}
/**
* Runs SQLs from string
*
* @param string $sqls
* @param mixed $replace_from
* @param mixed $replace_to
*/
function RunSQLText(&$sqls, $replace_from = null, $replace_to = null, $start_from=0)
{
$table_prefix = $this->systemConfig['Database']['TablePrefix'];
// add prefix to all tables
if (strlen($table_prefix) > 0) {
$replacements = Array ('CREATE TABLE ', 'INSERT INTO ', 'UPDATE ', 'ALTER TABLE ', 'DELETE FROM ', 'REPLACE INTO ');
foreach ($replacements as $replacement) {
$sqls = str_replace($replacement, $replacement.$table_prefix, $sqls);
}
$sqls = str_replace('DROP TABLE ', 'DROP TABLE IF EXISTS '.$table_prefix, $sqls);
}
if (isset($replace_from) && isset($replace_to)) {
// replace something additionally, e.g. module root category
$sqls = str_replace($replace_from, $replace_to, $sqls);
}
$sqls = str_replace("\r\n", "\n", $sqls); // convert to linux line endings
$sqls = preg_replace("/#([^;]*?)\n/", '', $sqls); // remove all comments
$sqls = explode(";\n", $sqls);
for ($i=$start_from; $i<count($sqls); $i++) {
$sql = trim($sqls[$i]);
if (!$sql) {
continue; // usually last line
}
if (substr($sql, 0, 13) == 'CREATE TABLE ' && $this->systemConfig['Database']['DBCollation']) {
// it is CREATE TABLE statement -> add collation
$sql .= ' COLLATE \''.$this->systemConfig['Database']['DBCollation'].'\'';
}
$this->Conn->Query($sql);
if ($this->Conn->getErrorCode() != 0) {
$this->errorMessage = 'Error: ('.$this->Conn->getErrorCode().') '.$this->Conn->getErrorMsg().'<br /><br />Database Query:<pre>'.htmlspecialchars($sql).'</pre>';
$this->LastQueryNum = $i+1;
return false;
}
}
return true;
}
function ImportLanguage($lang_file)
{
$lang_file = FULL_PATH.$lang_file.'.lang';
if (!file_exists($lang_file)) {
return ;
}
$lang_xml =& $this->Application->recallObjectP('LangXML', null, Array(), false); // false - don't use temp tables
$lang_xml->Parse($lang_file, '|0|1|2|', '');
}
/**
* Returns modules list found in modules folder
*
* @return Array
*/
function ScanModules()
{
static $modules = null;
if (!isset($modules)) {
$modules = Array();
$fh = opendir(MODULES_PATH);
while (($sub_folder = readdir($fh))) {
$folder_path = MODULES_PATH.'/'.$sub_folder;
if ($sub_folder != '.' && $sub_folder != '..' && is_dir($folder_path)) {
if ($sub_folder == 'core') {
// skip modules here
continue;
}
// this is folder in MODULES_PATH directory
if (file_exists($folder_path.'/install.php') && file_exists($folder_path.'/install/install_schema.sql')) {
$modules[] = $sub_folder;
}
}
}
}
return $modules;
}
/**
* Converts module version in format X.Y.Z to signle integer
*
* @param string $version
* @return int
*/
function ConvertModuleVersion($version)
{
$parts = explode('.', $version);
$bin = '';
foreach ($parts as $part) {
$bin .= str_pad(decbin($part), 8, '0', STR_PAD_LEFT);
}
return bindec($bin);
}
/**
* Returns list of modules, that can be upgraded
*
*/
function GetUpgradableModules()
{
$ret = Array ();
foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
$upgrades_file = sprintf(UPGRADES_FILE, $module_info['Path'], 'sql');
if (!file_exists($upgrades_file)) {
// no upgrade file
continue;
}
$sqls = file_get_contents($upgrades_file);
$versions_found = preg_match_all('/'.VERSION_MARK.'/s', $sqls, $regs);
if (!$versions_found) {
// upgrades file doesn't contain version definitions
continue;
}
$to_version = end($regs[1]);
$this_version = $this->ConvertModuleVersion($module_info['Version']);
if ($this->ConvertModuleVersion($to_version) > $this_version) {
// destination version is greather then current
foreach ($regs[1] as $version) {
if ($this->ConvertModuleVersion($version) > $this_version) {
$from_version = $version;
break;
}
}
$version_info = Array (
'FromVersion' => $from_version,
'ToVersion' => $to_version,
);
$ret[$module_name] = array_merge_recursive2($module_info, $version_info);
}
}
return $ret;
}
/**
* Returns content to show for current step
*
* @return string
*/
function GetStepBody()
{
$step_template = FULL_PATH.'/core/install/step_templates/'.$this->currentStep.'.tpl';
if (file_exists($step_template)) {
ob_start();
include_once ($step_template);
return ob_get_clean();
}
return '{step template "'.$this->currentStep.'" missing}';
}
/**
* Parses step information file, cache result for current step ONLY & return it
*
* @return Array
*/
function &_getStepInfo()
{
static $info = Array('help_title' => null, 'step_title' => null, 'help_body' => null, 'queried' => false);
if (!$info['queried']) {
$fdata = file_get_contents($this->StepDBFile);
$parser = xml_parser_create();
xml_parse_into_struct($parser, $fdata, $values, $index);
xml_parser_free($parser);
foreach ($index['STEP'] as $section_index) {
$step_data =& $values[$section_index];
if ($step_data['attributes']['NAME'] == $this->currentStep) {
$info['step_title'] = $step_data['attributes']['TITLE'];
if (isset($step_data['attributes']['HELP_TITLE'])) {
$info['help_title'] = $step_data['attributes']['HELP_TITLE'];
}
else {
// if help title not set, then use step title
$info['help_title'] = $step_data['attributes']['TITLE'];
}
$info['help_body'] = trim($step_data['value']);
break;
}
}
$info['queried'] = true;
}
return $info;
}
/**
* Returns particular information abou current step
*
* @param string $info_type
* @return string
*/
function GetStepInfo($info_type)
{
$step_info =& $this->_getStepInfo();
if (isset($step_info[$info_type])) {
return $step_info[$info_type];
}
return '{step "'.$this->currentStep.'"; param "'.$info_type.'" missing}';
}
/**
* Returns passed steps titles
*
* @param Array $steps
* @return Array
* @see kInstaller:PrintSteps
*/
function _getStepTitles($steps)
{
$fdata = file_get_contents($this->StepDBFile);
$parser = xml_parser_create();
xml_parse_into_struct($parser, $fdata, $values, $index);
xml_parser_free($parser);
$ret = Array ();
foreach ($index['STEP'] as $section_index) {
$step_data =& $values[$section_index];
if (in_array($step_data['attributes']['NAME'], $steps)) {
$ret[ $step_data['attributes']['NAME'] ] = $step_data['attributes']['TITLE'];
}
}
return $ret;
}
/**
* Returns current step number in active steps_preset.
* Value can't be cached, because same step can have different number in different presets
*
* @return int
*/
function GetStepNumber()
{
return array_search($this->currentStep, $this->steps[$this->stepsPreset]) + 1;
}
/**
* Returns step name to process next
*
* @return string
*/
function GetNextStep()
{
$next_index = $this->GetStepNumber();
if ($next_index > count($this->steps[$this->stepsPreset]) - 1) {
return -1;
}
return $this->steps[$this->stepsPreset][$next_index];
}
/**
* Returns step name, that was processed before this step
*
* @return string
*/
function GetPreviousStep()
{
$next_index = $this->GetStepNumber() - 1;
if ($next_index < 0) {
$next_index = 0;
}
return $this->steps[$this->stepsPreset][$next_index];
}
/**
* Prints all steps from active steps preset and highlights current step
*
* @param string $active_tpl
* @param string $passive_tpl
* @return string
*/
function PrintSteps($active_tpl, $passive_tpl)
{
$ret = '';
$step_titles = $this->_getStepTitles($this->steps[$this->stepsPreset]);
foreach ($this->steps[$this->stepsPreset] as $step_name) {
$template = $step_name == $this->currentStep ? $active_tpl : $passive_tpl;
$ret .= sprintf($template, $step_titles[$step_name]);
}
return $ret;
}
function ParseConfig($parse_section = false)
{
if (!file_exists($this->INIFile)) {
return Array();
}
if( file_exists($this->INIFile) && !is_readable($this->INIFile) ) {
die('Could Not Open Ini File');
}
$contents = file($this->INIFile);
$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));
+ $section = mb_substr($line, 1, (mb_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);
}
}
}
}
if ($resave) {
$fp = fopen($this->INIFile, 'w');
reset($contents);
fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
foreach ($contents as $line) {
fwrite($fp,"$line");
}
fclose($fp);
}
return $retval;
}
function SaveConfig()
{
$fp = fopen($this->INIFile, 'w');
fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
foreach ($this->systemConfig as $section_name => $section_data) {
fwrite($fp, '['.$section_name."]\n");
foreach ($section_data as $key => $value) {
fwrite($fp, $key.' = "'.$value.'"'."\n");
}
fwrite($fp, "\n");
}
fclose($fp);
}
/**
* Installation error handler for sql errors
*
* @param int $code
* @param string $msg
* @param string $sql
* @return bool
* @access private
*/
function DBErrorHandler($code, $msg, $sql)
{
$this->errorMessage = 'Query: <br />'.htmlspecialchars($sql).'<br />execution result is error:<br />['.$code.'] '.$msg;
return true;
}
/**
* Installation error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param Array $errcontext
*/
function ErrorHandler($errno, $errstr, $errfile = '', $errline = '', $errcontext = '')
{
if ($errno == E_USER_ERROR) {
// only react on user fatal errors
$this->Done($errstr);
}
}
}
/*function print_pre($s)
{
echo '<pre>', print_r($s, true). '</pre>';
}*/
?>
\ No newline at end of file
Property changes on: branches/RC/core/install.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.12.2.3
\ No newline at end of property
+1.12.2.4
\ No newline at end of property

Event Timeline