Index: install.php =================================================================== --- install.php (revision 14590) +++ install.php (working copy) @@ -226,12 +226,27 @@ $this->stepsPreset = $preset; } - function GetVar($name) + /** + * Returns variable from request + * + * @param string $name + * @return string|bool + * @access private + */ + private function GetVar($name) { return array_key_exists($name, $_REQUEST) ? $_REQUEST[$name] : false; } - function SetVar($name, $value) + /** + * Sets new value for request variable + * + * @param string $name + * @param mixed $value + * @return void + * @access private + */ + private function SetVar($name, $value) { $_REQUEST[$name] = $value; } @@ -1177,6 +1192,8 @@ } $upgrade_object = new $upgrade_classes[$module_path](); + /* @var $upgrade_object CoreUpgrades */ + $upgrade_object->setToolkit($this->toolkit); return $upgrade_object; Index: install/install_toolkit.php =================================================================== --- install/install_toolkit.php (revision 14590) +++ install/install_toolkit.php (working copy) @@ -119,17 +119,18 @@ * @param string $module_path * @param string $versions * @param string $mode upgrade mode = {install, standalone, upgrade} + * @return bool */ function CheckPrerequisites($module_path, $versions, $mode) { static $prerequisit_classes = Array (); $prerequisites_file = sprintf(PREREQUISITE_FILE, $module_path); - if (!file_exists($prerequisites_file) || !$versions) { + if ( !file_exists($prerequisites_file) || !$versions ) { return Array (); } - if (!isset($prerequisit_classes[$module_path])) { + if ( !isset($prerequisit_classes[$module_path]) ) { // save class name, because 2nd time // (in after call $prerequisite_class variable will not be present) include_once $prerequisites_file; @@ -137,7 +138,9 @@ } $prerequisite_object = new $prerequisit_classes[$module_path](); - if (method_exists($prerequisite_object, 'setToolkit')) { + /* @var $prerequisite_object InPortalPrerequisites */ + + if ( method_exists($prerequisite_object, 'setToolkit') ) { $prerequisite_object->setToolkit($this); } @@ -702,8 +705,9 @@ { static $fields = null; - if (!isset($fields)) { + if ( !isset($fields) ) { $ml_formatter =& $this->Application->recallObject('kMultiLanguage'); + /* @var $ml_formatter kMultiLanguage */ $fields['name'] = $ml_formatter->LangFieldName('Name'); $fields['description'] = $ml_formatter->LangFieldName('Description'); @@ -722,12 +726,12 @@ $category_fields['ParentId'] = $this->Application->getBaseCategory(); - if (isset($category_template)) { + if ( isset($category_template) ) { $category_fields['Template'] = $category_template; $category_fields['CachedTemplate'] = $category_template; } - if (isset($category_icon)) { + if ( isset($category_icon) ) { $category_fields['UseMenuIconUrl'] = 1; $category_fields['MenuIconUrl'] = $category_icon; } @@ -784,7 +788,7 @@ $module_folder = strtolower($module_folder); $module_name = $module_folder; - if ($module_folder == 'kernel') { + if ( $module_folder == 'kernel' ) { $module_name = 'in-portal'; $module_folder = 'core'; } @@ -810,6 +814,8 @@ // create correct columns in CustomData table $ml_helper =& $this->Application->recallObject('kMultiLanguageHelper'); + /* @var $ml_helper kMultiLanguageHelper */ + $ml_helper->createFields($prefix . '-cdata', true); } @@ -918,7 +924,7 @@ * Upgrades primary skin to the latest version * * @param Array $module_info - * @return string + * @return string|bool */ function upgradeSkin($module_info) { @@ -933,7 +939,7 @@ foreach ($matches as $index => $match) { $version_int = $this->ConvertModuleVersion($match[2][0]); - if ($version_int < $from_version_int) { + if ( $version_int < $from_version_int ) { // only process versions, that were released after currently used version continue; } @@ -949,7 +955,7 @@ ); } - if (!$versions) { + if ( !$versions ) { // not skin changes -> quit return true; } @@ -959,9 +965,9 @@ $primary_skin->Load(1, 'IsPrimary'); - if (!$primary_skin->isLoaded()) { + if ( !$primary_skin->isLoaded() ) { // we always got primary skin, but just in case - return ; + return false; } $temp_handler =& $this->Application->recallObject('skin_TempHandler', 'kTempTablesHandler'); @@ -970,15 +976,15 @@ // clone current skin $cloned_ids = $temp_handler->CloneItems('skin', '', Array ($primary_skin->GetID())); - if (!$cloned_ids) { + if ( !$cloned_ids ) { // can't clone - return ; + return false; } $skin =& $this->Application->recallObject('skin.tmp', null, Array ('skip_autoload' => true)); /* @var $skin kDBItem */ - $skin->Load( $cloned_ids[0] ); + $skin->Load($cloned_ids[0]); // save css to temp file (for patching) $skin_file = tempnam('/tmp', 'skin_css_'); @@ -1009,18 +1015,18 @@ $has_errors = false; foreach ($output as $version => $version_output) { - $version_errors = trim( preg_replace("/(^|\n)(patching file .*?|Hunk #.*?\.)(\n|$)/m", '', $version_output) ); + $version_errors = trim(preg_replace("/(^|\n)(patching file .*?|Hunk #.*?\.)(\n|$)/m", '', $version_output)); - if ($version_errors) { + if ( $version_errors ) { $has_errors = true; - $output[$version] = trim( preg_replace("/(^|\n)(patching file .*?)(\n|$)/m", '', $output[$version]) ); + $output[$version] = trim(preg_replace("/(^|\n)(patching file .*?)(\n|$)/m", '', $output[$version])); } else { unset($output[$version]); } } - if (!$has_errors) { + if ( !$has_errors ) { // copy patched css back to primary skin $primary_skin->SetDBField('CSS', $skin->GetDBField('CSS')); $primary_skin->Update(); Index: kernel/constants.php =================================================================== --- kernel/constants.php (revision 14590) +++ kernel/constants.php (working copy) @@ -40,7 +40,7 @@ define('SPACER_URL', $spacer_url); if (!$application->isAdmin) { - // don't show debugger buttons on front (if not overrided in "debug.php") + // don't show debugger buttons on front (if not overridden in "debug.php") kUtil::safeDefine('DBG_TOOLBAR_BUTTONS', 0); } Index: kernel/db/cat_event_handler.php =================================================================== --- kernel/db/cat_event_handler.php (revision 14590) +++ kernel/db/cat_event_handler.php (working copy) @@ -42,18 +42,26 @@ * Load item if id is available * * @param kEvent $event + * @return void + * @access protected */ function LoadItem(&$event) { $object =& $event->getObject(); + /* @var $object kDBItem */ + $id = $this->getPassedID($event); - if ($object->Load($id)) { + + if ( $object->Load($id) ) { $actions =& $this->Application->recallObject('kActions'); - $actions->Set($event->getPrefixSpecial().'_id', $object->GetID() ); + /* @var $actions Params */ + $actions->Set($event->getPrefixSpecial() . '_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')); + + if ( $use_pending_editing && $event->Special != 'original' ) { + $this->Application->SetVar($event->Prefix . '.original_id', $object->GetDBField('OrgId')); } } else { @@ -62,11 +70,13 @@ } /** - * Checks permissions of user + * Checks user permission to execute given $event * * @param kEvent $event + * @return bool + * @access public */ - function CheckPermission(&$event) + public function CheckPermission(&$event) { if (!$this->Application->isAdmin) { if ($event->Name == 'OnSetSortingDirect') { @@ -204,11 +214,16 @@ * Add selected items to clipboard with mode = COPY (CLONE) * * @param kEvent $event + * @return void + * @access protected */ - function OnCopy(&$event) + protected function OnCopy(&$event) { $this->Application->RemoveVar('clipboard'); + $clipboard_helper =& $this->Application->recallObject('ClipboardHelper'); + /* @var $clipboard_helper kClipboardHelper */ + $clipboard_helper->setClipboard($event, 'copy', $this->StoreSelectedIDs($event)); $this->clearSelectedIDs($event); } @@ -217,11 +232,15 @@ * Add selected items to clipboard with mode = CUT * * @param kEvent $event + * @return void + * @access protected */ - function OnCut(&$event) + protected function OnCut(&$event) { $this->Application->RemoveVar('clipboard'); $clipboard_helper =& $this->Application->recallObject('ClipboardHelper'); + /* @var $clipboard_helper kClipboardHelper */ + $clipboard_helper->setClipboard($event, 'cut', $this->StoreSelectedIDs($event)); $this->clearSelectedIDs($event); } @@ -250,30 +269,33 @@ * Performs category item paste * * @param kEvent $event + * @return void + * @access protected */ - function OnPaste(&$event) + protected function OnPaste(&$event) { - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) || !$this->_checkPastePermission($event)) { + if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) || !$this->_checkPastePermission($event) ) { $event->status = kEvent::erFAIL; return; } $clipboard_data = $event->getEventParam('clipboard_data'); - if (!$clipboard_data['cut'] && !$clipboard_data['copy']) { - return false; + if ( !$clipboard_data['cut'] && !$clipboard_data['copy'] ) { + return; } - if ($clipboard_data['copy']) { - $temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler'); + if ( $clipboard_data['copy'] ) { + $temp =& $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler'); /* @var $temp kTempTablesHandler */ $this->Application->SetVar('ResetCatBeforeClone', 1); // used in "kCatDBEventHandler::OnBeforeClone" $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)); + if ( $clipboard_data['cut'] ) { + $object =& $this->Application->recallObject($event->getPrefixSpecial() . '.item', $event->Prefix, Array ('skip_autoload' => true)); + /* @var $object kCatDBItem */ foreach ($clipboard_data['cut'] as $id) { $object->Load($id); @@ -288,44 +310,54 @@ * by calling its Delete method if sub-item has AutoDelete set to true in its config file * * @param kEvent $event + * @return void + * @access protected */ - function OnMassDelete(&$event) + protected function OnMassDelete(&$event) { - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) { + if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) { $event->status = kEvent::erFAIL; return; } - $event->status=kEvent::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)); + $to_delete = Array (); + + if ( $recycle_bin = $this->Application->ConfigValue('RecycleBinFolder') ) { + $rb =& $this->Application->recallObject('c.recycle', null, array ('skip_autoload' => true)); + /* @var $rb CategoriesItem */ + $rb->Load($recycle_bin); - $object =& $this->Application->recallObject($event->Prefix.'.recycleitem', null, Array ('skip_autoload' => true)); + + $object =& $this->Application->recallObject($event->Prefix . '.recycleitem', null, Array ('skip_autoload' => true)); + /* @var $object kCatDBItem */ + foreach ($ids as $id) { $object->Load($id); - if (preg_match('/^'.preg_quote($rb->GetDBField('ParentPath'),'/').'/', $object->GetDBField('ParentPath'))) { + + 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'); + $temp_handler =& $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler'); + /* @var $temp_handler kTempTablesHandler */ $event->setEventParam('ids', $ids); $this->customProcessing($event, 'before'); $ids = $event->getEventParam('ids'); - if($ids) - { - $temp->DeleteItems($event->Prefix, $event->Special, $ids); + if ( $ids ) { + $temp_handler->DeleteItems($event->Prefix, $event->Special, $ids); } + $this->clearSelectedIDs($event); } @@ -464,6 +496,8 @@ } $p_item =& $this->Application->recallObject($related_prefix.'.current', null, Array('skip_autoload' => true)); + /* @var $p_item kCatDBItem */ + $p_item->Load( (int)$id ); $p_resource_id = $p_item->GetDBField('ResourceId'); @@ -542,11 +576,14 @@ } /** - * Apply filters to list + * Apply any custom changes to list's sql query * * @param kEvent $event + * @return void + * @access protected + * @see kDBEventHandler::OnListBuild() */ - function SetCustomQuery(&$event) + protected function SetCustomQuery(&$event) { parent::SetCustomQuery($event); @@ -697,10 +734,12 @@ /** * Adds calculates fields for item statuses * - * @param kCatDBItem $object + * @param kDBItem|kDBList $object * @param kEvent $event + * @return void + * @access protected */ - function prepareObject(&$object, &$event) + protected function prepareObject(&$object, &$event) { $this->prepareItemStatuses($event); @@ -708,6 +747,8 @@ if ($event->Special == 'export' || $event->Special == 'import') { $export_helper =& $this->Application->recallObject('CatItemExportHelper'); + /* @var $export_helper kCatDBItemExportHelper */ + $export_helper->prepareExportColumns($event); } } @@ -763,24 +804,32 @@ } - function CalculateHotLimit(&$event) + /** + * Calculates hot limit for current item's table + * + * @param kEvent $event + * @return float + * @access protected + */ + protected function CalculateHotLimit(&$event) { $property_map = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings'); - if (!$property_map) { - return; + if ( !$property_map ) { + return 0.00; } $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'; + $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); - if ($this->Application->isCachingType(CACHING_TYPE_MEMORY)) { + if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) { $serial_name = $this->Application->incrementCacheSerial($event->Prefix, null, false); $this->Application->setCache($property_map['HotLimit'] . '[%' . $serial_name . '%]', $hot_limit); } @@ -795,8 +844,10 @@ * Moves item to preferred category, updates item hits * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemUpdate(&$event) + protected function OnBeforeItemUpdate(&$event) { parent::OnBeforeItemUpdate($event); @@ -805,62 +856,74 @@ // update hits field $property_map = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings'); - if ($property_map) { + if ( $property_map ) { $click_field = $property_map['ClickField']; - if( $this->Application->isAdminUser && ($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); + if ( $this->Application->isAdminUser && ($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); } } // change category $target_category = $object->GetDBField('CategoryId'); - if ($object->GetOriginalField('CategoryId') != $target_category) { + if ( $object->GetOriginalField('CategoryId') != $target_category ) { $object->MoveToCat($target_category); } } /** - * Load price from temp table if product mode is temp table + * Occurs after loading item, 'id' parameter + * allows to get id of item that was loaded * * @param kEvent $event + * @return void + * @access protected */ - function OnAfterItemLoad(&$event) + protected function OnAfterItemLoad(&$event) { + parent::OnAfterItemLoad($event); + $special = substr($event->Special, -6); $object =& $event->getObject(); /* @var $object kCatDBItem */ - if ($special == 'import' || $special == 'export') { + if ( $special == 'import' || $special == 'export' ) { $image_data = $object->getPrimaryImageData(); - if ($image_data) { + if ( $image_data ) { $thumbnail_image = $image_data[$image_data['LocalThumb'] ? 'ThumbPath' : 'ThumbUrl']; - if ($image_data['SameImages']) { + 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->GetFieldOption('Status', 'options'); + // substituting pending status value for pending editing + if ( $object->HasField('OrgId') && $object->GetDBField('OrgId') > 0 && $object->GetDBField('Status') == -2 ) { + $new_options = Array (); + $options = $object->GetFieldOption('Status', 'options', false, Array ()); + foreach ($options as $key => $val) { - if ($key == 2) $key = -2; + if ( $key == 2 ) { + $key = -2; + } + $new_options[$key] = $val; } + $object->SetFieldOption('Status', 'options', $new_options); } @@ -878,23 +941,29 @@ $file_helper->LoadItemFiles($object); } - if ( array_key_exists('MoreCategories', $object->VirtualFields) ) { + if ( $object->isVirtualField('MoreCategories') ) { // 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).'|' : ''); + $object->SetDBField('MoreCategories', $item_categories ? '|' . implode('|', $item_categories) . '|' : ''); } } + /** + * Occurs after updating item + * + * @param kEvent $event + * @access public + */ function OnAfterItemUpdate(&$event) { $this->CalculateHotLimit($event); - if ( substr($event->Special, -6) == 'import') { + if ( substr($event->Special, -6) == 'import' ) { $this->setCustomExportColumns($event); } $object =& $event->getObject(); - /* @var $object kDBItem */ + /* @var $object kCatDBItem */ if ( !$this->Application->isAdmin ) { $image_helper =& $this->Application->recallObject('ImageHelper'); @@ -909,7 +978,7 @@ // process file upload in virtual fields $file_helper->SaveItemFiles($object); - if ($event->Special != '-item') { + if ( $event->Special != '-item' ) { // don't touch categories during cloning $this->processAdditionalCategories($object, 'update'); } @@ -917,32 +986,36 @@ $recycle_bin = $this->Application->ConfigValue('RecycleBinFolder'); - if ($this->Application->isAdminUser && $recycle_bin) { + if ( $this->Application->isAdminUser && $recycle_bin ) { $sql = 'SELECT CategoryId FROM ' . $this->Application->getUnitOption('ci', 'TableName') . ' WHERE ItemResourceId = ' . $object->GetDBField('ResourceId') . ' AND PrimaryCat = 1'; $primary_category = $this->Conn->GetOne($sql); - if ($primary_category == $recycle_bin) { + if ( $primary_category == $recycle_bin ) { $event->CallSubEvent('OnAfterItemDelete'); } } } /** - * sets values for import process + * Sets values for import process * * @param kEvent $event + * @return void + * @access protected */ - function OnAfterItemCreate(&$event) + protected function OnAfterItemCreate(&$event) { - if ( substr($event->Special, -6) == 'import') { + parent::OnAfterItemCreate($event); + + if ( substr($event->Special, -6) == 'import' ) { $this->setCustomExportColumns($event); } if ( !$this->Application->isAdmin ) { $object =& $event->getObject(); - /* @var $object kDBItem */ + /* @var $object kCatDBItem */ $image_helper =& $this->Application->recallObject('ImageHelper'); /* @var $image_helper ImageHelper */ @@ -956,7 +1029,7 @@ // process file upload in virtual fields $file_helper->SaveItemFiles($object); - if ($event->Special != '-item') { + if ( $event->Special != '-item' ) { // don't touch categories during cloning $this->processAdditionalCategories($object, 'create'); } @@ -1001,6 +1074,8 @@ $keywords = kUtil::unhtmlentities( trim($this->Application->GetVar('keywords')) ); $query_object =& $this->Application->recallObject('HTTPQuery'); + /* @var $query_object kHTTPQuery */ + $sql = 'SHOW TABLES LIKE "'.$search_table.'"'; if(!isset($query_object->Get['keywords']) && @@ -1054,12 +1129,11 @@ $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') { + if ( $object->GetFieldOption($field, 'formatter') == 'kMultiLanguage' ) { $field_list[$key.'_primary'] = 'l'.$this->Application->GetDefaultLanguageId().'_'.$field; $field_list[$key] = 'l'.$lang.'_'.$field; @@ -1289,9 +1363,11 @@ 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 + /* @var $query_object kHTTPQuery */ + + if ( !isset($query_object->Post['andor']) ) { + // used when navigating by pages or changing sorting in search results + return; } $this->Application->RemoveVar('keywords'); @@ -1305,7 +1381,10 @@ $search_config = $this->Conn->Query($sql); $lang = $this->Application->GetVar('m_lang'); + $object =& $event->getObject(); + /* @var $object kDBList */ + $object->SetPage(1); $items_table = $this->Application->getUnitOption($event->Prefix, 'TableName'); @@ -1342,13 +1421,11 @@ $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') { + if ( $object->GetFieldOption($field, 'formatter') == 'kMultiLanguage' ) { $field_name = 'l'.$lang.'_'.$field; } else { @@ -1644,8 +1721,20 @@ return $condition; } - function getHuman($type, $search_data) + /** + * Returns human readable representation of searched data to be placed in search log + * @param string $type + * @param Array $search_data + * @return string + * @access protected + */ + protected function getHuman($type, $search_data) { + // all 3 variables are retrieved from $search_data array + /* @var $search_config Array */ + /* @var $verb string */ + /* @var $value string */ + $type = ucfirst(strtolower($type)); extract($search_data); @@ -1686,10 +1775,10 @@ return '"'.$ret.'"'; break; } + + return ''; } - - /** * Set's correct page for list * based on data provided with event @@ -1864,20 +1953,25 @@ * Create/Update primary image record in info found in imported data * * @param kEvent $event + * @return void + * @access protected */ - function restorePrimaryImage(&$event) + protected function restorePrimaryImage(&$event) { $object =& $event->getObject(); + /* @var $object kCatDBItem */ $has_image_info = $object->GetDBField('ImageAlt') && ($object->GetDBField('ThumbnailImage') || $object->GetDBField('FullImage')); - if (!$has_image_info) { - return false; + if ( !$has_image_info ) { + return ; } $image_data = $object->getPrimaryImageData(); - $image =& $this->Application->recallObject('img', null, Array('skip_autoload' => true)); - if ($image_data) { + $image =& $this->Application->recallObject('img', null, Array ('skip_autoload' => true)); + /* @var $image kDBItem */ + + if ( $image_data ) { $image->Load($image_data['ImageId']); } else { @@ -1889,23 +1983,23 @@ $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') ); + 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')) { + 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') ); + $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()) { + if ( $image->isLoaded() ) { $image->Update(); } else { @@ -1927,8 +2021,10 @@ { parent::OnNew($event); - if ($event->Special == 'import' || $event->Special == 'export') { + if ( $event->Special == 'import' || $event->Special == 'export' ) { $export_helper =& $this->Application->recallObject('CatItemExportHelper'); + /* @var $export_helper kCatDBItemExportHelper */ + $export_helper->setRequiredFields($event); } } @@ -1940,13 +2036,14 @@ */ function OnProcessSelected(&$event) { + $dst_field = $this->Application->RecallVar('dst_field'); $selected_ids = $this->Application->GetVar('selected_ids'); - $dst_field = $this->Application->RecallVar('dst_field'); - - if ($dst_field == 'ItemCategory') { + if ( $dst_field == 'ItemCategory' ) { // Item Edit -> Categories Tab -> New Categories $object =& $event->getObject(); + /* @var $object kCatDBItem */ + $category_ids = explode(',', $selected_ids['c']); foreach ($category_ids as $category_id) { $object->assignToCategory($category_id); @@ -1956,12 +2053,10 @@ 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 $url_params = Array ( $event->getPrefixSpecial() . '_id' => 0, $event->getPrefixSpecial() . '_event' => 'OnExportBegin', -// 'm_opener' => 's', ); $this->Application->EventManager->openerStackChange($url_params); @@ -1978,18 +2073,21 @@ function OnSaveSettings(&$event) { $event->redirect = false; - $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - if ($items_info) { + $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 =& $event->getObject(Array ('skip_autoload' => true)); + /* @var $object kDBItem */ + $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)); + $this->Application->StoreVar($event->getPrefixSpecial() . '_ItemsInfo', serialize($items_info)); } } @@ -2003,9 +2101,15 @@ $this->Application->StoreVar('ImportCategory', $this->Application->getBaseCategory()); } + /** + * Cancels item editing + * @param kEvent $event + * @return void + * @todo Used? + */ function OnCancelAction(&$event) { - $event->setRedirectParams(Array('pass' => 'all,'.$event->GetPrefixSpecial()), true); + $event->setRedirectParams(Array ('pass' => 'all,' . $event->getPrefixSpecial()), true); $event->redirect = $this->Application->GetVar('cancel_template'); } @@ -2021,10 +2125,12 @@ function cacheItemOwner(&$event, $id_field, $cached_field) { $object =& $event->getObject(); + /* @var $object kDBItem */ $user_id = $object->GetDBField($id_field); $options = $object->GetFieldOptions($id_field); - if (isset($options['options'][$user_id])) { + + if ( isset($options['options'][$user_id]) ) { $object->SetDBField($cached_field, $options['options'][$user_id]); } else { @@ -2032,90 +2138,107 @@ $table_name = $this->Application->getUnitOption('u', 'TableName'); $sql = 'SELECT Login - FROM '.$table_name.' - WHERE '.$id_field.' = '.$user_id; + FROM ' . $table_name . ' + WHERE ' . $id_field . ' = ' . $user_id; $object->SetDBField($cached_field, $this->Conn->GetOne($sql)); } } /** - * Saves item beeing edited into temp table + * Saves edited item into temp table + * If there is no id, new item is created in temp table * * @param kEvent $event + * @return void + * @access protected */ - function OnPreSave(&$event) + protected function OnPreSave(&$event) { parent::OnPreSave($event); + $use_pending_editing = $this->Application->getUnitOption($event->Prefix, 'UsePendingEditing'); - if ($event->status == kEvent::erSUCCESS && $use_pending_editing) { + + if ( $event->status == kEvent::erSUCCESS && $use_pending_editing ) { // decision: clone or not clone $object =& $event->getObject(); - if ($object->GetID() == 0 || $object->GetDBField('OrgId') > 0) { + /* @var $object kCatDBItem */ + + if ( $object->GetID() == 0 || $object->GetDBField('OrgId') > 0 ) { // new items or cloned items shouldn't be cloned again - return true; + return ; } + $perm_helper =& $this->Application->recallObject('PermissionsHelper'); + /* @var $perm_helper kPermissionsHelper */ + $owner_field = $this->getOwnerField($event->Prefix); - if ($perm_helper->ModifyCheckPermission($object->GetDBField($owner_field), $object->GetDBField('CategoryId'), $event->Prefix) == 2) { + 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'); + $temp_handler =& $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler'); + /* @var $temp_handler 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]; + 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'; + $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'); + $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]; + $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]); + $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())); + $temp_handler->DeleteItems($event->Prefix, $event->Special, Array ($object->GetID())); } } } /** - * Sets default expiration based on module setting + * Sets item's owner field * * @param kEvent $event + * @return void + * @access protected */ - function OnPreCreate(&$event) + protected function OnPreCreate(&$event) { parent::OnPreCreate($event); - if ($event->status == kEvent::erSUCCESS) { - $object =& $event->getObject(); - $owner_field = $this->getOwnerField($event->Prefix); + if ( $event->status != kEvent::erSUCCESS ) { + return ; + } - $object->SetDBField($owner_field, $this->Application->RecallVar('user_id')); - } + $object =& $event->getObject(); + /* @var $object kDBItem */ + + $owner_field = $this->getOwnerField($event->Prefix); + $object->SetDBField($owner_field, $this->Application->RecallVar('user_id')); } /** @@ -2129,16 +2252,21 @@ } /** - * 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! + * Occurs before an item has been cloned + * Id of newly created item is passed as event' 'id' param * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeClone(&$event) + protected function OnBeforeClone(&$event) { - if ($this->Application->GetVar('ResetCatBeforeClone')) { + parent::OnBeforeClone($event); + + if ( $this->Application->GetVar('ResetCatBeforeClone') ) { $object =& $event->getObject(); + /* @var $object kDBItem */ + $object->SetDBField('CategoryId', null); } } @@ -2147,16 +2275,20 @@ * Set status for new category item based on user permission in category * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemCreate(&$event) + protected function OnBeforeItemCreate(&$event) { + parent::OnBeforeItemCreate($event); + $object =& $event->getObject(); - /* @var $object kDBItem */ + /* @var $object kCatDBItem */ $is_admin = $this->Application->isAdminUser; $owner_field = $this->getOwnerField($event->Prefix); - if ((!$object->IsTempTable() && !$is_admin) || ($is_admin && !$object->GetDBField($owner_field))) { + if ( (!$object->IsTempTable() && !$is_admin) || ($is_admin && !$object->GetDBField($owner_field)) ) { // Front-end OR owner not specified -> set to currently logged-in user $object->SetDBField($owner_field, $this->Application->RecallVar('user_id')); } @@ -2165,7 +2297,7 @@ $object->SetDBField('ResourceId', $this->Application->NextResourceId()); } - if (!$this->Application->isAdmin) { + if ( !$this->Application->isAdmin ) { $this->setItemStatusByPermission($event); } } @@ -2184,7 +2316,7 @@ } $object =& $event->getObject(); - /* @var $object kDBItem */ + /* @var $object kCatDBItem */ $perm_helper =& $this->Application->recallObject('PermissionsHelper'); /* @var $perm_helper kPermissionsHelper */ @@ -2402,32 +2534,34 @@ } /** - * Apply same processing to each item beeing selected in grid + * Apply same processing to each item being selected in grid * * @param kEvent $event - * @access private + * @return void + * @access protected */ - function iterateItems(&$event) + protected function iterateItems(&$event) { - if ($event->Name != 'OnMassApprove' && $event->Name != 'OnMassDecline') { - return parent::iterateItems($event); + if ( $event->Name != 'OnMassApprove' && $event->Name != 'OnMassDecline' ) { + parent::iterateItems($event); } - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) { + if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) { $event->status = kEvent::erFAIL; - return; + return ; } - $object =& $event->getObject( Array('skip_autoload' => true) ); - /* @var $object kCatDBItem */ + $object =& $event->getObject(Array ('skip_autoload' => true)); + /* @var $object kCatDBItem */ $ids = $this->StoreSelectedIDs($event); - if ($ids) { + if ( $ids ) { foreach ($ids as $id) { + $ret = true; $object->Load($id); - switch ($event->Name) { + switch ( $event->Name ) { case 'OnMassApprove': $ret = $object->ApproveChanges(); break; @@ -2437,7 +2571,7 @@ break; } - if (!$ret) { + if ( !$ret ) { $event->status = kEvent::erFAIL; $event->redirect = false; break; @@ -2580,11 +2714,11 @@ { $remove_sortings = Array (); - if (!$this->Application->isAdmin) { + if ( !$this->Application->isAdmin ) { // remove Pick sorting on Front-end, when not required - $config_mapping = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping'); + $config_mapping = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping', Array ()); - if (!isset($config_mapping['ForceEditorPick']) || !$this->Application->ConfigValue($config_mapping['ForceEditorPick'])) { + if ( !isset($config_mapping['ForceEditorPick']) || !$this->Application->ConfigValue($config_mapping['ForceEditorPick']) ) { $remove_sortings[] = 'EditorsPick'; } } @@ -2593,11 +2727,12 @@ $remove_sortings = array_merge($remove_sortings, Array ('Priority', 'EditorsPick')); } - if (!$remove_sortings) { - return ; + if ( !$remove_sortings ) { + return; } $list_sortings = $this->Application->getUnitOption($event->Prefix, 'ListSortings', Array ()); + /* @var $list_sortings Array */ foreach ($list_sortings as $special => $sorting_fields) { foreach ($remove_sortings as $sorting_field) { @@ -2616,7 +2751,7 @@ function OnDownloadFile(&$event) { $object =& $event->getObject(); - /* @var $object kDBItem */ + /* @var $object kCatDBItem */ $event->status = kEvent::erSTOP; @@ -2650,7 +2785,7 @@ /* @var $rating_helper RatingHelper */ $object =& $event->getObject( Array ('skip_autoload' => true) ); - /* @var $object kDBItem */ + /* @var $object kCatDBItem */ $object->Load( $this->Application->GetVar('id') ); Index: kernel/db/cat_tag_processor.php =================================================================== --- kernel/db/cat_tag_processor.php (revision 14590) +++ kernel/db/cat_tag_processor.php (working copy) @@ -188,14 +188,19 @@ function ListReviews($params) { - $prefix = $this->Prefix.'-rev'; - $review_tag_processor =& $this->Application->recallObject($prefix.'.item_TagProcessor'); + $prefix = $this->Prefix . '-rev'; + + $review_tag_processor =& $this->Application->recallObject($prefix . '.item_TagProcessor'); + /* @var $review_tag_processor kDBTagProcessor */ + return $review_tag_processor->PrintList($params); } function ReviewCount($params) { $review_tag_processor =& $this->Application->recallObject('rev.item_TagProcessor'); + /* @var $review_tag_processor kDBTagProcessor */ + return $review_tag_processor->TotalRecords($params); } @@ -609,8 +614,8 @@ */ function LastUpdated($params) { - $category_id = (int)$this->Application->GetVar('m_cat_id'); - $local = array_key_exists('local', $params) && ($category_id > 0) ? $params['local'] : false; + $category_id = (int)$this->Application->GetVar('m_cat_id'); + $local = array_key_exists('local', $params) && ($category_id > 0) ? $params['local'] : false; $serial_name1 = $this->Application->incrementCacheSerial('c', $local ? $category_id : null, false); $serial_name2 = $this->Application->incrementCacheSerial($this->Prefix, null, false); @@ -618,41 +623,44 @@ $row_data = $this->Application->getCache($cache_key); - if ($row_data === false) { - if ($local && ($category_id > 0)) { + if ( $row_data === false ) { + if ( $local && ($category_id > 0) ) { // scan only current category & it's children - list ($tree_left, $tree_right) = $this->Application->getTreeIndex($category_id); + list ($tree_left, $tree_right) = $this->Application->getTreeIndex($category_id); - $sql = 'SELECT MAX(item_table.Modified) AS ModDate, MAX(item_table.CreatedOn) AS NewDate + $sql = 'SELECT MAX(item_table.Modified) AS ModDate, MAX(item_table.CreatedOn) AS NewDate FROM ' . $this->Application->getUnitOption($this->Prefix, 'TableName') . ' item_table LEFT JOIN ' . TABLE_PREFIX . 'CategoryItems ci ON (item_table.ResourceId = ci.ItemResourceId) LEFT JOIN ' . TABLE_PREFIX . 'Category c ON c.CategoryId = ci.CategoryId WHERE c.TreeLeft BETWEEN ' . $tree_left . ' AND ' . $tree_right; - } + } else { // scan all categories in system $sql = 'SELECT MAX(Modified) AS ModDate, MAX(CreatedOn) AS NewDate FROM ' . $this->Application->getUnitOption($this->Prefix, 'TableName'); - } + } - $this->Conn->nextQueryCachable = true; + $this->Conn->nextQueryCachable = true; $row_data = $this->Conn->GetRow($sql); $this->Application->setCache($cache_key, $row_data); } - if (!$row_data) { - return ''; - } + if ( !$row_data ) { + return ''; + } - $date = $row_data[ $row_data['NewDate'] > $row_data['ModDate'] ? 'NewDate' : 'ModDate' ]; + $date = $row_data[$row_data['NewDate'] > $row_data['ModDate'] ? 'NewDate' : 'ModDate']; - // format date - $format = isset($params['format']) ? $params['format'] : '_regional_DateTimeFormat'; - if (preg_match("/_regional_(.*)/", $format, $regs)) { + // format date + $format = isset($params['format']) ? $params['format'] : '_regional_DateTimeFormat'; + + if ( preg_match("/_regional_(.*)/", $format, $regs) ) { $lang =& $this->Application->recallObject('lang.current'); - if ($regs[1] == 'DateTimeFormat') { + /* @var $lang LanguagesItem */ + + if ( $regs[1] == 'DateTimeFormat' ) { // combined format - $format = $lang->GetDBField('DateFormat').' '.$lang->GetDBField('TimeFormat'); + $format = $lang->GetDBField('DateFormat') . ' ' . $lang->GetDBField('TimeFormat'); } else { // simple format Index: kernel/db/dblist.php =================================================================== --- kernel/db/dblist.php (revision 14590) +++ kernel/db/dblist.php (working copy) @@ -278,21 +278,21 @@ protected function getFilterStructure() { $filters = Array ( - Array ('type' => 'WhereFilter', 'class' => kDBList::FLT_SYSTEM, 'join_using' => kDBList::FLT_TYPE_AND), - Array ('type' => 'WhereFilter', 'class' => kDBList::FLT_NORMAL, 'join_using' => kDBList::FLT_TYPE_OR), - Array ('type' => 'WhereFilter', 'class' => kDBList::FLT_SEARCH, 'join_using' => kDBList::FLT_TYPE_OR), - Array ('type' => 'WhereFilter', 'class' => kDBList::FLT_VIEW, 'join_using' => kDBList::FLT_TYPE_AND), - Array ('type' => 'WhereFilter', 'class' => kDBList::FLT_CUSTOM, 'join_using' => kDBList::FLT_TYPE_AND), + Array ('type' => 'WhereFilter', 'class' => self::FLT_SYSTEM, 'join_using' => self::FLT_TYPE_AND), + Array ('type' => 'WhereFilter', 'class' => self::FLT_NORMAL, 'join_using' => self::FLT_TYPE_OR), + Array ('type' => 'WhereFilter', 'class' => self::FLT_SEARCH, 'join_using' => self::FLT_TYPE_OR), + Array ('type' => 'WhereFilter', 'class' => self::FLT_VIEW, 'join_using' => self::FLT_TYPE_AND), + Array ('type' => 'WhereFilter', 'class' => self::FLT_CUSTOM, 'join_using' => self::FLT_TYPE_AND), - Array ('type' => 'HavingFilter', 'class' => kDBList::FLT_SYSTEM, 'join_using' => kDBList::FLT_TYPE_AND), - Array ('type' => 'HavingFilter', 'class' => kDBList::FLT_NORMAL, 'join_using' => kDBList::FLT_TYPE_OR), - Array ('type' => 'HavingFilter', 'class' => kDBList::FLT_SEARCH, 'join_using' => kDBList::FLT_TYPE_OR), - Array ('type' => 'HavingFilter', 'class' => kDBList::FLT_VIEW, 'join_using' => kDBList::FLT_TYPE_AND), - Array ('type' => 'HavingFilter', 'class' => kDBList::FLT_CUSTOM, 'join_using' => kDBList::FLT_TYPE_AND), + Array ('type' => 'HavingFilter', 'class' => self::FLT_SYSTEM, 'join_using' => self::FLT_TYPE_AND), + Array ('type' => 'HavingFilter', 'class' => self::FLT_NORMAL, 'join_using' => self::FLT_TYPE_OR), + Array ('type' => 'HavingFilter', 'class' => self::FLT_SEARCH, 'join_using' => self::FLT_TYPE_OR), + Array ('type' => 'HavingFilter', 'class' => self::FLT_VIEW, 'join_using' => self::FLT_TYPE_AND), + Array ('type' => 'HavingFilter', 'class' => self::FLT_CUSTOM, 'join_using' => self::FLT_TYPE_AND), - Array ('type' => 'AggregateFilter', 'class' => kDBList::FLT_SYSTEM, 'join_using' => kDBList::FLT_TYPE_AND), - Array ('type' => 'AggregateFilter', 'class' => kDBList::FLT_NORMAL, 'join_using' => kDBList::FLT_TYPE_OR), - Array ('type' => 'AggregateFilter', 'class' => kDBList::FLT_VIEW, 'join_using' => kDBList::FLT_TYPE_AND), + Array ('type' => 'AggregateFilter', 'class' => self::FLT_SYSTEM, 'join_using' => self::FLT_TYPE_AND), + Array ('type' => 'AggregateFilter', 'class' => self::FLT_NORMAL, 'join_using' => self::FLT_TYPE_OR), + Array ('type' => 'AggregateFilter', 'class' => self::FLT_VIEW, 'join_using' => self::FLT_TYPE_AND), ); return $filters; @@ -307,16 +307,21 @@ * @param int $filter_scope filter subtype: FLT_NORMAL,FLT_SYSTEM,FLT_SEARCH,FLT_VIEW,FLT_CUSTOM * @access public */ - public function addFilter($name, $clause, $filter_type = kDBList::WHERE_FILTER, $filter_scope = kDBList::FLT_SYSTEM) + public function addFilter($name, $clause, $filter_type = self::WHERE_FILTER, $filter_scope = self::FLT_SYSTEM) { - $filter_source = Array( kDBList::WHERE_FILTER => 'WhereFilter', - kDBList::HAVING_FILTER => 'HavingFilter', - kDBList::AGGREGATE_FILTER => 'AggregateFilter'); + $filter_source = Array ( + self::WHERE_FILTER => 'WhereFilter', + self::HAVING_FILTER => 'HavingFilter', + self::AGGREGATE_FILTER => 'AggregateFilter' + ); + $filter_name = $filter_source[$filter_type]; $filter =& $this->$filter_name; $filter =& $filter[$filter_scope]; - $filter->addFilter($name,$clause); + /* @var $filter kMultipleFilter */ + + $filter->addFilter($name, $clause); } /** @@ -325,17 +330,23 @@ * @param string $name filter name (for internal use) * @param int $filter_type is filter having filter or where filter * @param int $filter_scope filter subtype: FLT_NORMAL,FLT_SYSTEM,FLT_SEARCH,FLT_VIEW,FLT_CUSTOM + * @return string * @access public */ - public function getFilter($name, $filter_type = kDBList::WHERE_FILTER, $filter_scope = kDBList::FLT_SYSTEM) + public function getFilter($name, $filter_type = self::WHERE_FILTER, $filter_scope = self::FLT_SYSTEM) { - $filter_source = Array( kDBList::WHERE_FILTER => 'WhereFilter', - kDBList::HAVING_FILTER => 'HavingFilter', - kDBList::AGGREGATE_FILTER => 'AggregateFilter'); + $filter_source = Array ( + self::WHERE_FILTER => 'WhereFilter', + self::HAVING_FILTER => 'HavingFilter', + self::AGGREGATE_FILTER => 'AggregateFilter' + ); + $filter_name = $filter_source[$filter_type]; $filter =& $this->$filter_name; $filter =& $filter[$filter_scope]; + /* @var $filter kMultipleFilter */ + return $filter->getFilter($name); } @@ -347,15 +358,20 @@ * @param int $filter_scope filter subtype: FLT_NORMAL,FLT_SYSTEM,FLT_SEARCH,FLT_VIEW,FLT_CUSTOM * @access public */ - public function removeFilter($name, $filter_type = kDBList::WHERE_FILTER, $filter_scope = kDBList::FLT_SYSTEM) + public function removeFilter($name, $filter_type = self::WHERE_FILTER, $filter_scope = self::FLT_SYSTEM) { - $filter_source = Array( kDBList::WHERE_FILTER => 'WhereFilter', - kDBList::HAVING_FILTER => 'HavingFilter', - kDBList::AGGREGATE_FILTER => 'AggregateFilter'); + $filter_source = Array ( + self::WHERE_FILTER => 'WhereFilter', + self::HAVING_FILTER => 'HavingFilter', + self::AGGREGATE_FILTER => 'AggregateFilter' + ); + $filter_name = $filter_source[$filter_type]; $filter =& $this->$filter_name; $filter =& $filter[$filter_scope]; + /* @var $filter kMultipleFilter */ + $filter->removeFilter($name); } @@ -464,13 +480,14 @@ } /** - * Queries the database with SQL resulted from {@link kDBList::GetSelectSQL()} and stores result in {@link kDBList::SelectRS} - * - * All the sorting, pagination, filtration of the list should be set prior to calling Query(). - * - * @param bool $force force re-query, when already queried - * @access public - */ + * Queries the database with SQL resulted from {@link kDBList::GetSelectSQL()} and stores result in {@link kDBList::SelectRS} + * + * All the sorting, pagination, filtration of the list should be set prior to calling Query(). + * + * @param bool $force force re-query, when already queried + * @return bool + * @access public + */ public function Query($force=false) { if (!$force && $this->Queried) return true; @@ -640,13 +657,16 @@ */ function GetFormattedTotal($field, $total_function) { - $val = $this->getTotal($field, $total_function); - $options = $this->GetFieldOptions($field); - $res = $val; - if (isset($options['formatter'])) { - $formatter =& $this->Application->recallObject($options['formatter']); - $res = $formatter->Format($val, $field, $this ); + $res = $this->getTotal($field, $total_function); + $formatter_class = $this->GetFieldOption($field, 'formatter'); + + if ( $formatter_class ) { + $formatter =& $this->Application->recallObject($formatter_class); + /* @var $formatter kFormatter */ + + $res = $formatter->Format($res, $field, $this); } + return $res; } @@ -707,22 +727,25 @@ private function GetWhereClause($for_counting=false,$system_filters_only=false) { $where =& $this->Application->makeClass('kMultipleFilter'); + /* @var $where kMultipleFilter */ + + $where->addFilter('system_where', $this->WhereFilter[self::FLT_SYSTEM] ); - $where->addFilter('system_where', $this->WhereFilter[kDBList::FLT_SYSTEM] ); + if (!$system_filters_only) { + $where->addFilter('view_where', $this->WhereFilter[self::FLT_VIEW] ); + $search_w = $this->WhereFilter[self::FLT_SEARCH]->getSQL(); - if (!$system_filters_only) { - $where->addFilter('view_where', $this->WhereFilter[kDBList::FLT_VIEW] ); - $search_w = $this->WhereFilter[kDBList::FLT_SEARCH]->getSQL(); if ($search_w || $for_counting) { // move search_having to search_where in case search_where isset or we are counting - $search_h = $this->extractCalculatedFields( $this->HavingFilter[kDBList::FLT_SEARCH]->getSQL() ); + $search_h = $this->extractCalculatedFields( $this->HavingFilter[self::FLT_SEARCH]->getSQL() ); $search_w = ($search_w && $search_h) ? $search_w.' OR '.$search_h : $search_w.$search_h; $where->addFilter('search_where', $search_w ); } // CUSTOM - $search_w = $this->WhereFilter[kDBList::FLT_CUSTOM]->getSQL(); + $search_w = $this->WhereFilter[self::FLT_CUSTOM]->getSQL(); + if ($search_w || $for_counting) { // move search_having to search_where in case search_where isset or we are counting - $search_h = $this->extractCalculatedFields( $this->HavingFilter[kDBList::FLT_CUSTOM]->getSQL() ); + $search_h = $this->extractCalculatedFields( $this->HavingFilter[self::FLT_CUSTOM]->getSQL() ); $search_w = ($search_w && $search_h) ? $search_w.' AND '.$search_h : $search_w.$search_h; $where->addFilter('custom_where', $search_w ); } @@ -751,6 +774,8 @@ { if ($for_counting) { $aggregate_filter =& $this->Application->makeClass('kMultipleFilter'); + /* @var $aggregate_filter kMultipleFilter */ + $aggregate_filter->addFilter('aggregate_system', $this->AggregateFilter[kDBList::FLT_SYSTEM]); if (!$system_filters_only) { $aggregate_filter->addFilter('aggregate_view', $this->AggregateFilter[kDBList::FLT_VIEW]); @@ -759,6 +784,7 @@ } $having =& $this->Application->makeClass('kMultipleFilter'); + /* @var $having kMultipleFilter */ $having->addFilter('system_having', $this->HavingFilter[kDBList::FLT_SYSTEM] ); if ($aggregated == 0) { @@ -1283,6 +1309,7 @@ * @param string $error_label * @param Array $error_params * @access public + * @todo Might not work correctly! */ public function SetError($field, $pseudo, $error_label = null, $error_params = null) { Index: kernel/event_handler.php =================================================================== --- kernel/event_handler.php (revision 14590) +++ kernel/event_handler.php (working copy) @@ -149,12 +149,13 @@ } /** - * Apply some special processing to object beeing + * Apply some special processing to object being * recalled before using it in other events that * call prepareObject * - * @param kDBBase $object + * @param kDBItem|kDBList $object * @param kEvent $event + * @return void * @access protected */ protected function prepareObject(&$object, &$event) @@ -166,9 +167,8 @@ * Checks user permission to execute given $event * * @param kEvent $event + * @return bool * @access public - * - * @return bool */ public function CheckPermission(&$event) { Index: kernel/event_manager.php =================================================================== --- kernel/event_manager.php (revision 14590) +++ kernel/event_manager.php (working copy) @@ -350,7 +350,9 @@ public function setEvent($prefix_special,$event_name) { $actions =& $this->Application->recallObject('kActions'); - $actions->Set('events['.$prefix_special.']',$event_name); + /* @var $actions Params */ + + $actions->Set('events[' . $prefix_special . ']', $event_name); } /** Index: kernel/globals.php =================================================================== --- kernel/globals.php (revision 14590) +++ kernel/globals.php (working copy) @@ -88,20 +88,21 @@ public static function print_r($data, $label = '', $on_screen = false) { $is_debug = false; - if (class_exists('kApplication') && !$on_screen) { + + if ( class_exists('kApplication') && !$on_screen ) { $application =& kApplication::Instance(); $is_debug = $application->isDebugMode(); } - if ($is_debug) { - if ($label) { + if ( $is_debug && isset($application) ) { + if ( $label ) { $application->Debugger->appendHTML('' . $label . ''); } $application->Debugger->dumpVars($data); } else { - if ($label) { + if ( $label ) { echo '' . $label . '
'; } @@ -316,6 +317,9 @@ * * @param string $url * @param mixed $data + * @param Array $headers + * @param string $request_type + * @param Array $curl_options * @return string * @access public * @deprecated Index: kernel/managers/cache_manager.php =================================================================== --- kernel/managers/cache_manager.php (revision 14590) +++ kernel/managers/cache_manager.php (working copy) @@ -239,7 +239,6 @@ unset($cache); return true; - } if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) { Index: kernel/managers/request_manager.php =================================================================== --- kernel/managers/request_manager.php (revision 14590) +++ kernel/managers/request_manager.php (working copy) @@ -97,9 +97,12 @@ } /** - * Creates and runs event + * Creates and runs event. Returns false, when prefix of given event isn't registered * - * @return kEvent + * @param string $prefix_special + * @param string $event_name + * + * @return kEvent|false * @access protected */ protected function &runEvent($prefix_special, $event_name) @@ -113,7 +116,9 @@ } if ( !$this->Application->EventManager->verifyEventPrefix($event, true) ) { - return ; + $false = false; + + return $false; } $event->setEventParam('top_prefix', $this->Application->GetTopmostPrefix($event->Prefix, true)); @@ -121,7 +126,7 @@ $event_handler =& $this->Application->recallObject($event->Prefix . '_EventHandler'); /* @var $event_handler kEventHandler */ - if (($this->Application->RecallVar('user_id') == USER_ROOT) || $event_handler->CheckPermission($event)) { + if ( ($this->Application->RecallVar('user_id') == USER_ROOT) || $event_handler->CheckPermission($event) ) { $this->Application->HandleEvent($event); } Index: kernel/managers/url_manager.php =================================================================== --- kernel/managers/url_manager.php (revision 14590) +++ kernel/managers/url_manager.php (working copy) @@ -261,6 +261,8 @@ } $session =& $this->Application->recallObject('Session'); + /* @var $session Session */ + $ssl = isset($params['__SSL__']) ? $params['__SSL__'] : 0; $sid = $session->NeedQueryString() && !$this->Application->RewriteURLs($ssl) ? $this->Application->GetSID() : ''; // if (getArrayValue($params,'admin') == 1) $sid = $this->Application->GetSID(); @@ -495,39 +497,46 @@ * @param string $prefix_special item's prefix & [special] * @param Array $params url params * @param bool $pass_events + * @return string + * @access protected */ - function BuildModuleEnv($prefix_special, &$params, $pass_events = false) + protected function BuildModuleEnv($prefix_special, &$params, $pass_events = false) { list($prefix) = explode('.', $prefix_special); - $query_vars = $this->Application->getUnitOption($prefix, 'QueryString'); + $query_vars = $this->Application->getUnitOption($prefix, 'QueryString', Array ()); + /* @var $query_vars Array */ - //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 + //if pass events is off and event is not implicitly 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 ''; + if ( !$query_vars ) { + return ''; + } - $tmp_string = Array(0 => $prefix_special); - foreach($query_vars as $index => $var_name) - { + $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->Application->GetVar($var_name); - if ( isset($params[$var_name]) ) unset( $params[$var_name] ); + $var_name = $prefix_special . '_' . $var_name; + $tmp_string[$index] = isset($params[$var_name]) ? $params[$var_name] : $this->Application->GetVar($var_name); + + if ( isset($params[$var_name]) ) { + unset($params[$var_name]); + } } - $escaped = array(); + $escaped = array (); foreach ($tmp_string as $tmp_val) { - $escaped[] = str_replace(Array('-',':'), Array('\-','\:'), $tmp_val); + $escaped[] = str_replace(Array ('-', ':'), Array ('\-', '\:'), $tmp_val); } $ret = implode('-', $escaped); - if ($this->Application->getUnitOption($prefix, 'PortalStyleEnv') == true) - { - $ret = preg_replace('/^([a-zA-Z]+)-([0-9]+)-(.*)/','\\1\\2-\\3', $ret); + if ( $this->Application->getUnitOption($prefix, 'PortalStyleEnv') == true ) { + $ret = preg_replace('/^([a-zA-Z]+)-([0-9]+)-(.*)/', '\\1\\2-\\3', $ret); } + return $ret; } Index: kernel/nparser/nparser.php =================================================================== --- kernel/nparser/nparser.php (revision 14590) +++ kernel/nparser/nparser.php (working copy) @@ -64,6 +64,13 @@ var $Cachable = Array (); /** + * Deep level during parsing + * + * @var int + */ + var $CacheLevel = 0; + + /** * Caching in templates enabled * * @var bool @@ -570,27 +577,49 @@ } } + /** + * Creates tag processor and stores it in local cache + factory + * + * @param string $prefix + * @return kTagProcessor + */ function &GetProcessor($prefix) { - static $Processors = array(); - if (!isset($Processors[$prefix])) { - $Processors[$prefix] = $this->Application->recallObject($prefix.'_TagProcessor'); + static $processors = Array (); + + if ( !isset($processors[$prefix]) ) { + $processors[$prefix] = $this->Application->recallObject($prefix . '_TagProcessor'); } - return $Processors[$prefix]; + return $processors[$prefix]; } - function SelectParam($params, $possible_names) + /** + * Not tag. Method for parameter selection from list in this TagProcessor + * + * @param Array $params + * @param Array $possible_names + * + * @return string + * @access protected + */ + protected function SelectParam($params, $possible_names) { - if (!is_array($params)) return; - if (!is_array($possible_names)) + if ( !is_array($params) ) { + return ''; + } - $possible_names = explode(',', $possible_names); - foreach ($possible_names as $name) - { - if( isset($params[$name]) ) return $params[$name]; + if ( !is_array($possible_names) ) { + $possible_names = explode(',', $possible_names); } - return false; + + foreach ($possible_names as $name) { + if ( isset($params[$name]) ) { + return $params[$name]; + } + } + + return ''; } function SetParams($params) Index: kernel/nparser/template_cache.php =================================================================== --- kernel/nparser/template_cache.php (revision 14590) +++ kernel/nparser/template_cache.php (working copy) @@ -416,29 +416,32 @@ * * @param string $dir * @param string $base_path base path to directory where folders should be created in + * @return bool + * @access protected */ - function CheckDir($dir, $base_path = '') + protected function CheckDir($dir, $base_path = '') { - if (file_exists($dir)) { + if ( file_exists($dir) ) { return true; } - 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; + // remove $base_path from beginning because it is already created during install + $dir = preg_replace('/^' . preg_quote($base_path . '/', '/') . '/', '', $dir, 1); + $segments = explode('/', $dir); + $cur_path = $base_path; - if ( !file_exists($cur_path) ) { - if ( !mkdir($cur_path) ) { - return false; - } + 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) ) { + if ( !mkdir($cur_path) ) { + return false; } } } + + return false; } } \ No newline at end of file Index: kernel/processors/main_processor.php =================================================================== --- kernel/processors/main_processor.php (revision 14590) +++ kernel/processors/main_processor.php (working copy) @@ -165,7 +165,7 @@ { $t = $params['template']; unset($params['template']); - return $this->Application->BuildEnv($t, $params, 'm', null, false); + return $this->Application->BuildEnv($t, $params, 'm', false, false); } function FormAction($params) @@ -415,14 +415,17 @@ function DumpSystemInfo($params) { $actions =& $this->Application->recallObject('kActions'); - $actions->Set('t', $this->Application->GetVar('t') ); + /* @var $actions Params */ + $actions->Set('t', $this->Application->GetVar('t')); + + $o = ''; $params = $actions->GetParams(); - $o=''; - foreach ($params AS $name => $val) - { + + foreach ($params AS $name => $val) { $o .= "\n"; } + return $o; } @@ -439,22 +442,24 @@ unset($params['template']); $form_fields = Array (); - if ($this->Application->RewriteURLs()) { + if ( $this->Application->RewriteURLs() ) { $session =& $this->Application->recallObject('Session'); - if ($session->NeedQueryString()) { + /* @var $session Session */ + + if ( $session->NeedQueryString() ) { $form_fields['sid'] = $this->Application->GetSID(); } } else { - $form_fields['env'] = $this->Application->BuildEnv($t, $params, 'm', null, false); + $form_fields['env'] = $this->Application->BuildEnv($t, $params, 'm', false, false); } - if ($this->Application->GetVar('admin') == 1) { + if ( $this->Application->GetVar('admin') == 1 ) { $form_fields['admin'] = 1; } $ret = ''; - $field_tpl = ''."\n"; + $field_tpl = '' . "\n"; foreach ($form_fields as $form_field => $field_value) { $ret .= sprintf($field_tpl, $form_field, $field_value); } @@ -572,22 +577,18 @@ } /** - * Checks if application variable - * specified by name value match - * value passed as parameter + * Checks if application variable specified by name value match value passed as parameter * * @param Array $params * @return bool - * @access public + * @access protected + * @deprecated */ - function GetEquals($params) + protected function GetEquals($params) { $name = $this->SelectParam($params, 'var,name,param'); - $value = $params['value']; - if ($this->Application->GetVar($name) == $value) { - return 1; - } + return $this->Application->GetVar($name) == $params['value']; } function ModuleInclude($params) @@ -722,6 +723,8 @@ function CheckPermission($params) { $perm_helper =& $this->Application->recallObject('PermissionsHelper'); + /* @var $perm_helper kPermissionsHelper */ + return $perm_helper->TagPermissionCheck($params); } @@ -842,44 +845,46 @@ { $ssl = $this->Application->isAdmin ? $this->Application->ConfigValue('AdminSSL_URL') : false; - if (!$ssl) { + if ( !$ssl ) { // not in admin or admin ssl url is empty $ssl_url = $this->Application->siteDomainField('SSLUrl'); $ssl = $ssl_url !== false ? $ssl_url : $this->Application->ConfigValue('SSL_URL'); } - if (!$ssl || ($this->Application->TemplatesCache->forceThemeName !== false)) { + if ( !$ssl || ($this->Application->TemplatesCache->forceThemeName !== false) ) { // SSL URL is not set - no way to require SSL // internal parsing (e.g. "TemplateParser::_parseTemplate") -> don't redirect - return ; + return; } $require = false; - if (isset($params['mode']) && $params['mode'] == 'required') { + if ( isset($params['mode']) && $params['mode'] == 'required' ) { $require = true; - if (isset($params['for_logged_in_only']) && $params['for_logged_in_only'] && !$this->Application->LoggedIn()) { + 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'])) { + if ( isset($params['condition']) ) { + if ( !$this->Application->ConfigValue($params['condition']) ) { $require = false; } } } - if (EDITING_MODE) { + if ( EDITING_MODE ) { // match SSL mode on front-end to one in administrative console, when browse modes are used $require = $this->Application->ConfigValue('Require_AdminSSL'); } $http_query =& $this->Application->recallObject('HTTPQuery'); + /* @var $http_query kHTTPQuery */ + $pass = $http_query->getRedirectParams(); $pass['pass_events'] = 1; // to make sure all events are passed when redirect happens - if ($require) { - if (PROTOCOL == 'https://') { + if ( $require ) { + if ( PROTOCOL == 'https://' ) { $this->Application->SetVar('__KEEP_SSL__', 1); return; } @@ -888,8 +893,11 @@ $this->Application->Redirect('', $pass); } else { - if (PROTOCOL == 'https://' && $this->Application->ConfigValue('Force_HTTP_When_SSL_Not_Required')) { - if ($this->Application->GetVar('__KEEP_SSL__')) return; + if ( PROTOCOL == 'https://' && $this->Application->ConfigValue('Force_HTTP_When_SSL_Not_Required') ) { + if ( $this->Application->GetVar('__KEEP_SSL__') ) { + return; + } + // $pass_more = Array ('pass' => 'm', 'm_cat_id' => 0, '__SSL__' => 0); $pass['__SSL__'] = 0; $this->Application->Redirect('', $pass); // $pass_more @@ -913,29 +921,30 @@ { $this->NoDebug($params); - if (isset($params['cache']) && $params['cache']) { + 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'; + $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'); + header('Cache-Control: public, cache, max-age=' . $params['cache']); + header("Expires: $expiration"); + header('Pragma: public'); // Getting headers sent by the client. $headers = $this->_requestHeaders(); // 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); + 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); + } } // xml documents are usually long @@ -947,6 +956,8 @@ } $lang =& $this->Application->recallObject('lang.current'); + /* @var $lang LanguagesItem */ + header('Content-type: text/html; charset=' . $lang->GetDBField('Charset')); return ''; Index: kernel/processors/tag_processor.php =================================================================== --- kernel/processors/tag_processor.php (revision 14590) +++ kernel/processors/tag_processor.php (working copy) @@ -35,7 +35,7 @@ /** * Processes tag * - * @param Tag $tag + * @param _BlockTag $tag * @return string * @access public */ @@ -44,23 +44,36 @@ return $this->ProcessParsedTag($tag->Tag, $tag->NP, $tag->getPrefixSpecial()); } - function CheckTag($tag, $prefix) + /** + * Checks, that tag is implemented in this tag processor + * + * @param string $tag + * @param string $prefix + * + * @return bool + * @access public + */ + public function CheckTag($tag, $prefix) { - $Method = $tag; - if(method_exists($this, $Method)) - { + $method = $tag; + + if ( method_exists($this, $method) ) { return true; } - else { - if ($this->Application->hasObject('TagsAggregator')) { - $aggregator =& $this->Application->recallObject('TagsAggregator'); - $tmp = $this->Application->processPrefix($prefix); - $tag_mapping = $aggregator->GetArrayValue($tmp['prefix'], $Method); - if ($tag_mapping) { - return true; - } + + if ( $this->Application->hasObject('TagsAggregator') ) { + $aggregator =& $this->Application->recallObject('TagsAggregator'); + /* @var $aggregator kArray */ + + $tmp = $this->Application->processPrefix($prefix); + $tag_mapping = $aggregator->GetArrayValue($tmp['prefix'], $method); + + if ( $tag_mapping ) { + return true; } } + + return false; } function FormCacheKey($tag, $params, $prefix) @@ -84,6 +97,7 @@ list ($prefix_only, ) = explode('.', $prefix); $this->Application->Parser->PrefixesInUse[$prefix_only] = 1; + $cache_key = ''; $backup_prefix = $this->Prefix; $backup_special = $this->Special; @@ -133,15 +147,18 @@ function processAggregatedTag($tag, $params, $prefix, $file = 'unknown', $line = 0) { - if ($this->Application->hasObject('TagsAggregator')) { + if ( $this->Application->hasObject('TagsAggregator') ) { $Method = $tag; $aggregator =& $this->Application->recallObject('TagsAggregator'); + /* @var $aggregator kArray */ + $tmp = $this->Application->processPrefix($prefix); $tag_mapping = $aggregator->GetArrayValue($tmp['prefix'], $Method); - if ($tag_mapping) { + + if ( $tag_mapping ) { // aggregated tag defined $tmp = $this->Application->processPrefix($tag_mapping[0]); - $__tag_processor = $tmp['prefix'].'_TagProcessor'; + $__tag_processor = $tmp['prefix'] . '_TagProcessor'; $processor =& $this->Application->recallObject($__tag_processor); /* @var $processor kTagProcessor */ @@ -151,7 +168,7 @@ $params['original_tag'] = $Method; // allows to define same method for different aggregated tags in same tag processor $params['PrefixSpecial'] = $this->getPrefixSpecial(); // $prefix; $ret = $processor->ProcessParsedTag($tag_mapping[1], $params, $prefix); - if (isset($params['result_to_var'])) { + if ( isset($params['result_to_var']) ) { $this->Application->Parser->SetParam($params['result_to_var'], $ret); $ret = ''; } @@ -213,46 +230,46 @@ } - /** - * Not tag, method for parameter - * selection from list in this TagProcessor - * - * @param Array $params - * @param string $possible_names - * @return string - * @access public - */ - function SelectParam($params, $possible_names = null) - { - if (!isset($possible_names)) { - // select 1st parameter non-empty parameter value - $possible_names = explode(',', $params['possible_names']); - foreach ($possible_names as $param_name) { - $value = $this->Application->Parser->GetParam($param_name); - if (((string)$value != '') && ((string)$value != '0')) { - return $value; + /** + * Not tag, method for parameter + * selection from list in this TagProcessor + * + * @param Array $params + * @param string $possible_names + * @return string|bool + * @access protected + */ + protected function SelectParam($params, $possible_names = null) + { + if ( !isset($possible_names) ) { + // select 1st parameter non-empty parameter value + $possible_names = explode(',', $params['possible_names']); + + foreach ($possible_names as $param_name) { + $value = $this->Application->Parser->GetParam($param_name); + $string_value = (string)$value; + + if ( ($string_value != '') && ($string_value != '0') ) { + return $value; + } } + + return false; } - return ''; - } + if ( !is_array($possible_names) ) { + $possible_names = explode(',', $possible_names); + } - if (!is_array($params)) { - // really happens? - return; - } + foreach ($possible_names as $name) { + if ( isset($params[$name]) ) { + return $params[$name]; + } + } - if (!is_array($possible_names)) { - $possible_names = explode(',', $possible_names); + return false; } - foreach ($possible_names as $name) { - if( isset($params[$name]) ) return $params[$name]; - } - - return false; - } - /** * Returns templates path for module, which is gathered from prefix module * Index: kernel/session/inp_session.php =================================================================== --- kernel/session/inp_session.php (revision 14590) +++ kernel/session/inp_session.php (working copy) @@ -16,6 +16,14 @@ class InpSession extends Session { + /** + * Enter description here... + * + * @var InpSessionStorage + * @access protected + */ + protected $Storage; + public function Init($prefix, $special) { $this->SessionTimeout = $this->Application->ConfigValue('SessionTimeout'); @@ -24,40 +32,49 @@ $this->SetCookiePath($path); $cookie_name = $this->Application->ConfigValue('SessionCookieName'); - if (!$cookie_name) { + + if ( !$cookie_name ) { $cookie_name = 'sid'; } $admin_session = ($this->Application->isAdmin && $special !== 'front') || ($special == 'admin'); - if ($admin_session) { + if ( $admin_session ) { $cookie_name = 'adm_' . $cookie_name; } $this->SetCookieName($cookie_name); - $this->SetCookieDomain(SERVER_NAME); - if ($admin_session) { + if ( $admin_session ) { $mode = self::smAUTO; } - elseif (defined('IS_INSTALL') && IS_INSTALL) { + elseif ( defined('IS_INSTALL') && IS_INSTALL ) { $mode = self::smCOOKIES_ONLY; } else { $ses_mode = $this->Application->ConfigValue('CookieSessions'); - if ($ses_mode == 2) $mode = self::smAUTO; - if ($ses_mode == 1) $mode = self::smCOOKIES_ONLY; - if ($ses_mode == 0) $mode = self::smGET_ONLY; + if ( $ses_mode == 2 ) { + $mode = self::smAUTO; + } + elseif ( $ses_mode == 1 ) { + $mode = self::smCOOKIES_ONLY; + } + elseif ( $ses_mode == 0 ) { + $mode = self::smGET_ONLY; + } + else { + $mode = self::smAUTO; + } } $this->SetMode($mode); parent::Init($prefix, $special); - if (!$this->Application->isAdmin && $this->GetField('PortalUserId') <= 0) { - $group_list = $this->Application->ConfigValue('User_GuestGroup').','.$this->Application->ConfigValue('User_LoggedInGroup'); + if ( !$this->Application->isAdmin && $this->GetField('PortalUserId') <= 0 ) { + $group_list = $this->Application->ConfigValue('User_GuestGroup') . ',' . $this->Application->ConfigValue('User_LoggedInGroup'); $this->SetField('GroupId', $this->Application->ConfigValue('User_GuestGroup')); $this->SetField('GroupList', $group_list); } Index: kernel/session/session.php =================================================================== --- kernel/session/session.php (revision 14590) +++ kernel/session/session.php (working copy) @@ -111,8 +111,9 @@ * Enter description here... * * @var SessionStorage + * @access protected */ - var $Storage; + protected $Storage; var $CachedNeedQueryString = null; @@ -338,26 +339,28 @@ function CheckIfCookiesAreOn() { - if ($this->Mode == self::smGET_ONLY) { + if ( $this->Mode == self::smGET_ONLY ) { //we don't need to bother checking if we would not use it $this->CookiesEnabled = false; - return; + return false; } $http_query =& $this->Application->recallObject('HTTPQuery'); + /* @var $http_query kHTTPQuery */ + $cookies_on = array_key_exists('cookies_on', $http_query->Cookie); // not good here $get_sid = getArrayValue($http_query->Get, $this->GETName); - if (($this->IsHTTPSRedirect() && $get_sid) || $this->getFlashSID()) { // Redirect from http to https on different domain OR flash uploader + if ( ($this->IsHTTPSRedirect() && $get_sid) || $this->getFlashSID() ) { // Redirect from http to https on different domain OR flash uploader $this->OriginalMode = $this->Mode; $this->SetMode(self::smGET_ONLY); } - if (!$cookies_on || $this->IsHTTPSRedirect() || $this->getFlashSID()) { + if ( !$cookies_on || $this->IsHTTPSRedirect() || $this->getFlashSID() ) { //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->_checkCookieReferer() && !$this->Application->GetVar('admin') && !$this->IsHTTPSRedirect()) { + if ( !$is_install && $this->_checkCookieReferer() && !$this->Application->GetVar('admin') && !$this->IsHTTPSRedirect() ) { $this->CookiesEnabled = false; } else { @@ -476,6 +479,8 @@ if (!$get_sid) { $http_query =& $this->Application->recallObject('HTTPQuery'); + /* @var $http_query kHTTPQuery */ + $get_sid = getArrayValue($http_query->Get, $this->GETName); } Index: kernel/session/session_storage.php =================================================================== --- kernel/session/session_storage.php (revision 14590) +++ kernel/session/session_storage.php (working copy) @@ -110,15 +110,23 @@ return array_merge($fields_hash, $this->DirectVars); } - function StoreSession($to_database = true) + /** + * Stores session to database + * + * @param bool $to_database + * + * @return void + * @access public + */ + public function StoreSession($to_database = true) { - if (defined('IS_INSTALL') && IS_INSTALL && $to_database && !$this->Application->TableFound($this->TableName)) { - return false; + if ( defined('IS_INSTALL') && IS_INSTALL && $to_database && !$this->Application->TableFound($this->TableName) ) { + return; } $fields_hash = $this->GetSessionDefaults(); - if ($to_database) { + if ( $to_database ) { $this->Conn->doInsert($fields_hash, $this->TableName); } @@ -206,39 +214,48 @@ //return $this->Conn->Query('UPDATE '.$this->TableName.' SET '.$var_name.' = '.$this->Conn->qstr($value).' WHERE '.$this->IDField.' = '.$this->Conn->qstr($this->Session->GetID()) ); } - function SaveData() + /** + * Saves changes in session to database using single REPLACE query + * + * @return void + * @access public + */ + public function SaveData() { - if(!$this->Session->SID) return false; // can't save without sid + if ( !$this->Session->SID ) { + // can't save without sid + return ; + } + $replace = ''; $ses_data = $this->Session->Data->GetParams(); - $replace = ''; - foreach ($ses_data as $key => $value) - { - if ( isset($this->OriginalData[$key]) && $this->OriginalData[$key] == $value) - { + 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($this->Session->SID), - $this->Conn->qstr($key), - $this->Conn->qstr($value)); + else { + $replace .= sprintf("(%s, %s, %s),", $this->Conn->qstr($this->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; + + if ( $replace != '' ) { + $query = ' REPLACE INTO ' . $this->SessionDataTable . ' (' . $this->IDField . ', ' . $this->DataVarField . ', ' . $this->DataValueField . ') VALUES ' . $replace; $this->Conn->Query($query); } - if ($this->ChangedDirectVars) { - $changes = array(); + if ( $this->ChangedDirectVars ) { + $changes = Array (); + foreach ($this->ChangedDirectVars as $var) { - $changes[] = $var.' = '.$this->Conn->qstr($this->DirectVars[$var]); + $changes[] = $var . ' = ' . $this->Conn->qstr($this->DirectVars[$var]); } - $query = 'UPDATE '.$this->TableName.' SET '.implode(',', $changes).' WHERE '.$this->IDField.' = '.$this->Conn->qstr($this->Session->GetID()); + + $query = ' UPDATE ' . $this->TableName . ' + SET ' . implode(',', $changes) . ' + WHERE ' . $this->IDField . ' = ' . $this->Conn->qstr($this->Session->GetID()); $this->Conn->Query($query); } } Index: kernel/utility/debugger.php =================================================================== --- kernel/utility/debugger.php (revision 14590) +++ kernel/utility/debugger.php (working copy) @@ -156,7 +156,7 @@ var $Application = null; /** - * Set to true if fatal error occured + * Set to true if fatal error occurred * * @var bool */ @@ -358,18 +358,20 @@ function InitReport() { - if (!class_exists('kApplication')) return false; + if ( !class_exists('kApplication') ) { + return ; + } $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).'@'; + $this->rowSeparator = '@' . (is_object($application->Factory) ? $application->GetSID() : 0) . '@'; // $this->rowSeparator = '@'.rand(0,100000).'@'; // include debugger files from this url - $reg_exp = '/^'.preg_quote(FULL_PATH, '/').'/'; + $reg_exp = '/^' . preg_quote(FULL_PATH, '/') . '/'; $kernel_path = preg_replace($reg_exp, '', KERNEL_PATH, 1); - $this->baseURL = PROTOCOL.SERVER_NAME.(defined('PORT') ? ':'.PORT : '').rtrim(BASE_PATH, '/').$kernel_path.'/utility/debugger'; + $this->baseURL = PROTOCOL . SERVER_NAME . (defined('PORT') ? ':' . PORT : '') . rtrim(BASE_PATH, '/') . $kernel_path . '/utility/debugger'; // save debug output in this folder $this->tempFolder = defined('RESTRICTED') ? RESTRICTED : WRITEABLE . '/cache'; @@ -977,6 +979,8 @@ if (array_key_exists('object', $trace_results[$i + 1]) && isset($trace_results[$i + 1]['object']->Prefix)) { $object =& $trace_results[$i + 1]['object']; + /* @var $object kBase */ + $prefix_special = rtrim($object->Prefix . '.' . $object->Special, '.'); $this->ProfilerData[$key]['prefix_special'] = $prefix_special; } @@ -1154,8 +1158,13 @@ /** * Generates report * + * @param bool $returnResult + * @param bool $clean_output_buffer + * + * @return string + * @access public */ - function printReport($returnResult = false, $clean_output_buffer = true) + public 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) @@ -1192,7 +1201,7 @@ $this->appendHTML($this->highlightString($this->print_r($this->ProfilePoints, true))); /*foreach ($this->ProfilePoints as $point => $locations) { - foreach ($locations as $location => $occurences) { + foreach ($locations as $location => $occurrences) { } @@ -1338,6 +1347,8 @@ $this->reportDone = true; } + + return ''; } /** @@ -1402,13 +1413,16 @@ /** * User-defined error handler * + * @throws Exception * @param int $errno * @param string $errstr * @param string $errfile * @param int $errline * @param array $errcontext + * @return bool + * @access public */ - function saveError($errno, $errstr, $errfile = '', $errline = '', $errcontext = '') + public function saveError($errno, $errstr, $errfile = null, $errline = null, $errcontext = Array ()) { $this->ProfilerData['error_handling']['begins'] = memory_get_usage(); @@ -1425,7 +1439,7 @@ } if ( DebuggerUtil::constOn('DBG_IGNORE_STRICT_ERRORS') && defined('E_STRICT') && ($errno == E_STRICT) ) { - return ; + return false; } $this->expandError($errstr, $errfile, $errline); @@ -1446,14 +1460,18 @@ // append debugger report to data in buffer & clean buffer afterwards die( $this->breakOutofBuffering(false) . $this->printReport(true) ); } + + return true; } /** * User-defined exception handler * - * @param Exception $errno + * @param Exception $exception + * @return void + * @access public */ - function saveException($exception) + public function saveException($exception) { $this->ProfilerData['error_handling']['begins'] = memory_get_usage(); @@ -1534,9 +1552,16 @@ $this->appendHTML($ret); } - function AttachToApplication() { - if (!DebuggerUtil::constOn('DBG_HANDLE_ERRORS')) { - return true; + /** + * Attaches debugger to Application + * + * @return void + * @access public + */ + public function AttachToApplication() + { + if ( !DebuggerUtil::constOn('DBG_HANDLE_ERRORS') ) { + return; } if ( class_exists('kApplication') ) { @@ -1551,8 +1576,8 @@ $this->Application->exceptionHandlers[] = Array (&$this, 'saveException'); } else { - set_error_handler( Array(&$this, 'saveError') ); - set_exception_handler( Array(&$this, 'saveException') ); + set_error_handler( Array (&$this, 'saveError') ); + set_exception_handler( Array (&$this, 'saveException') ); } } Index: kernel/utility/email_send.php =================================================================== --- kernel/utility/email_send.php (revision 14590) +++ kernel/utility/email_send.php (working copy) @@ -1737,25 +1737,31 @@ * * @param string $text * @param bool $multiple - * @param bool $allowOnlyDomain - * @return string + * @param bool $allow_only_domain + * @return Array|bool + * @access public */ - 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'; + public function ExtractRecipientEmail($text, $multiple = false, $allow_only_domain = false) + { + if ( $allow_only_domain ) { + $pattern = '/((' . REGEX_EMAIL_USER . '@)?' . REGEX_EMAIL_DOMAIN . ')/i'; } - if ($multiple) { - if (preg_match_all($pattern, $text, $findemail) >= 1) { - return $findemail[1]; - } else { + else { + $pattern = '/(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')/i'; + } + if ( $multiple ) { + if ( preg_match_all($pattern, $text, $found_emails) >= 1 ) { + return $found_emails[1]; + } + else { return false; } - } else { - if (preg_match($pattern, $text, $findemail) == 1) { - return $findemail[1]; - } else { + } + else { + if ( preg_match($pattern, $text, $found_emails) == 1 ) { + return $found_emails[1]; + } + else { return false; } } Index: kernel/utility/filters.php =================================================================== --- kernel/utility/filters.php (revision 14590) +++ kernel/utility/filters.php (working copy) @@ -45,7 +45,7 @@ * Adds new or replaces old filter with same name * * @param string $name - * @param mixed $clause kMultipleFilter object or where clause ifself + * @param string|kMultipleFilter $clause kMultipleFilter object or where clause itself * @access public */ function addFilter($name, $clause) Index: kernel/utility/formatters/ccdate_formatter.php =================================================================== --- kernel/utility/formatters/ccdate_formatter.php (revision 14590) +++ kernel/utility/formatters/ccdate_formatter.php (working copy) @@ -46,38 +46,55 @@ $object->setVirtualFields($add_fields); } - function UpdateSubFields($field, $value, &$options, &$object) + /** + * Used for split fields like timestamp -> date, time + * Called from DBItem to update sub fields values after loading item + * + * @param string $field + * @param string $value + * @param Array $options + * @param kDBItem $object + * @return void + * @access public + */ + public function UpdateSubFields($field, $value, &$options, &$object) { - if(!$value) return false; + if ( !$value ) { + return ; + } + $date = explode('/', $value); - $object->SetDBField( $options['month_field'], $date[0] ); - $object->SetDBField( $options['year_field'], $date[1] ); + $object->SetDBField($options['month_field'], $date[0]); + $object->SetDBField($options['year_field'], $date[1]); } /** * Will work in future if we could attach 2 formatters to one field * - * @param string $value + * @param mixed $value * @param string $field_name * @param kDBItem $object - * @return string + * @return mixed + * @access public */ - function Parse($value, $field_name, &$object) + public function Parse($value, $field_name, &$object) { -// if ( is_null($value) ) return ''; - $options = $object->GetFieldOptions($field_name); $month = $object->GetDirtyField($options['month_field']); $year = $object->GetDirtyField($options['year_field']); - if( !(int)$month && !(int)$year ) return NULL; + if ( !(int)$month && !(int)$year ) { + return NULL; + } + $is_valid = ($month >= 1 && $month <= 12) && ($year >= 0 && $year <= 99); - if (!$is_valid) { + if ( !$is_valid ) { $object->SetError($field_name, 'bad_type'); } - return $month.'/'.$year; + + return $month . '/' . $year; } } \ No newline at end of file Index: kernel/utility/formatters/customfield_formatter.php =================================================================== --- kernel/utility/formatters/customfield_formatter.php (revision 14590) +++ kernel/utility/formatters/customfield_formatter.php (working copy) @@ -19,6 +19,15 @@ class kCustomFieldFormatter extends kFormatter { + /** + * Formats value of a given field + * + * @param string $value + * @param string $field_name + * @param kDBItem|kDBList $object + * @param string $format + * @return string + */ function Format($value, $field_name, &$object, $format=null) { $options = $object->GetFieldOptions($field_name); Index: kernel/utility/formatters/filesize_formatter.php =================================================================== --- kernel/utility/formatters/filesize_formatter.php (revision 14590) +++ kernel/utility/formatters/filesize_formatter.php (working copy) @@ -14,6 +14,15 @@ class kFilesizeFormatter extends kFormatter { + /** + * Formats value of a given field + * + * @param string $value + * @param string $field_name + * @param kDBItem|kDBList $object + * @param string $format + * @return string + */ function Format($value, $field_name, &$object, $format=null) { if ($value >= 1099511627776) { Index: kernel/utility/formatters/left_formatter.php =================================================================== --- kernel/utility/formatters/left_formatter.php (revision 14590) +++ kernel/utility/formatters/left_formatter.php (working copy) @@ -22,52 +22,74 @@ */ class kLEFTFormatter extends kFormatter { + /** + * Formats value of a given field + * + * @param string $value + * @param string $field_name + * @param kDBItem|kDBList $object + * @param string $format + * @return string + */ function Format($value, $field_name, &$object, $format=null) { - if ( is_null($value) ) return ''; + if ( is_null($value) ) { + return ''; + } $options = $object->GetFieldOptions($field_name); - if ( isset($format) ) $options['format'] = $format; + if ( isset($format) ) { + $options['format'] = $format; + } - if( !isset($options['options'][$value]) ) - { + if ( !isset($options['options'][$value]) ) { // required option is not defined in config => query for it - $sql = sprintf($options['left_sql'],$options['left_title_field'],$options['left_key_field'], $db->escape($value)); + $sql = sprintf($options['left_sql'], $options['left_title_field'], $options['left_key_field'], $this->Conn->escape($value)); $options['options'][$value] = $this->Conn->GetOne($sql); - if ($options['options'][$value] === false) return $value; + + if ( $options['options'][$value] === false ) { + return $value; + } } + return $options['options'][$value]; } /** - * Parse value from form submit + * Performs basic type validation on form field value * * @param mixed $value * @param string $field_name * @param kDBItem $object * @return mixed + * @access public */ - function Parse($value, $field_name, &$object) + public function Parse($value, $field_name, &$object) { - if ($value == '') return NULL; + if ( $value == '' ) { + return NULL; + } $options = $object->GetFieldOptions($field_name); $found = isset($options['options']) ? array_search($value, $options['options']) : false; - if ($found !== false) { + + if ( $found !== false ) { // requested option found among field options return $found; } // requested option is not found in field options -> query for it - $sql = sprintf($options['left_sql'], $options['left_key_field'], $options['left_title_field'], $db->escape($value)); + $sql = sprintf($options['left_sql'], $options['left_key_field'], $options['left_title_field'], $this->Conn->escape($value)); $found = $this->Conn->GetOne($sql); - if ($found !== false) { + + if ( $found !== false ) { // option successfully retrieved from db -> cache it $options['options'][$found] = $value; } $skip_errors = array_key_exists('skip_errors', $options) && $options['skip_errors']; - if ($found === false && !$skip_errors) { + + if ( $found === false && !$skip_errors ) { // option not found at all -> return not formatted value & set error $object->SetError($field_name, 'invalid_option', 'la_error_InvalidOption'); return $value; Index: kernel/utility/formatters/options_formatter.php =================================================================== --- kernel/utility/formatters/options_formatter.php (revision 14590) +++ kernel/utility/formatters/options_formatter.php (working copy) @@ -14,6 +14,15 @@ class kOptionsFormatter extends kFormatter { + /** + * Formats value of a given field + * + * @param string $value + * @param string $field_name + * @param kDBItem|kDBList $object + * @param string $format + * @return string + */ function Format($value, $field_name, &$object, $format=null) { if ( is_null($value) ) { @@ -70,20 +79,31 @@ } } - function Parse($value, $field_name, &$object) + /** + * Performs basic type validation on form field value + * + * @param mixed $value + * @param string $field_name + * @param kDBItem $object + * @return mixed + * @access public + */ + public function Parse($value, $field_name, &$object) { - if ($value == '') return NULL; + if ( $value == '' ) { + return NULL; + } + $found = $option_key = false; $options = $object->GetFieldOptions($field_name); $use_phrases = getArrayValue($options, 'use_phrases'); - $found = false; foreach ($options['options'] as $option_key => $option_value) { - if ($use_phrases) { + if ( $use_phrases ) { $option_value = $this->Application->Phrase($option_value); } - if ($option_value == $value) { + if ( $option_value == $value ) { $found = true; break; } Index: kernel/utility/formatters/password_formatter.php =================================================================== --- kernel/utility/formatters/password_formatter.php (revision 14590) +++ kernel/utility/formatters/password_formatter.php (working copy) @@ -47,6 +47,15 @@ } } + /** + * Formats value of a given field + * + * @param string $value + * @param string $field_name + * @param kDBItem|kDBList $object + * @param string $format + * @return string + */ function Format($value, $field_name, &$object, $format=null) { return $value; @@ -58,16 +67,18 @@ * @param mixed $value * @param string $field_name * @param kDBItem $object - * @return string + * @return mixed + * @access public */ - function Parse($value, $field_name, &$object) + public function Parse($value, $field_name, &$object) { $options = $object->GetFieldOptions($field_name); $flip_count = 0; $fields_set = true; + $password_field = $verify_field = ''; $fields = Array ('master_field', 'verify_field'); - + // 1. collect values from both Password and VerifyPassword fields while ($flip_count < 2) { if ( getArrayValue($options, $fields[0]) ) { Index: kernel/utility/formatters/upload_formatter.php =================================================================== --- kernel/utility/formatters/upload_formatter.php (revision 14590) +++ kernel/utility/formatters/upload_formatter.php (working copy) @@ -41,9 +41,10 @@ * @param mixed $value * @param string $field_name * @param kDBItem $object - * @return string + * @return mixed + * @access public */ - function Parse($value, $field_name, &$object) + public function Parse($value, $field_name, &$object) { $ret = !is_array($value) ? $value : ''; $options = $object->GetFieldOptions($field_name); @@ -194,7 +195,7 @@ * * @param string $value * @param string $field_name - * @param kDBItem $object + * @param kDBItem|kDBList $object * @param string $format * @return string */ Index: kernel/utility/http_query.php =================================================================== --- kernel/utility/http_query.php (revision 14590) +++ kernel/utility/http_query.php (working copy) @@ -407,64 +407,58 @@ function convertFiles() { - if (!$_FILES) - { - return false; + if ( !$_FILES ) { + return ; } - $file_keys = Array('error','name','size','tmp_name','type'); + $tmp = Array (); + $file_keys = Array ('error', 'name', 'size', 'tmp_name', 'type'); - $tmp = Array(); - foreach($_FILES as $file_name => $file_info) - { - if( is_array($file_info['error']) ) - { - $tmp[$file_name] = $this->getArrayLevel( $file_info['error'], $file_name ); + foreach ($_FILES as $file_name => $file_info) { + if ( is_array($file_info['error']) ) { + $tmp[$file_name] = $this->getArrayLevel($file_info['error'], $file_name); } - else - { + else { $normal_files[$file_name] = $file_info; } } - if(!$tmp) return false; + if ( !$tmp ) { + return ; + } $files = $_FILES; - $_FILES = Array(); + $_FILES = Array (); - foreach($tmp as $prefix => $prefix_files) - { + foreach ($tmp as $prefix => $prefix_files) { $anchor =& $_FILES; - foreach($prefix_files['keys'] as $key) - { + foreach ($prefix_files['keys'] as $key) { $anchor =& $anchor[$key]; } - foreach($prefix_files['value'] as $field_name) - { - unset($inner_anchor); - unset($copy); + + foreach ($prefix_files['value'] as $field_name) { + unset($inner_anchor, $copy); $work_copy = $prefix_files['keys']; - foreach($file_keys as $file_key) - { + + foreach ($file_keys as $file_key) { $inner_anchor =& $files[$prefix][$file_key]; - if (isset($copy)) - { + + if ( isset($copy) ) { $work_copy = $copy; } - else - { + else { $copy = $work_copy; } + array_shift($work_copy); - foreach($work_copy as $prefix_file_key) - { + foreach ($work_copy as $prefix_file_key) { $inner_anchor =& $inner_anchor[$prefix_file_key]; } + $anchor[$field_name][$file_key] = $inner_anchor[$field_name]; } } } - // keys: img_temp, 0, values: LocalPath, ThumbPath } @@ -493,17 +487,21 @@ } /** - * Owerwrites GET events with POST events in case if they are set and not empty + * Overwrites GET events with POST events in case if they are set and not empty * + * @return void + * @access protected */ - function convertPostEvents() + protected function convertPostEvents() { - $events = $this->Get('events'); - if (is_array($events)) { + $events = $this->Get('events', Array ()); + /* @var $events Array */ + + if ( is_array($events) ) { + $events = array_filter($events); + foreach ($events as $prefix_special => $event_name) { - if ($event_name) { - $this->Set($prefix_special.'_event', $event_name); - } + $this->Set($prefix_special . '_event', $event_name); } } } @@ -535,6 +533,8 @@ function processRewriteURL() { $mod_rw_helper =& $this->Application->recallObject('ModRewriteHelper'); + /* @var $mod_rw_helper kModRewriteHelper */ + $mod_rw_helper->processRewriteURL(); } @@ -807,37 +807,39 @@ { $log_file = (defined('RESTRICTED') ? RESTRICTED : FULL_PATH) . '/' . $filename; - if ( is_writable( dirname($log_file) ) ) { + if ( is_writable(dirname($log_file)) ) { $fp = fopen($log_file, 'a'); - if ($fp) { + if ( $fp ) { $session =& $this->Application->recallObject('Session'); + /* @var $session Session */ + $user_id = $session->GetField('PortalUserId'); $admin_mark = $this->Application->isAdmin ? 'ADMIN' : 'FRONT'; - $data = '['.date('D M d H:i:s Y').'] '.$admin_mark.'; ip: '.$_SERVER['REMOTE_ADDR'].'; user_id: '.$user_id.'; sid: '.$this->Application->GetSID().'; request: '."\n"; - if ($this->Get) { - $data .= "_GET:\n".print_r($this->Get, true); + $data = '[' . date('D M d H:i:s Y') . '] ' . $admin_mark . '; ip: ' . $_SERVER['REMOTE_ADDR'] . '; user_id: ' . $user_id . '; sid: ' . $this->Application->GetSID() . '; request: ' . "\n"; + if ( $this->Get ) { + $data .= "_GET:\n" . print_r($this->Get, true); } - if ($this->Post) { - $data .= "_POST:\n".print_r($this->Post, true); + if ( $this->Post ) { + $data .= "_POST:\n" . print_r($this->Post, true); } - if ($this->Cookie) { - $data .= "_COOKIE:\n".print_r($this->Cookie, true); + if ( $this->Cookie ) { + $data .= "_COOKIE:\n" . print_r($this->Cookie, true); } - $data .= str_repeat('=', 100)."\n"; + $data .= str_repeat('=', 100) . "\n"; fwrite($fp, $data); fclose($fp); } else { - trigger_error('Requrest Log directory not writable', E_USER_WARNING); + trigger_error('Request Log directory not writable', E_USER_WARNING); } } else { - trigger_error('Requrest Log directory not writable', E_USER_WARNING); + trigger_error('Request Log directory not writable', E_USER_WARNING); } } Index: kernel/utility/params.php =================================================================== --- kernel/utility/params.php (revision 14590) +++ kernel/utility/params.php (working copy) @@ -57,9 +57,10 @@ * * @param string $name * @param string $val + * @return void * @access public */ - function Set($name, $val) + public function Set($name, $val) { $this->_Params[$name] = $val; } @@ -79,11 +80,11 @@ * Gets parameter value by parameter name * * @param string $name Name of variable to retrieve - * @param int $default default value returned in case if varible not present + * @param mixed $default default value returned in case if variable not present * @return string * @access public */ - function Get($name, $default = false) + public function Get($name, $default = false) { return isset($this->_Params[$name]) ? $this->_Params[$name] : $default; } Index: kernel/utility/temp_handler.php =================================================================== --- kernel/utility/temp_handler.php (revision 14590) +++ kernel/utility/temp_handler.php (working copy) @@ -40,8 +40,16 @@ var $FinalRefs = Array(); + var $TableIdCounter = 0; + var $CopiedTables = Array(); + /** + * Foreign key cache + * + * @var Array + */ + var $FKeysCache = Array (); /** * IDs of newly cloned items (key - prefix.special, value - array of ids) @@ -152,14 +160,17 @@ $tables['ParentTableKey'] = $this->Application->getUnitOption($prefix, 'ParentTableKey'); }*/ - $this->FinalRefs[ $tables['TableName'] ] = $tables['TableId']; // don't forget to add main table to FinalRefs too + $this->FinalRefs[ $tables['TableName'] ] = $tables['TableId']; // don't forget to add main table to FinalRefs too - $SubItems = $this->Application->getUnitOption($prefix,'SubItems'); - if (is_array($SubItems)) { - foreach ($SubItems as $prefix) { + $sub_items = $this->Application->getUnitOption($prefix, 'SubItems', Array ()); + /* @var $sub_items Array */ + + if ( is_array($sub_items) ) { + foreach ($sub_items as $prefix) { $this->AddTables($prefix, $tables); } } + $this->SetTables($tables); } @@ -194,7 +205,7 @@ function AddTables($prefix, &$tables) { - if (!$this->Application->prefixRegistred($prefix)) { + if ( !$this->Application->prefixRegistred($prefix) ) { // allows to skip subitem processing if subitem module not enabled/installed return ; } @@ -213,25 +224,23 @@ $this->FinalRefs[ $tmp['TableName'] ] = $tmp['TableId']; - $constrain = $this->Application->getUnitOption($prefix,'Constrain'); - if ($constrain) - { + $constrain = $this->Application->getUnitOption($prefix, 'Constrain'); + if ( $constrain ) { $tmp['Constrain'] = $constrain; - $this->FinalRefs[ $tmp['TableName'].$tmp['Constrain'] ] = $tmp['TableId']; + $this->FinalRefs[ $tmp['TableName'] . $tmp['Constrain'] ] = $tmp['TableId']; } - $SubItems = $this->Application->getUnitOption($prefix,'SubItems'); - $same_sub_counter = 1; - if( is_array($SubItems) ) - { - foreach($SubItems as $prefix) - { + $sub_items = $this->Application->getUnitOption($prefix, 'SubItems', Array ()); + /* @var $sub_items Array */ + + if ( is_array($sub_items) ) { + foreach ($sub_items as $prefix) { $this->AddTables($prefix, $tmp); } } if ( !is_array(getArrayValue($tables, 'SubTables')) ) { - $tables['SubTables'] = array(); + $tables['SubTables'] = Array (); } $tables['SubTables'][] = $tmp; @@ -247,7 +256,7 @@ } $object =& $this->Application->recallObject($prefix.'.'.$special, $prefix, Array('skip_autoload' => true)); - /* @var $object kDBItem */ + /* @var $object kCatDBItem */ $object->PopulateMultiLangFields(); @@ -509,64 +518,85 @@ } } - function DoCopyTempToOriginal($master, $parent_prefix = null, $current_ids = Array()) + /** + * Copies data from temp to live table and returns IDs of copied records + * + * @param Array $master + * @param string $parent_prefix + * @param Array $current_ids + * @return Array + * @access public + */ + public function DoCopyTempToOriginal($master, $parent_prefix = null, $current_ids = Array()) { - if (!$current_ids) { - $query = 'SELECT '.$master['IdField'].' FROM '.$this->GetTempName($master['TableName']); - if (isset($master['Constrain'])) $query .= ' WHERE '.$master['Constrain']; + if ( !$current_ids ) { + $query = 'SELECT ' . $master['IdField'] . ' FROM ' . $this->GetTempName($master['TableName']); + + if ( isset($master['Constrain']) ) { + $query .= ' WHERE ' . $master['Constrain']; + } + $current_ids = $this->Conn->GetCol($query); } - $table_sig = $master['TableName'].(isset($master['Constrain']) ? $master['Constrain'] : ''); + $table_sig = $master['TableName'] . (isset($master['Constrain']) ? $master['Constrain'] : ''); if ($current_ids) { // delete all ids from live table - for MasterTable ONLY! // because items from Sub Tables get deteleted in CopySubTablesToLive !BY ForeignKey! - if ($master['TableName'] == $this->MasterTable) { - $this->RaiseEvent( 'OnBeforeDeleteFromLive', $master['Prefix'], '', $current_ids ); + if ( $master['TableName'] == $this->MasterTable ) { + $this->RaiseEvent('OnBeforeDeleteFromLive', $master['Prefix'], '', $current_ids); - $query = 'DELETE FROM '.$master['TableName'].' WHERE '.$master['IdField'].' IN ('.join(',', $current_ids).')'; + $query = 'DELETE FROM ' . $master['TableName'] . ' WHERE ' . $master['IdField'] . ' IN (' . join(',', $current_ids) . ')'; $this->Conn->Query($query); } if ( getArrayValue($master, 'SubTables') ) { - if( in_array($table_sig, $this->CopiedTables) || $this->FinalRefs[$table_sig] != $master['TableId'] ) return; + if ( in_array($table_sig, $this->CopiedTables) || $this->FinalRefs[$table_sig] != $master['TableId'] ) { + return Array (); + } - foreach($current_ids AS $id) - { - $this->RaiseEvent( 'OnBeforeCopyToLive', $master['Prefix'], '', Array($id) ); + foreach ($current_ids AS $id) { + $this->RaiseEvent('OnBeforeCopyToLive', $master['Prefix'], '', Array ($id)); //reset negative ids to 0, so autoincrement in live table works fine - if($id < 0) - { - $query = 'UPDATE '.$this->GetTempName($master['TableName']).' - SET '.$master['IdField'].' = 0 - WHERE '.$master['IdField'].' = '.$id; - if (isset($master['Constrain'])) $query .= ' AND '.$master['Constrain']; + if ( $id < 0 ) { + $query = ' UPDATE ' . $this->GetTempName($master['TableName']) . ' + SET ' . $master['IdField'] . ' = 0 + WHERE ' . $master['IdField'] . ' = ' . $id; + + if ( isset($master['Constrain']) ) { + $query .= ' AND ' . $master['Constrain']; + } + $this->Conn->Query($query); $id_to_copy = 0; } - else - { + else { $id_to_copy = $id; } //copy current id_to_copy (0 for new or real id) to live table - $query = 'INSERT INTO '.$master['TableName'].' - SELECT * FROM '.$this->GetTempName($master['TableName']).' - WHERE '.$master['IdField'].' = '.$id_to_copy; + $query = ' INSERT INTO ' . $master['TableName'] . ' + SELECT * FROM ' . $this->GetTempName($master['TableName']) . ' + WHERE ' . $master['IdField'] . ' = ' . $id_to_copy; $this->Conn->Query($query); + $insert_id = $id_to_copy == 0 ? $this->Conn->getInsertID() : $id_to_copy; - $this->saveID($master['Prefix'], '', array($id => $insert_id)); - $this->RaiseEvent( 'OnAfterCopyToLive', $master['Prefix'], '', Array($insert_id), null, array('temp_id' => $id) ); + $this->saveID($master['Prefix'], '', array ($id => $insert_id)); + $this->RaiseEvent('OnAfterCopyToLive', $master['Prefix'], '', Array ($insert_id), null, Array ('temp_id' => $id)); $this->UpdateForeignKeys($master, $insert_id, $id); //delete already copied record from master temp table - $query = 'DELETE FROM '.$this->GetTempName($master['TableName']).' - WHERE '.$master['IdField'].' = '.$id_to_copy; - if (isset($master['Constrain'])) $query .= ' AND '.$master['Constrain']; + $query = ' DELETE FROM ' . $this->GetTempName($master['TableName']) . ' + WHERE ' . $master['IdField'] . ' = ' . $id_to_copy; + + if ( isset($master['Constrain']) ) { + $query .= ' AND ' . $master['Constrain']; + } + $this->Conn->Query($query); } @@ -575,37 +605,38 @@ // when all of ids in current master has been processed, copy all sub-tables data $this->CopySubTablesToLive($master, $current_ids); } - elseif( !in_array($table_sig, $this->CopiedTables) && ($this->FinalRefs[$table_sig] == $master['TableId']) ) { //If current master doesn't have sub-tables - we could use mass operations - // We don't need to delete items from live here, as it get deleted in the beggining of the method for MasterTable + elseif ( !in_array($table_sig, $this->CopiedTables) && ($this->FinalRefs[$table_sig] == $master['TableId']) ) { //If current master doesn't have sub-tables - we could use mass operations + // We don't need to delete items from live here, as it get deleted in the beginning of the method for MasterTable // or in parent table processing for sub-tables + $live_ids = Array (); $this->RaiseEvent('OnBeforeCopyToLive', $master['Prefix'], '', $current_ids); - $live_ids = array(); foreach ($current_ids as $an_id) { - if ($an_id > 0) { + if ( $an_id > 0 ) { $live_ids[$an_id] = $an_id; // positive (already live) IDs will be copied in on query all togather below, // so we just store it here continue; } - else { // zero or negaitve ids should be copied one by one to get their InsertId - // reseting to 0 so it get inserted into live table with autoincrement - $query = 'UPDATE '.$this->GetTempName($master['TableName']).' - SET '.$master['IdField'].' = 0 - WHERE '.$master['IdField'].' = '.$an_id; + else { // zero or negative ids should be copied one by one to get their InsertId + // resetting to 0 so it get inserted into live table with autoincrement + $query = ' UPDATE ' . $this->GetTempName($master['TableName']) . ' + SET ' . $master['IdField'] . ' = 0 + WHERE ' . $master['IdField'] . ' = ' . $an_id; // constrain is not needed here because ID is already unique $this->Conn->Query($query); // copying - $query = 'INSERT INTO '.$master['TableName'].' - SELECT * FROM '.$this->GetTempName($master['TableName']).' - WHERE '.$master['IdField'].' = 0'; + $query = ' INSERT INTO ' . $master['TableName'] . ' + SELECT * FROM ' . $this->GetTempName($master['TableName']) . ' + WHERE ' . $master['IdField'] . ' = 0'; $this->Conn->Query($query); + $live_ids[$an_id] = $this->Conn->getInsertID(); //storing newly created live id //delete already copied record from master temp table - $query = 'DELETE FROM '.$this->GetTempName($master['TableName']).' - WHERE '.$master['IdField'].' = 0'; + $query = ' DELETE FROM ' . $this->GetTempName($master['TableName']) . ' + WHERE ' . $master['IdField'] . ' = 0'; $this->Conn->Query($query); $this->UpdateChangeLogForeignKeys($master, $live_ids[$an_id], $an_id); @@ -613,32 +644,38 @@ } // copy ALL records to live table - $query = 'INSERT INTO '.$master['TableName'].' - SELECT * FROM '.$this->GetTempName($master['TableName']); - if (isset($master['Constrain'])) $query .= ' WHERE '.$master['Constrain']; + $query = ' INSERT INTO ' . $master['TableName'] . ' + SELECT * FROM ' . $this->GetTempName($master['TableName']); + + if ( isset($master['Constrain']) ) { + $query .= ' WHERE ' . $master['Constrain']; + } + $this->Conn->Query($query); $this->CopiedTables[] = $table_sig; $this->RaiseEvent('OnAfterCopyToLive', $master['Prefix'], '', $live_ids); $this->saveID($master['Prefix'], '', $live_ids); - // no need to clear temp table - it will be dropped by next statement } } - if ($this->FinalRefs[ $master['TableName'] ] != $master['TableId']) return; + if ( $this->FinalRefs[ $master['TableName'] ] != $master['TableId'] ) { + return Array (); + } /*if ( is_array(getArrayValue($master, 'ForeignKey')) ) { //if multiple ForeignKeys if ( $master['ForeignKey'][$parent_prefix] != end($master['ForeignKey']) ) { return; // Do not delete temp table if not all ForeignKeys have been processed (current is not the last) } }*/ + $this->DropTempTable($master['TableName']); $this->Application->resetCounters($master['TableName']); - if (!isset($this->savedIDs[ $master['Prefix'] ])) { - $this->savedIDs[ $master['Prefix'] ] = Array(); + if ( !isset($this->savedIDs[ $master['Prefix'] ]) ) { + $this->savedIDs[ $master['Prefix'] ] = Array (); } return $this->savedIDs[ $master['Prefix'] ]; @@ -655,6 +692,8 @@ if (!isset($connection)) { $connection =& $this->Application->makeClass( 'kDBConnection', Array (SQL_TYPE, Array (&$this->Application, 'handleSQLError')) ); + /* @var $connection kDBConnection */ + $connection->debugMode = $this->Application->isDebugMode(); $connection->Connect(SQL_SERVER, SQL_USER, SQL_PASS, SQL_DB, true); } @@ -761,26 +800,40 @@ } } - function RaiseEvent($name, $prefix, $special, $ids, $foreign_key = null, $add_params = null) + /** + * Raises event using IDs, that are currently being processed in temp handler + * + * @param string $name + * @param string $prefix + * @param string $special + * @param Array $ids + * @param string $foreign_key + * @param Array $add_params + * @return bool + * @access protected + */ + protected function RaiseEvent($name, $prefix, $special, $ids, $foreign_key = null, $add_params = null) { - if ( !is_array($ids) ) return ; + if ( !is_array($ids) ) { + return true; + } - $event_key = $prefix.($special ? '.' : '').$special.':'.$name; + $event_key = $prefix . ($special ? '.' : '') . $special . ':' . $name; $event = new kEvent($event_key); - if (isset($foreign_key)) { + if ( isset($foreign_key) ) { $event->setEventParam('foreign_key', $foreign_key); } $set_temp_id = ($name == 'OnAfterCopyToLive') && (!is_array($add_params) || !array_key_exists('temp_id', $add_params)); - foreach($ids as $index => $id) { + foreach ($ids as $index => $id) { $event->setEventParam('id', $id); - if ($set_temp_id) { + if ( $set_temp_id ) { $event->setEventParam('temp_id', $index); } - if (is_array($add_params)) { + if ( is_array($add_params) ) { foreach ($add_params as $name => $val) { $event->setEventParam($name, $val); } @@ -820,7 +873,7 @@ $sleep_count = 0; do { - // aquire lock + // acquire lock $conn->ChangeQuery('LOCK TABLES '.TABLE_PREFIX.'Semaphores WRITE'); $sql = 'SELECT SessionKey Index: kernel/utility/unit_config_reader.php =================================================================== --- kernel/utility/unit_config_reader.php (revision 14590) +++ kernel/utility/unit_config_reader.php (working copy) @@ -702,13 +702,14 @@ protected function ProcessDependencies($prefix) { $config =& $this->configData[$prefix]; - $deps = getArrayValue($config, '_Dependencies'); + $dependencies = getArrayValue($config, '_Dependencies'); + /* @var $dependencies Array */ - if (!$deps) { + if ( !$dependencies ) { return ; } - foreach ($deps as $real_class => $requires) { + foreach ($dependencies as $real_class => $requires) { foreach ($requires as $class) { $this->Application->registerDependency($real_class, $class); } @@ -720,9 +721,9 @@ 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(); + $sub_configs = isset($main_config[$config_key]) && $main_config[$config_key] ? $main_config[$config_key] : Array (); + if ( !$sub_configs ) { + return Array (); } unset($main_config[$config_key]); @@ -766,7 +767,7 @@ $config_found = file_exists(FULL_PATH . $filename) && $this->configAllowed($filename); if (defined('DEBUG_MODE') && DEBUG_MODE && defined('DBG_PROFILE_INCLUDES') && DBG_PROFILE_INCLUDES) { - if ( in_array($filename, get_required_files()) ) { + if ( in_array($filename, get_included_files()) ) { return ''; } Index: units/admin/admin_events_handler.php =================================================================== --- units/admin/admin_events_handler.php (revision 14590) +++ units/admin/admin_events_handler.php (working copy) @@ -35,11 +35,13 @@ } /** - * Checks permissions of user + * Checks user permission to execute given $event * * @param kEvent $event + * @return bool + * @access public */ - function CheckPermission(&$event) + public function CheckPermission(&$event) { $perm_value = null; @@ -99,7 +101,14 @@ $this->Conn->Query('DELETE FROM ' . TABLE_PREFIX . 'CachedUrls'); } - function OnResetSections(&$event) + /** + * Resets tree section cache and refreshes admin section tree + * + * @param kEvent $event + * @return void + * @access protected + */ + protected function OnResetSections(&$event) { if ($this->Application->GetVar('ajax') == 'yes') { $event->status = kEvent::erSTOP; @@ -585,14 +594,15 @@ function OnCSVImportStep(&$event) { $import_helper =& $this->Application->recallObject('CSVHelper'); - /* @var $export_helper kCSVHelper */ + /* @var $import_helper kCSVHelper */ $prefix_special = $import_helper->ImportData('prefix'); $prefix_elems = preg_split('/\.|_/', $prefix_special, 2); $perm_sections = $this->Application->getUnitOption($prefix_elems[0], 'PermSection'); - if(!$this->Application->CheckPermission($perm_sections['main'].'.add') && !$this->Application->CheckPermission($perm_sections['main'].'.edit')) { + + if ( !$this->Application->CheckPermission($perm_sections['main'] . '.add') && !$this->Application->CheckPermission($perm_sections['main'] . '.edit') ) { $event->status = kEvent::erPERM_FAIL; - return ; + return; } $import_helper->ImportStep(); @@ -1080,13 +1090,20 @@ } - function runSchemaText($sql) + /** + * Run given schema sqls and return error, if any + * + * @param $sql + * @return string + * @access protected + */ + protected function runSchemaText($sql) { - $table_prefix = 'restore'.TABLE_PREFIX; -// $table_prefix = TABLE_PREFIX; + $table_prefix = 'restore' . TABLE_PREFIX; - if (strlen($table_prefix) > 0) { + if ( strlen($table_prefix) > 0 ) { $replacements = Array ('INSERT INTO ', 'UPDATE ', 'ALTER TABLE ', 'DELETE FROM ', 'REPLACE INTO '); + foreach ($replacements as $replacement) { $sql = str_replace($replacement, $replacement . $table_prefix, $sql); } @@ -1095,45 +1112,44 @@ $sql = str_replace('CREATE TABLE ', 'CREATE TABLE IF NOT EXISTS ' . $table_prefix, $sql); $sql = str_replace('DROP TABLE ', 'DROP TABLE IF EXISTS ' . $table_prefix, $sql); - $commands = explode("# --------------------------------------------------------",$sql); - if(count($commands)>0) - { -// $query_func = getConnectionInterface('query',$dbo_type); -// $errorno_func = getConnectionInterface('errorno',$dbo_type); -// $errormsg_func = getConnectionInterface('errormsg',$dbo_type); + $commands = explode("# --------------------------------------------------------", $sql); - for($i = 0; $i < count($commands); $i++) - { - $cmd = $commands[$i]; - $cmd = trim($cmd); - if(strlen($cmd)>0) - { - $this->Conn->Query($cmd); - if($this->Conn->errorCode != 0) - { - return $this->Conn->errorMessage." COMMAND:
$cmd
"; - } - } - } - } + if ( count($commands) > 0 ) { + for ($i = 0; $i < count($commands); $i++) { + $cmd = trim( $commands[$i] ); + + if ( strlen($cmd) > 0 ) { + $this->Conn->Query($cmd); + + if ( $this->Conn->errorCode != 0 ) { + return $this->Conn->errorMessage . " COMMAND:
$cmd
"; + } + } + } + } + + return ''; } - function runSQLText($allsql) + /** + * Runs given sqls and return error message, if any + * + * @param $all_sqls + * @return string + * @access protected + */ + protected function runSQLText($all_sqls) { $line = 0; -// $query_func = getConnectionInterface('query',$dbo_type); -// $errorno_func = getConnectionInterface('errorno',$dbo_type); -// $errormsg_func = getConnectionInterface('errormsg',$dbo_type); - while($line0 && substr($sql,0,1)!="#") - { - $table_prefix = 'restore'.TABLE_PREFIX; + while ( $line < count($all_sqls) ) { + $sql = $all_sqls[$line]; + if ( strlen(trim($sql)) > 0 && substr($sql, 0, 1) != "#" ) { + $table_prefix = 'restore' . TABLE_PREFIX; - if (strlen($table_prefix) > 0) { + if ( strlen($table_prefix) > 0 ) { $replacements = Array ('INSERT INTO ', 'UPDATE ', 'ALTER TABLE ', 'DELETE FROM ', 'REPLACE INTO '); + foreach ($replacements as $replacement) { $sql = str_replace($replacement, $replacement . $table_prefix, $sql); } @@ -1141,23 +1157,23 @@ $sql = str_replace('CREATE TABLE ', 'CREATE TABLE IF NOT EXISTS ' . $table_prefix, $sql); $sql = str_replace('DROP TABLE ', 'DROP TABLE IF EXISTS ' . $table_prefix, $sql); + $sql = trim($sql); - $sql = trim($sql); - if(strlen($sql)>0) - { + if ( strlen($sql) > 0 ) { $this->Conn->Query($sql); - if($this->Conn->errorCode != 0) - { - return $this->Conn->errorMessage." COMMAND:
$sql
"; - } + if ( $this->Conn->errorCode != 0 ) { + return $this->Conn->errorMessage . " COMMAND:
$sql
"; + } } } + $line++; } + + return ''; } - /** * Starts restore process * Index: units/admin/admin_tag_processor.php =================================================================== --- units/admin/admin_tag_processor.php (revision 14590) +++ units/admin/admin_tag_processor.php (working copy) @@ -306,7 +306,10 @@ function ListSectionPermissions($params) { $section_name = isset($params['section_name']) ? $params['section_name'] : $this->Application->GetVar('section_name'); + $sections_helper =& $this->Application->recallObject('SectionsHelper'); + /* @var $sections_helper kSectionsHelper */ + $section_data =& $sections_helper->getSectionData($section_name); $block_params = array_merge($section_data, Array('name' => $params['render_as'], 'section_name' => $section_name)); @@ -326,8 +329,7 @@ $params[$param_name] = kUtil::replaceModuleSection($param_value); } - $m =& $this->Application->recallObject('m_TagProcessor'); - return $m->ModuleInclude($params); + return $this->Application->ProcessParsedTag('m', 'ModuleInclude', $params); } function TodayDate($params) @@ -493,8 +495,7 @@ // user can override default parameters (except pass_through of course) $params = array_merge($default_params, $params); - $main_processor =& $this->Application->recallObject('m_TagProcessor'); - return $main_processor->T($params); + return $this->Application->ProcessParsedTag('m', 'T', $params); } function TimeFrame($params) @@ -502,62 +503,75 @@ $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']) { + 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; + $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); + $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; + $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); + $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); + $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); + $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); + $timestamp = adodb_mktime(23, 59, 59, 12, 31, $y - 1); break; + + default: + $timestamp = 0; + break; } + if ( isset($params['format']) ) { + $format = $params['format']; - if (isset($params['format'])) { - $format = $params['format']; - if(preg_match("/_regional_(.*)/", $format, $regs)) - { + if ( preg_match("/_regional_(.*)/", $format, $regs) ) { $lang =& $this->Application->recallObject('lang.current'); + /* @var $lang LanguagesItem */ + $format = $lang->GetDBField($regs[1]); } + return adodb_date($format, $timestamp); } return $timestamp; - } /** @@ -813,14 +827,21 @@ return $skin_helper->AdminSkinTag($params); } - function PrintCompileErrors($params) + /** + * Prints errors, discovered during mass template compilation + * + * @param $params + * @return string + * @access protected + */ + protected function PrintCompileErrors($params) { $block_params = $this->prepareTagParams($params); $block_params['name'] = $params['render_as']; $errors = $this->Application->RecallVar('compile_errors'); - if (!$errors) { - return ; + if ( !$errors ) { + return ''; } $ret = ''; Index: units/agents/agent_eh.php =================================================================== --- units/agents/agent_eh.php (revision 14590) +++ units/agents/agent_eh.php (working copy) @@ -93,8 +93,11 @@ * Don't allow to delete other user's messages * * @param kEvent $event + * @param string $type + * @return void + * @access protected */ - function customProcessing(&$event, $type) + protected function customProcessing(&$event, $type) { if ($event->Name == 'OnMassDelete' && $type == 'before') { if ($this->Application->isDebugMode()) { Index: units/categories/categories_event_handler.php =================================================================== --- units/categories/categories_event_handler.php (revision 14590) +++ units/categories/categories_event_handler.php (working copy) @@ -56,11 +56,13 @@ } /** - * Checks permissions of user + * Checks user permission to execute given $event * * @param kEvent $event + * @return bool + * @access public */ - function CheckPermission(&$event) + public function CheckPermission(&$event) { if ($event->Name == 'OnResetCMSMenuCache') { // events from "Tools -> System Tools" section are controlled via that section "edit" permission @@ -258,8 +260,11 @@ * Apply system filter to categories list * * @param kEvent $event + * @return void + * @access protected + * @see kDBEventHandler::OnListBuild() */ - function SetCustomQuery(&$event) + protected function SetCustomQuery(&$event) { parent::SetCustomQuery($event); @@ -395,6 +400,8 @@ } $p_item =& $this->Application->recallObject($related_prefix . '.current', null, Array('skip_autoload' => true)); + /* @var $p_item kCatDBItem */ + $p_item->Load( (int)$id ); $p_resource_id = $p_item->GetDBField('ResourceId'); @@ -615,9 +622,9 @@ if ($page_id === false && EDITING_MODE) { // create missing pages, when in editing mode $object =& $this->Application->recallObject($this->Prefix . '.rebuild', null, Array('skip_autoload' => true)); - /* @var $object kDBItem */ + /* @var $object CategoriesItem */ - $created = $this->_prepareAutoPage($object, $template, null, SMS_MODE_AUTO, false); // create virtual (not system!) page + $created = $this->_prepareAutoPage($object, $template, null, SMS_MODE_AUTO); // create virtual (not system!) page if ($created) { if ($this->Application->ConfigValue('QuickCategoryPermissionRebuild') || !$this->Application->isAdmin) { $updater =& $this->Application->makeClass('kPermCacheUpdater'); @@ -657,8 +664,10 @@ * * @param kCatDBItem $object * @param kEvent $event + * @return void + * @access protected */ - function prepareObject(&$object, &$event) + protected function prepareObject(&$object, &$event) { if ($event->Special != '-virtual') { $object =& $event->getObject( Array('skip_autoload' => true) ); @@ -681,14 +690,17 @@ */ function OnAfterCopyToLive(&$event) { + $object =& $this->Application->recallObject($event->Prefix . '.-item', null, Array ('skip_autoload' => true, 'live_table' => true)); + /* @var $object CategoriesItem */ + $parent_path = false; - $object =& $this->Application->recallObject($event->Prefix.'.-item', null, Array('skip_autoload' => true, 'live_table' => true)); - $object->Load($event->getEventParam('id')); - if ($event->getEventParam('temp_id') == 0) { - if ($object->isLoaded()) { + $object->Load( $event->getEventParam('id') ); + + if ( $event->getEventParam('temp_id') == 0 ) { + if ( $object->isLoaded() ) { // update path only for real categories (not including "Home" root category) - $fields_hash = Array('ParentPath' => $object->buildParentPath()); - $this->Conn->doUpdate($fields_hash, $object->TableName, 'CategoryId = '.$object->GetID()); + $fields_hash = Array ('ParentPath' => $object->buildParentPath()); + $this->Conn->doUpdate($fields_hash, $object->TableName, 'CategoryId = ' . $object->GetID()); $parent_path = $fields_hash['ParentPath']; } } @@ -696,7 +708,7 @@ $parent_path = $object->GetDBField('ParentPath'); } - if ($parent_path) { + if ( $parent_path ) { $cache_updater =& $this->Application->makeClass('kPermCacheUpdater', Array (null, $parent_path)); /* @var $cache_updater kPermCacheUpdater */ @@ -708,36 +720,39 @@ * Set cache modification mark if needed * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeDeleteFromLive(&$event) + protected function OnBeforeDeleteFromLive(&$event) { + parent::OnBeforeDeleteFromLive($event); + $id = $event->getEventParam('id'); - // loding anyway, because this object is needed by "c-perm:OnBeforeDeleteFromLive" event - $temp_object =& $event->getObject( Array('skip_autoload' => true) ); - /* @var $temp_object kDBItem */ - + // loading anyway, because this object is needed by "c-perm:OnBeforeDeleteFromLive" event + $temp_object =& $event->getObject(Array ('skip_autoload' => true)); + /* @var $temp_object CategoriesItem */ + $temp_object->Load($id); - if ($id == 0) { - if ($temp_object->isLoaded()) { + if ( $id == 0 ) { + if ( $temp_object->isLoaded() ) { // new category -> update cache (not loaded when "Home" category) $this->Application->StoreVar('PermCache_UpdateRequired', 1); } + return ; } // existing category was edited, check if in-cache fields are modified - $live_object =& $this->Application->recallObject($event->Prefix.'.-item', null, Array('live_table' => true, 'skip_autoload' => true)); + $live_object =& $this->Application->recallObject($event->Prefix . '.-item', null, Array ('live_table' => true, 'skip_autoload' => true)); + /* @var $live_object CategoriesItem */ + $live_object->Load($id); + $cached_fields = Array ('l' . $this->Application->GetDefaultLanguageId() . '_Name', 'Filename', 'Template', 'ParentId', 'Priority'); - $cached_fields = Array( - 'l' . $this->Application->GetDefaultLanguageId() . '_Name', - 'Filename', 'Template', 'ParentId', 'Priority' - ); - foreach ($cached_fields as $cached_field) { - if ($live_object->GetDBField($cached_field) != $temp_object->GetDBField($cached_field)) { + if ( $live_object->GetDBField($cached_field) != $temp_object->GetDBField($cached_field) ) { // use session instead of REQUEST because of permission editing in category can contain // multiple submits, that changes data before OnSave event occurs $this->Application->StoreVar('PermCache_UpdateRequired', 1); @@ -761,8 +776,10 @@ * Reset root-category flag when new category is created * * @param kEvent $event + * @return void + * @access protected */ - function OnPreCreate(&$event) + protected function OnPreCreate(&$event) { // 1. for permission editing of Home category $this->Application->RemoveVar('IsRootCategory_' . $this->Application->GetVar('m_wid')); @@ -770,11 +787,13 @@ parent::OnPreCreate($event); $object =& $event->getObject(); + /* @var $object kDBItem */ // 2. preset template $category_id = $this->Application->GetVar('m_cat_id'); $root_category = $this->Application->getBaseCategory(); - if ($category_id == $root_category) { + + if ( $category_id == $root_category ) { $object->SetDBField('Template', $this->_getDefaultDesign()); } @@ -792,32 +811,27 @@ * Checks cache update mark and redirect to cache if needed * * @param kEvent $event + * @return void + * @access protected */ - function OnSave(&$event) + protected function OnSave(&$event) { + // get data from live table before it is overwritten by parent OnSave method call $ids = $this->getSelectedIDs($event, true); $is_editing = implode('', $ids); + $old_statuses = $is_editing ? $this->_getCategoryStatus($ids) : Array (); - if ($is_editing) { - $old_statuses = $this->_getCategoryStatus($ids); - } - $object =& $event->getObject(); /* @var $object CategoriesItem */ - /*if ($object->IsRoot()) { - $event->setEventParam('master_ids', Array(0)); - $this->RemoveRequiredFields($object); - }*/ - parent::OnSave($event); - if ($event->status != kEvent::erSUCCESS) { - return ; + if ( $event->status != kEvent::erSUCCESS ) { + return; } // 1. update priorities - $tmp = $this->Application->RecallVar('priority_changes'.$this->Application->GetVar('m_wid')); + $tmp = $this->Application->RecallVar('priority_changes' . $this->Application->GetVar('m_wid')); $changes = $tmp ? unserialize($tmp) : Array (); $changed_ids = array_keys($changes); @@ -826,21 +840,21 @@ $priority_helper->updatePriorities($event, $changes, Array (0 => $event->getEventParam('ids'))); - if ($this->Application->RecallVar('PermCache_UpdateRequired')) { + if ( $this->Application->RecallVar('PermCache_UpdateRequired') ) { $this->Application->RemoveVar('IsRootCategory_' . $this->Application->GetVar('m_wid')); } $this->Application->StoreVar('RefreshStructureTree', 1); $this->_resetMenuCache(); - if ($is_editing) { + if ( $is_editing ) { // 2. send email event to category owner, when it's status is changed (from admin) $object->SwitchToLive(); $new_statuses = $this->_getCategoryStatus($ids); $process_statuses = Array (STATUS_ACTIVE, STATUS_DISABLED); foreach ($new_statuses as $category_id => $new_status) { - if ($new_status != $old_statuses[$category_id] && in_array($new_status, $process_statuses)) { + if ( $new_status != $old_statuses[$category_id] && in_array($new_status, $process_statuses) ) { $object->Load($category_id); $email_event = $new_status == STATUS_ACTIVE ? 'CATEGORY.APPROVE' : 'CATEGORY.DENY'; $this->Application->EmailEventUser($email_event, $object->GetDBField('CreatedById')); @@ -868,18 +882,20 @@ /** * Creates a new item in temp table and - * stores item id in App vars and Session on succsess + * stores item id in App vars and Session on success * * @param kEvent $event + * @return void + * @access protected */ - function OnPreSaveCreated(&$event) + protected function OnPreSaveCreated(&$event) { - $object =& $event->getObject( Array('skip_autoload' => true) ); + $object =& $event->getObject( Array ('skip_autoload' => true) ); /* @var $object CategoriesItem */ - if ($object->IsRoot()) { + if ( $object->IsRoot() ) { // don't create root category while saving permissions - return ; + return; } $priority_helper =& $this->Application->recallObject('PriorityHelper'); @@ -910,13 +926,15 @@ $this->Conn->Query($sql); } - /** - * Exclude root categories from deleting - * - * @param kEvent $event - */ - function customProcessing(&$event, $type) + * Exclude root categories from deleting + * + * @param kEvent $event + * @param string $type + * @return void + * @access protected + */ + protected function customProcessing(&$event, $type) { if ($event->Name == 'OnMassDelete' && $type == 'before') { $ids = $event->getEventParam('ids'); @@ -1001,28 +1019,31 @@ * by calling its Delete method if sub-item has AutoDelete set to true in its config file * * @param kEvent $event + * @return void + * @access protected */ - function OnMassDelete(&$event) + protected function OnMassDelete(&$event) { - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) { + if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) { $event->status = kEvent::erFAIL; - return; + return ; } + $to_delete = Array (); $ids = $this->StoreSelectedIDs($event); - $to_delete = array(); - if ($recycle_bin = $this->Application->ConfigValue('RecycleBinFolder')) { + + if ( $recycle_bin = $this->Application->ConfigValue('RecycleBinFolder') ) { $rb =& $this->Application->recallObject('c.recycle', null, Array ('skip_autoload' => true)); /* @var $rb CategoriesItem */ $rb->Load($recycle_bin); - - $cat =& $event->getObject(Array('skip_autoload' => true)); + + $cat =& $event->getObject(Array ('skip_autoload' => true)); /* @var $cat CategoriesItem */ foreach ($ids as $id) { $cat->Load($id); - if (preg_match('/^'.preg_quote($rb->GetDBField('ParentPath'),'/').'/', $cat->GetDBField('ParentPath'))) { + if ( preg_match('/^' . preg_quote($rb->GetDBField('ParentPath'), '/') . '/', $cat->GetDBField('ParentPath')) ) { $to_delete[] = $id; continue; } @@ -1037,7 +1058,7 @@ $this->customProcessing($event, 'before'); $ids = $event->getEventParam('ids'); - if ($ids) { + if ( $ids ) { $recursive_helper =& $this->Application->recallObject('RecursiveHelper'); /* @var $recursive_helper kRecursiveHelper */ @@ -1067,7 +1088,10 @@ function OnCopy(&$event) { $this->Application->RemoveVar('clipboard'); + $clipboard_helper =& $this->Application->recallObject('ClipboardHelper'); + /* @var $clipboard_helper kClipboardHelper */ + $clipboard_helper->setClipboard($event, 'copy', $this->StoreSelectedIDs($event)); $this->clearSelectedIDs($event); } @@ -1080,7 +1104,10 @@ function OnCut(&$event) { $this->Application->RemoveVar('clipboard'); + $clipboard_helper =& $this->Application->recallObject('ClipboardHelper'); + /* @var $clipboard_helper kClipboardHelper */ + $clipboard_helper->setClipboard($event, 'cut', $this->StoreSelectedIDs($event)); $this->clearSelectedIDs($event); } @@ -1122,28 +1149,31 @@ } /** - * Paste categories with subitems from clipboard + * Paste categories with sub-items from clipboard * * @param kEvent $event + * @return void + * @access protected */ - function OnPaste(&$event) + protected function OnPaste(&$event) { - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) || !$this->_checkPastePermission($event)) { + if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) || !$this->_checkPastePermission($event) ) { $event->status = kEvent::erFAIL; - return ; + return; } $clipboard_data = $event->getEventParam('clipboard_data'); - if (!$clipboard_data['cut'] && !$clipboard_data['copy']) { - return false; + if ( !$clipboard_data['cut'] && !$clipboard_data['copy'] ) { + return; } // 1. get ParentId of moved category(-es) before it gets updated!!!) + $source_category_id = 0; $id_field = $this->Application->getUnitOption($event->Prefix, 'IDField'); $table_name = $this->Application->getUnitOption($event->Prefix, 'TableName'); - if ($clipboard_data['cut']) { + if ( $clipboard_data['cut'] ) { $sql = 'SELECT ParentId FROM ' . $table_name . ' WHERE ' . $id_field . ' = ' . $clipboard_data['cut'][0]; @@ -1153,11 +1183,11 @@ $recursive_helper =& $this->Application->recallObject('RecursiveHelper'); /* @var $recursive_helper kRecursiveHelper */ - if ($clipboard_data['cut']) { + if ( $clipboard_data['cut'] ) { $recursive_helper->MoveCategories($clipboard_data['cut'], $this->Application->GetVar('m_cat_id')); } - if ($clipboard_data['copy']) { + if ( $clipboard_data['copy'] ) { // don't allow to copy/paste system OR theme-linked virtual pages $sql = 'SELECT ' . $id_field . ' @@ -1165,8 +1195,8 @@ WHERE ' . $id_field . ' IN (' . implode(',', $clipboard_data['copy']) . ') AND (`Type` = ' . PAGE_TYPE_VIRTUAL . ') AND (ThemeId = 0)'; $allowed_ids = $this->Conn->GetCol($sql); - if (!$allowed_ids) { - return ; + if ( !$allowed_ids ) { + return; } foreach ($allowed_ids as $id) { @@ -1177,17 +1207,17 @@ $priority_helper =& $this->Application->recallObject('PriorityHelper'); /* @var $priority_helper kPriorityHelper */ - if ($clipboard_data['cut']) { - $priority_helper->recalculatePriorities($event, 'ParentId = '.$source_category_id); + if ( $clipboard_data['cut'] ) { + $priority_helper->recalculatePriorities($event, 'ParentId = ' . $source_category_id); } // recalculate priorities of newly pasted categories in destination category $parent_id = $this->Application->GetVar('m_cat_id'); $priority_helper->recalculatePriorities($event, 'ParentId = ' . $parent_id); - if ($clipboard_data['cut'] || $clipboard_data['copy']) { + if ( $clipboard_data['cut'] || $clipboard_data['copy'] ) { // rebuild with progress bar - if ($this->Application->ConfigValue('QuickCategoryPermissionRebuild')) { + if ( $this->Application->ConfigValue('QuickCategoryPermissionRebuild') ) { $updater =& $this->Application->makeClass('kPermCacheUpdater'); /* @var $updater kPermCacheUpdater */ @@ -1254,12 +1284,16 @@ * Sets correct status for new categories created on front-end * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemCreate(&$event) + protected function OnBeforeItemCreate(&$event) { + parent::OnBeforeItemCreate($event); + $this->_beforeItemChange($event); - if ($this->Application->isAdminUser || $event->Prefix == 'st') { + if ( $this->Application->isAdminUser || $event->Prefix == 'st' ) { // don't check category permissions when auto-creating structure pages return ; } @@ -1269,14 +1303,17 @@ $new_status = false; $category_id = $this->Application->GetVar('m_cat_id'); - if ($perm_helper->CheckPermission('CATEGORY.ADD', 0, $category_id)) { + + if ( $perm_helper->CheckPermission('CATEGORY.ADD', 0, $category_id) ) { $new_status = STATUS_ACTIVE; } - else if ($perm_helper->CheckPermission('CATEGORY.ADD.PENDING', 0, $category_id)) { - $new_status = STATUS_PENDING; + else { + if ( $perm_helper->CheckPermission('CATEGORY.ADD.PENDING', 0, $category_id) ) { + $new_status = STATUS_PENDING; + } } - if ($new_status) { + if ( $new_status ) { $object =& $event->getObject(); /* @var $object kDBItem */ @@ -1285,10 +1322,6 @@ // don't forget to set Priority for suggested from Front-End categories $min_priority = $this->_getNextPriority($object->GetDBField('ParentId'), $object->TableName); $object->SetDBField('Priority', $min_priority); - - /*if (!$this->Application->isAdminUser) { - $object->SetDBField('IsMenu', 0); // add all suggested categories as non-menu - }*/ } else { $event->status = kEvent::erPERM_FAIL; @@ -1315,15 +1348,17 @@ * Sets correct status for new categories created on front-end * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemUpdate(&$event) + protected function OnBeforeItemUpdate(&$event) { parent::OnBeforeItemUpdate($event); $object =& $event->getObject(); /* @var $object kDBItem */ - if ($object->GetChangedFields()) { + if ( $object->GetChangedFields() ) { $object->SetDBField('ModifiedById', $this->Application->RecallVar('user_id')); } @@ -1393,12 +1428,16 @@ { parent::SetPagination($event); - if (!$this->Application->isAdmin) { + if ( !$this->Application->isAdmin ) { $page_var = $event->getEventParam('page_var'); - if ($page_var !== false) { + + if ( $page_var !== false ) { $page = $this->Application->GetVar($page_var); - if (is_numeric($page)) { + + if ( is_numeric($page) ) { $object =& $event->getObject(); + /* @var $object kDBList */ + $object->SetPage($page); } } @@ -1406,40 +1445,41 @@ } /** - * Apply same processing to each item beeing selected in grid + * Apply same processing to each item being selected in grid * * @param kEvent $event - * @access private + * @return void + * @access protected */ - function iterateItems(&$event) + protected function iterateItems(&$event) { - if ($event->Name != 'OnMassApprove' && $event->Name != 'OnMassDecline') { - return parent::iterateItems($event); + if ( $event->Name != 'OnMassApprove' && $event->Name != 'OnMassDecline' ) { + parent::iterateItems($event); } - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) { + if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) { $event->status = kEvent::erFAIL; return; } - $object =& $event->getObject( Array('skip_autoload' => true) ); + $object =& $event->getObject(Array ('skip_autoload' => true)); /* @var $object CategoriesItem */ $ids = $this->StoreSelectedIDs($event); - if ($ids) { + if ( $ids ) { $propagate_category_status = $this->Application->GetVar('propagate_category_status'); - $status_field = array_shift( $this->Application->getUnitOption($event->Prefix,'StatusField') ); + $status_field = array_shift( $this->Application->getUnitOption($event->Prefix, 'StatusField') ); foreach ($ids as $id) { $object->Load($id); $object->SetDBField($status_field, $event->Name == 'OnMassApprove' ? 1 : 0); - if ($object->Update()) { - if ($propagate_category_status) { - $sql = 'UPDATE '.$object->TableName.' - SET '.$status_field.' = '.$object->GetDBField($status_field).' - WHERE TreeLeft BETWEEN '.$object->GetDBField('TreeLeft').' AND '.$object->GetDBField('TreeRight'); + if ( $object->Update() ) { + if ( $propagate_category_status ) { + $sql = 'UPDATE ' . $object->TableName . ' + SET ' . $status_field . ' = ' . $object->GetDBField($status_field) . ' + WHERE TreeLeft BETWEEN ' . $object->GetDBField('TreeLeft') . ' AND ' . $object->GetDBField('TreeRight'); $this->Conn->Query($sql); } @@ -1514,19 +1554,24 @@ /** * Returns default design based on given virtual template (used from kApplication::Run) * + * @param string $t * @return string + * @access public */ - function GetDesignTemplate($t = null) + public function GetDesignTemplate($t = null) { - if (!isset($t)) { + if ( !isset($t) ) { $t = $this->Application->GetVar('t'); } $page =& $this->Application->recallObject($this->Prefix . '.-virtual', null, Array ('page' => $t)); - if ($page->isLoaded()) { + /* @var $page CategoriesItem */ + + if ( $page->isLoaded() ) { $real_t = $page->GetDBField('CachedTemplate'); - $this->Application->SetVar('m_cat_id', $page->GetDBField('CategoryId') ); - if ($page->GetDBField('FormId')) { + $this->Application->SetVar('m_cat_id', $page->GetDBField('CategoryId')); + + if ( $page->GetDBField('FormId') ) { $this->Application->SetVar('form_id', $page->GetDBField('FormId')); } } @@ -1550,7 +1595,7 @@ $template = $theme->GetField('TemplateAliases', $real_t); - if ($template) { + if ( $template ) { return $template; } @@ -1684,10 +1729,14 @@ } /** - * Enter description here... + * Creates category based on given TPL file * - * @param StructureItem $object + * @param CategoriesItem $object * @param string $template + * @param int $theme_id + * @param int $system_mode + * @param array $template_info + * @return bool */ function _prepareAutoPage(&$object, $template, $theme_id = null, $system_mode = SMS_MODE_AUTO, $template_info = Array ()) { @@ -1980,12 +2029,14 @@ * Removes this item and it's children (recursive) from structure dropdown * * @param kEvent $event + * @return void + * @access protected */ - function OnAfterItemLoad(&$event) + protected function OnAfterItemLoad(&$event) { parent::OnAfterItemLoad($event); - if (!$this->Application->isAdmin) { + if ( !$this->Application->isAdmin ) { // calculate priorities dropdown only for admin return ; } @@ -1994,9 +2045,9 @@ /* @var $object kDBItem */ // remove this category & it's children from dropdown - $sql = 'SELECT '.$object->IDField.' - FROM '.$this->Application->getUnitOption($event->Prefix, 'TableName').' - WHERE ParentPath LIKE "'.$object->GetDBField('ParentPath').'%"'; + $sql = 'SELECT ' . $object->IDField . ' + FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . ' + WHERE ParentPath LIKE "' . $object->GetDBField('ParentPath') . '%"'; $remove_categories = $this->Conn->GetCol($sql); $field_options = $object->GetFieldOptions('ParentId'); @@ -2008,9 +2059,9 @@ $priority_helper =& $this->Application->recallObject('PriorityHelper'); /* @var $priority_helper kPriorityHelper */ - $priority_helper->preparePriorities($event, false, 'ParentId = '.$object->GetDBField('ParentId')); + $priority_helper->preparePriorities($event, false, 'ParentId = ' . $object->GetDBField('ParentId')); - // storing prioriry right after load for comparing when updating + // storing priority right after load for comparing when updating $object->SetDBField('OldPriority', $object->GetDBField('Priority')); } @@ -2186,14 +2237,15 @@ $keywords = kUtil::unhtmlentities( trim($this->Application->GetVar('keywords')) ); $query_object =& $this->Application->recallObject('HTTPQuery'); + /* @var $query_object kHTTPQuery */ + $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 ( !isset($query_object->Get['keywords']) && !isset($query_object->Post['keywords']) && $this->Conn->Query($sql) ) { + // used when navigating by pages or changing sorting in search results + return; } + if(!$keywords || strlen($keywords) < $this->Application->ConfigValue('Search_MinKeyword_Length')) { $this->Conn->Query('DROP TABLE IF EXISTS '.$search_table); @@ -2241,12 +2293,11 @@ $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') { + if ( $object->GetFieldOption($field, 'formatter') == 'kMultiLanguage' ) { $field_list[$key.'_primary'] = 'l'.$this->Application->GetDefaultLanguageId().'_'.$field; $field_list[$key] = 'l'.$lang.'_'.$field; @@ -2465,12 +2516,14 @@ * Load item if id is available * * @param kEvent $event + * @return void + * @access protected */ - function LoadItem(&$event) + protected function LoadItem(&$event) { - if ($event->Special != '-virtual') { + if ( $event->Special != '-virtual' ) { parent::LoadItem($event); - return ; + return; } $object =& $event->getObject(); @@ -2478,14 +2531,16 @@ $id = $this->getPassedID($event); - if ($object->isLoaded() && !is_array($id) && ($object->GetID() == $id)) { + if ( $object->isLoaded() && !is_array($id) && ($object->GetID() == $id) ) { // object is already loaded by same id - return ; + return; } - if ($object->Load($id, null, true)) { + if ( $object->Load($id, null, true) ) { $actions =& $this->Application->recallObject('kActions'); - $actions->Set($event->getPrefixSpecial().'_id', $object->GetID() ); + /* @var $actions Params */ + + $actions->Set($event->getPrefixSpecial() . '_id', $object->GetID()); } else { $object->setID($id); Index: units/categories/categories_item.php =================================================================== --- units/categories/categories_item.php (revision 14590) +++ units/categories/categories_item.php (working copy) @@ -16,7 +16,16 @@ class CategoriesItem extends kDBItem { - function Create($force_id = false, $system_create = false) + + /** + * 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! + * @param bool $system_create + * @return bool + * @access public + */ + public function Create($force_id = false, $system_create = false) { // set parent category first, so filename generation could use it $parent_category = $this->GetDBField('ParentId') > 0 ? $this->GetDBField('ParentId') : $this->Application->GetVar('m_cat_id'); @@ -52,7 +61,16 @@ } - function Update($id=null, $system_update = false) + /** + * Updates previously loaded record with current item' values + * + * @access public + * @param int $id Primary Key Id to update + * @param bool $system_update + * @return bool + * @access public + */ + public function Update($id = null, $system_update = false) { $this->checkFilename(); $this->generateFilename(); @@ -183,16 +201,23 @@ /** * Generate item's filename based on it's title field value * - * @return string + * @return void + * @access protected */ - function generateFilename() + protected function generateFilename() { - if ( !$this->GetDBField('AutomaticFilename') && $this->GetDBField('Filename') ) return false; + if ( !$this->GetDBField('AutomaticFilename') && $this->GetDBField('Filename') ) { + return ; + } $ml_formatter =& $this->Application->recallObject('kMultiLanguage'); - $name = $this->stripDisallowed( $this->GetDBField( $ml_formatter->LangFieldName('Name', true) ) ); + /* @var $ml_formatter kMultiLanguage */ - if ( $name != $this->GetDBField('Filename') ) $this->SetDBField('Filename', $name); + $name = $this->stripDisallowed( $this->GetDBField($ml_formatter->LangFieldName('Name', true)) ); + + if ( $name != $this->GetDBField('Filename') ) { + $this->SetDBField('Filename', $name); + } } /** Index: units/categories/categories_tag_processor.php =================================================================== --- units/categories/categories_tag_processor.php (revision 14590) +++ units/categories/categories_tag_processor.php (working copy) @@ -192,6 +192,8 @@ function CurrentCategoryName($params) { $cat_object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix.'_List'); + /* @var $cat_object kDBList */ + $sql = 'SELECT '.$this->getTitleField().' FROM '.$cat_object->TableName.' WHERE CategoryId = '.(int)$this->Application->GetVar('m_cat_id'); @@ -213,13 +215,16 @@ function getTitleField() { $ml_formatter =& $this->Application->recallObject('kMultiLanguage'); + /* @var $ml_formatter kMultiLanguage */ + return $ml_formatter->LangFieldName('Name'); } /** * Returns symlinked category for given category * - * @param $category_id + * @param int $category_id + * @return int */ function getCategorySymLink($category_id) { @@ -536,42 +541,41 @@ * * @param Array $params * @return string + * @access protected */ - function SaveWarning($params) + protected function SaveWarning($params) { - if ($this->Prefix == 'st') { + if ( $this->Prefix == 'st' ) { // don't use this method for other prefixes then Category, that use this tag processor return parent::SaveWarning($params); } $main_prefix = getArrayValue($params, 'main_prefix'); - if ($main_prefix && $main_prefix != '$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'); + $temp_tables = substr($this->Application->GetVar($top_prefix . '_mode'), 0, 1) == 't'; + $modified = $this->Application->RecallVar($top_prefix . '_modified'); - if (!$temp_tables) { - $this->Application->RemoveVar($top_prefix.'_modified'); + if ( !$temp_tables ) { + $this->Application->RemoveVar($top_prefix . '_modified'); return ''; } $block_name = $this->SelectParam($params, 'render_as,name'); - if ($block_name) { + if ( $block_name ) { $block_params = $this->prepareTagParams($params); $block_params['name'] = $block_name; $block_params['edit_mode'] = $temp_tables ? 1 : 0; $block_params['display'] = $temp_tables && $modified ? 1 : 0; return $this->Application->ParseBlock($block_params); } - else { - return $temp_tables && $modified ? 1 : 0; - } - return ; + + return $temp_tables && $modified ? 1 : 0; } /** @@ -602,6 +606,8 @@ function IsRootCategory($params) { $object =& $this->getObject($params); + /* @var $object CategoriesItem */ + return $object->IsRoot(); } @@ -681,19 +687,19 @@ { static $current_path = null; - if (!isset($current_path)) { + if ( !isset($current_path) ) { $sql = 'SELECT ParentPath FROM ' . TABLE_PREFIX . 'Category WHERE CategoryId = ' . (int)$this->Application->GetVar('m_cat_id'); $current_path = $this->Conn->GetOne($sql); } - if (array_key_exists('parent_path', $params)) { + if ( array_key_exists('parent_path', $params) ) { $test_path = $params['parent_path']; } else { $template = $params['template']; - if ($template) { + if ( $template ) { // when using from "c:CachedMenu" tag $sql = 'SELECT ParentPath FROM ' . TABLE_PREFIX . 'Category @@ -703,16 +709,18 @@ else { // when using from "c:PrintList" tag $cat_id = array_key_exists('cat_id', $params) && $params['cat_id'] ? $params['cat_id'] : false; - if ($cat_id === false) { + if ( $cat_id === false ) { // category not supplied -> get current from PrintList $category =& $this->getObject($params); } else { - if ("$cat_id" == 'Root') { + if ( "$cat_id" == 'Root' ) { $cat_id = $this->Application->findModule('Name', $params['module'], 'RootCat'); } $category =& $this->Application->recallObject($this->Prefix . '.-c' . $cat_id, $this->Prefix, Array ('skip_autoload' => true)); + /* @var $category CategoriesItem */ + $category->Load($cat_id); } @@ -769,8 +777,8 @@ $row_data = $this->Application->getCache($cache_key); - if ($row_data === false) { - if ($local && ($category_id > 0)) { + if ( $row_data === false ) { + if ( $local && ($category_id > 0) ) { // scan only current category & it's children list ($tree_left, $tree_right) = $this->Application->getTreeIndex($category_id); @@ -789,17 +797,20 @@ $this->Application->setCache($cache_key, $row_data); } - if (!$row_data) { + if ( !$row_data ) { return ''; } - $date = $row_data[ $row_data['NewDate'] > $row_data['ModDate'] ? 'NewDate' : 'ModDate' ]; + $date = $row_data[$row_data['NewDate'] > $row_data['ModDate'] ? 'NewDate' : 'ModDate']; // format date $format = isset($params['format']) ? $params['format'] : '_regional_DateTimeFormat'; - if (preg_match("/_regional_(.*)/", $format, $regs)) { + + if ( preg_match("/_regional_(.*)/", $format, $regs) ) { $lang =& $this->Application->recallObject('lang.current'); - if ($regs[1] == 'DateTimeFormat') { + /* @var $lang LanguagesItem */ + + if ( $regs[1] == 'DateTimeFormat' ) { // combined format $format = $lang->GetDBField('DateFormat') . ' ' . $lang->GetDBField('TimeFormat'); } @@ -902,19 +913,20 @@ * * @param Array $params * @return string + * @access protected */ - function SpellingSuggestions($params) + protected function SpellingSuggestions($params) { $keywords = kUtil::unhtmlentities( trim($this->Application->GetVar('keywords')) ); - if (!$keywords) { - return ; + if ( !$keywords ) { + return ''; } // 1. try to get already cached suggestion $cache_key = 'search.suggestion[%SpellingDictionary%]:' . $keywords; $suggestion = $this->Application->getCache($cache_key); - if ($suggestion !== false) { + if ( $suggestion !== false ) { return $suggestion; } @@ -927,8 +939,9 @@ WHERE MisspelledWord = ' . $this->Conn->qstr($keywords); $suggestion = $this->Conn->GetOne($sql); - if ($suggestion !== false) { + if ( $suggestion !== false ) { $this->Application->setCache($cache_key, $suggestion); + return $suggestion; } @@ -939,22 +952,20 @@ $curl_helper =& $this->Application->recallObject('CurlHelper'); /* @var $curl_helper kCurlHelper */ - $xml_data = $curl_helper->Send($url . urlencode($keywords)); + $xml_data = $curl_helper->Send( $url . urlencode($keywords) ); $xml_helper =& $this->Application->recallObject('kXMLHelper'); /* @var $xml_helper kXMLHelper */ $root_node =& $xml_helper->Parse($xml_data); + /* @var $root_node kXMLNode */ $result = $root_node->FindChild('RESULT'); /* @var $result kXMLNode */ - if (is_object($result)) { + if ( is_object($result) ) { // webservice responded -> save in local database - $fields_hash = Array ( - 'MisspelledWord' => $keywords, - 'SuggestedCorrection' => $result->Data, - ); + $fields_hash = Array ('MisspelledWord' => $keywords, 'SuggestedCorrection' => $result->Data); $this->Conn->doInsert($fields_hash, $table_name); $this->Application->setCache($cache_key, $result->Data); @@ -1075,7 +1086,7 @@ * Returns page object based on requested params * * @param Array $params - * @return PagesItem + * @return CategoriesItem */ function &_getPage($params) { @@ -1323,14 +1334,14 @@ /** * Includes admin css and js, that are required for cms usage on Front-Edn * - * * @param Array $params * @return string + * @access protected */ - function EditingScripts($params) + protected function EditingScripts($params) { - if ($this->Application->GetVar('admin_scripts_included') || !EDITING_MODE) { - return ; + if ( $this->Application->GetVar('admin_scripts_included') || !EDITING_MODE ) { + return ''; } $this->Application->SetVar('admin_scripts_included', 1); @@ -1344,17 +1355,16 @@ $js_url . '/../incs/cms.css', ); - $css_compressed = $minify_helper->CompressScriptTag( Array ('files' => implode('|', $to_compress)) ); + $css_compressed = $minify_helper->CompressScriptTag(Array ('files' => implode('|', $to_compress))); $ret = '' . "\n"; - if (EDITING_MODE == EDITING_MODE_DESIGN) { + if ( EDITING_MODE == EDITING_MODE_DESIGN ) { $ret .= ' '; } - $ret .= '' . "\n"; $ret .= '' . "\n"; @@ -1389,11 +1399,11 @@ $ret .= "var \$use_popups = " . ($use_popups > 0 ? 'true' : 'false') . ";\n"; $ret .= "var \$modal_windows = " . ($use_popups == 2 ? 'true' : 'false') . ";\n"; - if (EDITING_MODE != EDITING_MODE_BROWSE) { + if ( EDITING_MODE != EDITING_MODE_BROWSE ) { $ret .= "var base_url = '" . $this->Application->BaseURL() . "';" . "\n"; $ret .= 'TB.closeHtml = \'close
\';' . "\n"; - $url_params = Array('m_theme' => '', 'pass' => 'm', 'm_opener' => 'r', '__NO_REWRITE__' => 1, 'no_amp' => 1); + $url_params = Array ('m_theme' => '', 'pass' => 'm', 'm_opener' => 'r', '__NO_REWRITE__' => 1, 'no_amp' => 1); $browse_url = $this->Application->HREF('catalog/catalog', ADMIN_DIRECTORY, $url_params, 'index.php'); $browse_url = preg_replace('/&(admin|editing_mode)=[\d]/', '', $browse_url); @@ -1401,7 +1411,7 @@ var topmost = window.top; topmost.document.title = document.title + \' - ' . addslashes($this->Application->Phrase('la_AdministrativeConsole', false)) . '\'; - t = \''.$this->Application->GetVar('t').'\'; + t = \'' . $this->Application->GetVar('t') . '\'; if (window.parent.frames["menu"] != undefined) { if ( $.isFunction(window.parent.frames["menu"].SyncActive) ) { @@ -1413,7 +1423,7 @@ $ret .= '' . "\n"; - if (EDITING_MODE != EDITING_MODE_BROWSE) { + if ( EDITING_MODE != EDITING_MODE_BROWSE ) { // add form, so admin scripts could work $ret .= '
Index: units/category_items/category_items_dbitem.php =================================================================== --- units/category_items/category_items_dbitem.php (revision 14590) +++ units/category_items/category_items_dbitem.php (working copy) @@ -12,36 +12,36 @@ * See http://www.in-portal.org/license for copyright notices and details. */ - defined('FULL_PATH') or die('restricted access!'); +defined('FULL_PATH') or die('restricted access!'); - class CategoryItems_DBItem extends kDBItem +class CategoryItems_DBItem extends kDBItem { + + /** + * Returns part of SQL WHERE clause identifying the record, ex. id = 25 + * + * @param string $method Child class may want to know who called GetKeyClause, Load(), Update(), Delete() send its names as method + * @see kDBItem::Load() + * @see kDBItem::Update() + * @see kDBItem::Delete() + * + * @return string + * @access protected + */ + protected function GetKeyClause($method = null) { + $table_info = $this->getLinkedInfo(); + return '(CategoryId=' . $this->GetID() . ' AND ' . $table_info['ForeignKey'] . '=' . $table_info['ParentId'] . ')'; + } - /** - * 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 - * @return void - * @see kDBItem::Load() - * @see kDBItem::Update() - * @see kDBItem::Delete() - */ - function GetKeyClause($method=null) - { - $table_info = $this->getLinkedInfo(); - return '(CategoryId='.$this->ID.' AND '.$table_info['ForeignKey'].'='.$table_info['ParentId'].')'; - } - - /** - * Generate and set new temporary id - * - * @access private - */ - function setTempID() - { - // don't set temp id for this item - } - - } \ No newline at end of file + /** + * Generate and set new temporary id + * + * @return void + * @access public + */ + public function setTempID() + { + // don't set temp id for this item + } +} \ No newline at end of file Index: units/category_items/category_items_event_handler.php =================================================================== --- units/category_items/category_items_event_handler.php (revision 14590) +++ units/category_items/category_items_event_handler.php (working copy) @@ -16,17 +16,21 @@ class CategoryItemsEventHander extends kDBEventHandler { - /** * Setting language dependant navbar as calculated field * * @param kEvent $event + * @return void + * @access protected + * @see kDBEventHandler::OnListBuild() */ - function SetCustomQuery(&$event) + protected function SetCustomQuery(&$event) { $object =& $event->getObject(); $ml_formatter =& $this->Application->recallObject('kMultiLanguage'); + /* @var $ml_formatter kMultiLanguage */ + $object->addCalculatedField('CategoryName', 'c.'.$ml_formatter->LangFieldName('CachedNavbar')); } @@ -55,8 +59,11 @@ * Apply custom processing to item * * @param kEvent $event + * @param string $type + * @return void + * @access protected */ - function customProcessing(&$event, $type) + protected function customProcessing(&$event, $type) { if($event->Name == 'OnMassDelete') { @@ -108,29 +115,36 @@ * In case if item is deleted from it's last category, then delete item too. * * @param kEvent $event + * @return void + * @access protected */ - function OnDeleteFromCategory(&$event) + protected function OnDeleteFromCategory(&$event) { $category_ids = $event->getEventParam('category_ids'); - if(!$category_ids) return false; + if ( !$category_ids ) { + return ; + } + $item_prefix = $event->getEventParam('item_prefix'); - $item =& $this->Application->recallObject($item_prefix.'.-item', null, Array('skip_autoload' => true)); + $item =& $this->Application->recallObject($item_prefix . '.-item', null, Array ('skip_autoload' => true)); + /* @var $item kCatDBItem */ $ci_table = $this->Application->getUnitOption($event->Prefix, 'TableName'); $item_table = $this->Application->getUnitOption($item_prefix, 'TableName'); - $sql = 'SELECT ItemResourceId, CategoryId FROM %1$s INNER JOIN %2$s ON (%1$s.ResourceId = %2$s.ItemResourceId) WHERE CategoryId IN (%3$s)'; - $category_items = $this->Conn->Query( sprintf($sql, $item_table, $ci_table, implode(',', $category_ids) ) ); + $sql = 'SELECT ItemResourceId, CategoryId + FROM %1$s + INNER JOIN %2$s ON (%1$s.ResourceId = %2$s.ItemResourceId) + WHERE CategoryId IN (%3$s)'; + $category_items = $this->Conn->Query( sprintf($sql, $item_table, $ci_table, implode(',', $category_ids)) ); - $item_hash = Array(); - foreach($category_items as $ci_row) - { + $item_hash = Array (); + foreach ($category_items as $ci_row) { $item_hash[ $ci_row['ItemResourceId'] ][] = $ci_row['CategoryId']; } - foreach($item_hash as $item_resource_id => $delete_category_ids) - { + foreach ($item_hash as $item_resource_id => $delete_category_ids) { $item->Load($item_resource_id, 'ResourceId'); $item->DeleteFromCategories($delete_category_ids); } Index: units/category_items/category_items_tag_processor.php =================================================================== --- units/category_items/category_items_tag_processor.php (revision 14590) +++ units/category_items/category_items_tag_processor.php (working copy) @@ -38,8 +38,9 @@ function GetMainID() { - $object =& $this->Application->recallObject( $this->getPrefixSpecial() ); + $object =& $this->getObject(); $table_info = $object->getLinkedInfo(); + return $table_info['ParentId']; } } \ No newline at end of file Index: units/config_search/config_search_event_handler.php =================================================================== --- units/config_search/config_search_event_handler.php (revision 14590) +++ units/config_search/config_search_event_handler.php (working copy) @@ -20,13 +20,16 @@ * Changes permission section to one from REQUEST, not from config * * @param kEvent $event + * @return bool + * @access public */ - function CheckPermission(&$event) + public function CheckPermission(&$event) { $module = $this->Application->GetVar('module'); $main_prefix = $this->Application->findModule('Name', $module, 'Var'); $section = $this->Application->getUnitOption($main_prefix.'.search', 'PermSection'); $event->setEventParam('PermSection', $section); + return parent::CheckPermission($event); } @@ -34,13 +37,15 @@ * Apply any custom changes to list's sql query * * @param kEvent $event + * @return void * @access protected - * @see OnListBuild + * @see kDBEventHandler::OnListBuild() */ - function SetCustomQuery(&$event) + protected function SetCustomQuery(&$event) { $object =& $event->getObject(); - + /* @var $object kDBList */ + // show only items that belong to selected module $module = $this->Application->GetVar('module'); $object->addFilter('module_filter', '%1$s.ModuleName = '.$this->Conn->qstr($module)); @@ -75,33 +80,46 @@ $event->SetRedirectParam('section', $this->Application->GetVar('section')); } + /** + * Cancels kDBItem Editing/Creation + * + * @param kEvent $event + * @return void + * @access protected + */ function OnCancel(&$event) { parent::OnCancel($event); + $event->SetRedirectParam('opener', 's'); } /** - * [HOOK] Enter description here... + * [HOOK] Creates search config record corresponding to custom field, that was just created * * @param kEvent $event + * @return void + * @access protected */ - function OnCreateCustomField(&$event) + protected function OnCreateCustomField(&$event) { $custom_field =& $event->MasterEvent->getObject(); - if ($custom_field->GetDBField('Type') == 6 || $custom_field->GetDBField('IsSystem') == 1) { + /* @var $custom_field kDBItem */ + + if ( $custom_field->GetDBField('Type') == 6 || $custom_field->GetDBField('IsSystem') == 1 ) { // user & system custom fields are not searchable - return false; + return ; } - $object =& $event->getObject( Array('skip_autoload' => true) ); + $object =& $event->getObject(Array ('skip_autoload' => true)); + /* @var $object kDBItem */ $custom_id = $custom_field->GetID(); - if (!$object->isLoaded() || ($object->GetDBField('CustomFieldId') != $custom_id)) { + if ( !$object->isLoaded() || ($object->GetDBField('CustomFieldId') != $custom_id) ) { $object->Load($custom_id, 'CustomFieldId'); } - $cf_search = Array(); + $cf_search = Array (); $element_type = $custom_field->GetDBField('ElementType'); $cf_search['DisplayOrder'] = $custom_field->GetDBField('DisplayOrder'); @@ -114,14 +132,19 @@ $cf_search['TableName'] = 'CustomField'; $sql = 'SELECT Module - FROM '.TABLE_PREFIX.'ItemTypes - WHERE ItemType = '.$custom_field->GetDBField('Type'); + FROM ' . TABLE_PREFIX . 'ItemTypes + WHERE ItemType = ' . $custom_field->GetDBField('Type'); - $cf_search['ModuleName'] = $this->Conn->GetOne($sql); + $cf_search['ModuleName'] = $this->Conn->GetOne($sql); $object->SetFieldsFromHash($cf_search); $object->SetDBField('CustomFieldId', $custom_id); - $result = $object->isLoaded() ? $object->Update() : $object->Create(); + if ( $object->isLoaded() ) { + $object->Update(); + } + else { + $object->Create(); + } } } \ No newline at end of file Index: units/configuration/configuration.php =================================================================== --- units/configuration/configuration.php (revision 14590) +++ units/configuration/configuration.php (working copy) @@ -12,44 +12,53 @@ * See http://www.in-portal.org/license for copyright notices and details. */ - defined('FULL_PATH') or die('restricted access!'); +defined('FULL_PATH') or die('restricted access!'); - class ConfigurationItem extends kDBItem { +class ConfigurationItem extends kDBItem { - /** - * Returns key clause for Load,Update,Delete operations - * Applies current section filter to affect only configuration values, - * that are allowed by section in get, which is permission checked before - * - * @param string $method - * @param Array $keys_hash - * @return string - */ - function GetKeyClause($method=null, $keys_hash = null) - { - $keys_hash['Section'] = $this->Application->GetVar('section'); - $keys_hash[$this->IDField] = $this->ID; - return parent::GetKeyClause($method, $keys_hash); - } + /** + * Returns part of SQL WHERE clause identifying the record, ex. id = 25 + * + * @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 + * @see kDBItem::Load() + * @see kDBItem::Update() + * @see kDBItem::Delete() + * + * @return string + * @access protected + */ + protected function GetKeyClause($method = null, $keys_hash = null) + { + $keys_hash['Section'] = $this->Application->GetVar('section'); + $keys_hash[$this->IDField] = $this->GetID(); - /** - * 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) - { - if (!parent::SetError($field, $pseudo, $error_label, $error_params)) { - // this field already has an error -> don't overwrite it - return false; - } + return parent::GetKeyClause($method, $keys_hash); + } - $list_errors = $this->Application->GetVar('errors_' . $this->getPrefixSpecial(), Array ()); - $list_errors[ $this->GetDBField('VariableName') ] = $this->GetErrorMsg($field); - $this->Application->SetVar('errors_' . $this->getPrefixSpecial(), $list_errors); + /** + * Set's field error, if pseudo passed not found then create it with message text supplied. + * Don't overwrite existing pseudo translation. + * + * @param string $field + * @param string $pseudo + * @param string $error_label + * @param Array $error_params + * + * @return bool + * @access public + */ + public function SetError($field, $pseudo, $error_label = null, $error_params = null) + { + if ( !parent::SetError($field, $pseudo, $error_label, $error_params) ) { + // this field already has an error -> don't overwrite it + return false; } - } \ No newline at end of file + $list_errors = $this->Application->GetVar('errors_' . $this->getPrefixSpecial(), Array ()); + $list_errors[ $this->GetDBField('VariableName') ] = $this->GetErrorMsg($field); + $this->Application->SetVar('errors_' . $this->getPrefixSpecial(), $list_errors); + + return true; + } +} \ No newline at end of file Index: units/configuration/configuration_event_handler.php =================================================================== --- units/configuration/configuration_event_handler.php (revision 14590) +++ units/configuration/configuration_event_handler.php (working copy) @@ -20,8 +20,10 @@ * Changes permission section to one from REQUEST, not from config * * @param kEvent $event + * @return bool + * @access public */ - function CheckPermission(&$event) + public function CheckPermission(&$event) { $event->setEventParam('PermSection', $this->Application->GetVar('section')); return parent::CheckPermission($event); @@ -31,10 +33,11 @@ * Apply any custom changes to list's sql query * * @param kEvent $event + * @return void * @access protected - * @see OnListBuild + * @see kDBEventHandler::OnListBuild() */ - function SetCustomQuery(&$event) + protected function SetCustomQuery(&$event) { $object =& $event->getObject(); /* @var $object kDBList */ @@ -57,50 +60,55 @@ } /** - * Enter description here... + * Performs validation of configuration variable value * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemUpdate(&$event) + protected function OnBeforeItemUpdate(&$event) { static $default_field_options = null; + parent::OnBeforeItemUpdate($event); + $object =& $event->getObject(); /* @var $object kDBItem */ // ability to validate each configuration variable separately - if (!isset($default_field_options)) { + if ( !isset($default_field_options) ) { $default_field_options = $object->GetFieldOptions('VariableValue'); } $new_field_options = $default_field_options; $validation = $object->GetDBField('Validation'); - if ($validation) { + + if ( $validation ) { $new_field_options = array_merge($new_field_options, unserialize($validation)); } + $object->SetFieldOptions('VariableValue', $new_field_options); // if password field is empty, then don't update - if ($object->GetDBField('ElementType') == 'password') { - if (trim($object->GetDBField('VariableValue')) == '') { + if ( $object->GetDBField('ElementType') == 'password' ) { + if ( trim($object->GetDBField('VariableValue')) == '' ) { $field_options = $object->GetFieldOptions('VariableValue'); $field_options['skip_empty'] = 1; $object->SetFieldOptions('VariableValue', $field_options); - }else { + } + else { $password_formatter =& $this->Application->recallObject('kPasswordFormatter'); + /* @var $password_formatter kPasswordFormatter */ + $object->SetDBField('VariableValue', $password_formatter->EncryptPassword($object->GetDBField('VariableValue'), 'b38')); } } - $field_values = $this->Application->GetVar( $event->getPrefixSpecial(true) ); + $field_name = $object->GetDBField('VariableName'); + $field_values = $this->Application->GetVar($event->getPrefixSpecial(true)); + $state_country_hash = Array ('Comm_State' => 'Comm_Country', 'Comm_Shipping_State' => 'Comm_Shipping_Country'); - $state_country_hash = Array ( - 'Comm_State' => 'Comm_Country', - 'Comm_Shipping_State' => 'Comm_Shipping_Country' - ); - - $field_name = $object->GetDBField('VariableName'); - if (array_key_exists($field_name, $state_country_hash)) { + if ( array_key_exists($field_name, $state_country_hash) ) { // if this is state field $sql = 'SELECT VariableId FROM ' . $this->Application->getUnitOption('conf', 'TableName') . ' @@ -110,8 +118,8 @@ $check_state = $object->GetDBField('VariableValue'); $check_country = $field_values[$country_variable_id]['VariableValue']; - if (!$check_country || !$check_state) { - return true; + if ( !$check_country || !$check_state ) { + return; } $cs_helper =& $this->Application->recallObject('CountryStatesHelper'); @@ -119,7 +127,7 @@ $state_iso = $cs_helper->getStateIso($check_state, $check_country); - if ($state_iso !== false) { + if ( $state_iso !== false ) { $object->SetDBField('VariableValue', $state_iso); } else { @@ -128,13 +136,12 @@ } } - if ($object->GetDBField('VariableName') == 'AdminConsoleInterface') { + if ( $object->GetDBField('VariableName') == 'AdminConsoleInterface' ) { $can_change = $this->Application->ConfigValue('AllowAdminConsoleInterfaceChange'); - if (($object->GetDBField('VariableValue') != $object->GetOriginalField('VariableValue')) && !$can_change) { + if ( ($object->GetDBField('VariableValue') != $object->GetOriginalField('VariableValue')) && !$can_change ) { $object->SetError('VariableValue', 'not_allowed', 'la_error_OperationNotAllowed'); } - } } Index: units/content/content_eh.php =================================================================== --- units/content/content_eh.php (revision 14590) +++ units/content/content_eh.php (working copy) @@ -17,11 +17,13 @@ class ContentEventHandler extends kDBEventHandler { /** - * Checks permissions of user + * Checks user permission to execute given $event * * @param kEvent $event + * @return bool + * @access public */ - function CheckPermission(&$event) + public function CheckPermission(&$event) { $perm_helper =& $this->Application->recallObject('PermissionsHelper'); /* @var $perm_helper kPermissionsHelper */ Index: units/country_states/country_state_eh.php =================================================================== --- units/country_states/country_state_eh.php (revision 14590) +++ units/country_states/country_state_eh.php (working copy) @@ -20,8 +20,11 @@ * Applies edit picker filters * * @param kEvent $event + * @return void + * @access protected + * @see kDBEventHandler::OnListBuild() */ - function SetCustomQuery(&$event) + protected function SetCustomQuery(&$event) { parent::SetCustomQuery($event); @@ -43,8 +46,10 @@ * Makes sure, that state country is always specified * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemCreate(&$event) + protected function OnBeforeItemCreate(&$event) { parent::OnBeforeItemCreate($event); @@ -55,8 +60,10 @@ * Makes sure, that state country is always specified * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemUpdate(&$event) + protected function OnBeforeItemUpdate(&$event) { parent::OnBeforeItemUpdate($event); Index: units/custom_data/custom_data_event_handler.php =================================================================== --- units/custom_data/custom_data_event_handler.php (revision 14590) +++ units/custom_data/custom_data_event_handler.php (working copy) @@ -36,7 +36,15 @@ $this->createCustomFields($event->MasterEvent->Prefix); } - function scanCustomFields($prefix) + /** + * Returns list of custom fields for a given $prefix + * + * @param $prefix + * + * @return Array|bool + * @access protected + */ + protected function scanCustomFields($prefix) { static $custom_fields = Array (); @@ -107,27 +115,33 @@ * Fills cloned cdata config with data from it's parent * * @param kEvent $event + * @return void + * @access protected */ - function OnAfterConfigRead(&$event) + protected function OnAfterConfigRead(&$event) { $main_prefix = $this->Application->getUnitOption($event->Prefix, 'ParentPrefix'); - if (!$main_prefix) { - return false; + if ( !$main_prefix ) { + return ; } $custom_fields = $this->scanCustomFields($main_prefix); - if (!$custom_fields) { - return false; + if ( !$custom_fields ) { + return ; } // 2. create fields (for customdata item) - $fields = $this->Application->getUnitOption($event->Prefix, 'Fields', Array()); - $field_options = Array('type' => 'string', 'formatter' => 'kMultiLanguage', 'db_type' => 'text', 'default' => ''); + $fields = $this->Application->getUnitOption($event->Prefix, 'Fields', Array ()); + $field_options = Array ('type' => 'string', 'formatter' => 'kMultiLanguage', 'db_type' => 'text', 'default' => ''); + foreach ($custom_fields as $custom_id => $custom_params) { - if (isset($fields['cust_'.$custom_id])) continue; - $fields['cust_'.$custom_id] = $field_options; - $fields['cust_'.$custom_id]['force_primary'] = !$custom_params['MultiLingual']; + if ( isset($fields['cust_' . $custom_id]) ) { + continue; + } + $fields['cust_' . $custom_id] = $field_options; + $fields['cust_' . $custom_id]['force_primary'] = !$custom_params['MultiLingual']; } + $this->Application->setUnitOption($event->Prefix, 'Fields', $fields); } @@ -135,16 +149,18 @@ * Creates "cust_" virtual fields for main item * * @param string $prefix + * @return void + * @access protected */ - function createCustomFields($prefix) + protected function createCustomFields($prefix) { $custom_fields = $this->scanCustomFields($prefix); - if (!$custom_fields) { - return false; + if ( !$custom_fields ) { + return; } - $calculated_fields = Array(); - $virtual_fields = $this->Application->getUnitOption($prefix, 'VirtualFields', Array()); + $calculated_fields = Array (); + $virtual_fields = $this->Application->getUnitOption($prefix, 'VirtualFields', Array ()); $cf_helper =& $this->Application->recallObject('InpCustomFieldsHelper'); /* @var $cf_helper InpCustomFieldsHelper */ @@ -153,16 +169,16 @@ foreach ($custom_fields as $custom_id => $custom_params) { $custom_name = $custom_params['FieldName']; - $field_options = Array('type' => 'string', 'default' => $custom_params['DefaultValue']); + $field_options = Array ('type' => 'string', 'default' => $custom_params['DefaultValue']); // raises warnings during 4.3.9 -> 5.0.0 upgrade, no fatal sqls though if ( $custom_params['IsRequired'] ) { $field_options['required'] = 1; } - $calculated_fields['cust_' . $custom_name] = 'cust.l' . $this->Application->GetDefaultLanguageId() .'_cust_' . $custom_id; + $calculated_fields['cust_' . $custom_name] = 'cust.l' . $this->Application->GetDefaultLanguageId() . '_cust_' . $custom_id; - switch ($custom_params['ElementType']) { + switch ( $custom_params['ElementType'] ) { case 'date': unset($field_options['options']); $field_options['formatter'] = 'kDateFormatter'; @@ -178,7 +194,7 @@ case 'select': case 'multiselect': case 'radio': - if ($custom_params['ValueList']) { + if ( $custom_params['ValueList'] ) { // $is_install check prevents 335 bad phrase sql errors on upgrade to 5.1.0 $field_options['options'] = $is_install ? Array () : $cf_helper->GetValuesHash($custom_params['ValueList']); $field_options['formatter'] = 'kOptionsFormatter'; @@ -187,7 +203,7 @@ break; default: - if ($custom_params['MultiLingual']) { + if ( $custom_params['MultiLingual'] ) { $field_options['formatter'] = 'kMultiLanguage'; $calculated_fields['cust_' . $custom_name] = 'cust.l%2$s_cust_' . $custom_id; } @@ -201,9 +217,9 @@ $custom_fields[$custom_id] = $custom_name; } - $config_calculated_fields = $this->Application->getUnitOption($prefix, 'CalculatedFields', Array()); + $config_calculated_fields = $this->Application->getUnitOption($prefix, 'CalculatedFields', Array ()); foreach ($config_calculated_fields as $special => $special_fields) { - if ($special == '-virtual') { + if ( $special == '-virtual' ) { continue; } Index: units/custom_fields/custom_fields_event_handler.php =================================================================== --- units/custom_fields/custom_fields_event_handler.php (revision 14590) +++ units/custom_fields/custom_fields_event_handler.php (working copy) @@ -20,8 +20,10 @@ * Changes permission section to one from REQUEST, not from config * * @param kEvent $event + * @return bool + * @access public */ - function CheckPermission(&$event) + public function CheckPermission(&$event) { $sql = 'SELECT Prefix FROM '.TABLE_PREFIX.'ItemTypes @@ -38,10 +40,11 @@ * Apply any custom changes to list's sql query * * @param kEvent $event + * @return void * @access protected - * @see OnListBuild + * @see kDBEventHandler::OnListBuild() */ - function SetCustomQuery(&$event) + protected function SetCustomQuery(&$event) { $object =& $event->getObject(); /* @var $object kDBList */ @@ -57,7 +60,7 @@ } if ($item_type) { - $hidden_fields = array_map(Array(&$this->Conn, 'qstr'), $this->_getHiddenFiels($event)); + $hidden_fields = array_map(Array(&$this->Conn, 'qstr'), $this->_getHiddenFields($event)); if ($hidden_fields) { $object->addFilter('hidden_filter', '%1$s.FieldName NOT IN (' . implode(',', $hidden_fields) . ')'); @@ -95,20 +98,22 @@ * * @param kEvent $event * @return Array + * @access protected */ - function _getHiddenFiels(&$event) + protected function _getHiddenFields(&$event) { $prefix = $this->_getSourcePrefix($event); + $hidden_fields = Array (); $virtual_fields = $this->Application->getUnitOption($prefix, 'VirtualFields', Array ()); $custom_fields = $this->Application->getUnitOption($prefix, 'CustomFields', Array ()); + /* @var $custom_fields Array */ - $hidden_fields = Array (); foreach ($custom_fields as $custom_field) { $check_field = 'cust_' . $custom_field; $show_mode = array_key_exists('show_mode', $virtual_fields[$check_field]) ? $virtual_fields[$check_field]['show_mode'] : true; - if (($show_mode === false) || (($show_mode === smDEBUG) && !(defined('DEBUG_MODE') && DEBUG_MODE))) { + if ( ($show_mode === false) || (($show_mode === smDEBUG) && !(defined('DEBUG_MODE') && DEBUG_MODE)) ) { $hidden_fields[] = $custom_field; } } @@ -120,25 +125,29 @@ * Prevents from duplicate item creation * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemCreate(&$event) + protected function OnBeforeItemCreate(&$event) { + parent::OnBeforeItemCreate($event); + $object =& $event->getObject(); + /* @var $object kDBItem */ - $live_table = $this->Application->getUnitOption($event->Prefix, 'TableName'); $sql = 'SELECT COUNT(*) - FROM '.$live_table.' - WHERE FieldName = '.$this->Conn->qstr($object->GetDBField('FieldName')).' AND Type = '.$object->GetDBField('Type'); + FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . ' + WHERE FieldName = ' . $this->Conn->qstr($object->GetDBField('FieldName')) . ' AND Type = ' . $object->GetDBField('Type'); $found = $this->Conn->GetOne($sql); - if ($found) { + if ( $found ) { $event->status = kEvent::erFAIL; $object->SetError('FieldName', 'duplicate', 'la_error_CustomExists'); } } /** - * Occurse after deleting item, id of deleted item + * Occurs after deleting item, id of deleted item * is stored as 'id' param of event * * @param kEvent $event @@ -147,42 +156,50 @@ function OnAfterItemDelete(&$event) { $object =& $event->getObject(); - $main_prefix = $this->getPrefixByItemType($object->GetDBField('Type')); + /* @var $object kDBItem */ + $main_prefix = $this->getPrefixByItemType( $object->GetDBField('Type') ); + $ml_helper =& $this->Application->recallObject('kMultiLanguageHelper'); /* @var $ml_helper kMultiLanguageHelper */ // call main item config to clone cdata table $this->Application->getUnitOption($main_prefix, 'TableName'); - $ml_helper->deleteField($main_prefix.'-cdata', $event->getEventParam('id')); + $ml_helper->deleteField($main_prefix . '-cdata', $event->getEventParam('id')); } /** * Get config prefix based on item type * - * @param unknown_type $item_type - * @return unknown + * @param int $item_type + * @return string + * @access protected */ - function getPrefixByItemType($item_type) + protected function getPrefixByItemType($item_type) { $sql = 'SELECT Prefix - FROM '.TABLE_PREFIX.'ItemTypes - WHERE ItemType = '.$item_type; + FROM ' . TABLE_PREFIX . 'ItemTypes + WHERE ItemType = ' . $item_type; + return $this->Conn->GetOne($sql); } /** - * Enter description here... + * Creates new database columns, once custom field is successfully created * * @param kEvent $event + * @return void + * @access protected */ - function OnSaveCustomField(&$event) + protected function OnSaveCustomField(&$event) { - if ($event->MasterEvent->status != kEvent::erSUCCESS) { - return false; + if ( $event->MasterEvent->status != kEvent::erSUCCESS ) { + return ; } $object =& $event->getObject(); + /* @var $object kDBItem */ + $main_prefix = $this->getPrefixByItemType($object->GetDBField('Type')); $ml_helper =& $this->Application->recallObject('kMultiLanguageHelper'); @@ -191,13 +208,23 @@ // call main item config to clone cdata table define('CUSTOM_FIELD_ADDED', 1); // used in cdata::scanCustomFields method $this->Application->getUnitOption($main_prefix, 'TableName'); - $ml_helper->createFields($main_prefix.'-cdata'); + $ml_helper->createFields($main_prefix . '-cdata'); } - function OnMassDelete(&$event) + /** + * 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 + * @return void + * @access protected + */ + protected function OnMassDelete(&$event) { parent::OnMassDelete($event); - $event->setRedirectParams(Array('opener' => 's'), true); + + $event->SetRedirectParam('opener', 's'); } /** @@ -206,12 +233,16 @@ * done in OnPreSaveCreated * * @param kEvent $event + * @return void + * @access protected */ - function OnPreCreate(&$event) + protected function OnPreCreate(&$event) { parent::OnPreCreate($event); $object =& $event->getObject(); + /* @var $object kDBItem */ + $object->SetDBField('Type', $this->Application->GetVar('cf_type')); } @@ -219,27 +250,29 @@ * Prepares ValueList field's value as xml for editing * * @param kEvent $event + * @return void + * @access protected */ - function OnAfterItemLoad(&$event) + protected function OnAfterItemLoad(&$event) { parent::OnAfterItemLoad($event); $object =& $event->getObject(); /* @var $object kDBItem */ - if (!in_array($object->GetDBField('ElementType'), $this->_getMultiElementTypes())) { + if ( !in_array($object->GetDBField('ElementType'), $this->_getMultiElementTypes()) ) { return ; } $custom_field_helper =& $this->Application->recallObject('InpCustomFieldsHelper'); /* @var $custom_field_helper InpCustomFieldsHelper */ - $options = $custom_field_helper->GetValuesHash( $object->GetDBField('ValueList'), VALUE_LIST_SEPARATOR, false ); + $options = $custom_field_helper->GetValuesHash($object->GetDBField('ValueList'), VALUE_LIST_SEPARATOR, false); $records = Array (); $option_key = key($options); - if ($option_key === '' || $option_key == 0) { + if ( $option_key === '' || $option_key == 0 ) { // remove 1st empty option, and add it later, when options will be saved, but allow string option keys unset($options[$option_key]); // keep index, don't use array_unshift! } @@ -258,9 +291,10 @@ /** * Returns custom field element types, that will use minput control * - * @return unknown + * @return Array + * @access protected */ - function _getMultiElementTypes() + protected function _getMultiElementTypes() { return Array ('select', 'multiselect', 'radio'); } @@ -269,15 +303,17 @@ * Saves minput content to ValueList field * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemUpdate(&$event) + protected function OnBeforeItemUpdate(&$event) { parent::OnBeforeItemUpdate($event); $object =& $event->getObject(); /* @var $object kDBItem */ - if (!in_array($object->GetDBField('ElementType'), $this->_getMultiElementTypes())) { + if ( !in_array($object->GetDBField('ElementType'), $this->_getMultiElementTypes()) ) { return ; } @@ -287,13 +323,13 @@ $ret = $object->GetDBField('ElementType') == 'select' ? Array ('' => '=+') : Array (); $records = $minput_helper->parseMInputXML($object->GetDBField('Options')); - if ($object->GetDBField('SortValues')) { + if ( $object->GetDBField('SortValues') ) { usort($records, Array (&$this, '_sortValues')); ksort($records); } foreach ($records as $record) { - if (substr($record['OptionKey'], 0, 3) == 'SQL') { + if ( substr($record['OptionKey'], 0, 3) == 'SQL' ) { $ret[] = $record['OptionTitle']; } else { Index: units/custom_fields/custom_fields_tag_processor.php =================================================================== --- units/custom_fields/custom_fields_tag_processor.php (revision 14590) +++ units/custom_fields/custom_fields_tag_processor.php (working copy) @@ -86,17 +86,21 @@ $prev_heading = ''; $display_original = false; $source_prefix = getArrayValue($params, 'SourcePrefix'); - if ($source_prefix) { + $source_object = $original_object = null; + + if ( $source_prefix ) { $source_object =& $this->Application->recallObject($source_prefix, null, Array ('raise_warnings' => 0)); // it's possible, that in some cases object will not be loaded /* @var $source_object kCatDBItem */ - $display_original = $this->Application->ProcessParsedTag($source_prefix, 'DisplayOriginal', Array('display_original' => $this->setParamValue($params, 'display_original'))); + $display_original = $this->Application->ProcessParsedTag($source_prefix, 'DisplayOriginal', Array ('display_original' => $this->setParamValue($params, 'display_original'))); } - if ($display_original) { + if ( $display_original ) { $block_params['display_original'] = $display_original; $block_params['original_title'] = $this->setParamValue($params, 'original_title'); - $original_object =& $this->Application->recallObject($source_prefix.'.original', null, Array ('raise_warnings' => 0)); // it's possible, that in some cases object will not be loaded + + $original_object =& $this->Application->recallObject($source_prefix . '.original', null, Array ('raise_warnings' => 0)); // it's possible, that in some cases object will not be loaded + /* @var $original_object kCatDBItem */ } if ($this->Special == 'general') { @@ -104,38 +108,38 @@ } $i = 0; - while (!$list->EOL()) - { + while ( !$list->EOL() ) { $block_params['is_last'] = ($i == $list->GetSelectedCount() - 1); $block_params['not_last'] = !$block_params['is_last']; // for front-end - $this->Application->SetVar( $this->getPrefixSpecial().'_id', $list->GetDBField($id_field) ); // for edit/delete links using GET + $this->Application->SetVar($this->getPrefixSpecial() . '_id', $list->GetDBField($id_field)); // for edit/delete links using GET - if ($source_prefix) { + if ( $source_prefix ) { $field_name = 'cust_' . $list->GetDBField('FieldName'); - + $formatter = $source_object->GetFieldOption($field_name, 'formatter'); $language_prefix = $formatter == 'kMultiLanguage' ? 'l' . $this->Application->GetVar('m_lang') . '_' : ''; - - $list->SetDBField($params['value_field'], $source_object->GetDBField($language_prefix . 'cust_'.$list->GetDBField('FieldName'))); - if ($display_original) { - $list->SetDBField('OriginalValue', $original_object->GetField('cust_'.$list->GetDBField('FieldName'))); + $list->SetDBField($params['value_field'], $source_object->GetDBField($language_prefix . 'cust_' . $list->GetDBField('FieldName'))); + + if ( $display_original ) { + $list->SetDBField('OriginalValue', $original_object->GetField('cust_' . $list->GetDBField('FieldName'))); } - $block_params['field'] = $block_params['virtual_field'] = 'cust_'.$list->GetDBField('FieldName'); - $block_params['show_heading'] = ($prev_heading != $list->GetDBField('Heading') ) ? 1 : 0; + $block_params['field'] = $block_params['virtual_field'] = 'cust_' . $list->GetDBField('FieldName'); + $block_params['show_heading'] = ($prev_heading != $list->GetDBField('Heading')) ? 1 : 0; $list->SetDBField('DirectOptions', $source_object->GetFieldOption($field_name, 'options')); } - $o.= $this->Application->ParseBlock($block_params); + $o .= $this->Application->ParseBlock($block_params); $prev_heading = $list->GetDBField('Heading'); $list->GoNext(); $i++; } - $this->Application->SetVar( $this->getPrefixSpecial().'_id', ''); + $this->Application->SetVar($this->getPrefixSpecial() . '_id', ''); + return $o; } Index: units/email_events/email_event_tp.php =================================================================== --- units/email_events/email_event_tp.php (revision 14590) +++ units/email_events/email_event_tp.php (working copy) @@ -23,11 +23,12 @@ */ function ModifyUnitConfig($params) { - if (!$this->Application->isDebugMode()) { - $grids = $this->Application->getUnitOption($this->Prefix, 'Grids'); + if ( !$this->Application->isDebugMode() ) { + $grids = $this->Application->getUnitOption($this->Prefix, 'Grids', Array ()); + /* @var $grids Array */ foreach ($grids as $grid_name => $grid_data) { - if (array_key_exists('Enabled', $grid_data['Fields'])) { + if ( array_key_exists('Enabled', $grid_data['Fields']) ) { unset($grids[$grid_name]['Fields']['Enabled']); } } Index: units/email_events/email_events_event_handler.php =================================================================== --- units/email_events/email_events_event_handler.php (revision 14590) +++ units/email_events/email_events_event_handler.php (working copy) @@ -47,8 +47,10 @@ * Changes permission section to one from REQUEST, not from config * * @param kEvent $event + * @return bool + * @access public */ - function CheckPermission(&$event) + public function CheckPermission(&$event) { $module = $this->Application->GetVar('module'); @@ -76,10 +78,11 @@ * Apply any custom changes to list's sql query * * @param kEvent $event + * @return void * @access protected - * @see OnListBuild + * @see kDBEventHandler::OnListBuild() */ - function SetCustomQuery(&$event) + protected function SetCustomQuery(&$event) { $object =& $event->getObject(); /* @var $object kDBList */ @@ -96,11 +99,13 @@ } /** - * Sets event id + * Set default headers * * @param kEvent $event + * @return void + * @access protected */ - function OnPreCreate(&$event) + protected function OnPreCreate(&$event) { parent::OnPreCreate($event); @@ -649,22 +654,24 @@ } /** - * Raised when email message shoul be sent + * Raised when email message should be sent * * @param kEvent $event + * @return void + * @access protected */ - function OnEmailEvent(&$event) + protected function OnEmailEvent(&$event) { $email_event_name = $event->getEventParam('EmailEventName'); - if (strpos($email_event_name, '_') !== false) { + if ( strpos($email_event_name, '_') !== false ) { throw new Exception('Invalid email event name ' . $email_event_name . '. Use only UPPERCASE characters and dots as email event names'); } $object =& $this->_getEmailEvent($event); - if (!is_object($object)) { + if ( !is_object($object) ) { // email event not found OR it's won't be send under given circumstances - return false; + return ; } // additional parameters from kApplication->EmailEvent @@ -677,15 +684,15 @@ // 2. prepare message to be sent $message_language = $this->_getSendLanguage($send_params); $message_template = $this->_getMessageBody($event, $message_language); - if (!trim($message_template)) { + if ( !trim($message_template) ) { trigger_error('Message template is empty', E_USER_WARNING); - return false; + return ; } list ($message_headers, $message_body) = $this->ParseMessageBody($message_template, $send_params); - if (!trim($message_body)) { + if ( !trim($message_body) ) { trigger_error('Message template is empty after parsing', E_USER_WARNING); - return false; + return ; } // 3. set headers & send message @@ -695,8 +702,8 @@ $message_subject = isset($message_headers['Subject']) ? $message_headers['Subject'] : 'Mail message'; $esender->SetSubject($message_subject); - if ($this->Application->isDebugMode()) { - // set special header with event name, so it will be easier to determite what's actually was received + if ( $this->Application->isDebugMode() ) { + // set special header with event name, so it will be easier to determine what's actually was received $message_headers['X-Event-Name'] = $email_event_name . ' - ' . ($object->GetDBField('Type') == EmailEvent::EVENT_TYPE_ADMIN ? 'ADMIN' : 'USER'); } @@ -708,7 +715,7 @@ $event->status = $esender->Deliver() ? kEvent::erSUCCESS : kEvent::erFAIL; - if ($event->status == kEvent::erSUCCESS) { + if ( $event->status == kEvent::erSUCCESS ) { // all keys, that are not used in email sending are written to log record $send_keys = Array ('from_email', 'from_name', 'to_email', 'to_name', 'message'); foreach ($send_keys as $send_key) { @@ -716,15 +723,15 @@ } $fields_hash = Array ( - 'fromuser' => $from_name.' ('.$from_email.')', - 'addressto' => $to_name.' ('.$to_email.')', + 'fromuser' => $from_name . ' (' . $from_email . ')', + 'addressto' => $to_name . ' (' . $to_email . ')', 'subject' => $message_subject, 'timestamp' => adodb_mktime(), 'event' => $email_event_name, 'EventParams' => serialize($send_params), ); - $this->Conn->doInsert($fields_hash, TABLE_PREFIX.'EmailLog'); + $this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'EmailLog'); } } @@ -741,19 +748,20 @@ { static $prev_language_id = null; - if (!isset($language_id)) { + if ( !isset($language_id) ) { // restore language $language_id = $prev_language_id; } $this->Application->SetVar('m_lang', $language_id); + $language =& $this->Application->recallObject('lang.current'); - /* @var $lang_object kDBItem */ + /* @var $language LanguagesItem */ $language->Load($language_id); $this->Application->Phrases->LanguageId = $language_id; - $this->Application->Phrases->Phrases = Array(); + $this->Application->Phrases->Phrases = Array (); $prev_language_id = $language_id; // for restoring it later } @@ -870,8 +878,10 @@ * Fixes default recipient type * * @param kEvent $event + * @return void + * @access protected */ - function OnAfterItemLoad(&$event) + protected function OnAfterItemLoad(&$event) { parent::OnAfterItemLoad($event); @@ -1011,8 +1021,10 @@ * Don't allow to enable/disable events in non-debug mode * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemCreate(&$event) + protected function OnBeforeItemCreate(&$event) { parent::OnBeforeItemCreate($event); @@ -1023,8 +1035,10 @@ * Don't allow to enable/disable events in non-debug mode * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemUpdate(&$event) + protected function OnBeforeItemUpdate(&$event) { parent::OnBeforeItemUpdate($event); Index: units/favorites/favorites_eh.php =================================================================== --- units/favorites/favorites_eh.php (revision 14590) +++ units/favorites/favorites_eh.php (working copy) @@ -68,8 +68,10 @@ * Prepares Favorite record fields * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemCreate(&$event) + protected function OnBeforeItemCreate(&$event) { $object =& $event->getObject(); /* @var $object kDBItem */ Index: units/fck/fck_eh.php =================================================================== --- units/fck/fck_eh.php (revision 14590) +++ units/fck/fck_eh.php (working copy) @@ -17,11 +17,13 @@ class FckEventHandler extends kDBEventHandler { /** - * Checks permissions of user + * Checks user permission to execute given $event * * @param kEvent $event + * @return bool + * @access public */ - function CheckPermission(&$event) + public function CheckPermission(&$event) { if ($this->Application->isAdminUser) { // this limits all event execution only to logged-in users in admin @@ -101,15 +103,15 @@ } $fck_helper =& $this->Application->recallObject('FCKHelper'); - /* @var fck_helper fckFCKHelper*/ + /* @var $fck_helper fckFCKHelper*/ - if (!$fck_helper->IsAllowedExtension($folder, $new_name)) { + if ( !$fck_helper->IsAllowedExtension($folder, $new_name) ) { echo 203; return; } - if (!rename($sServerDir.$old_name,$sServerDir.$new_name)) { - // echo $sServerDir.$old_name.' -> '.$sServerDir.$new_name; + if ( !rename($sServerDir . $old_name, $sServerDir . $new_name) ) { +// echo $sServerDir.$old_name.' -> '.$sServerDir.$new_name; echo 205; return; } @@ -192,16 +194,24 @@ } } - function OnUploadFile(&$event) + /** + * Uploads a file from FCK file browser + * + * @param kEvent $event + * @return void + * @access protected + */ + protected function OnUploadFile(&$event) { $event->status = kEvent::erSTOP; - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) { + if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) { return; } $fck_helper =& $this->Application->recallObject('FCKHelper'); - /* @var fck_helper fckFCKHelper*/ + /* @var $fck_helper fckFCKHelper*/ + $fck_helper->UploadFile(); } } \ No newline at end of file Index: units/fck/fck_tp.php =================================================================== --- units/fck/fck_tp.php (revision 14590) +++ units/fck/fck_tp.php (working copy) @@ -48,7 +48,7 @@ function CheckCreateDefaultFolders() { $fck_helper =& $this->Application->recallObject('FCKHelper'); - /* @var fck_helper fckFCKHelper*/ + /* @var $fck_helper fckFCKHelper */ $default_folders = defined('FCK_DEFAULT_FOLDERS') ? FCK_DEFAULT_FOLDERS : Array ('Files', 'Images', 'Flash', 'Media', 'Documents'); Index: units/files/file_eh.php =================================================================== --- units/files/file_eh.php (revision 14590) +++ units/files/file_eh.php (working copy) @@ -34,10 +34,16 @@ * Remembers user, who is created file record. Makes file primary if no other files are uploaded. * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemCreate(&$event) + protected function OnBeforeItemCreate(&$event) { + parent::OnBeforeItemCreate($event); + $object =& $event->getObject(); + /* @var $object kDBItem */ + $object->SetDBField('CreatedById', $this->Application->RecallVar('user_id')); } @@ -45,22 +51,36 @@ * Resets primary file mark when more then one file is marked as primary * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemUpdate(&$event) + protected function OnBeforeItemUpdate(&$event) { + parent::OnBeforeItemUpdate($event); + $object =& $event->getObject(); + /* @var $object kDBItem */ - if (!$object->GetDBField('FileName')) { + if ( !$object->GetDBField('FileName') ) { $object->SetDBField('FileName', basename($object->GetDBField('FilePath'))); } } - function SetCustomQuery(&$event) + /** + * Apply any custom changes to list's sql query + * + * @param kEvent $event + * @return void + * @access protected + * @see kDBEventHandler::OnListBuild() + */ + protected function SetCustomQuery(&$event) { parent::SetCustomQuery($event); $object =& $event->getObject(); - + /* @var $object kDBList */ + if (!$this->Application->isAdminUser) { $object->addFilter('active_filter', '%1$s.Status = '.STATUS_ACTIVE); } Index: units/forms/drafts/draft_eh.php =================================================================== --- units/forms/drafts/draft_eh.php (revision 14590) +++ units/forms/drafts/draft_eh.php (working copy) @@ -16,13 +16,14 @@ class DraftEventHandler extends kDBEventHandler { - /** * Sets user, who created draft * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemCreate(&$event) + protected function OnBeforeItemCreate(&$event) { parent::OnBeforeItemCreate($event); Index: units/forms/form_fields/form_field_eh.php =================================================================== --- units/forms/form_fields/form_field_eh.php (revision 14590) +++ units/forms/form_fields/form_field_eh.php (working copy) @@ -34,8 +34,11 @@ * Shows fields based on user logged-in status * * @param kEvent $event + * @return void + * @access protected + * @see kDBEventHandler::OnListBuild() */ - function SetCustomQuery(&$event) + protected function SetCustomQuery(&$event) { parent::SetCustomQuery($event); Index: units/forms/form_submissions/form_submissions_eh.php =================================================================== --- units/forms/form_submissions/form_submissions_eh.php (revision 14590) +++ units/forms/form_submissions/form_submissions_eh.php (working copy) @@ -16,7 +16,14 @@ class FormSubmissionsEventHandler extends kDBEventHandler { - function CheckPermission(&$event) + /** + * Checks user permission to execute given $event + * + * @param kEvent $event + * @return bool + * @access public + */ + public function CheckPermission(&$event) { if (!$this->Application->isAdmin) { if ($event->Name == 'OnCreate') { @@ -145,11 +152,20 @@ $this->Application->setUnitOption($event->Prefix, 'Grids', $conf_grids); } - function SetCustomQuery(&$event) + /** + * Apply any custom changes to list's sql query + * + * @param kEvent $event + * @return void + * @access protected + * @see kDBEventHandler::OnListBuild() + */ + protected function SetCustomQuery(&$event) { $object =& $event->getObject(); - $form_id = $this->Application->GetVar('form_id'); - $object->addFilter('form_filter','%1$s.FormId = '.$form_id); + /* @var $object kDBList */ + + $object->addFilter('form_filter', '%1$s.FormId = ' . (int)$this->Application->GetVar('form_id')); } /** @@ -212,8 +228,10 @@ * Processes Captcha code * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemCreate(&$event) + protected function OnBeforeItemCreate(&$event) { parent::OnBeforeItemCreate($event); @@ -225,7 +243,7 @@ if ( !$object->GetDBField('ReferrerURL') ) { $referrer = $this->Application->GetVar('original_referrer'); - if (!$referrer) { + if ( !$referrer ) { $base_url = preg_quote($this->Application->BaseURL(), '/'); $referrer = preg_replace('/^' . $base_url . '/', '/', $_SERVER['HTTP_REFERER'], 1); } @@ -239,7 +257,7 @@ $form =& $form_submission_helper->getForm($object); // validate captcha code - if ($form->GetDBField('UseSecurityImage') && !$this->Application->LoggedIn()) { + if ( $form->GetDBField('UseSecurityImage') && !$this->Application->LoggedIn() ) { $captcha_helper =& $this->Application->recallObject('CaptchaHelper'); /* @var $captcha_helper kCaptchaHelper */ @@ -251,8 +269,10 @@ * Checks, that target submission was selected for merging * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemUpdate(&$event) + protected function OnBeforeItemUpdate(&$event) { parent::OnBeforeItemUpdate($event); @@ -319,8 +339,10 @@ * Fills merge-to dropdown * * @param kEvent $event + * @return void + * @access protected */ - function OnAfterItemLoad(&$event) + protected function OnAfterItemLoad(&$event) { parent::OnAfterItemLoad($event); @@ -382,9 +404,7 @@ $options[$submission_id] = $option_title; } - $field_options = $object->GetFieldOptions('MergeToSubmission'); - $field_options['options'] = $options; - $object->SetFieldOptions('MergeToSubmission', $field_options); + $object->SetFieldOption('MergeToSubmission', 'options', $options); } /** Index: units/forms/forms/forms_tp.php =================================================================== --- units/forms/forms/forms_tp.php (revision 14590) +++ units/forms/forms/forms_tp.php (working copy) @@ -18,19 +18,24 @@ function CheckBox($params) { - $field = $this->SelectParam($params, 'name,field'); - $object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params); + $object =& $this->getObject($params); + /* @var $object kDBItem */ - $value = $object->GetDBField($field); + $value = $object->GetDBField($this->SelectParam($params, 'name,field')); - if ($value) return 'checked'; - if (is_null($value)) return $params['default']; + if ( $value ) { + return 'checked'; + } + + if ( is_null($value) ) { + return $params['default']; + } return ''; } function MaxUploadSize($params) { - return round(MAX_UPLOAD_SIZE/1024/1024).' Mb'; + return round(MAX_UPLOAD_SIZE / 1024 / 1024) . ' Mb'; } } \ No newline at end of file Index: units/forms/submission_log/submission_log_eh.php =================================================================== --- units/forms/submission_log/submission_log_eh.php (revision 14590) +++ units/forms/submission_log/submission_log_eh.php (working copy) @@ -32,12 +32,13 @@ } /** - * Checks event permissions + * Checks user permission to execute given $event * * @param kEvent $event * @return bool + * @access public */ - function CheckPermission(&$event) + public function CheckPermission(&$event) { $section = $event->getSection(); $form_id = $this->Application->GetVar('form_id'); @@ -75,7 +76,8 @@ /* @var $form_submission_helper FormSubmissionHelper */ $form =& $form_submission_helper->getForm($form_submission); - + /* @var $form kDBItem */ + $from_email = $form->GetDBField('ReplyFromEmail'); $to_email = $form_submission_helper->getFieldByRole($form_submission, SubmissionFormField::COMMUNICATION_ROLE_EMAIL); @@ -233,8 +235,10 @@ * Updates last operation dates for log record * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemCreate(&$event) + protected function OnBeforeItemCreate(&$event) { parent::OnBeforeItemCreate($event); @@ -246,8 +250,10 @@ * Updates last operation dates for log record * * @param kEvent $event + * @return void + * @access protected */ - function OnBeforeItemUpdate(&$event) + protected function OnBeforeItemUpdate(&$event) { parent::OnBeforeItemUpdate($event); @@ -392,8 +398,10 @@ * Updates last update time for submission * * @param kEvent $event + * @return void + * @access protected */ - function OnAfterItemCreate(&$event) + protected function OnAfterItemCreate(&$event) { parent::OnAfterItemCreate($event); @@ -405,11 +413,11 @@ $this->_updateSubmission($event); $reply_to = $object->GetDBField('ReplyTo'); - if (!$reply_to) { + if ( !$reply_to ) { $reply_to = $this->_getLastMessageId($event, !$this->Application->GetVar('client_mode')); } - if ($reply_to) { + if ( $reply_to ) { // this is reply to other message -> mark it as replied $org_message =& $this->Application->recallObject($event->Prefix . '.-item', null, Array ('skip_autoload' => true)); /* @var $org_message kDBItem */ @@ -419,7 +427,7 @@ $org_message->Update(); } - if ($this->Application->GetVar('client_mode')) { + if ( $this->Application->GetVar('client_mode') ) { // new reply from client received -> send notification about it $this->Application->EmailEventAdmin('FORM.SUBMISSION.REPLY.FROM.USER'); } Index: units/groups/groups_event_handler.php =================================================================== --- units/groups/groups_event_handler.php (revision 14590) +++ units/groups/groups_event_handler.php (working copy) @@ -17,11 +17,14 @@ class GroupsEventHandler extends kDBEventHandler { /** - * Adds grouping by userid + * Adds grouping by user id * * @param kEvent $event + * @return void + * @access protected + * @see kDBEventHandler::OnListBuild() */ - function SetCustomQuery(&$event) + protected function SetCustomQuery(&$event) { $object =& $event->getObject(); /* @var $object kDBList */ @@ -53,8 +56,10 @@ * Refreshes left tree on save * * @param kEvent $event + * @return void + * @access protected */ - function OnSave(&$event) + protected function OnSave(&$event) { parent::OnSave($event); Index: units/helpers/brackets_helper.php =================================================================== --- units/helpers/brackets_helper.php (revision 14590) +++ units/helpers/brackets_helper.php (working copy) @@ -306,16 +306,21 @@ } } + /** + * Sorts brackets and returns sorted array + * + * @param kEvent $event + * @return Array + */ function arrangeBrackets(&$event) { $object =& $event->getObject(); + /* @var $object kDBItem */ $temp = $this->getBrackets($event); - foreach($temp as $id => $record) - { - if( $record[$this->max_field] == '∞' ) - { + foreach ($temp as $id => $record) { + if ( $record[$this->max_field] == '∞' ) { $temp[$id][$this->max_field] = -1; } } @@ -352,7 +357,7 @@ } // sort brackets by 2nd column (Max values) - uasort($temp, Array(&$this, 'compareBrackets') ); + uasort($temp, Array (&$this, 'compareBrackets')); reset($temp); $first_item = each($temp); $first_item_key = $first_item['key']; @@ -360,15 +365,14 @@ $linked_info = $object->getLinkedInfo(); $sql = 'SELECT %s FROM %s WHERE %s = %s'; $ids = $this->Conn->GetCol( sprintf($sql, $object->IDField, $object->TableName, $linked_info['ForeignKey'], $linked_info['ParentId']) ); - if( is_array($ids) ) - { - usort($ids, Array(&$this, 'sortBracketIDs') ); + + if ( is_array($ids) ) { + usort($ids, Array (&$this, 'sortBracketIDs')); } // $min_id = min( min($ids) - 1, -1 ); - foreach($temp as $key => $record) - { + foreach ($temp as $key => $record) { $temp[$key][$this->min_field] = $start; $start = $temp[$key][$this->max_field]; } @@ -455,14 +459,18 @@ } /** - * Replate infinity mark with -1 before saving to db + * Replace infinity mark with -1 before saving to db * * @param kEvent $event */ function replaceInfinity(&$event) { $object =& $event->getObject(); - if($object->GetDBField($this->max_field) == '∞') $object->SetDBField($this->max_field, -1); + /* @var $object kDBItem */ + + if ( $object->GetDBField($this->max_field) == '∞' ) { + $object->SetDBField($this->max_field, -1); + } } } \ No newline at end of file Index: units/helpers/category_helper.php =================================================================== --- units/helpers/category_helper.php (revision 14590) +++ units/helpers/category_helper.php (working copy) @@ -283,7 +283,7 @@ */ function getCategoryParentPath($main_category_id) { - if ($main_category_id == 0) { + if ( $main_category_id == 0 ) { // don't query path for "Home" category return Array (); } @@ -291,28 +291,30 @@ $cache_key = 'parent_paths_named[%CIDSerial:' . $main_category_id . '%]'; $cached_path = $this->Application->getCache($cache_key); - if ($cached_path === false) { + if ( $cached_path === false ) { $ml_formatter =& $this->Application->recallObject('kMultiLanguage'); + /* @var $ml_formatter kMultiLanguage */ + $navbar_field = $ml_formatter->LangFieldName('CachedNavBar'); $id_field = $this->Application->getUnitOption('c', 'IDField'); $table_name = $this->Application->getUnitOption('c', 'TableName'); $this->Conn->nextQueryCachable = true; - $sql = 'SELECT '.$navbar_field.', ParentPath - FROM '.$table_name.' - WHERE '.$id_field.' = '.$main_category_id; + $sql = 'SELECT ' . $navbar_field . ', ParentPath + FROM ' . $table_name . ' + WHERE ' . $id_field . ' = ' . $main_category_id; $category_data = $this->Conn->GetRow($sql); $cached_path = Array (); $skip_category = $this->Application->getBaseCategory(); - if ($category_data) { + if ( $category_data ) { $category_names = explode('&|&', $category_data[$navbar_field]); $category_ids = explode('|', substr($category_data['ParentPath'], 1, -1)); foreach ($category_ids as $category_index => $category_id) { - if ($category_id == $skip_category) { + if ( $category_id == $skip_category ) { continue; } @@ -326,26 +328,31 @@ return $cached_path; } - /** - * Not tag, method for parameter - * selection from list in this TagProcessor + /** + * Not tag. Method for parameter selection from list in this TagProcessor * * @param Array $params - * @param string $possible_names + * @param Array $possible_names + * * @return string - * @access public + * @access protected */ - function SelectParam($params, $possible_names) + protected function SelectParam($params, $possible_names) { - if (!is_array($params)) return; - if (!is_array($possible_names)) + if ( !is_array($params) ) { + return ''; + } + if ( !is_array($possible_names) ) { + $possible_names = explode(',', $possible_names); + } - $possible_names = explode(',', $possible_names); - foreach ($possible_names as $name) - { - if( isset($params[$name]) ) return $params[$name]; + foreach ($possible_names as $name) { + if ( isset($params[$name]) ) { + return $params[$name]; + } } - return false; + + return ''; } /** Index: units/helpers/controls/edit_picker_helper.php =================================================================== --- units/helpers/controls/edit_picker_helper.php (revision 14590) +++ units/helpers/controls/edit_picker_helper.php (working copy) @@ -95,7 +95,7 @@ } /** - * Saves value to subitem's table + * Saves value to sub-item's table * * @param kEvent $sub_event * @param string $store_field main item's field name, to get values from @@ -158,16 +158,25 @@ } } + /** + * Returns constrain for picker options query + * + * @param kDBItem $object + * @param string $store_field + * @param string $mode + * @return bool|string + */ function _getConstrain(&$object, $store_field, $mode = 'filter') { $field_options = $object->GetFieldOptions($store_field); - $constrain = array_key_exists('option_constrain', $field_options) ? $field_options['option_constrain'] : false; + $constrain = array_key_exists('option_constrain', $field_options) ? $field_options['option_constrain'] + : false; - if ($mode == 'filter') { + if ( $mode == 'filter' ) { // filter on edit form return $constrain; } - elseif ($constrain) { + elseif ( $constrain ) { // load or save return sprintf($field_options['options_sql'], $field_options['option_key_field']); } Index: units/helpers/controls/minput_helper.php =================================================================== --- units/helpers/controls/minput_helper.php (revision 14590) +++ units/helpers/controls/minput_helper.php (working copy) @@ -16,17 +16,19 @@ class MInputHelper extends kHelper { - /** - * Returns user education table name + * Returns table for given prefix * - * @param kDBItem $object + * @param string $prefix + * @param bool $temp * @return string + * @access protected */ - function getTable($prefix, $temp=false) + protected function getTable($prefix, $temp = false) { $table_name = $this->Application->getUnitOption($prefix, 'TableName'); - return $temp ? $this->Application->GetTempName($table_name, 'prefix:'.$prefix) : $table_name; + + return $temp ? $this->Application->GetTempName($table_name, 'prefix:' . $prefix) : $table_name; } function prepareMInputXML($records, $use_fields) @@ -112,7 +114,8 @@ $root_node =& $xml_helper->Parse($xml); $root_node =& $root_node->FindChild('records'); - if (!$root_node || !$root_node->firstChild) { + + if ( !$root_node || !$root_node->firstChild ) { return false; } @@ -121,17 +124,16 @@ /* @var $current_node kXMLNode */ do { - $record = Array(); + $record = Array (); $sub_node =& $current_node->firstChild; /* @var $current_node kXMLNode */ do { - $record[$sub_node->Attributes['NAME']] = $sub_node->Data; + $record[ $sub_node->Attributes['NAME'] ] = $sub_node->Data; + } while ( ($sub_node =& $sub_node->NextSibling()) ); - }while ( ($sub_node =& $sub_node->NextSibling()) ); - $records[] = $record; - } while (($current_node =& $current_node->NextSibling())); + } while ( ($current_node =& $current_node->NextSibling()) ); return $records; } @@ -195,10 +197,12 @@ function SaveValues(&$sub_event, $store_field) { $main_object =& $sub_event->MasterEvent->getObject(); + /* @var $main_object kDBItem */ + $affected_field = $main_object->GetDBField($store_field); - $object =& $this->Application->recallObject($sub_event->getPrefixSpecial(), null, Array('skip_autoload' => true)); - /*@var $object kDBItem*/ + $object =& $this->Application->recallObject($sub_event->getPrefixSpecial(), null, Array ('skip_autoload' => true)); + /* @var $object kDBItem */ $sub_table = $object->TableName; $foreign_key = $this->Application->getUnitOption($sub_event->Prefix, 'ForeignKey'); Index: units/helpers/count_helper.php =================================================================== --- units/helpers/count_helper.php (revision 14590) +++ units/helpers/count_helper.php (working copy) @@ -75,11 +75,13 @@ } /** - * Resets counter, whitch are affected by one of specified tables + * Resets counter, which are affected by one of specified tables * * @param string $tables comma separated tables list used in counting sqls + * @return void + * @access public */ - function resetCounters($tables) + public function resetCounters($tables) { $tables = explode(',', $tables); $prefix_length = strlen(TABLE_PREFIX); Index: units/helpers/country_states_helper.php =================================================================== --- units/helpers/country_states_helper.php (revision 14590) +++ units/helpers/country_states_helper.php (working copy) @@ -128,6 +128,15 @@ return $this->Conn->GetOne($sql); } + /** + * Checks, that entered state matches entered country + * + * @param kEvent $event + * @param string $state_field + * @param string $country_field + * @param bool $auto_required + * @return void + */ function CheckStateField(&$event, $state_field, $country_field, $auto_required = true) { $object =& $event->getObject(); @@ -135,16 +144,16 @@ $country_iso = $object->GetDBField($country_field); - if ($auto_required) { + if ( $auto_required ) { $object->setRequired($state_field, $this->CountryHasStates($country_iso)); } $state = $object->GetDBField($state_field); - if ($country_iso && $state) { + if ( $country_iso && $state ) { $state_iso = $this->getStateIso($state, $country_iso); - if ($state_iso !== false) { + if ( $state_iso !== false ) { // replace state name with it's ISO code $object->SetDBField($state_field, $state_iso); } Index: units/helpers/custom_fields_helper.php =================================================================== --- units/helpers/custom_fields_helper.php (revision 14590) +++ units/helpers/custom_fields_helper.php (working copy) @@ -77,14 +77,16 @@ } /** - * Replace SQL's in valueList with appropriate queried values + * Replace SQLs in valueList with appropriate queried values * * @param string $valueString * @param string $separator + * @param bool $parse_sqls * @return string + * @access public * @todo Apply refactoring to embedded vars stuff */ - function ParseConfigSQL($valueString, $separator = VALUE_LIST_SEPARATOR, $parse_sqls = true) + public function ParseConfigSQL($valueString, $separator = VALUE_LIST_SEPARATOR, $parse_sqls = true) { if ($parse_sqls) { $string = trim( str_replace(Array('', '%3$s'), Array (TABLE_PREFIX, $this->Application->GetVar('m_lang')), $valueString) ); Index: units/helpers/deployment_helper.php =================================================================== --- units/helpers/deployment_helper.php (revision 14590) +++ units/helpers/deployment_helper.php (working copy) @@ -28,9 +28,9 @@ private $lineEnding = PHP_EOL; - public function DeploymentHelper() + public function __construct() { - parent::kHelper(); + parent::__construct(); set_time_limit(0); ini_set('memory_limit', -1); Index: units/helpers/email_message_helper.php =================================================================== --- units/helpers/email_message_helper.php (revision 14590) +++ units/helpers/email_message_helper.php (working copy) @@ -10,6 +10,7 @@ */ function parseTemplate($text) { + $line_id = 1; $ret = Array ('Subject' => '', 'Headers' => '', 'Body' => ''); $headers = Array(); $lines = explode("\n", $text); // "\n" is lost in process Index: units/helpers/file_helper.php =================================================================== --- units/helpers/file_helper.php (revision 14590) +++ units/helpers/file_helper.php (working copy) @@ -221,12 +221,15 @@ * @param string $prefix * @param string $field_name * @param Array $virtual_fields + * @param bool $is_image + * @return void + * @access protected */ - function _createCustomFields($prefix, $field_name, &$virtual_fields, $is_image) + protected function _createCustomFields($prefix, $field_name, &$virtual_fields, $is_image = false) { $virtual_fields['Delete' . $field_name] = Array ('type' => 'int', 'default' => 0); - if ($is_image) { + if ( $is_image ) { $virtual_fields[$field_name . 'Alt'] = Array ('type' => 'string', 'default' => ''); } } Index: units/helpers/filenames_helper.php =================================================================== --- units/helpers/filenames_helper.php (revision 14590) +++ units/helpers/filenames_helper.php (working copy) @@ -77,9 +77,12 @@ } /** - * replace not allowed symbols with "_" chars + remove duplicate "_" chars in result + * Replace not allowed symbols with "_" chars + remove duplicate "_" chars in result * - * @param string $string + * @param string $table + * @param string $id_field + * @param int $item_id + * @param string $filename * @return string */ function stripDisallowed($table, $id_field, $item_id, $filename) Index: units/helpers/form_submission_helper.php =================================================================== --- units/helpers/form_submission_helper.php (revision 14590) +++ units/helpers/form_submission_helper.php (working copy) @@ -73,6 +73,7 @@ * @param kDBItem $form_submission * @param string $name * @return string + * @todo Might not work correctly! */ function getFieldByName(&$form_submission, $name, $formatted = false, $format = null) { @@ -110,7 +111,7 @@ $form =& $this->Application->recallObject('form', null, Array ('skip_autoload' => true)); /* @var $form kDBItem */ - if (!$form->isLoaded() || ($form->GetID() != $form_id)) { + if ( !$form->isLoaded() || ($form->GetID() != $form_id) ) { $form->Load($form_id); } Index: units/helpers/geocode_helper.php =================================================================== --- units/helpers/geocode_helper.php (revision 14590) +++ units/helpers/geocode_helper.php (working copy) @@ -125,37 +125,40 @@ * @param string $city * @param string $state * @param int $zip - * @return Array (lon, lat) + * @param bool $no_cache + * @param bool $force_cache + * @return Array|bool (lon, lat) + * @access public */ - function GetCoordinates($address, $city, $state, $zip, $no_cache = false, $force_cache = false) + public function GetCoordinates($address, $city, $state, $zip, $no_cache = false, $force_cache = false) { - if (!$zip && !$state) { + if ( !$zip && !$state ) { // if state or zip missing then do nothing return false; } $zip_info = $no_cache ? false : $this->GetFromCache($address, $city, $state, $zip); -// $zip_info = $this->GetFromCache($address, $city, $state, $zip); - if (!$zip_info && !$force_cache) { + if ( !$zip_info && !$force_cache ) { list($lon, $lat, $zip4, $dpbc, $carrier, $geocode_answer) = $this->QueryCoordinatesFromGoogle($address, $city, $state, $zip); - if ($lon != '' && $lat != '') { + if ( $lon != '' && $lat != '' ) { // valid position returned by geocode => add to cache $fields_hash = Array( - 'zipcode' => $zip4, - 'address' => $address, - 'city' => $city, - 'state' => $state, - 'lat' => $lat, - 'lon' => $lon, - 'zip4' => $zip4, - 'dpbc' => $dpbc, - 'carrier' => $carrier, - 'geocode_answer' => $geocode_answer, - ); - $this->Conn->doInsert($fields_hash, TABLE_PREFIX.'ZipCodes'); - return Array($lon, $lat, $zip4, $dpbc, $carrier); + 'zipcode' => $zip4, + 'address' => $address, + 'city' => $city, + 'state' => $state, + 'lat' => $lat, + 'lon' => $lon, + 'zip4' => $zip4, + 'dpbc' => $dpbc, + 'carrier' => $carrier, + 'geocode_answer' => $geocode_answer, + ); + + $this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'ZipCodes'); + return Array ($lon, $lat, $zip4, $dpbc, $carrier); } else { // bad case, rie call failed => no data retrieved @@ -163,7 +166,7 @@ } } - return Array($zip_info['lon'], $zip_info['lat'], getArrayValue($zip_info, 'zip4'), getArrayValue($zip_info, 'dpbc'), getArrayValue($zip_info, 'carrier')); + return Array ($zip_info['lon'], $zip_info['lat'], getArrayValue($zip_info, 'zip4'), getArrayValue($zip_info, 'dpbc'), getArrayValue($zip_info, 'carrier')); } /** @@ -173,14 +176,14 @@ * @param string $city * @param string $state * @param int $zip - * @return Array (lon, lat) + * @return Array|bool (lon, lat) */ function GetFromCache($address, $city, $state, $zip) { $zip = substr($zip, 0, 5); // use only first 5 digits $sql = 'SELECT lon, lat - FROM '.TABLE_PREFIX.'ZipCodes - WHERE zipcode = '.$this->Conn->qstr($zip); + FROM ' . TABLE_PREFIX . 'ZipCodes + WHERE zipcode = ' . $this->Conn->qstr($zip); return $this->Conn->GetRow($sql); } } \ No newline at end of file Index: units/helpers/image_helper.php =================================================================== --- units/helpers/image_helper.php (revision 14590) +++ units/helpers/image_helper.php (working copy) @@ -548,9 +548,9 @@ } /** - * Puts existing item images (from subitem) to virtual fields (in main item) + * Puts existing item images (from sub-item) to virtual fields (in main item) * - * @param kCatDBItem $object + * @param kCatDBItem|kDBItem $object */ function LoadItemImages(&$object) { @@ -601,7 +601,7 @@ /** * Saves newly uploaded images to external image table * - * @param kCatDBItem $object + * @param kCatDBItem|kDBItem $object */ function SaveItemImages(&$object) { @@ -669,7 +669,7 @@ /** * Adds ability to load custom fields along with main image field * - * @param kCatDBItem $object + * @param kCatDBItem|kDBItem $object * @param Array $fields_hash * @param int $counter 0 - primary image, other number - additional image number */ @@ -683,7 +683,7 @@ /** * Adds ability to save custom field along with main image save * - * @param kCatDBItem $object + * @param kCatDBItem|kDBItem $object * @param Array $fields_hash * @param int $counter 0 - primary image, other number - additional image number */ @@ -697,7 +697,7 @@ /** * Checks, that item can use image upload capabilities * - * @param kCatDBItem $object + * @param kCatDBItem|kDBItem $object * @return bool */ function _canUseImages(&$object) Index: units/helpers/json_helper.php =================================================================== --- units/helpers/json_helper.php (revision 14590) +++ units/helpers/json_helper.php (working copy) @@ -54,56 +54,62 @@ { $type = $this->getType($data); - switch ($type) { + switch ( $type ) { case 'object': - $data = '{'.$this->processData($data, $type).'}'; + $data = '{' . $this->processData($data, $type) . '}'; break; case 'array': - $data = '['.$this->processData($data, $type).']'; + $data = '[' . $this->processData($data, $type) . ']'; break; default: - if (is_int($data) || is_float($data)) { + if ( is_int($data) || is_float($data) ) { $data = (string)$data; - } elseif (is_string($data)) { - $data = '"'.$this->escape($data).'"'; - } elseif (is_bool($data)) { + } + elseif ( is_string($data) ) { + $data = '"' . $this->escape($data) . '"'; + } + elseif ( is_bool($data) ) { $data = $data ? 'true' : 'false'; - } else { + } + else { $data = 'null'; } } + return $data; } /** * Enter description here... * - * @param unknown_type $input - * @param unknown_type $type - * @return unknown + * @param Array $data + * @param string $type + * @return string */ function processData($data, $type) { - $output = Array(); + $output = Array (); // If data is an object - it should be converted as a key => value pair - if ($type == 'object'){ - foreach($data as $key => $value) { - $output[] = '"'.$key.'": '.$this->encode($value); + if ( $type == 'object' ) { + foreach ($data as $key => $value) { + $output[] = '"' . $key . '": ' . $this->encode($value); } - } else { - foreach($data as $key => $value) { + } + else { + foreach ($data as $value) { $output[] = $this->encode($value); } } - return implode(',', $output);; + + return implode(',', $output); } /** * Function determines type of variable * - * @param unknown_type $data - * @return unknown + * @param mixed $data + * @return string */ function getType(&$data) { Index: units/helpers/language_import_helper.php =================================================================== --- units/helpers/language_import_helper.php (revision 14590) +++ units/helpers/language_import_helper.php (working copy) @@ -471,7 +471,7 @@ * @param int $language_id * @param string $prefix * @param string $unique_field - * @param string $data_fields + * @param Array $data_fields */ function _performUpgrade($language_id, $prefix, $unique_field, $data_fields) { @@ -550,6 +550,7 @@ * @param int $language_id * @param string $prefix * @param string $unique_field + * @param string $data_field * @param bool $temp_mode * @return Array */ @@ -618,10 +619,13 @@ * Create temp table for prefix, if table already exists, then delete it and create again * * @param string $prefix + * @param bool $drop_only + * @return string Name of created temp table + * @access protected */ - function _prepareTempTable($prefix, $drop_only = false) + protected function _prepareTempTable($prefix, $drop_only = false) { - $idfield = $this->Application->getUnitOption($prefix, 'IDField'); + $id_field = $this->Application->getUnitOption($prefix, 'IDField'); $table = $this->Application->getUnitOption($prefix,'TableName'); $temp_table = $this->Application->GetTempName($table); @@ -633,7 +637,7 @@ $this->Conn->Query($sql); $sql = 'ALTER TABLE %1$s CHANGE %2$s %2$s INT(11) NOT NULL DEFAULT "0"'; - $this->Conn->Query( sprintf($sql, $temp_table, $idfield) ); + $this->Conn->Query( sprintf($sql, $temp_table, $id_field) ); switch ($prefix) { case 'phrases': Index: units/helpers/list_helper.php =================================================================== --- units/helpers/list_helper.php (revision 14590) +++ units/helpers/list_helper.php (working copy) @@ -88,7 +88,7 @@ if ($config_mapping) { if (!array_key_exists('PerPage', $config_mapping)) { - trigger_error('Incorrect mapping of PerPage key in config for prefix ' . $event->Prefix . '', E_USER_WARNING); + trigger_error('Incorrect mapping of PerPage key in config for prefix ' . $prefix . '', E_USER_WARNING); } $per_page = $this->Application->ConfigValue($config_mapping['PerPage']); Index: units/helpers/mailbox_helper.php =================================================================== --- units/helpers/mailbox_helper.php (revision 14590) +++ units/helpers/mailbox_helper.php (working copy) @@ -204,10 +204,12 @@ * @param string $message * @param Array $verify_callback * @param Array $process_callback + * @param Array $callback_params * @param bool $include_attachment_contents * @return bool + * @access protected */ - function normalize($message, $verify_callback, $process_callback, $callback_params, $include_attachment_contents = true) + protected function normalize($message, $verify_callback, $process_callback, $callback_params, $include_attachment_contents = true) { // Decode message $this->decodeMime($message, $include_attachment_contents); Index: units/helpers/mailing_list_helper.php =================================================================== --- units/helpers/mailing_list_helper.php (revision 14590) +++ units/helpers/mailing_list_helper.php (working copy) @@ -72,28 +72,32 @@ /** * Returns mass mail sender name & email * + * @param Array $mailing_data * @return Array + * @access protected */ - function _getSenderData(&$mailing_data) + protected function _getSenderData(&$mailing_data) { $is_root = true; - if ($mailing_data['PortalUserId'] > 0) { + $email_address = $name = ''; + + if ( $mailing_data['PortalUserId'] > 0 ) { $sender =& $this->Application->recallObject('u.-item', null, Array ('skip_autoload' => true)); /* @var $sender UsersItem */ $sender->Load($mailing_data['PortalUserId']); $email_address = $sender->GetDBField('Email'); - $name = trim( $sender->GetDBField('FirstName') . ' ' . $sender->GetDBField('LastName') ); + $name = trim($sender->GetDBField('FirstName') . ' ' . $sender->GetDBField('LastName')); $is_root = false; } - if ($is_root || !$email_address) { + if ( $is_root || !$email_address ) { $email_address = $this->Application->ConfigValue('Smtp_AdminMailFrom'); } - if ($is_root || !$name) { - $name = strip_tags( $this->Application->ConfigValue('Site_Name') ); + if ( $is_root || !$name ) { + $name = strip_tags($this->Application->ConfigValue('Site_Name')); } return Array ($name, $email_address); @@ -149,7 +153,7 @@ } if ($recipient_type != 'u' && $recipient_type != 'g') { - // theese are already emails + // these are already emails return $recipient_ids; } @@ -166,6 +170,10 @@ LEFT JOIN ' . TABLE_PREFIX . 'PortalUser u ON u.PortalUserId = ug.PortalUserId WHERE (ug.GroupId IN (' . implode(',', $recipient_ids) . ')) AND (u.Email <> "")'; break; + + default: + $sql = ''; + break; } return $this->Conn->GetCol($sql); Index: units/helpers/menu_helper.php =================================================================== --- units/helpers/menu_helper.php (revision 14590) +++ units/helpers/menu_helper.php (working copy) @@ -33,10 +33,13 @@ /** * Builds site menu * + * @param string $prefix_special * @param Array $params + * * @return string + * @access public */ - function menuTag($prefix_special, $params) + public function menuTag($prefix_special, $params) { list ($menu, $root_path) = $this->_prepareMenu(); $cat = $this->_getCategoryId($params); @@ -52,7 +55,7 @@ if (array_key_exists('level', $params) && $params['level'] > count($levels)) { // current level is deeper, then requested level - return ; + return ''; } $level = max(array_key_exists('level', $params) ? $params['level'] - 1 : count($levels) - 1, 0); Index: units/helpers/minifiers/js_minify_helper.php =================================================================== --- units/helpers/minifiers/js_minify_helper.php (revision 14590) +++ units/helpers/minifiers/js_minify_helper.php (working copy) @@ -68,6 +68,9 @@ /** * Perform minification, return result + * + * @param string $input + * @return string */ public function minify($input) { @@ -110,6 +113,10 @@ * ACTION_KEEP_A = Output A. Copy B to A. Get the next B. * ACTION_DELETE_A = Copy B to A. Get the next B. * ACTION_DELETE_A_B = Get the next B. + * + * @param int $command + * @return void + * @access protected */ protected function action($command) { @@ -224,6 +231,10 @@ /** * Is $c a letter, digit, underscore, dollar sign, escape, or non-ASCII? + * + * @param string $c + * @return bool + * @access protected */ protected function isAlphaNum($c) { @@ -244,6 +255,8 @@ return $get; } } + + return ''; } protected function multipleLineComment() @@ -270,6 +283,8 @@ } $comment .= $get; } + + return ''; } /** Index: units/helpers/minifiers/minify_helper.php =================================================================== --- units/helpers/minifiers/minify_helper.php (revision 14590) +++ units/helpers/minifiers/minify_helper.php (working copy) @@ -52,20 +52,21 @@ /** * When used as non-block tag, then compress given files and return url to result * - * @param Array $files + * @param Array $params * @return string + * @access public */ - function CompressScriptTag($params) + public function CompressScriptTag($params) { // put to queue - if (array_key_exists('to', $params)) { + if ( array_key_exists('to', $params) ) { $files = $this->Application->GetVar($params['to'], ''); $this->Application->SetVar($params['to'], $files . '|' . $params['files']); return ''; } - if (array_key_exists('from', $params)) { + if ( array_key_exists('from', $params) ) { // get from queue $files = $this->Application->GetVar($params['from']); } @@ -82,18 +83,18 @@ $was_compressed = array_key_exists($hash, $this->compressInfo); - if ($was_compressed) { + if ( $was_compressed ) { $current_file = WRITEABLE . '/' . sprintf($file_mask, $this->compressInfo[$hash]); - if (!file_exists($current_file)) { + if ( !file_exists($current_file) ) { // when info exists, but file doesn't -> re-compress $was_compressed = false; } - if ($this->debugMode) { + if ( $this->debugMode ) { // check if any of listed files was changed since compressed file was created (only, when in debug mode) foreach ($files as $file) { - if (filemtime($file) > $this->compressInfo[$hash]) { + if ( filemtime($file) > $this->compressInfo[$hash] ) { $was_compressed = false; break; } @@ -101,13 +102,13 @@ } } - if (!$was_compressed) { + if ( !$was_compressed ) { $string = ''; $path_length = strlen(FULL_PATH) + 1; foreach ($files as $file) { // add filename before for easier debugging - if ($this->debugMode) { + if ( $this->debugMode ) { $string .= '/* === File: ' . substr($file, $path_length) . ' === */' . "\n"; $string .= '/* ' . str_repeat('=', strlen(substr($file, $path_length)) + 14) . ' */' . "\n\n"; } @@ -117,8 +118,8 @@ } // remove previous version of compressed file - if (isset($current_file)) { - if (file_exists($current_file)) { + if ( isset($current_file) ) { + if ( file_exists($current_file) ) { unlink($current_file); } } @@ -131,7 +132,7 @@ // compress collected data $this->compressInfo[$hash] = adodb_mktime(); - if (!$this->debugMode) { + if ( !$this->debugMode ) { // don't compress merged js/css file in debug mode to allow js/css debugging $this->compressString($string, $extension); } Index: units/helpers/mod_rewrite_helper.php =================================================================== --- units/helpers/mod_rewrite_helper.php (revision 14590) +++ units/helpers/mod_rewrite_helper.php (working copy) @@ -1012,35 +1012,38 @@ { list ($prefix) = explode('.', $prefix_special); - $query_vars = $this->Application->getUnitOption($prefix, 'QueryString'); - if (!$query_vars) { + $query_vars = $this->Application->getUnitOption($prefix, 'QueryString', Array ()); + /* @var $query_vars Array */ + + if ( !$query_vars ) { // given prefix doesn't use "env" variable to pass it's data return false; } $event_key = array_search('event', $query_vars); - if ($event_key) { + if ( $event_key ) { // pass through event of this prefix unset($query_vars[$event_key]); } - if (array_key_exists($prefix_special . '_event', $params) && !$params[$prefix_special . '_event']) { + if ( array_key_exists($prefix_special . '_event', $params) && !$params[$prefix_special . '_event'] ) { // if empty event, then remove it from url - unset( $params[$prefix_special . '_event'] ); + unset($params[$prefix_special . '_event']); } // if pass events is off and event is not implicity passed - if (!$keep_events && !array_key_exists($prefix_special . '_event', $params)) { + if ( !$keep_events && !array_key_exists($prefix_special . '_event', $params) ) { unset($params[$prefix_special . '_event']); // remove event from url if requested //otherwise it will use value from get_var } $processed_params = Array (); - foreach ($query_vars as $index => $var_name) { + foreach ($query_vars as $var_name) { // if value passed in params use it, otherwise use current from application $var_name = $prefix_special . '_' . $var_name; $processed_params[$var_name] = array_key_exists($var_name, $params) ? $params[$var_name] : $this->Application->GetVar($var_name); - if (array_key_exists($var_name, $params)) { + + if ( array_key_exists($var_name, $params) ) { unset($params[$var_name]); } } Index: units/helpers/modules_helper.php =================================================================== --- units/helpers/modules_helper.php (revision 14590) +++ units/helpers/modules_helper.php (working copy) @@ -39,6 +39,8 @@ function _EnableCookieSID() { $session =& $this->Application->recallObject('Session'); + /* @var $session Session */ + return $session->CookiesEnabled; } @@ -196,27 +198,30 @@ /** * Get all modules, that don't require licensing * + * @param Array $vars * @return Array + * @access protected */ - function _getFreeModules($vars) + protected function _getFreeModules($vars) { $skip_modules = Array ('.', '..'); $domain = $this->_GetDomain($vars); - if (!$this->_IsLocalSite($domain)) { - array_push($skip_modules, 'in-commerce', 'in-auction'); - } + if ( !$this->_IsLocalSite($domain) ) { + array_push($skip_modules, 'in-commerce', 'in-auction'); + } $ret = Array (); - $folder = dir(MODULES_PATH); + $folder = dir(MODULES_PATH); - if ($folder === false) { - return Array (); - } + if ( $folder === false ) { + return Array (); + } - while (($entry = $folder->read()) !== false) { + while ( ($entry = $folder->read()) !== false ) { $entry_lowercased = strtolower($entry); - if (!is_dir($folder->path . '/' . $entry) || in_array($entry_lowercased, $skip_modules)) { + + if ( !is_dir($folder->path . '/' . $entry) || in_array($entry_lowercased, $skip_modules) ) { continue; } Index: units/helpers/multilanguage_helper.php =================================================================== --- units/helpers/multilanguage_helper.php (revision 14590) +++ units/helpers/multilanguage_helper.php (working copy) @@ -159,10 +159,11 @@ * * @param string $prefix * @param bool $refresh Forces config field structure to be re-read from database + * @return void */ function createFields($prefix, $refresh = false) { - if ($refresh && preg_match('/(.*)-cdata$/', $prefix, $regs)) { + if ( $refresh && preg_match('/(.*)-cdata$/', $prefix, $regs) ) { // call main item config to clone cdata table $this->Application->UnitConfigReader->loadConfig($regs[1]); $this->Application->UnitConfigReader->runAfterConfigRead($prefix); @@ -171,52 +172,55 @@ $table_name = $this->Application->getUnitOption($prefix, 'TableName'); $this->curFields = $this->Application->getUnitOption($prefix, 'Fields'); - if (!($table_name && $this->curFields) || ($table_name && !$this->Conn->TableFound($table_name))) { + if ( !($table_name && $this->curFields) || ($table_name && !$this->Conn->TableFound($table_name)) ) { // invalid config found or prefix not found - return true; + return ; } $this->initLanguageCount(); - $sqls = Array(); + $sqls = Array (); $this->readTableStructure($table_name, $refresh); - foreach($this->curFields as $field_name => $field_options) - { - if (getArrayValue($field_options, 'formatter') == 'kMultiLanguage') { - if (isset($field_options['master_field'])) { + foreach ($this->curFields as $field_name => $field_options) { + if ( getArrayValue($field_options, 'formatter') == 'kMultiLanguage' ) { + if ( isset($field_options['master_field']) ) { unset($this->curFields[$field_name]); continue; } $this->setSourceField($field_name); - if ($this->languageCount > 0) { + if ( $this->languageCount > 0 ) { // `l77_Name` VARCHAR( 255 ) NULL DEFAULT '0'; - $field_mask = Array(); - $field_mask['name'] = 'l%s_'.$field_name; + $field_mask = Array (); + $field_mask['name'] = 'l%s_' . $field_name; $field_mask['null'] = getArrayValue($field_options, 'not_null') ? 'NOT NULL' : 'NULL'; - if ($this->curSourceField) { - $default_value = $this->getFieldParam('Default') != 'NULL' ? $this->Conn->qstr($this->getFieldParam('Default')) : $this->getFieldParam('Default'); + if ( $this->curSourceField ) { + $default_value = $this->getFieldParam('Default') != 'NULL' + ? $this->Conn->qstr($this->getFieldParam('Default')) + : $this->getFieldParam('Default'); $field_mask['type'] = $this->getFieldParam('Type'); } else { - $default_value = is_null($field_options['default']) ? 'NULL' : $this->Conn->qstr($field_options['default']); + $default_value = is_null($field_options['default']) ? 'NULL' + : $this->Conn->qstr($field_options['default']); $field_mask['type'] = $field_options['db_type']; } - $field_mask['default'] = ($field_mask['null'] == 'NOT NULL' && $default_value == 'NULL') ? '' : 'DEFAULT '.$default_value; + $field_mask['default'] = ($field_mask['null'] == 'NOT NULL' && $default_value == 'NULL') ? '' + : 'DEFAULT ' . $default_value; - if (strtoupper($field_mask['type']) == 'TEXT') { + if ( strtoupper($field_mask['type']) == 'TEXT' ) { // text fields in mysql doesn't have default value - $field_mask = $field_mask['name'].' '.$field_mask['type'].' '.$field_mask['null']; + $field_mask = $field_mask['name'] . ' ' . $field_mask['type'] . ' ' . $field_mask['null']; } else { - $field_mask = $field_mask['name'].' '.$field_mask['type'].' '.$field_mask['null'].' '.$field_mask['default']; + $field_mask = $field_mask['name'] . ' ' . $field_mask['type'] . ' ' . $field_mask['null'] . ' ' . $field_mask['default']; } $alter_sqls = $this->generateAlterSQL($field_mask, 1, $this->languageCount); - if ($alter_sqls) { - $sqls[] = 'ALTER TABLE '.$table_name.' '.$alter_sqls; + if ( $alter_sqls ) { + $sqls[] = 'ALTER TABLE ' . $table_name . ' ' . $alter_sqls; } } } @@ -233,15 +237,17 @@ * @param string $prefix * @param int $src_language * @param int $dst_language + * @return void + * @access public */ - function copyMissingData($prefix, $src_language, $dst_language) + public function copyMissingData($prefix, $src_language, $dst_language) { $table_name = $this->Application->getUnitOption($prefix, 'TableName'); $this->curFields = $this->Application->getUnitOption($prefix, 'Fields'); - if (!($table_name && $this->curFields) || ($table_name && !$this->Conn->TableFound($table_name))) { + if ( !($table_name && $this->curFields) || ($table_name && !$this->Conn->TableFound($table_name)) ) { // invalid config found or prefix not found - return true; + return ; } foreach ($this->curFields as $field_name => $field_options) { Index: units/helpers/permissions_helper.php =================================================================== --- units/helpers/permissions_helper.php (revision 14590) +++ units/helpers/permissions_helper.php (working copy) @@ -421,7 +421,10 @@ elseif ($perm_event) { // check permission by event name list ($prefix, $event) = explode(':', $perm_event); + $event_handler =& $this->Application->recallObject($prefix.'_EventHandler'); + /* @var $event_handler kEventHandler */ + return $event_handler->CheckPermission( new kEvent($perm_event) ); } Index: units/helpers/priority_helper.php =================================================================== --- units/helpers/priority_helper.php (revision 14590) +++ units/helpers/priority_helper.php (working copy) @@ -28,6 +28,7 @@ function preparePriorities(&$event, $is_new = false, $constrain = '') { $object =& $event->getObject(); + /* @var $object kDBItem */ $field_options = $object->GetFieldOptions('Priority'); $table_name = $this->Application->getUnitOption($event->Prefix, 'TableName'); Index: units/helpers/rating_helper.php =================================================================== --- units/helpers/rating_helper.php (revision 14590) +++ units/helpers/rating_helper.php (working copy) @@ -46,9 +46,11 @@ * @param kDBItem $object * @param bool $show_div * @param string $additional_msg + * @param string $additional_style * @return string + * @access public */ - function ratingBar(&$object, $show_div = true, $additional_msg = '', $additional_style = '') + public function ratingBar(&$object, $show_div = true, $additional_msg = '', $additional_style = '') { $perm_prefix = $this->Application->getUnitOption($object->Prefix, 'PermItemPrefix'); $static = !$this->Application->CheckPermission($perm_prefix . '.RATE', 0, $object->GetDBField('CategoryId')); @@ -60,35 +62,35 @@ /* @var $spam_helper SpamHelper */ $config_mapping = $this->Application->getUnitOption($object->Prefix, 'ConfigMapping'); - $review_settings = $config_mapping['RatingDelayValue'].':'.$config_mapping['RatingDelayInterval']; + $review_settings = $config_mapping['RatingDelayValue'] . ':' . $config_mapping['RatingDelayInterval']; $spam_helper->InitHelper($object->GetDBField('ResourceId'), 'Rating', $review_settings, $object->GetCol('ResourceId')); $user_voted = $spam_helper->InSpamControl(); // now draw the rating bar - $unit_selected_width = $additional_style? $this->ratingSmallUnitWidth : $this->ratingUnitWidth; + $unit_selected_width = $additional_style ? $this->ratingSmallUnitWidth : $this->ratingUnitWidth; $rating_width = $total_votes ? @number_format($total_rating / $total_votes, 2) * $unit_selected_width : 0; $rating1 = $total_votes ? @number_format($total_rating / $total_votes, 1) : 0; $rating2 = $total_votes ? @number_format($total_rating / $total_votes, 2) : 0; $rater = '