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($line
$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 = \'